From b08c6e6fc42b21dc100d6cca7e15aecd6b56dbc6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 21:29:48 +0000 Subject: [PATCH] craft-raw: Minolta MRW, Epson ERF, Mamiya MEF and Kodak DCS520C Four formats only LightCraft decodes, one feature each (mrw, erf, mef, kodak), moved from its vendor modules at 5ff567a4 with their tests; the MRW block container comes from lightcraft-meta. src/shared.rs holds the level helpers the maker decoders share. ERF and MEF state no white balance: the estimate LightCraft made from the preview is develop-side work, so wb_multipliers is None for them here. --- NOTICE | 5 +- README.md | 3 +- crates/raw/Cargo.toml | 12 +- crates/raw/README.md | 8 + crates/raw/src/erf.rs | 229 ++++++++++++++++++++++++++++ crates/raw/src/kodak.rs | 283 ++++++++++++++++++++++++++++++++++ crates/raw/src/lib.rs | 38 +++++ crates/raw/src/mef.rs | 270 ++++++++++++++++++++++++++++++++ crates/raw/src/mrw.rs | 321 +++++++++++++++++++++++++++++++++++++++ crates/raw/src/shared.rs | 189 +++++++++++++++++++++++ crates/raw/src/tests.rs | 3 +- 11 files changed, 1355 insertions(+), 6 deletions(-) create mode 100644 crates/raw/src/erf.rs create mode 100644 crates/raw/src/kodak.rs create mode 100644 crates/raw/src/mef.rs create mode 100644 crates/raw/src/mrw.rs create mode 100644 crates/raw/src/shared.rs diff --git a/NOTICE b/NOTICE index 3fb6885003..d3adbafbb4 100644 --- a/NOTICE +++ b/NOTICE @@ -91,8 +91,9 @@ Source provenance crates/raw (craft-raw) is moved from LightCraft, with behaviour ported from two other readers: - LightCraft, crates/raw (src/lib.rs, dng.rs, dngwrite.rs, tiffraw.rs, unpack.rs, ljpeg.rs, jxl.rs, - opcodes.rs, profile.rs, gaintable.rs, semantic.rs, preview.rs, vendor/crw.rs, vendor/hasselblad.rs - and their tests), + opcodes.rs, profile.rs, gaintable.rs, semantic.rs, preview.rs, vendor/crw.rs, vendor/hasselblad.rs, + vendor.rs (shared level helpers), vendor/mrw.rs, vendor/erf.rs, vendor/mef.rs, vendor/kodak.rs and their + tests) and crates/meta/src/mrw.rs (the MRW block container), revision 5ff567a4a2e067bef1b6bce152c11e7f727ccbaf. https://github.com/storytold/lightcraft Copyright (c) 2026 ArtCraft Team and the LightCraft contributors. diff --git a/README.md b/README.md index 508c5ecb9e..0f64a5c16f 100644 --- a/README.md +++ b/README.md @@ -88,7 +88,8 @@ craft- = { git = "https://github.com/storytold/craft-libs", rev = "> 4`, +//! `(b1 & 15) << 8 | b2`), then a pad byte. Read the other way (least significant first, as the Olympus blocks are) +//! the frame is noise: the mean step between same-colour neighbours is 150..199 codes against 11..18. +//! - `CFAPattern` `00 01 01 02`: RGGB. +//! - The maker note (`EPSON\0\x01\0`, then a big-endian IFD with offsets from the file start) holds four black levels +//! as `u32` in tag `0x0401` (61..65; in Bayer-cell order), above which the darkest 0.01% of samples sit; `0x020b` x +//! `0x020c` is the picture size, 3008 x 2000. Registered against the 640 x 424 preview JPEG (correlation of the +//! green channel over every even offset), that picture starts at column 20, row 12 in all three files. +//! - White: the saturation plateau (4095 on the clipped R-D1x frame), else 4095. +//! - No maker-note tag tracks the as-shot white balance across the three files, so `wb_multipliers` is `None`: +//! a developer estimates it (LightCraft measures it from the preview's neutral pixels; on the R-D1s sample that +//! gives red 2.68 and blue 1.31). An estimate from picture content is not the file-format layer's. +//! - The preview is the maker note's tag `0x0280`, a JPEG whose first byte is stored as `ee` (found by the +//! structural scan in `preview::scan_for_jpeg`). +use crate::{BlackLevel, Camera, Cfa, ColorData, Limits, Mode, OpcodeLists, Orientation, RawData, RawError, RawFormat, RawImage, Rect, Result}; +use craft_tiff::image::chunk_bytes; +use craft_tiff::{Ifd, Tiff, tags as t}; + +/// Epson's private compression code for the 16-byte block layout. +const BLOCKS16: u16 = 32769; +/// Maker-note tags. +const MN_BLACK: u16 = 0x0401; +const MN_WIDTH: u16 = 0x020b; +const MN_HEIGHT: u16 = 0x020c; +/// Where the picture starts in the sensor frame (measured, see the module notes). +const CROP_ORIGIN: (usize, usize) = (20, 12); + +/// The raw IFD of an Epson ERF: CFA, 12 bits, compression 32769, one strip of 16-byte blocks of ten samples. +pub(crate) fn raw_ifd(tiff: &Tiff, len: usize) -> Option<&Ifd> { + let make = tiff.find(t::MAKE).and_then(|e| e.value.as_str())?; + if !make.to_ascii_uppercase().contains("EPSON") { + return None; + } + tiff.all_ifds().into_iter().find(|i| { + let Ok(info) = i.image() else { return false }; + let (w, h) = (info.width as u64, info.height as u64); + i.u16(t::PHOTOMETRIC) == Some(t::photometric::CFA) + && i.u16(t::COMPRESSION) == Some(BLOCKS16) + && i.u16(t::BITS_PER_SAMPLE) == Some(12) + && w > 0 + && w % 10 == 0 + && matches!(info.chunks(len as u64).as_slice(), [c] if Some(c.len) == (w * 8 / 5).checked_mul(h)) + }) +} + +/// The maker-note IFD (`EPSON\0\x01\0` then an IFD in the file's byte order, offsets from the file start). +fn maker_note(bytes: &[u8], tiff: &Tiff) -> Option { + let e = tiff.exif()?.get(t::MAKER_NOTE)?; + let start = usize::try_from(e.offset).ok()?; + if !bytes.get(start..)?.starts_with(b"EPSON\0") { + return None; + } + let opts = craft_tiff::ParseOptions { max_ifds: 1, max_depth: 0, follow_children: false, ..Default::default() }; + craft_tiff::parse_ifd_at(bytes, e.offset.checked_add(8)?, tiff.order, 0, false, &opts).ok().map(|(i, _)| i) +} + +/// Unpack a strip of 16-byte blocks (15 bytes of ten MSB-first 12-bit samples, one pad byte). +fn unpack(src: &[u8], out: &mut [u16]) { + let (blocks, _) = src.as_chunks::<16>(); + let (pixels, _) = out.as_chunks_mut::<10>(); + for (b, px) in blocks.iter().zip(pixels) { + crate::unpack::unpack_msb(&b[..15], 12, px); + } +} + +pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result { + let tiff = Tiff::parse(bytes)?; + let ifd0 = tiff.ifds.first().ok_or_else(|| RawError::Corrupt("Erf TIFF without IFDs".into()))?; + let raw = raw_ifd(&tiff, bytes.len()).ok_or_else(|| RawError::Unsupported("Erf raw image not found".into()))?; + let info = raw.image()?; + let (w, h) = (info.width as usize, info.height as usize); + let n = w.checked_mul(h).filter(|n| *n > 0 && *n <= limits.samples()).ok_or(RawError::Limit("image too large"))?; + let cfa = match (raw.u64s(t::CFA_REPEAT_PATTERN_DIM).as_deref(), raw.bytes(t::CFA_PATTERN_EP)) { + (Some([2, 2]), Some(p)) if p.len() == 4 && p.iter().all(|&c| c <= 2) => Cfa { width: 2, height: 2, pattern: p.to_vec() }, + _ => return Err(RawError::Unsupported("Erf raw without a 2x2 CFAPattern".into())), + }; + let mn = maker_note(bytes, &tiff); + let black = match mn.as_ref().and_then(|m| m.u64s(MN_BLACK)).as_deref() { + Some(v @ [_, _, _, _]) if v.iter().all(|&b| b < 4095) => { + BlackLevel { repeat_rows: 2, repeat_cols: 2, values: v.iter().map(|&b| b as f32).collect(), delta_h: vec![], delta_v: vec![] } + } + _ => BlackLevel::uniform(0.0), + }; + let size = mn.as_ref().and_then(|m| Some((m.u32(MN_WIDTH)? as usize, m.u32(MN_HEIGHT)? as usize))); + let crop = match size { + Some((cw, ch)) if cw > 0 && ch > 0 && CROP_ORIGIN.0 + cw <= w && CROP_ORIGIN.1 + ch <= h => Rect::new(CROP_ORIGIN.0, CROP_ORIGIN.1, cw, ch), + _ => Rect::new(0, 0, w, h), + }; + // the white balance is measured from the samples, so the header probe reads them too + // the strip length is the tag value, so a short file must fail before the sample buffer is sized from it + let chunks = info.chunks(bytes.len() as u64); + let src = chunks + .first() + .and_then(|c| chunk_bytes(bytes, c).filter(|s| s.len() as u64 == c.len)) + .ok_or_else(|| RawError::Corrupt("Erf strip outside file".into()))?; + let mut d = vec![0u16; n]; + unpack(src, &mut d); + let white = crate::shared::white_from_data(&d, 12); + let data = if mode == Mode::Full { RawData::U16(d) } else { RawData::U16(Vec::new()) }; + let img = RawImage { + format: RawFormat::Erf, + width: w, + height: h, + cpp: 1, + data, + cfa: Some(cfa), + bits: 12, + black, + white: vec![white], + active_area: Rect::new(0, 0, w, h), + crop, + orientation: Orientation::from_exif(ifd0.u16(t::ORIENTATION).unwrap_or(1)), + color: ColorData::default(), + wb_multipliers: None, + linearized: false, + opcodes: OpcodeLists::default(), + camera: tiff.ifds.first().map(Camera::from_ifd0).unwrap_or_default(), + cinema: Default::default(), + pixel_aspect: 1.0, + }; + img.validate_for(mode)?; + Ok(img) +} + +#[cfg(test)] +mod tests { + use super::*; + use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; + + /// Pack ten-sample groups into 16-byte blocks, MSB first, zero pad. + fn pack(px: &[u16]) -> Vec { + let mut out = Vec::new(); + for g in px.chunks(10) { + for p in g.chunks(2) { + let (a, b) = (p[0], p[1]); + out.extend_from_slice(&[(a >> 4) as u8, ((a & 15) << 4) as u8 | (b >> 8) as u8, b as u8]); + } + out.push(0); + } + out + } + + fn sample(w: u32, h: u32, px: &[u16]) -> Vec { + let mut raw = IfdBuilder::new(); + raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); + raw.set(t::IMAGE_WIDTH, Value::Long(vec![w])); + raw.set(t::IMAGE_LENGTH, Value::Long(vec![h])); + raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![12])); + raw.set(t::COMPRESSION, Value::Short(vec![BLOCKS16])); + raw.set(t::PHOTOMETRIC, Value::Short(vec![t::photometric::CFA])); + raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); + raw.set(t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2])); + raw.set_image(ImageData::Strips { rows_per_strip: h, strips: vec![pack(px)] }); + let mut ifd0 = IfdBuilder::new(); + ifd0.set(t::MAKE, Value::Ascii("SEIKO EPSON CORP.".into())); + ifd0.set(t::MODEL, Value::Ascii("R-D1".into())); + ifd0.set(t::ORIENTATION, Value::Short(vec![1])); + ifd0.add_sub_ifd(raw); + TiffWriter::new(craft_tiff::ByteOrder::Big, false).write(&[ifd0]).unwrap() + } + + #[test] + fn decodes_the_block_layout() { + let (w, h) = (20u32, 6u32); + let px: Vec = (0..w * h).map(|i| (i * 37 % 4096) as u16).collect(); + let f = sample(w, h, &px); + assert_eq!(crate::probe(&f), Some(RawFormat::Erf)); + let r = crate::decode(&f).unwrap(); + assert_eq!(r.data, RawData::U16(px)); + assert_eq!(r.cfa.as_ref().map(Cfa::name).as_deref(), Some("RGGB")); + assert_eq!(r.wb_multipliers, None, "the file states none"); + assert_eq!(crate::probe_info(&f).unwrap(), r.info()); + } + + #[test] + fn malformed_files_never_panic() { + let px: Vec = (0..200).map(|i| (i * 13 % 4096) as u16).collect(); + let f = sample(20, 10, &px); + for n in (0..f.len()).step_by(3) { + let _ = crate::decode(&f[..n]); + } + for i in 0..f.len() { + for v in [0u8, 0xff] { + let mut g = f.clone(); + g[i] = v; + let _ = crate::decode(&g); + let _ = crate::probe_info(&g); + } + } + } + + /// Rewrite the raw IFD's height, rows per strip and strip length in place (the strip data stays as written). + fn declare(f: &mut [u8], rows: u32, strip_len: u32) { + let tiff = Tiff::parse(f).unwrap(); + let raw = &tiff.ifds[0].sub_ifds[0]; + let spots: Vec<_> = [(t::IMAGE_LENGTH, rows), (t::ROWS_PER_STRIP, rows), (t::STRIP_BYTE_COUNTS, strip_len)] + .into_iter() + .map(|(tag, v)| { + let e = raw.entries.iter().find(|e| e.tag == tag).unwrap(); + (e.offset as usize, matches!(e.value, Value::Short(_)), v) + }) + .collect(); + for (at, short, v) in spots { + if short { + f[at..at + 2].copy_from_slice(&u16::try_from(v).unwrap().to_be_bytes()); + } else { + f[at..at + 4].copy_from_slice(&v.to_be_bytes()); + } + } + } + + #[test] + fn a_strip_longer_than_the_file_is_an_error() { + // storytold/lightcraft#2119: the declared strip length matched the size, so a few bytes of data were decoded as a full frame + let px: Vec = (0..40).map(|i| (i * 13 % 4096) as u16).collect(); + let mut f = sample(20, 2, &px); + declare(&mut f, 2000, 32 * 2000); + assert_eq!(crate::probe(&f), Some(RawFormat::Erf)); + assert!(matches!(crate::probe_info(&f), Err(RawError::Corrupt(_)))); + assert!(matches!(crate::decode(&f), Err(RawError::Corrupt(_)))); + } +} diff --git a/crates/raw/src/kodak.rs b/crates/raw/src/kodak.rs new file mode 100644 index 0000000000..88756975dc --- /dev/null +++ b/crates/raw/src/kodak.rs @@ -0,0 +1,283 @@ +//! Kodak DCS520C raw TIFF: the CFA sub-IFD holds one lossless JPEG (SOF3) stream of two components. +//! +//! Sources: TIFF 6.0 (container; `GrayResponseCurve` `0x123`; the CFA tags `CFARepeatPatternDim` and `CFAPattern`), +//! ITU T.81 (lossless JPEG, process SOF3), the lossless-JPEG decoder in [`crate::ljpeg`], the file's `KodakIFD` +//! (`0x8290`, a plain IFD with absolute offsets) and black-box analysis of the one CC0 sample from +//! raw.pixls.us (2573, DCS520C; every number below was measured on it): +//! +//! - The raw IFD is `Compression` 7, photometric 32803 (CFA), 12 bits, one strip, `ImageWidth` x `ImageLength` = +//! 1736 x 1160. Its stream is a 12-bit lossless JPEG of 868 x 1160 with two components; the decoder's interleaved +//! output (component 0, component 1, per pixel) is the mosaic row by row, so component 0 is the even columns and +//! component 1 the odd ones. The stream ends exactly at the strip's end. Recognised structurally: a Kodak make +//! and a stream whose width times its component count is the IFD's `ImageWidth`. +//! - `CFAPattern` bytes `01 00 02 01` (anchored at the first sample) are GRBG; the decoded colours follow the IFD0 +//! RGB thumbnail (156 x 104) with that layout. +//! - The samples span only 191..=622 because they are stored companded: IFD `GrayResponseCurve` (`0x123`, 4096 +//! entries) is a non-decreasing table that is the identity below 216 and expands the rest to 12-bit linear +//! values (623 distinct values, stored 622 gives 4095 and so does every higher code). Applying it makes the +//! frame linear with 12-bit white 4095. +//! - No masked border: all four edges are picture. Black differs per colour: the darkest 0.01% of each CFA +//! position's samples sit at 220 (G), 223 (R) and 197 (B) after the table (scene shadows end at the sensor's +//! black), so black is measured per position from the samples. +//! - White balance: five rational triples in the `KodakIFD` look like neutral sensor values (`0x848`, `0x849`, +//! `0x84a`, `0x84c`, `0x84d`). Against the thumbnail's neutral pixels (370 pixels with R, G and B within 6 of +//! each other) the raw G/R is 0.94 and G/B 1.96; `0x848` (1913, 1834, 921) gives 0.96 and 1.99, the others +//! 0.77..1.25 and 2.08..2.96, so its green over red and over blue are the gains. +use crate::{ + BlackLevel, Camera, Cfa, ColorData, Limits, Mode, OpcodeLists, Orientation, RawData, RawError, RawFormat, RawImage, Rect, Result, ljpeg, +}; +use craft_tiff::image::chunk_bytes; +use craft_tiff::{Ifd, Tiff, tags as t}; + +/// The vendor IFD pointer (`KodakIFD`). +const KODAK_IFD: u16 = 0x8290; +/// Rational triple (red, green, blue) of neutral sensor values, see the module notes. +const NEUTRAL: u16 = 0x848; +/// TIFF `GrayResponseCurve`. +const RESPONSE_CURVE: u16 = 0x123; +/// Entries of the response curve: one per 12-bit code. +const CURVE_LEN: usize = 4096; + +/// The raw sub-IFD of a Kodak DCS TIFF with this layout: the CFA image whose single lossless JPEG stream has two +/// components, `ImageWidth / 2` columns and `ImageLength` rows, 12 bits. +pub(crate) fn raw_ifd<'a>(tiff: &'a Tiff, bytes: &[u8]) -> Option<&'a Ifd> { + let make = tiff.find(t::MAKE).and_then(|e| e.value.as_str())?; + if !make.to_ascii_uppercase().starts_with("KODAK") { + return None; + } + tiff.all_ifds().into_iter().find(|i| { + if i.u16(t::PHOTOMETRIC) != Some(t::photometric::CFA) || i.u16(t::COMPRESSION) != Some(t::compression::JPEG) { + return false; + } + let Ok(info) = i.image() else { return false }; + let chunks = info.chunks(bytes.len() as u64); + let [chunk] = chunks.as_slice() else { return false }; + let Some(src) = chunk_bytes(bytes, chunk) else { return false }; + matches!( + ljpeg::frame_info(src), + Ok((w, h, 2, 12)) if w.checked_mul(2) == Some(info.width as usize) && h == info.height as usize + ) && i.u64s(RESPONSE_CURVE).is_some_and(|c| c.len() == CURVE_LEN) + }) +} + +pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result { + let tiff = Tiff::parse(bytes)?; + let ifd0 = tiff.ifds.first().ok_or_else(|| RawError::Corrupt("Kodak TIFF without IFDs".into()))?; + let raw = raw_ifd(&tiff, bytes).ok_or_else(|| RawError::Unsupported("Kodak raw image not found".into()))?; + let info = raw.image()?; + let (w, h) = (info.width as usize, info.height as usize); + let n = w.checked_mul(h).filter(|n| *n > 0 && *n <= limits.samples()).ok_or(RawError::Limit("image too large"))?; + let cfa = match (raw.u64s(t::CFA_REPEAT_PATTERN_DIM).as_deref(), raw.bytes(t::CFA_PATTERN_EP)) { + (Some([2, 2]), Some(p)) if p.len() == 4 && p.iter().all(|&c| c <= 2) => Cfa { width: 2, height: 2, pattern: p.to_vec() }, + _ => return Err(RawError::Unsupported("Kodak raw without a 2x2 CFAPattern".into())), + }; + let curve: Vec = raw + .u64s(RESPONSE_CURVE) + .filter(|c| c.len() == CURVE_LEN && c.windows(2).all(|p| p[0] <= p[1]) && c.iter().all(|&v| v < CURVE_LEN as u64)) + .ok_or_else(|| RawError::Unsupported("Kodak raw without a usable response curve".into()))? + .into_iter() + .map(|v| v as u16) + .collect(); + let (black, data) = if mode == Mode::Full { + let chunks = info.chunks(bytes.len() as u64); + let src = chunks.first().and_then(|c| chunk_bytes(bytes, c)).ok_or_else(|| RawError::Corrupt("Kodak strip outside file".into()))?; + let f = ljpeg::decode(src, n)?; + if f.components != 2 || f.width * 2 != w || f.height != h || f.data.len() != n { + return Err(RawError::Corrupt("Kodak lossless JPEG does not match the image size".into())); + } + let mut d = f.data; + for v in &mut d { + *v = curve.get(usize::from(*v)).copied().unwrap_or(CURVE_LEN as u16 - 1); + } + (measured_black(&d, w), RawData::U16(d)) + } else { + (BlackLevel::uniform(0.0), RawData::U16(Vec::new())) + }; + let wb = kodak_ifd(bytes, &tiff, ifd0) + .and_then(|k| k.f64s(NEUTRAL)) + .filter(|v| v.len() == 3 && v.iter().all(|&x| x > 0.0)) + .map(|v| [(v[1] / v[0]) as f32, 1.0, (v[1] / v[2]) as f32]); + let img = RawImage { + format: RawFormat::KodakDcs, + width: w, + height: h, + cpp: 1, + data, + cfa: Some(cfa), + bits: 12, + black, + white: vec![(CURVE_LEN - 1) as f32], + active_area: Rect::new(0, 0, w, h), + crop: Rect::new(0, 0, w, h), + orientation: Orientation::from_exif(ifd0.u16(t::ORIENTATION).unwrap_or(1)), + color: ColorData::default(), + wb_multipliers: wb, + linearized: false, + pixel_aspect: 1.0, + opcodes: OpcodeLists::default(), + camera: tiff.ifds.first().map(Camera::from_ifd0).unwrap_or_default(), + cinema: Default::default(), + }; + img.validate_for(mode)?; + Ok(img) +} + +/// The vendor IFD (`KodakIFD`): a plain IFD with absolute value offsets. +fn kodak_ifd(bytes: &[u8], tiff: &Tiff, ifd0: &Ifd) -> Option { + let off = u64::from(ifd0.u32(KODAK_IFD)?); + let opts = craft_tiff::ParseOptions { max_ifds: 4, max_depth: 1, follow_children: false, ..Default::default() }; + craft_tiff::parse_ifd_at(bytes, off, tiff.order, 0, false, &opts).ok().map(|(i, _)| i) +} + +/// Black level per CFA position (the mosaic's first sample is position 0): the value below which only 0.01% of that +/// position's samples fall, see the module notes. Uniform 0 for an empty frame. +fn measured_black(d: &[u16], w: usize) -> BlackLevel { + let mut hist = vec![[0u32; CURVE_LEN]; 4]; + let mut count = [0u64; 4]; + for (y, row) in d.chunks(w.max(1)).enumerate() { + for (x, &v) in row.iter().enumerate() { + let p = (y & 1) * 2 + (x & 1); + hist[p][usize::from(v).min(CURVE_LEN - 1)] += 1; + count[p] += 1; + } + } + if count.contains(&0) { + return BlackLevel::uniform(0.0); + } + let values = (0..4) + .map(|p| { + let limit = count[p].div_ceil(10_000); + let mut seen = 0u64; + let level = hist[p] + .iter() + .position(|&c| { + seen += u64::from(c); + seen >= limit + }) + .unwrap_or(0); + level as f32 + }) + .collect(); + BlackLevel { repeat_rows: 2, repeat_cols: 2, values, ..Default::default() } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{decode, probe, probe_info}; + use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; + + const W: usize = 16; + const H: usize = 8; + + /// A response curve: the identity below 100, then steeper, saturating at 4095. + fn curve() -> Vec { + (0..CURVE_LEN as u32).map(|i| if i < 100 { i as u16 } else { (100 + (i - 100) * 7).min(4095) as u16 }).collect() + } + + /// Stored mosaic: values 60..=300, in the range the curve expands. + fn stored() -> Vec { + (0..W * H).map(|i| 60 + ((i * 37) % 241) as u16).collect() + } + + /// A big-endian IFD of `(tag, SRATIONAL triple)` entries at `at` in the file. + fn kodak_ifd_bytes(at: usize, tag: u16, v: [i32; 3]) -> Vec { + let mut b = vec![0, 1]; + b.extend(tag.to_be_bytes()); + b.extend(10u16.to_be_bytes()); + b.extend(3u32.to_be_bytes()); + b.extend(((at + 2 + 12 + 4) as u32).to_be_bytes()); + b.extend([0; 4]); + for x in v { + b.extend(x.to_be_bytes()); + b.extend(1i32.to_be_bytes()); + } + b + } + + fn file(make: &str, stream: Vec, width: u32, with_curve: bool, wb: Option<[i32; 3]>) -> Vec { + let mut raw = IfdBuilder::new(); + raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); + raw.set(t::IMAGE_WIDTH, Value::Short(vec![width as u16])); + raw.set(t::IMAGE_LENGTH, Value::Short(vec![H as u16])); + raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![12])); + raw.set(t::COMPRESSION, Value::Short(vec![7])); + raw.set(t::PHOTOMETRIC, Value::Short(vec![32803])); + raw.set(t::SAMPLES_PER_PIXEL, Value::Short(vec![1])); + if with_curve { + raw.set(RESPONSE_CURVE, Value::Short(curve())); + } + raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); + raw.set(t::CFA_PATTERN_EP, Value::Byte(vec![1, 0, 2, 1])); + raw.set_image(ImageData::Strips { rows_per_strip: H as u32, strips: vec![stream] }); + let build = |ptr: u32| { + let mut ifd0 = IfdBuilder::new(); + ifd0.set(t::MAKE, Value::Ascii(make.into())); + ifd0.set(t::MODEL, Value::Ascii("DCS520C".into())); + if wb.is_some() { + ifd0.set(KODAK_IFD, Value::Long(vec![ptr])); + } + ifd0.add_sub_ifd(raw.clone()); + TiffWriter::new(ByteOrder::Big, false).write(&[ifd0]).unwrap() + }; + let mut bytes = build(0); + if let Some(v) = wb { + let at = bytes.len().next_multiple_of(2); + bytes = build(at as u32); + bytes.resize(at, 0); + bytes.extend(kodak_ifd_bytes(at, NEUTRAL, v)); + } + bytes + } + + fn stream() -> Vec { + ljpeg::encode(&stored(), W / 2, H, 2, 12, 1, 0) + } + + /// Known answer: two interleaved components are the even and odd columns, the response curve linearises them, + /// the layout is GRBG, white balance comes from the vendor IFD, black is measured per CFA position. + #[test] + fn two_component_stream_decodes_through_the_response_curve() { + let bytes = file("Kodak", stream(), W as u32, true, Some([1900, 1800, 900])); + assert_eq!(probe(&bytes), Some(RawFormat::KodakDcs)); + let r = decode(&bytes).unwrap(); + assert_eq!((r.format, r.width, r.height, r.bits), (RawFormat::KodakDcs, W, H, 12)); + let want: Vec = stored().iter().map(|&v| curve()[usize::from(v)]).collect(); + assert_eq!(r.data, RawData::U16(want.clone())); + assert_eq!(r.cfa.as_ref().unwrap().name(), "GRBG"); + assert_eq!(r.white, vec![4095.0]); + assert_eq!(r.wb_multipliers, Some([1800.0 / 1900.0, 1.0, 2.0])); + // 0.01% of 32 samples is the smallest one of each position + let w = &want; + let min = |y0: usize, x0: usize| (y0..H).step_by(2).flat_map(|y| (x0..W).step_by(2).map(move |x| w[y * W + x])).min().unwrap() as f32; + assert_eq!(r.black.values, vec![min(0, 0), min(0, 1), min(1, 0), min(1, 1)]); + let i = probe_info(&bytes).unwrap(); + assert_eq!((i.format, i.width, i.height, i.wb_multipliers), (RawFormat::KodakDcs, W, H, r.wb_multipliers)); + } + + /// Without the vendor IFD there is no white balance; the layout is recognised from the structure alone, so + /// another make, one component, a stream of another width or a missing curve change nothing for other files. + #[test] + fn only_this_layout_is_claimed() { + assert_eq!(decode(&file("Kodak", stream(), W as u32, true, None)).unwrap().wb_multipliers, None); + assert_ne!(probe(&file("Canon", stream(), W as u32, true, None)), Some(RawFormat::KodakDcs)); + assert_ne!(probe(&file("Kodak", stream(), W as u32 + 2, true, None)), Some(RawFormat::KodakDcs)); + assert_ne!(probe(&file("Kodak", stream(), W as u32, false, None)), Some(RawFormat::KodakDcs)); + let one = ljpeg::encode(&stored()[..W * H / 2], W, H / 2, 1, 12, 1, 0); + assert_ne!(probe(&file("Kodak", one, W as u32, true, None)), Some(RawFormat::KodakDcs)); + } + + /// Hostile input: truncated streams and tables report errors instead of panicking. + #[test] + fn damaged_files_are_errors() { + let s = stream(); + for cut in [s.len() / 2, 40, 0] { + let bytes = file("Kodak", s[..cut].to_vec(), W as u32, true, Some([1, 1, 1])); + if probe(&bytes) == Some(RawFormat::KodakDcs) { + assert!(decode(&bytes).is_err() || cut == s.len()); + } + } + let bytes = file("Kodak", s, W as u32, true, Some([0, 5, 0])); + assert_eq!(decode(&bytes).unwrap().wb_multipliers, None); + } +} diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index 3b4422614c..1769978404 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -25,6 +25,10 @@ //! | `dng` | Adobe DNG: uncompressed (any depth, packed), lossless JPEG, lossy JPEG, Deflate (integer and floating point), strips and tiles, CFA and LinearRaw, DNG 1.7 interleaved storage; reading and writing | //! | `jxl` | JPEG XL compressed DNG (DNG 1.7, compression 52546) through `jxl-oxide`; implies `dng` | //! | `crw` | Canon CRW (CIFF), decoded by `craft-crw` and returned through this crate's types | +//! | `mrw` | Minolta / Konica Minolta MRW: 12-bit packed and 16-bit word mosaics in the `\0MRM` block container | +//! | `erf` | Epson ERF (R-D1 family): 12-bit samples in 16-byte blocks | +//! | `mef` | Mamiya MEF (ZD): uncompressed 12-bit packed | +//! | `kodak` | Kodak DCS520C TIFF: two-component lossless JPEG with a response curve | //! | `hasselblad` | Hasselblad 3FR and FFF (and other CFA TIFFs in the DNG layout without a DNG version): uncompressed and Hasselblad's lossless JPEG; implies `dng` | //! //! [`probe`] names every container it can tell apart whatever the features; [`RawFormat::is_supported`] says @@ -49,18 +53,28 @@ mod crw; mod dng; #[cfg(feature = "dng")] pub mod dngwrite; +#[cfg(feature = "erf")] +mod erf; pub mod gaintable; #[cfg(feature = "hasselblad")] mod hasselblad; #[cfg(feature = "jxl")] mod jxl; +#[cfg(feature = "kodak")] +mod kodak; pub mod ljpeg; +#[cfg(feature = "mef")] +mod mef; +#[cfg(feature = "mrw")] +mod mrw; pub mod opcodes; mod preview; pub mod profile; #[cfg(feature = "dng")] pub mod semantic; // (the TIFF pixel plumbing every TIFF-based maker shares; DNG is its only user so far) +#[allow(dead_code)] // each maker uses some of these helpers; which are live depends on the features +mod shared; #[cfg_attr(not(feature = "dng"), allow(dead_code))] mod tiffraw; #[cfg_attr(not(feature = "dng"), allow(dead_code))] @@ -296,6 +310,10 @@ impl RawFormat { (self == RawFormat::Dng && cfg!(feature = "dng")) || (self == RawFormat::Crw && cfg!(feature = "crw")) || (self == RawFormat::CfaTiff && cfg!(feature = "hasselblad")) + || (self == RawFormat::KodakDcs && cfg!(feature = "kodak")) + || (self == RawFormat::Mrw && cfg!(feature = "mrw")) + || (self == RawFormat::Erf && cfg!(feature = "erf")) + || (self == RawFormat::Mef && cfg!(feature = "mef")) } } @@ -370,6 +388,18 @@ pub fn probe(bytes: &[u8]) -> Option { if make.starts_with("SAMSUNG") && samsung_raw { return Some(RawFormat::Srw); } + #[cfg(feature = "erf")] + if erf::raw_ifd(&t, bytes.len()).is_some() { + return Some(RawFormat::Erf); + } + #[cfg(feature = "mef")] + if mef::raw_ifd(&t, bytes.len()).is_some() { + return Some(RawFormat::Mef); + } + #[cfg(feature = "kodak")] + if kodak::raw_ifd(&t, bytes).is_some() { + return Some(RawFormat::KodakDcs); + } #[cfg(feature = "dng")] if dng::is_plain_cfa_tiff(&t, bytes) { return Some(RawFormat::CfaTiff); @@ -556,6 +586,14 @@ fn decode_in(bytes: &[u8], mode: Mode, limits: &Limits) -> Result { RawFormat::Crw => crw::decode(bytes, mode, limits), #[cfg(feature = "hasselblad")] RawFormat::CfaTiff => hasselblad::decode(bytes, mode, limits), + #[cfg(feature = "kodak")] + RawFormat::KodakDcs => kodak::decode(bytes, mode, limits), + #[cfg(feature = "mrw")] + RawFormat::Mrw => mrw::decode(bytes, mode, limits), + #[cfg(feature = "erf")] + RawFormat::Erf => erf::decode(bytes, mode, limits), + #[cfg(feature = "mef")] + RawFormat::Mef => mef::decode(bytes, mode, limits), RawFormat::OtherTiff => Err(RawError::Unsupported(other_tiff_reason(bytes))), other => Err(RawError::Unsupported(format!("{other:?} files are not decoded by this build"))), } diff --git a/crates/raw/src/mef.rs b/crates/raw/src/mef.rs new file mode 100644 index 0000000000..a0856ff472 --- /dev/null +++ b/crates/raw/src/mef.rs @@ -0,0 +1,270 @@ +//! Mamiya MEF (ZD): a big-endian TIFF whose first `SubIFDs` child is an uncompressed 12-bit packed CFA image. +//! +//! Sources: TIFF 6.0 (container, MSB-first bit packing, `CFAPattern`) and black-box analysis of the one CC0 +//! MEF sample on raw.pixls.us (Mamiya ZD); every number below was measured on it. +//! +//! - IFD0 is a 144 x 192 RGB thumbnail with three `SubIFDs`: the raw (4016 x 5344, 12 bits, `Compression` 1, +//! photometric CFA, one strip of exactly 1.5 bytes per pixel, two samples in three bytes most significant bits +//! first, as TIFF packs them), a 992 x 1328 and a 240 x 320 RGB preview, all uncompressed and 8 bits. No JPEG. +//! - `CFAPattern` `00 01 01 02`: RGGB; the two green sites agree (means 254 and 256 against 235 and 165). +//! - No masked border and no stored black level: the darkest 0.01% of each site's samples sit at 3..6 and the +//! minimum is 0, so black is 0. White: the saturation plateau, else 4095. +//! - The 992 x 1328 preview shows a 3968 x 5312 window (4 sensor pixels per preview pixel) that starts at column 24, +//! row 12: that offset gives the best correlation of the preview's luminance with the box-filtered mosaic (0.965, +//! against 0.83 for the full frame). It is the default crop. +//! - Orientation is the raw IFD's own `Orientation` (6 on the sample, a portrait shot). +//! - No white-balance tag was found (the maker note holds an ICC-like profile), so `wb_multipliers` is `None`: a +//! developer estimates the gains (LightCraft measures them from that preview's neutral pixels). +use crate::{BlackLevel, Camera, Cfa, ColorData, Limits, Mode, OpcodeLists, Orientation, RawData, RawError, RawFormat, RawImage, Rect, Result}; +use craft_tiff::image::chunk_bytes; +use craft_tiff::{Ifd, Tiff, tags as t}; + +/// Where the preview's window starts in the sensor frame, and how many sensor pixels one preview pixel covers. +const CROP_ORIGIN: (usize, usize) = (24, 12); +const PREVIEW_SCALE: usize = 4; + +fn is_mamiya(tiff: &Tiff) -> bool { + tiff.find(t::MAKE).and_then(|e| e.value.as_str()).is_some_and(|m| m.to_ascii_uppercase().starts_with("MAMIYA")) +} + +/// The raw IFD of a Mamiya MEF: CFA, 12 bits, uncompressed, one strip of 1.5 bytes per pixel. +pub(crate) fn raw_ifd(tiff: &Tiff, len: usize) -> Option<&Ifd> { + if !is_mamiya(tiff) { + return None; + } + tiff.all_ifds().into_iter().find(|i| { + let Ok(info) = i.image() else { return false }; + let (w, h) = (info.width as u64, info.height as u64); + i.u16(t::PHOTOMETRIC) == Some(t::photometric::CFA) + && i.u16(t::COMPRESSION).unwrap_or(1) == 1 + && i.u16(t::BITS_PER_SAMPLE) == Some(12) + && w > 0 + && w % 2 == 0 + && matches!(info.chunks(len as u64).as_slice(), [c] if Some(c.len) == (w * 3 / 2).checked_mul(h)) + }) +} + +/// The largest uncompressed 8-bit RGB sub-IFD (the preview): its pixels, width and height. +fn rgb_preview<'a>(tiff: &Tiff, bytes: &'a [u8]) -> Option<(&'a [u8], usize, usize)> { + tiff.all_ifds() + .into_iter() + .filter_map(|i| { + let info = i.image().ok()?; + let ok = i.u16(t::PHOTOMETRIC) == Some(2) + && i.u16(t::COMPRESSION).unwrap_or(1) == 1 + && i.u16(t::SAMPLES_PER_PIXEL) == Some(3) + && i.u64s(t::BITS_PER_SAMPLE).is_some_and(|b| b.iter().all(|&v| v == 8)); + let (w, h) = (info.width as usize, info.height as usize); + let chunks = info.chunks(bytes.len() as u64); + let [c] = chunks.as_slice() else { return None }; + let px = chunk_bytes(bytes, c)?; + (ok && px.len() >= w.checked_mul(h)?.checked_mul(3)?).then_some((px, w, h)) + }) + .max_by_key(|(_, w, h)| w * h) +} + +pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result { + let tiff = Tiff::parse(bytes)?; + let raw = raw_ifd(&tiff, bytes.len()).ok_or_else(|| RawError::Unsupported("Mef raw image not found".into()))?; + let info = raw.image()?; + let (w, h) = (info.width as usize, info.height as usize); + let n = w.checked_mul(h).filter(|n| *n > 0 && *n <= limits.samples()).ok_or(RawError::Limit("image too large"))?; + let cfa = match (raw.u64s(t::CFA_REPEAT_PATTERN_DIM).as_deref(), raw.bytes(t::CFA_PATTERN_EP)) { + (Some([2, 2]), Some(p)) if p.len() == 4 && p.iter().all(|&c| c <= 2) => Cfa { width: 2, height: 2, pattern: p.to_vec() }, + _ => return Err(RawError::Unsupported("Mef raw without a 2x2 CFAPattern".into())), + }; + let preview = rgb_preview(&tiff, bytes); + let crop = match preview { + Some((_, pw, ph)) => { + let (cw, ch) = (pw.saturating_mul(PREVIEW_SCALE), ph.saturating_mul(PREVIEW_SCALE)); + if cw > 0 && ch > 0 && CROP_ORIGIN.0 + cw <= w && CROP_ORIGIN.1 + ch <= h { + Rect::new(CROP_ORIGIN.0, CROP_ORIGIN.1, cw, ch) + } else { + Rect::new(0, 0, w, h) + } + } + None => Rect::new(0, 0, w, h), + }; + // the white balance is measured from the samples, so the header probe reads them too + // the strip length is the tag value, so a short file must fail before the sample buffer is sized from it + let chunks = info.chunks(bytes.len() as u64); + let src = chunks + .first() + .and_then(|c| chunk_bytes(bytes, c).filter(|s| s.len() as u64 == c.len)) + .ok_or_else(|| RawError::Corrupt("Mef strip outside file".into()))?; + // 12-bit MSB packing takes 3 bytes per 2 samples; a strip that cannot hold the declared + // samples is a truncated file, not a picture — unpacking it would run past the real bytes + // through every output sample (a short strip asks for the whole allocation and more). + let need = n.div_ceil(2).saturating_mul(3); + if src.len() < need { + return Err(RawError::Corrupt(format!("a Mef strip of {} bytes cannot hold the declared {n} samples", src.len()))); + } + let mut d = vec![0u16; n]; + crate::unpack::unpack_msb(src, 12, &mut d); + let white = crate::shared::white_from_data(&d, 12); + let black = BlackLevel::uniform(0.0); + let data = if mode == Mode::Full { RawData::U16(d) } else { RawData::U16(Vec::new()) }; + let orientation = raw.u16(t::ORIENTATION).or_else(|| tiff.ifds.first().and_then(|i| i.u16(t::ORIENTATION))).unwrap_or(1); + let img = RawImage { + format: RawFormat::Mef, + width: w, + height: h, + cpp: 1, + data, + cfa: Some(cfa), + bits: 12, + black, + white: vec![white], + active_area: Rect::new(0, 0, w, h), + crop, + orientation: Orientation::from_exif(orientation), + color: ColorData::default(), + wb_multipliers: None, + linearized: false, + opcodes: OpcodeLists::default(), + camera: tiff.ifds.first().map(Camera::from_ifd0).unwrap_or_default(), + cinema: Default::default(), + pixel_aspect: 1.0, + }; + img.validate_for(mode)?; + Ok(img) +} + +#[cfg(test)] +mod tests { + use super::*; + use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; + + fn pack(px: &[u16]) -> Vec { + px.chunks(2).flat_map(|p| [(p[0] >> 4) as u8, ((p[0] & 15) << 4) as u8 | (p[1] >> 8) as u8, p[1] as u8]).collect() + } + + fn sample(w: u32, h: u32, px: &[u16]) -> Vec { + sample_strip(w, h, &pack(px)) + } + + fn sample_strip(w: u32, h: u32, strip: &[u8]) -> Vec { + let mut raw = IfdBuilder::new(); + raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); + raw.set(t::IMAGE_WIDTH, Value::Long(vec![w])); + raw.set(t::IMAGE_LENGTH, Value::Long(vec![h])); + raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![12])); + raw.set(t::COMPRESSION, Value::Short(vec![1])); + raw.set(t::PHOTOMETRIC, Value::Short(vec![t::photometric::CFA])); + raw.set(t::ORIENTATION, Value::Short(vec![6])); + raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); + raw.set(t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2])); + raw.set_image(ImageData::Strips { rows_per_strip: h, strips: vec![strip.to_vec()] }); + let mut ifd0 = IfdBuilder::new(); + ifd0.set(t::MAKE, Value::Ascii("Mamiya-OP Co.,Ltd.".into())); + ifd0.set(t::MODEL, Value::Ascii("MAMIYA ZD".into())); + ifd0.add_sub_ifd(raw); + TiffWriter::new(ByteOrder::Big, false).write(&[ifd0]).unwrap() + } + + /// A strip that cannot hold the declared samples is a truncated file, refused as corrupt + /// instead of unpacked: `unpack_msb` would otherwise run `n` samples through the few real + /// bytes, filling the rest from nothing. + #[test] + fn a_strip_too_short_for_the_declared_samples_is_refused() { + let px: Vec = (0..16 * 6).map(|i| (i * 41 % 4096) as u16).collect(); + let f = sample(16, 6, &px); + assert!(crate::decode(&f).is_ok()); + // A truncated file shaped like a real one: IFD tables first, strip last — only its first + // 20 packed bytes remain, while the IFD still declares the full 1.5 B/sample length. The + // probe accepts the file on the declared length; before the byte gate below, `unpack_msb` + // ran the dimension-sized allocation through those 20 bytes, filling it from nothing. + let u32be = |b: &[u8], a: usize| u32::from_be_bytes([b[a], b[a + 1], b[a + 2], b[a + 3]]); + let full = pack(&px); + let at = f.windows(full.len()).position(|w| w == full).expect("strip bytes in the file"); + let after_strip = at + full.len(); + let moved = after_strip - (at + 20); + let mut g = f[..8].to_vec(); + g.extend(std::iter::repeat_n(0u8, at + 20 - 8)); + g.extend_from_slice(&f[after_strip..]); + // repoint the first-IFD pointer and ifd0's MAKE / MODEL / SubIfds offsets (the tables now + // sit `moved` earlier); the raw sub-IFD's strip offset and byte count are patched below + let poke = |b: &mut [u8], a: usize| { + let v = u32::from_be_bytes([b[a], b[a + 1], b[a + 2], b[a + 3]]); + if v as usize >= after_strip { + b[a..a + 4].copy_from_slice(&(v - moved as u32).to_be_bytes()); + } + }; + let ifd0_at = u32be(&g, 4) as usize - moved; + g[4..8].copy_from_slice(&(ifd0_at as u32).to_be_bytes()); + let n = u16::from_be_bytes([g[ifd0_at], g[ifd0_at + 1]]) as usize; + for i in 0..n { + poke(&mut g, ifd0_at + 2 + i * 12 + 8); + } + // the raw sub-IFD: entries follow its count; tag 273 (StripOffsets) is the seventh, held + // inline — repoint it at the strip's new home, and append the truncated strip for real + let sub_at = u32be(&g, ifd0_at + 2 + 2 * 12 + 8) as usize; + let e_offsets = sub_at + 2 + 6 * 12 + 8; + let strip_at = g.len() as u32; + g[e_offsets..e_offsets + 4].copy_from_slice(&strip_at.to_be_bytes()); + g.extend_from_slice(&full[..20]); + assert_eq!(crate::probe(&g), Some(RawFormat::Mef)); + let r = crate::decode(&g); + assert!(matches!(r, Err(RawError::Corrupt(_))), "{r:?}"); + } + + #[test] + fn decodes_packed_12_bit() { + let px: Vec = (0..16 * 6).map(|i| (i * 41 % 4096) as u16).collect(); + let f = sample(16, 6, &px); + assert_eq!(crate::probe(&f), Some(RawFormat::Mef)); + let r = crate::decode(&f).unwrap(); + assert_eq!(r.data, RawData::U16(px)); + assert_eq!(r.orientation, Orientation::from_exif(6)); + assert_eq!(r.crop, Rect::new(0, 0, 16, 6)); + assert_eq!(crate::probe_info(&f).unwrap(), r.info()); + } + + #[test] + fn malformed_files_never_panic() { + let px: Vec = (0..16 * 6).map(|i| (i * 7 % 4096) as u16).collect(); + let f = sample(16, 6, &px); + for n in 0..f.len() { + let _ = crate::decode(&f[..n]); + } + for i in 0..f.len() { + for v in [0u8, 0xff] { + let mut g = f.clone(); + g[i] = v; + let _ = crate::decode(&g); + let _ = crate::probe_info(&g); + } + } + } + + /// Rewrite the raw IFD's height, rows per strip and strip length in place (the strip data stays as written). + fn declare(f: &mut [u8], rows: u32, strip_len: u32) { + let tiff = Tiff::parse(f).unwrap(); + let raw = &tiff.ifds[0].sub_ifds[0]; + let spots: Vec<_> = [(t::IMAGE_LENGTH, rows), (t::ROWS_PER_STRIP, rows), (t::STRIP_BYTE_COUNTS, strip_len)] + .into_iter() + .map(|(tag, v)| { + let e = raw.entries.iter().find(|e| e.tag == tag).unwrap(); + (e.offset as usize, matches!(e.value, Value::Short(_)), v) + }) + .collect(); + for (at, short, v) in spots { + if short { + f[at..at + 2].copy_from_slice(&u16::try_from(v).unwrap().to_be_bytes()); + } else { + f[at..at + 4].copy_from_slice(&v.to_be_bytes()); + } + } + } + + #[test] + fn a_strip_longer_than_the_file_is_an_error() { + // storytold/lightcraft#2119: the declared strip length matched the size, so a few bytes of data were decoded as a full frame + let px: Vec = (0..40).map(|i| (i * 13 % 4096) as u16).collect(); + let mut f = sample(20, 2, &px); + declare(&mut f, 2000, 30 * 2000); + assert_eq!(crate::probe(&f), Some(RawFormat::Mef)); + assert!(matches!(crate::probe_info(&f), Err(RawError::Corrupt(_)))); + assert!(matches!(crate::decode(&f), Err(RawError::Corrupt(_)))); + } +} diff --git a/crates/raw/src/mrw.rs b/crates/raw/src/mrw.rs new file mode 100644 index 0000000000..780f351bfd --- /dev/null +++ b/crates/raw/src/mrw.rs @@ -0,0 +1,321 @@ +//! Minolta / Konica Minolta MRW: a block container around a 12-bit Bayer mosaic. +//! +//! Sources: the public prose description of the MRW layout (Dalibor Jelínek's MRW notes) and black-box +//! analysis of the eight CC0 MRW samples on raw.pixls.us (DiMAGE 7, 7Hi, A1, A2, A200, Dynax / Maxxum / ALPHA-7 +//! Digital); every number below was measured on them. +//! +//! - `PRD` (24 bytes, big-endian): 8 ASCII version bytes, sensor rows and columns (`u16` each), image rows and +//! columns, data size (12 or 16 bits per stored sample), pixel size (12), storage method (`0x59` = 12-bit +//! packed: two samples in three bytes, most significant bits first; `0x52` = one 12-bit sample per big-endian +//! 16-bit word), two unknown bytes and the Bayer layout as a `u16` (`1` = RGGB, `4` = GBRG). The sensor data +//! starts after the header and is exactly sensor rows x columns samples in every sample. +//! - The sensor frame is 8 columns and 6 to 8 rows larger than the image size, but every edge holds picture (no +//! masked border), so the whole frame is the active area and the image size is the default crop. +//! - Black is 0: the darkest samples are 0 in every packed file and 13..34 in the unpacked ones, with no offset +//! left to subtract. White is the saturation plateau where the frame has one (3964 on the A1, 3965 on a clipped +//! DiMAGE 7, 4020 on the A200, 4076 on the 7D), else 4095. +//! - The layout code was checked against the embedded preview: with `1` the two greens are the equal (0,1) and +//! (1,0) positions; in the A200 (`4`) the greens are (0,0) and (1,1), and only red at (1,0) reproduces the +//! preview's red-dominated colour. +//! - `WBG` (12 bytes): four scale bytes, then four big-endian `u16` coefficients in the order of the Bayer cell +//! read row by row (RGGB: R G G B, GBRG: G B R G). Red over green and blue over green are the as-shot gains; +//! applied to the raw channel means they reproduce the preview's colour balance within the colour matrix's +//! reach on all eight samples. +//! - `TTW` is a TIFF with IFD0 (orientation), Exif and the maker note; the preview JPEG sits in it with its first +//! byte overwritten (see `preview::scan_for_jpeg`). +use crate::{ + BlackLevel, Camera, Cfa, ColorData, Limits, Mode, OpcodeLists, Orientation, RawData, RawError, RawFormat, RawImage, Rect, Result, unpack, +}; +use craft_tiff::{Tiff, tags as t}; + +/// Storage method codes in `PRD`. +const PACKED_12: u8 = 0x59; +const WORDS_16: u8 = 0x52; + +/// What `PRD` says about the sensor data. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Prd { + sensor: (usize, usize), + image: (usize, usize), + packed: bool, + cfa: &'static str, +} + +fn be16(b: &[u8], at: usize) -> Option { + b.get(at..at + 2).map(|s| u16::from_be_bytes([s[0], s[1]])) +} + +fn prd(b: &[u8]) -> Result { + let u = |at| be16(b, at).map(usize::from).ok_or_else(|| RawError::Corrupt("Mrw PRD block too short".into())); + let (sh, sw, ih, iw) = (u(8)?, u(10)?, u(12)?, u(14)?); + let (size, storage) = (b.get(16).copied(), b.get(18).copied()); + let packed = match (size, storage) { + (Some(12), Some(PACKED_12)) => true, + (Some(16), Some(WORDS_16)) => false, + _ => return Err(RawError::Unsupported(format!("Mrw storage {size:?}/{storage:?} is not decoded yet"))), + }; + let cfa = match u(22)? { + 1 => "RGGB", + 4 => "GBRG", + other => return Err(RawError::Unsupported(format!("Mrw Bayer layout {other}"))), + }; + if sw == 0 || sh == 0 || (packed && sw % 2 != 0) { + return Err(RawError::Corrupt("Mrw sensor size".into())); + } + Ok(Prd { sensor: (sw, sh), image: (iw.min(sw), ih.min(sh)), packed, cfa }) +} + +// --- the block container: the file starts with `\0MRM` and a big-endian `u32` length; the sensor data begins right +// after that many bytes (at `8 + length`). In between is a sequence of blocks, each a four-byte name (`\0PRD`, +// `\0TTW`, `\0WBG`, `\0RIF`, `\0PAD`), a big-endian `u32` length and that many bytes. `\0TTW` holds a complete +// big-endian TIFF (IFD0, Exif, maker note) whose offsets are relative to the block. + +/// The blocks and the offset of the sensor data in an MRW file. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Mrw<'a> { + /// `(name without the leading NUL, contents)`, in file order. + pub(crate) blocks: Vec<([u8; 3], &'a [u8])>, + /// Absolute offset of the sensor data. + pub(crate) data_offset: usize, +} + +impl<'a> Mrw<'a> { + /// The first block called `name` (e.g. `b"PRD"`). + pub(crate) fn block(&self, name: &[u8; 3]) -> Option<&'a [u8]> { + self.blocks.iter().find(|(n, _)| n == name).map(|(_, d)| *d) + } +} + +/// At most this many blocks are walked (real files have four or five). +const MAX_BLOCKS: usize = 64; + +fn be32(b: &[u8], at: usize) -> Option { + let s = b.get(at..at.checked_add(4)?)?; + Some(u32::from_be_bytes([s[0], s[1], s[2], s[3]]) as usize) +} + +/// Parse the block list of an MRW file. `None` when the magic is missing or the header length points past the +/// file; a block that runs past the header is dropped together with everything after it. +pub(crate) fn parse(bytes: &[u8]) -> Option> { + if !bytes.starts_with(b"\0MRM") { + return None; + } + let data_offset = be32(bytes, 4)?.checked_add(8).filter(|&o| o <= bytes.len())?; + let mut blocks = Vec::new(); + let mut at = 8usize; + while blocks.len() < MAX_BLOCKS && at.saturating_add(8) <= data_offset { + let (Some(name), Some(len)) = (bytes.get(at..at + 4), be32(bytes, at + 4)) else { break }; + let start = at + 8; + let Some(end) = start.checked_add(len).filter(|&e| e <= data_offset) else { break }; + let Some(data) = bytes.get(start..end) else { break }; + if name[0] == 0 { + blocks.push(([name[1], name[2], name[3]], data)); + } + at = end; + } + Some(Mrw { blocks, data_offset }) +} + +pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result { + let m = parse(bytes).ok_or_else(|| RawError::Corrupt("Mrw block header".into()))?; + let p = prd(m.block(b"PRD").ok_or_else(|| RawError::Unsupported("Mrw file without a PRD block".into()))?)?; + let (w, h) = p.sensor; + let n = w.checked_mul(h).filter(|n| *n <= limits.samples()).ok_or(RawError::Limit("image too large"))?; + let need = if p.packed { n / 2 * 3 } else { n * 2 }; + let src = bytes + .get(m.data_offset..) + .and_then(|s| s.get(..need)) + .ok_or_else(|| RawError::Corrupt(format!("Mrw sensor data truncated (needs {need} bytes)")))?; + let cfa = Cfa::bayer_static(p.cfa); + let (data, white) = if mode == Mode::Full { + let mut d = vec![0u16; n]; + if p.packed { + unpack::unpack_msb(src, 12, &mut d); + } else { + unpack::read_u16s(src, craft_tiff::ByteOrder::Big, &mut d); + for v in &mut d { + *v = (*v).min(4095); + } + } + let white = crate::shared::white_from_data(&d, 12); + (RawData::U16(d), white) + } else { + (RawData::U16(Vec::new()), 4095.0) + }; + let wb = m.block(b"WBG").and_then(|b| wb_from(b, &cfa)); + let tiff = m.block(b"TTW").and_then(|b| Tiff::parse(b).ok()); + let orientation = tiff.as_ref().and_then(|t| t.ifds.first()).and_then(|i| i.u16(t::ORIENTATION)).unwrap_or(1); + let img = RawImage { + format: RawFormat::Mrw, + width: w, + height: h, + cpp: 1, + data, + cfa: Some(cfa), + bits: 12, + black: BlackLevel::uniform(0.0), + white: vec![white], + active_area: Rect::new(0, 0, w, h), + crop: Rect::new(0, 0, p.image.0, p.image.1), + orientation: Orientation::from_exif(orientation), + color: ColorData::default(), + wb_multipliers: wb, + linearized: false, + opcodes: OpcodeLists::default(), + camera: tiff.as_ref().and_then(|t| t.ifds.first()).map(Camera::from_ifd0).unwrap_or_default(), + cinema: Default::default(), + pixel_aspect: 1.0, + }; + img.validate_for(mode)?; + Ok(img) +} + +/// As-shot gains from `WBG`: four coefficients in Bayer-cell order after four scale bytes. +fn wb_from(b: &[u8], cfa: &Cfa) -> Option<[f32; 3]> { + let mut sum = [0f32; 3]; + let mut count = [0f32; 3]; + for (i, &c) in cfa.pattern.iter().enumerate().take(4) { + let v = f32::from(be16(b, 4 + 2 * i)?); + let k = usize::from(c).min(2); + sum[k] += v; + count[k] += 1.0; + } + if count.contains(&0.0) || sum.iter().any(|&s| s <= 0.0) { + return None; + } + let mean = |k: usize| sum[k] / count[k]; + Some([mean(0) / mean(1), 1.0, mean(2) / mean(1)]) +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + /// A synthetic MRW: `PRD` with the given storage, `WBG`, a `TTW` TIFF with orientation 6, then the samples. + pub(crate) fn sample(w: u16, h: u16, packed: bool, layout: u16, wbg: [u16; 4], samples: &[u16]) -> Vec { + let mut prd = b"21810002".to_vec(); + for v in [h, w, h - 2, w - 2] { + prd.extend_from_slice(&v.to_be_bytes()); + } + prd.extend_from_slice(&[if packed { 12 } else { 16 }, 12, if packed { PACKED_12 } else { WORDS_16 }, 0, 0, 0]); + prd.extend_from_slice(&layout.to_be_bytes()); + let mut wb = vec![2u8; 4]; + for v in wbg { + wb.extend_from_slice(&v.to_be_bytes()); + } + let mut ifd0 = craft_tiff::IfdBuilder::new(); + ifd0.set(t::MAKE, craft_tiff::Value::Ascii("Minolta Co., Ltd.".into())); + ifd0.set(t::ORIENTATION, craft_tiff::Value::Short(vec![6])); + let ttw = craft_tiff::TiffWriter::default().write(&[ifd0]).unwrap(); + let mut body = Vec::new(); + for (name, data) in [(b"PRD", &prd), (b"WBG", &wb), (b"TTW", &ttw)] { + body.push(0); + body.extend_from_slice(name); + body.extend_from_slice(&(data.len() as u32).to_be_bytes()); + body.extend_from_slice(data); + } + let mut f = b"\0MRM".to_vec(); + f.extend_from_slice(&(body.len() as u32).to_be_bytes()); + f.extend_from_slice(&body); + if packed { + for p in samples.chunks(2) { + let (a, b) = (p[0], p.get(1).copied().unwrap_or(0)); + f.extend_from_slice(&[(a >> 4) as u8, ((a & 15) << 4) as u8 | (b >> 8) as u8, b as u8]); + } + } else { + for v in samples { + f.extend_from_slice(&v.to_be_bytes()); + } + } + f + } + + #[test] + fn decodes_packed_and_word_storage() { + let (w, h) = (8u16, 6u16); + let px: Vec = (0..48).map(|i| (i * 85) as u16 % 4096).collect(); + for packed in [true, false] { + let f = sample(w, h, packed, 1, [408, 256, 256, 450], &px); + assert_eq!(crate::probe(&f), Some(RawFormat::Mrw)); + let r = crate::decode(&f).unwrap(); + assert_eq!((r.width, r.height, r.bits), (8, 6, 12)); + assert_eq!(r.data, RawData::U16(px.clone()), "packed {packed}"); + assert_eq!(r.cfa.as_ref().map(Cfa::name).as_deref(), Some("RGGB")); + assert_eq!(r.crop, Rect::new(0, 0, 6, 4)); + assert_eq!(r.orientation, Orientation::from_exif(6)); + assert_eq!(r.camera.make.as_deref(), Some("Minolta Co., Ltd.")); + let wb = r.wb_multipliers.unwrap(); + assert!((wb[0] - 408.0 / 256.0).abs() < 1e-6 && (wb[2] - 450.0 / 256.0).abs() < 1e-6, "{wb:?}"); + assert_eq!(crate::probe_info(&f).unwrap(), r.info()); + } + } + + /// GBRG (layout 4): the coefficients follow the cell, so the second is blue and the third red. + #[test] + fn gbrg_white_balance_follows_the_cell() { + let f = sample(4, 4, true, 4, [255, 416, 480, 255], &[100; 16]); + let r = crate::decode(&f).unwrap(); + assert_eq!(r.cfa.as_ref().map(Cfa::name).as_deref(), Some("GBRG")); + let wb = r.wb_multipliers.unwrap(); + assert!((wb[0] - 480.0 / 255.0).abs() < 1e-6 && (wb[2] - 416.0 / 255.0).abs() < 1e-6, "{wb:?}"); + } + + /// Truncations and corrupted header bytes give errors, never panics. + #[test] + fn malformed_files_never_panic() { + let f = sample(8, 6, true, 1, [408, 256, 256, 450], &[7; 48]); + for n in 0..f.len() { + assert!(crate::decode(&f[..n]).is_err() || n == f.len()); + } + for i in 8..f.len().min(120) { + for v in [0u8, 0xff, 0x52, 0x59] { + let mut g = f.clone(); + g[i] = v; + let _ = crate::decode(&g); + let _ = crate::probe_info(&g); + } + } + assert!(matches!(crate::decode(b"\0MRM\0\x01\0\0"), Err(RawError::Corrupt(_)))); + assert!(matches!(crate::decode(b"\0MRM\0\0\0\0"), Err(RawError::Unsupported(w)) if w.contains("Mrw"))); + } +} + +#[cfg(test)] +mod container_tests { + use super::*; + + fn block(name: &[u8; 3], data: &[u8]) -> Vec { + let mut v = vec![0]; + v.extend_from_slice(name); + v.extend_from_slice(&(data.len() as u32).to_be_bytes()); + v.extend_from_slice(data); + v + } + + #[test] + fn walks_blocks_and_finds_the_data() { + let mut body = block(b"PRD", &[1, 2, 3]); + body.extend(block(b"WBG", &[4; 12])); + let mut f = b"\0MRM".to_vec(); + f.extend_from_slice(&(body.len() as u32).to_be_bytes()); + f.extend_from_slice(&body); + f.extend_from_slice(&[9, 9]); + let m = parse(&f).unwrap(); + assert_eq!(m.block(b"PRD"), Some(&[1u8, 2, 3][..])); + assert_eq!(m.block(b"WBG").map(<[u8]>::len), Some(12)); + assert_eq!(m.block(b"TTW"), None); + assert_eq!(m.data_offset, f.len() - 2); + } + + #[test] + fn hostile_lengths_never_panic() { + assert_eq!(parse(b"\0MRM"), None); + assert_eq!(parse(b"\0MRM\xff\xff\xff\xff"), None); + // a block claiming more than the header holds is dropped + let f = b"\0MRM\0\0\0\x0c\0PRD\xff\xff\xff\xff\0\0\0\0"; + assert_eq!(parse(f).map(|m| m.blocks.len()), Some(0)); + for n in 0..f.len() { + let _ = parse(&f[..n]); + } + } +} diff --git a/crates/raw/src/shared.rs b/crates/raw/src/shared.rs new file mode 100644 index 0000000000..cf7eed1076 --- /dev/null +++ b/crates/raw/src/shared.rs @@ -0,0 +1,189 @@ +//! Helpers the maker decoders share: the Exif CFA layout, and black and white levels measured from the samples +//! for files that state none. + +use crate::{BlackLevel, Cfa, Rect}; +use craft_tiff::Tiff; +use std::ops::Range; + +/// The colour-filter layout from the Exif `CFAPattern` tag (`0xa302`: two 16-bit repeat counts, found in either +/// byte order, then one byte per site: 0 = red, 1 = green, 2 = blue), when it describes a 2×2 Bayer cell. +pub(crate) fn cfa_from_exif(tiff: &Tiff) -> Option { + let &[c0, c1, r0, r1, s0, s1, s2, s3] = tiff.exif()?.bytes(crate::EXIF_CFA_PATTERN)? else { return None }; + let two = |a: u8, b: u8| matches!((a, b), (2, 0) | (0, 2)); + let name = match [s0, s1, s2, s3] { + [0, 1, 1, 2] => "RGGB", + [2, 1, 1, 0] => "BGGR", + [1, 0, 2, 1] => "GRBG", + [1, 2, 0, 1] => "GBRG", + _ => return None, + }; + (two(c0, c1) && two(r0, r1)).then(|| Cfa::bayer_static(name)) +} + +/// Black level per 2×2 CFA position (anchored at the active area origin) from masked sensor columns `cols` over +/// rows `rows`. Falls back to 0 when the region is empty. +pub(crate) fn black_from_columns(data: &[u16], width: usize, cols: Range, rows: Range, active: Rect) -> BlackLevel { + let height = data.len() / width.max(1); + let (mut sum, mut n) = ([0f64; 4], [0u64; 4]); + for y in rows.start..rows.end.min(height) { + let py = (y as isize - active.y as isize).rem_euclid(2) as usize; + for x in cols.start..cols.end.min(width) { + let px = (x as isize - active.x as isize).rem_euclid(2) as usize; + sum[py * 2 + px] += data[y * width + x] as f64; + n[py * 2 + px] += 1; + } + } + if n.contains(&0) { + return BlackLevel::uniform(0.0); + } + BlackLevel { repeat_rows: 2, repeat_cols: 2, values: (0..4).map(|i| (sum[i] / n[i] as f64) as f32).collect(), delta_h: vec![], delta_v: vec![] } +} + +/// Samples of up to 512 evenly spaced rows of the active area, for [`white_from_data`]: the borders can hold +/// their own saturated runs (0xffff junk on RW2, masked rows at 16383 on some Canon CR2s). The step is odd so both +/// row parities, and with them every CFA site, are read. +pub(crate) fn active_rows(data: &[u16], w: usize, a: Rect) -> Vec { + let step = (a.height / 512).max(1) | 1; + (a.y..a.y + a.height).step_by(step).filter_map(|y| data.get(y * w + a.x..y * w + a.x + a.width)).flatten().copied().collect() +} + +/// White level estimate: the saturation plateau if a noticeable number of samples sit at the maximum value, +/// otherwise the full `bits` range. A few stray samples above the plateau (hot pixels, e.g. on a Canon EOS 70D +/// CR2) don't hide it. +pub(crate) fn white_from_data(data: &[u16], bits: u32) -> f32 { + let full_level = (1u32 << bits.clamp(1, 16)) - 1; + let full = full_level as f32; + let step = (data.len() / 2_000_000).max(1); + // samples above the nominal range are padding / invalid (e.g. 0xFFFF fill), not saturation + let mut hist = vec![0usize; full_level as usize + 1]; + for &v in data.iter().step_by(step) { + if let Some(h) = hist.get_mut(v as usize) { + *h += 1; + } + } + let min_plateau = (data.len() / 20_000).max(16); + // the top of the data, skipping up to half a plateau's worth of strays so a real plateau can't be skipped + let strays = min_plateau / 2; + let mut above = 0usize; + let Some(mx) = hist.iter().enumerate().rev().find_map(|(v, &n)| { + above += n * step; + (above > strays).then_some(v as u32) + }) else { + return full; + }; + let band = (mx / 256).max(1); + let near = mx.saturating_sub(band); + let below = near.saturating_sub(band); + let count = |from: u32, to: u32| hist.get(from as usize..to as usize).map_or(0, |h| h.iter().sum::()); + // the strays count as saturated too + let top = count(near, full_level + 1); + let under = count(below, near); + // a saturation plateau is a spike: many more samples in the top band than in the band just below it + if mx as f32 > full * 0.5 && top * step >= min_plateau && top >= 4 * under + 4 { + // plateau: use its lower edge so everything at saturation maps to ≥ 1.0 + near as f32 + } else { + full + } +} + +#[cfg(test)] +pub(crate) fn declare_strip_len(file: &mut [u8], len: u32, declared: u32) { + let big = file.starts_with(b"MM"); + let entry = |v: u32| -> Vec { + if big { + [&279u16.to_be_bytes()[..], &4u16.to_be_bytes(), &1u32.to_be_bytes(), &v.to_be_bytes()].concat() + } else { + [&279u16.to_le_bytes()[..], &4u16.to_le_bytes(), &1u32.to_le_bytes(), &v.to_le_bytes()].concat() + } + }; + let (old, new) = (entry(len), entry(declared)); + let at: Vec = file.windows(old.len()).enumerate().filter(|(_, w)| *w == old.as_slice()).map(|(i, _)| i).collect(); + assert_eq!(at.len(), 1, "one StripByteCounts entry of {len} bytes"); + file[at[0]..at[0] + new.len()].copy_from_slice(&new); +} + +#[cfg(test)] +mod tests { + use super::*; + use craft_tiff::tags as t; + + /// `file`, whose image IFD holds one strip, as two strips at the same offset whose StripByteCounts are LONG8 (which + /// classic TIFF readers accept) `[u64::MAX, 1]`: their sum is past `u64::MAX`. + pub(super) fn huge_strip_counts(mut file: Vec) -> Vec { + let tiff = Tiff::parse(&file).unwrap(); + let o = tiff.order; + let ifd = tiff.all_ifds().into_iter().find(|i| i.contains(t::STRIP_OFFSETS)).unwrap(); + let (base, rows, offset) = (ifd.offset as usize, ifd.u32(t::IMAGE_LENGTH).unwrap(), ifd.u32(t::STRIP_OFFSETS).unwrap()); + assert!(rows >= 2); + let at = file.len() as u32; + // appended: the two strip offsets (LONG), then the two byte counts (LONG8) + let mut tail = Vec::new(); + o.put_u32(&mut tail, offset); + o.put_u32(&mut tail, offset); + o.put_u64(&mut tail, u64::MAX); + o.put_u64(&mut tail, 1); + for i in 0..usize::from(o.read_u16(&file, base).unwrap()) { + let e = base + 2 + 12 * i; + let (ty, count, value) = match o.read_u16(&file, e).unwrap() { + t::STRIP_OFFSETS => (4u16, 2u32, at), + t::ROWS_PER_STRIP => (4, 1, rows.div_ceil(2)), + t::STRIP_BYTE_COUNTS => (16, 2, at + 8), + _ => continue, + }; + let mut entry = Vec::new(); + o.put_u16(&mut entry, ty); + o.put_u32(&mut entry, count); + o.put_u32(&mut entry, value); + file[e + 2..e + 12].copy_from_slice(&entry); + } + file.extend_from_slice(&tail); + file + } + + #[test] + fn black_columns_by_parity() { + // 8 wide, masked columns 0..4, active starts at x=4 (even) + let data: Vec = (0..8 * 6) + .map(|i| { + let (x, y) = (i % 8, i / 8); + if x < 4 { [100, 101, 102, 103][(y % 2) * 2 + x % 2] } else { 5000 } + }) + .collect(); + let b = black_from_columns(&data, 8, 0..4, 0..6, Rect::new(4, 0, 4, 6)); + assert_eq!(b.values, vec![100.0, 101.0, 102.0, 103.0]); + let b = black_from_columns(&data, 8, 0..4, 0..6, Rect::new(3, 1, 4, 5)); + assert_eq!(b.at(0, 0, 0, 1), 103.0); + assert_eq!(black_from_columns(&data, 8, 0..0, 0..6, Rect::new(0, 0, 8, 6)), BlackLevel::uniform(0.0)); + } + + #[test] + fn white_plateau() { + let mut d: Vec = (0..100_000).map(|i| (i % 10000) as u16).collect(); + assert_eq!(white_from_data(&d, 14), 16383.0); + d.extend(std::iter::repeat_n(15000u16, 1000)); + let w = white_from_data(&d, 14); + assert!((14900.0..=15000.0).contains(&w), "{w}"); + assert_eq!(white_from_data(&[], 12), 4095.0); + } + + /// A Canon EOS 70D CR2 saturates at 13583 but has a handful of samples up to 14426 (out of ~20M): the plateau + /// is still found instead of falling back to 16383 (≈0.3 EV too dark, highlights never seen as clipped). + /// A plateau on the blue sites alone (odd rows) is still found: an even row step would read one row parity only. + #[test] + fn active_rows_reads_both_row_parities() { + let n = 2048; + let d: Vec = (0..n * n).map(|i| if (i / n) % 2 == 1 && i % 2 == 1 { 15000 } else { (i % 10000) as u16 }).collect(); + let w = white_from_data(&active_rows(&d, n, Rect::new(0, 0, n, n)), 14); + assert!((14900.0..=15000.0).contains(&w), "{w}"); + } + + #[test] + fn white_plateau_with_strays_above() { + let mut d: Vec = (0..100_000).map(|i| (2048 + i % 10000) as u16).collect(); + d.extend(std::iter::repeat_n(13583u16, 5000)); + d.extend([13700, 13900, 14100, 14426]); + let w = white_from_data(&d, 14); + assert!((13500.0..=13583.0).contains(&w), "{w}"); + } +} diff --git a/crates/raw/src/tests.rs b/crates/raw/src/tests.rs index 19362c7072..4c07ccecb0 100644 --- a/crates/raw/src/tests.rs +++ b/crates/raw/src/tests.rs @@ -207,7 +207,8 @@ fn private_containers_are_recognised_by_their_magic() { assert_eq!(probe(b"FOVb\x02\0\x02\0"), Some(RawFormat::X3f)); assert_eq!(RawFormat::Crw.is_supported(), cfg!(feature = "crw")); assert!(RawFormat::Dng.is_supported()); - assert!(!RawFormat::Mrw.is_supported() && !RawFormat::X3f.is_supported()); + assert_eq!(RawFormat::Mrw.is_supported(), cfg!(feature = "mrw")); + assert!(!RawFormat::X3f.is_supported()); // a CRW signature with no heap behind it is corrupt, not a panic #[cfg(feature = "crw")] assert!(matches!(decode(b"II\x1a\0\0\0HEAPCCDR\0\0"), Err(RawError::Corrupt(_))));