craft-raw: Kelvin presets for more CR2, CR3, PEF and RW2 raws (#2234)

Reads the camera's white-balance presets as a Kelvin curve where the
decoders gave none:
- CR2 ColorData versions 1 to 12 (5-word records), version 10 at either
  of its two layouts, picked by the Daylight record's 5200 K;
- CR3 ColorData versions 16-19, 32-34, 48 and 64-66;
- PEF maker note 0x0221 (entries of 53190 - K and the red/blue
  multipliers);
- RW2/RWL/RAW tag 0x0027: the D55 and 3200 K studio tungsten
  multipliers as a neutral pair with their chromaticities
  (KelvinPresets::from_neutral_lights / neutral_lights).
Ported from storytold/lightcraft#2527.


Claude-Session: https://claude.ai/code/session_01Fnx9MwPUug72xHRgg993uc

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Phil Hart
2026-11-18 15:02:12 -05:00
committed by GitHub
co-authored by Claude Opus 5.5
parent ccabfee3b5
commit 0976e3fd19
5 changed files with 247 additions and 19 deletions
+56 -14
View File
@@ -115,25 +115,56 @@ fn wb_from_color_balance(v: &[u64]) -> Option<[f32; 3]> {
/// Flash, in that order. Fluorescent is left out (a green light off the locus) and so is the Kelvin row (it holds the
/// dial's last setting, and on some bodies a temperature that doesn't match its own levels: 6036 K with the camera at
/// 5500 K on the PowerShot G1 X Mark III, Daylight's levels at 5213 K on the EOS 2000D). Positions from the ExifTool
/// Canon tag-name documentation's `ColorData5` / `ColorData8` tables, confirmed with ExifTool run as a black-box tool
/// on files of each version: -4 on a PowerShot G1 X Mark III (`ColorData5`: 8-word records, the second record after
/// Daylight a repeat of it), 13, 14 and 15 on the CC0 corpus samples of the EOS 5D Mark IV, 2000D and 6D Mark II
/// (`ColorData8`: 5-word records). Other versions give no presets.
fn preset_rows(version: i16) -> Option<[(usize, usize); 5]> {
match version {
-4 => Some([(95, 102), (111, 118), (119, 126), (127, 134), (151, 158)]),
13..=15 => Some([(133, 137), (138, 142), (143, 147), (148, 152), (163, 167)]),
_ => None,
/// Canon tag-name documentation's `ColorData1`–`ColorData8` tables, confirmed with ExifTool run as a black-box tool
/// on files of each version and by reading the words of 453 CR2 files (reporters' samples and the CC0 corpus): -4 on
/// a PowerShot G1 X Mark III (`ColorData5`: 8-word records, the second record after Daylight a repeat of it);
/// everything else is 5-word records `R G G B Kelvin` in the order Daylight (5200 K), Shade (7000), Cloudy (6000),
/// Tungsten (3200), Fluorescent, Kelvin, Flash (thirty words after Daylight): version 1 from word 78, 2–9 from 83, 10
/// from 103 on the EOS 1200D family and from 128 on the others, 11 from 128, 12–15 from 133. A version with two
/// layouts is read at the one whose Daylight record names 5200 K. Other versions give no presets.
fn preset_rows(version: i16) -> &'static [[(usize, usize); 5]] {
const fn records(daylight: usize) -> [(usize, usize); 5] {
preset_records(daylight, daylight + 30)
}
const G1X3: [(usize, usize); 5] = [(95, 102), (111, 118), (119, 126), (127, 134), (151, 158)];
const AT_78: [(usize, usize); 5] = records(78);
const AT_83: [(usize, usize); 5] = records(83);
const AT_103: [(usize, usize); 5] = records(103);
const AT_128: [(usize, usize); 5] = records(128);
const AT_133: [(usize, usize); 5] = records(133);
match version {
-4 => &[G1X3],
1 => &[AT_78],
2..=9 => &[AT_83],
10 => &[AT_103, AT_128],
11 => &[AT_128],
12..=15 => &[AT_133],
_ => &[],
}
}
/// The five preset records (Daylight, Shade, Cloudy, Tungsten, Flash) of a `ColorData` array whose Daylight record
/// starts at word `daylight` and Flash record at `flash`: Daylight, Shade, Cloudy and Tungsten follow each other
/// in 5-word records `R G G B Kelvin`. Also used by CR3 (`ColorData` words of the same record layout).
pub(crate) const fn preset_records(daylight: usize, flash: usize) -> [(usize, usize); 5] {
[(daylight, daylight + 4), (daylight + 5, daylight + 9), (daylight + 10, daylight + 14), (daylight + 15, daylight + 19), (flash, flash + 4)]
}
/// The camera's planckian white-balance presets from the `ColorData` words ([`preset_rows`]) as a Kelvin curve;
/// `None` for an unknown version, a short array or presets that don't make a curve.
fn kelvin_presets_from_color_data(v: &[u64]) -> Option<crate::kelvin::KelvinPresets> {
let version = *v.first()? as u16 as i16;
let rows = preset_rows(version)?;
let rows = match preset_rows(version) {
[one] => one,
many => many.iter().find(|rows| v.get(rows[0].1) == Some(&5200))?,
};
presets_at(v, rows)
}
/// The Kelvin curve of the preset records at `rows` ((levels word, temperature word) of each) in `v`.
pub(crate) fn presets_at(v: &[u64], rows: &[(usize, usize); 5]) -> Option<crate::kelvin::KelvinPresets> {
let mut points = Vec::with_capacity(rows.len());
for (at, temp_at) in rows {
for &(at, temp_at) in rows {
let q = v.get(at..at + 4)?;
let temp = *v.get(temp_at)? as f32;
if let Some(wb) = wb_from_levels(q[0] as f32, q[1] as f32, q[2] as f32, q[3] as f32)
@@ -700,7 +731,7 @@ pub(crate) mod tests {
fn color_data_with_presets(version: i16, presets: &[(u16, u16, u16)]) -> Vec<u64> {
let mut v = vec![0u64; 400];
v[0] = u64::from(version as u16);
for ((at, temp_at), &(r, b, k)) in preset_rows(version).unwrap().into_iter().zip(presets) {
for ((at, temp_at), &(r, b, k)) in preset_rows(version).first().unwrap().iter().copied().zip(presets) {
v[at..at + 4].copy_from_slice(&[r.into(), 1024, 1024, b.into()]);
v[temp_at] = k.into();
}
@@ -720,9 +751,20 @@ pub(crate) mod tests {
want.sort_by(|a, b| a.0.total_cmp(&b.0));
assert_eq!(p.points(), want);
let eos = [(2013, 1479, 5200), (2300, 1280, 7000), (2153, 1374, 6000), (1442, 2089, 3200), (2203, 1371, 6156)];
for version in [13, 14, 15] {
for version in [1, 2, 3, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15] {
assert!(kelvin_presets_from_color_data(&color_data_with_presets(version, &eos)).is_some(), "{version}");
}
// version 10 has two layouts: the one whose Daylight record says 5200 K is read
let mut b = vec![0u64; 400];
b[0] = 10;
for (&(at, temp_at), &(r, bl, k)) in preset_rows(10)[1].iter().zip(&eos) {
b[at..at + 4].copy_from_slice(&[r.into(), 1024, 1024, bl.into()]);
b[temp_at] = k.into();
}
assert!(kelvin_presets_from_color_data(&b).is_some(), "10, second layout");
b[132] = 5000;
assert!(kelvin_presets_from_color_data(&b).is_none(), "10, neither layout names Daylight at 5200 K");
assert!(kelvin_presets_from_color_data(&[10]).is_none());
// a preset that would turn the curve back (Flash cooler than Shade's levels say) is dropped, not fatal
let mut odd = g1x3;
odd[4] = (1500, 1300, 9000);
@@ -753,7 +795,7 @@ pub(crate) mod tests {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
if i == 0 { [0xfffc, 13, 14, 15][(seed % 4) as usize] } else { seed % 70000 }
if i == 0 { [0xfffc, 1, 10, 13, 14, 15][(seed % 6) as usize] } else { seed % 70000 }
})
.collect();
let _ = kelvin_presets_from_color_data(&v);
+51 -1
View File
@@ -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)
}
/// 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() },
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;
+40 -2
View File
@@ -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] {
return None;
}
let mut out = Self::from_neutral_pair(warm, cool)?;
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());
}
}
+46 -1
View File
@@ -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])]));
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(&note(&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(&note(&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];
+54 -1
View File
@@ -122,6 +122,8 @@ const COMPRESSION: u16 = 0x000b;
const LINEARITY_LIMIT: [u16; 3] = [0x000e, 0x000f, 0x0010];
const BLACK_RGB: [u16; 3] = [0x001c, 0x001d, 0x001e];
const WB_RGB: [u16; 3] = [0x0024, 0x0025, 0x0026];
/// The table of the white balance types (see [`panasonic_kelvin_presets`]).
const WB_TABLE: u16 = 0x0027;
const RAW_FORMAT: u16 = 0x002d;
/// The in-camera aspect-ratio crop: top, left, bottom, right in sensor coordinates.
const CROP: [u16; 4] = [0x002f, 0x0030, 0x0031, 0x0032];
@@ -341,6 +343,28 @@ fn decode_words(src: &[u8], shift: u32, out: &mut [u16]) {
});
}
/// CIE daylight D55, CIE 1931 (x, y).
const D55_XY: [f64; 2] = [0.33242, 0.34743];
/// The 3200 K Planckian light (the ISO 7589 studio tungsten lamp), CIE 1931 (x, y) from Kim et al.'s (2002) cubic
/// approximation of the Planckian locus.
const TUNGSTEN_3200_XY: [f64; 2] = [0.423_181_806_762_695_35, 0.399_077_685_165_656_9];
/// The Kelvin scale of a body without colour matrices, from tag `0x0027` (`WBInfo2`; tag number and entry layout
/// from `exiftool -v3` run as a black-box tool on the files): a count, then that many entries of the white
/// balance type and the camera's red, green and blue multipliers for it. Types 20 and 24 are the cameras' "D55" and
/// "ISO studio tungsten" whites: CIE daylight D55 (5500 K) and the ISO 7589 studio tungsten lamp, a 3200 K
/// Planckian light. Those two give a neutral pair ([`crate::kelvin::KelvinPresets::from_neutral_lights`]).
fn panasonic_kelvin_presets(ifd: &Ifd, order: ByteOrder) -> Option<crate::kelvin::KelvinPresets> {
let v = u16_array(ifd, WB_TABLE, order)?;
let n = (*v.first()? as usize).min(v.len() / 4);
let entry = |code: u16| {
let e = v.get(1..)?.as_chunks::<4>().0.iter().take(n).find(|e| e[0] == code)?;
Some([f32::from(e[1]), f32::from(e[2]), f32::from(e[3])])
};
let (tungsten, d55) = (entry(24)?, entry(20)?);
crate::kelvin::KelvinPresets::from_neutral_lights([TUNGSTEN_3200_XY, D55_XY], tungsten, d55)
}
/// A tag as a `u16` array: SHORT values, or the little-endian contents of an UNDEFINED / BYTE value.
fn u16_array(ifd: &Ifd, tag: u16, order: ByteOrder) -> Option<Vec<u16>> {
match ifd.value(tag)? {
@@ -669,7 +693,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma
active_area: active,
crop,
orientation: Orientation::from_exif(ifd0.u16(t::ORIENTATION).unwrap_or(1)),
color: ColorData::default(),
color: ColorData { kelvin_presets: panasonic_kelvin_presets(ifd0, tiff.order), ..Default::default() },
wb_multipliers: wb,
linearized: false,
linearization_table: None,
@@ -943,6 +967,35 @@ mod tests {
}
}
#[test]
fn white_balance_table_gives_kelvin_presets() {
let (w, h) = (70usize, 20usize);
let target = image(w, h, 200, 4000);
let mut stream = vec![];
for px in target.chunks(14) {
stream.extend_from_slice(&encode_block(px, None).0);
}
let payload = rotate(stream);
let mut tags = vec![short(CFA_PATTERN, 1), short(BITS, 12), short(RAW_FORMAT, 4)];
tags.extend(BLACK_RGB.iter().map(|&tag| short(tag, 128)));
tags.extend(WB_RGB.iter().zip([512, 256, 384]).map(|(&tag, v)| short(tag, v)));
let decode = |table: Option<Vec<u16>>| {
let mut tags = tags.clone();
tags.extend(table.map(|t| (WB_TABLE, Value::Short(t))));
crate::decode(&file(w as u16, h as u16, &tags, &payload, &|off| vec![(RAW_OFFSET, Value::Long(vec![off]))])).unwrap()
};
assert!(decode(None).color.kelvin_presets.is_none());
// three entries: Fine Weather (ignored), D55 and ISO studio tungsten, as red/green/blue multipliers
let table = vec![3, 9, 480, 256, 400, 20, 380, 256, 500, 24, 250, 256, 700];
let p = decode(Some(table)).color.kelvin_presets.unwrap();
let unit = |r: f32, b: f32| [r / 256.0, 1.0, b / 256.0];
assert_eq!(p.neutral_pair(), Some([unit(250.0, 700.0), unit(380.0, 500.0)]));
assert_eq!(p.neutral_lights(), Some([TUNGSTEN_3200_XY, D55_XY]));
// a missing light, or a count beyond the data, gives none
assert!(decode(Some(vec![1, 20, 500, 256, 380])).color.kelvin_presets.is_none());
assert!(decode(Some(vec![9, 20, 500, 256, 380, 24, 700, 256])).color.kelvin_presets.is_none());
}
#[test]
fn format4_and_6_round_trip_through_files() {
// format 4: 14 pixels per block, rotated chunks, blocks continuous across rows (here 70 = 5 blocks per row)