diff --git a/crates/raw/README.md b/crates/raw/README.md index f0faf0670..d17dd62d7 100644 --- a/crates/raw/README.md +++ b/crates/raw/README.md @@ -54,7 +54,7 @@ One module and one Cargo feature per maker or container family. All are on by de | `jxl` | JPEG XL DNG (DNG 1.7, compression 52546) | Lossless and lossy tiles through `jxl-oxide`; implies `dng` | | `crw` | Canon CRW (CIFF) | Decoded by [`craft-crw`](../crw/README.md), the one CRW decoder, and returned through this crate's types | | `cr2` | Canon CR2 | The lossless-JPEG frame of IFD 3 de-sliced (`0xc640`); the layout from `CR2CFAPattern` (`0xc5e0`); image area from `SensorInfo`; black measured on the masked columns; white from the saturation plateau; as-shot white balance from `ColorData` or `WBInfo`; the white-balance presets at their temperatures (`ColorData::kelvin_presets`). sRAW / mRAW (subsampled YCbCr, 4:2:2 and 4:2:0) come out as linear white-balanced RGB with three samples per pixel, the chroma gains measured against the file's own 16-bit RGB image in IFD 2 | -| `nef` | Nikon NEF / NRW | Uncompressed (16-bit words, 12-bit packed, Coolpix word packing), the packed layouts labelled compression 34713, Nikon's Huffman coding (lossless and lossy types, 12 and 14 bits, "lossy after split") with the `0x0096` linearisation table, small raw (YCbCr 4:2:2) as linear white-balanced RGB; black from `0x003d` or the NRW block, as-shot white balance from `0x000c`, `CropArea` or the measured image area of bodies that record none, masked trailing columns left out of the active area, the D1X pixel aspect, and the in-file distortion correction as a `WarpRectilinear` opcode ([derivation](docs/nikon-lens-corrections.md)). High Efficiency (HE / HE★) is refused by name; the previews still read | +| `nef` | Nikon NEF / NRW | Uncompressed (16-bit words, 12-bit packed, Coolpix word packing), the two interlaced fields of the E5400, E5700, E8400 and E8800 (the E5700 CYGM mosaic as approximate linear RGB), the packed layouts labelled compression 34713, Nikon's Huffman coding (lossless and lossy types, 12 and 14 bits, "lossy after split") with the `0x0096` linearisation table, small raw (YCbCr 4:2:2) as linear white-balanced RGB; black from `0x003d` or the NRW block, as-shot white balance from `0x000c`, `CropArea` or the measured image area of bodies that record none, masked trailing columns left out of the active area, the D1X pixel aspect, and the in-file distortion correction as a `WarpRectilinear` opcode ([derivation](docs/nikon-lens-corrections.md)). High Efficiency (HE / HE★) is refused by name; the previews still read | | `rw2` | Panasonic RW2, Leica RWL, older Panasonic / Leica RAW | Packed blocks (formats 2, 5, 7), formats 4 and 6, format 8 prefix-coded strips and tiles (a sample outside the bit depth makes the strip corrupt), 16-bit words; black per colour from `0x001c`–`0x001e` (plus the 15 counts formats 4 and 6 store above it, 15 when no black is recorded); white from the saturation plateau; sensor borders as the active area and the in-camera aspect crop; mapped-out defect pixels filled; as-shot white balance from `0x0024`–`0x0026`; the in-camera distortion correction (`0x0119`) as a `WarpRectilinear` opcode. Raw formats 1 and 3 and compression 34826 are refused (no samples of them) | | `raf` | Fujifilm RAF | The RAF header, records and raw IFD; uncompressed Bayer and X-Trans (16-bit words, 12-bit LSB-first, 32-bit word packing); Fujifilm's lossless and lossy striped compression ([derivation](docs/raf-compression.md), [corpus](docs/raf-corpus.sha256)); black, as-shot white balance and, for bodies without colour matrices, the camera's neutral multipliers for Illuminant A and D65 (`ColorData::kelvin_presets`, a neutral pair); orientation, make and model from the embedded JPEG's Exif; the in-file distortion and vignetting corrections as opcodes; the embedded preview, also by range from the header alone (`bounded_preview`, `embedded_preview_from_range`). The pre-2010 FinePix layout without a raw IFD is refused | | `orf` | Olympus / OM System ORF | Uncompressed: 16-bit words (12-bit values in the top bits shifted down), 12-bit packed in 32-bit words (XZ-2), 12-bit two-field (older compacts), 16-byte blocks of ten 12-bit samples (E-300, E-330, E-500, high-resolution modes); CFA from Exif `CFAPattern`; black, as-shot white balance (relative to `WB_GLevel`) and crop from the maker note's ImageProcessing, or from the main note on bodies without it; the CameraSettings preview. Compressed ORF is refused ([why](docs/orf-compression.md)); its preview still reads | diff --git a/crates/raw/src/coolpix.rs b/crates/raw/src/coolpix.rs new file mode 100644 index 000000000..058a8ce58 --- /dev/null +++ b/crates/raw/src/coolpix.rs @@ -0,0 +1,230 @@ +//! Two-field Nikon Coolpix raws: E5700 (CYGM four-colour filter), E5400, E8400 and E8800 (RGB Bayer). +//! +//! The layout was measured clean-room by black-box analysis of the CC0 raw.pixls.us files (E5700 2576 x 1924, +//! E8400 and E8800 3280 x 2454), not taken from any other raw converter: +//! +//! * one strip of `w * h * 1.5` bytes: 12-bit samples packed MSB-first, two per three bytes, no row padding (the +//! ordinary uncompressed NEF reader unpacks it); +//! * the strip holds two interlaced fields of `h / 2` full-width rows, field A first and field B second. Interleaving +//! them line by line gives the sensor image. The E5700 puts B on the even lines (`out[2k] = B[k]`, `out[2k+1] = A[k]`), +//! the other bodies put A on the even lines. The order is a property of the model, not something the files state: the +//! `0x828e` colour-filter tag is anchored at line 0 of the interleaved image, so the wrong parity swaps the two rows +//! of every filter cell (a green cast on the CYGM file); +//! * black level 0, white level 4095, nothing masked; +//! * E5400, E8400 and E8800: `0x828e = [2, 1, 1, 0]`, an ordinary BGGR Bayer. E5700: `0x828e = [5, 3, 1, 4]`, i.e. Y C / G M. +//! +//! Field storage, like field order, is a property of the body: the Nikon reader rearranges rows only for the +//! models in [`field_order`], and only when the file has their measured legacy layout (binary maker-note version +//! 0.2.0.0, one tight 12-bit strip). Of 370 NEFs from 86 bodies checked, exactly these four bodies' files use that +//! maker-note version, and all four store fields. Other files, including any unmeasured body, keep their stored rows. +//! +//! CYGM to RGB is deliberately simple. Each of the four colour planes is bilinearly interpolated to full resolution, +//! scaled by fixed per-plane gains ([`CYGM_GAINS`]) and combined with the ideal complementary-colour relations +//! `Y = R + G, C = G + B, M = R + B`: `R = (Y + M - C) / 2`, `B = (C + M - Y) / 2` and `G` as the mean of the green +//! plane and `(Y + C - M) / 2`. A fitted 3 x 4 matrix was rejected: it was ill-conditioned on a nearly neutral scene, +//! and a free fit of the four gains against the camera JPEG turned the green gain negative. +//! Limits: no per-camera colour matrix (colours are approximate), the files' own white balance is not read (the gains +//! give a fixed daylight balance; the white-balance controls adjust from there), bilinear (soft, zippered at edges) +//! interpolation, negative results clamp to zero. + +/// The measured two-field bodies and whether the first stored field holds the even lines of the sensor image. +const FIELD_BODIES: [(&str, bool); 4] = [("E5400", true), ("E5700", false), ("E8400", true), ("E8800", true)]; + +/// For a measured two-field body, whether the first field of its strip (rows `0..h/2`) holds the even lines; +/// `None` for every other model. (The `0x828e` colour-filter tag is anchored at line 0 of the interleaved image, +/// so the wrong parity swaps the two rows of every filter cell.) +pub(crate) fn field_order(model: &str) -> Option { + let model = model.trim(); + FIELD_BODIES.iter().find(|(name, _)| *name == model).map(|&(_, first_even)| first_even) +} + +/// Interleave the two fields of `samples` (`h / 2` rows each, field A first) into a `w x h` image. +pub(crate) fn deinterlace(samples: &[u16], w: usize, h: usize, first_field_even: bool) -> Option> { + let n = w.checked_mul(h).filter(|n| *n <= crate::MAX_SAMPLES)?; + if w == 0 || h < 2 || !h.is_multiple_of(2) || samples.len() != n { + return None; + } + let (a, b) = samples.split_at_checked(n / 2)?; + let (even, odd) = if first_field_even { (a, b) } else { (b, a) }; + let mut out = Vec::with_capacity(n); + for (even_row, odd_row) in even.chunks_exact(w).zip(odd.chunks_exact(w)) { + out.extend_from_slice(even_row); + out.extend_from_slice(odd_row); + } + (out.len() == n).then_some(out) +} + +/// The colour-filter tag of the four-colour (CYGM) sensor: Y C / G M. +pub(crate) const CYGM_PATTERN: [u8; 4] = [5, 3, 1, 4]; + +const CODE_G: u8 = 1; +const CODE_C: u8 = 3; +const CODE_M: u8 = 4; +const CODE_Y: u8 = 5; + +/// Fixed E5700 plane gains, in the order Y, C, G, M. Measured on the CC0 raw.pixls.us E5700 file (the only E5700 +/// raw available) against its own camera JPEG (640 x 480, linearised): on the bins the camera rendered neutral +/// (channel spread under 8 %, mid-tone, unclipped; 215 of 19,200 at 160 x 120), the median per-bin gains that make +/// `Y = C = M = 2 G`, normalised to the weakest of Y, C, M. Over bin grids of 160 x 120 to 640 x 480 and neutrality +/// thresholds of 4 to 12 % the gains stay within 1.043-1.048, 0.613-0.616 and 1.265-1.271 (bootstrap 95 % intervals +/// within 0.006), and gains fitted on one half of the frame keep the other half's neutrals near neutral. +pub(crate) const CYGM_GAINS: [f32; 4] = [1.046, 1.0, 0.614, 1.268]; + +/// Output scale of the converted RGB. +const CYGM_SCALE: f32 = 4.0; + +/// White level of the converted RGB: a clipped neutral patch reaches 4095 in the weakest-gained of Y, C, M +/// (gain 1.0, C) and gives half of it in R, G, B. Fixed, so the header probe and the full decode report the same value. +pub(crate) const CYGM_WHITE: f32 = 4095.0 * 0.5 * CYGM_SCALE; + +/// Bilinear tap along one axis of a sub-sampled plane: (low index, high index, weight of the high one) for output +/// coordinate `c` of a plane of `n` samples starting at `phase`. +fn tap(n: usize, phase: usize, c: usize) -> (usize, usize, f32) { + let last = n.saturating_sub(1); + match c.checked_sub(phase) { + None => (0, 0, 0.0), + Some(d) => { + let i = d / 2; + (i.min(last), (i + 1).min(last), if d % 2 == 1 { 0.5 } else { 0.0 }) + } + } +} + +/// Linear-light RGB (interleaved, `u16`, white level [`CYGM_WHITE`]) from a CYGM mosaic. +/// +/// `pattern` is the `0x828e` tag, row-major over the 2 x 2 cell at (0, 0); it must hold each of Y, C, G, M once. +pub(crate) fn cygm_to_rgb(mosaic: &[u16], w: usize, h: usize, pattern: [u8; 4]) -> Option> { + use rayon::prelude::*; + let pixels = w.checked_mul(h)?; + let output_samples = pixels.checked_mul(3).filter(|n| *n <= crate::MAX_SAMPLES)?; + if w < 4 || h < 4 || !w.is_multiple_of(2) || !h.is_multiple_of(2) || mosaic.len() != pixels { + return None; + } + // phase (py * 2 + px) of each colour: [Y, C, G, M]. Four different codes found means four different phases. + let phase_of = |code: u8| pattern.iter().position(|&c| c == code); + let phases = [phase_of(CODE_Y)?, phase_of(CODE_C)?, phase_of(CODE_G)?, phase_of(CODE_M)?]; + let (pw, prows) = (w / 2, h / 2); + // the four sub-sampled planes, in colour order Y, C, G, M + let planes = phases.map(|p| { + let (py, px) = (p / 2, p % 2); + mosaic.chunks_exact(w).skip(py).step_by(2).flat_map(|row| row.iter().skip(px).step_by(2).map(|&v| f32::from(v))).collect::>() + }); + if planes.iter().any(|p| p.len() != pw * prows) { + return None; + } + + let mut out = vec![0u16; output_samples]; + out.par_chunks_mut(w * 3).enumerate().for_each(|(y, row)| { + for (x, px) in row.as_chunks_mut::<3>().0.iter_mut().enumerate() { + let mut v = [0f32; 4]; + for (((slot, plane), &p), &gain) in v.iter_mut().zip(&planes).zip(&phases).zip(&CYGM_GAINS) { + let (y0, y1, fy) = tap(prows, p / 2, y); + let (x0, x1, fx) = tap(pw, p % 2, x); + let at = |i: usize, j: usize| plane.get(i * pw + j).copied().unwrap_or(0.0); + let top = at(y0, x0) * (1.0 - fx) + at(y0, x1) * fx; + let bot = at(y1, x0) * (1.0 - fx) + at(y1, x1) * fx; + *slot = (top * (1.0 - fy) + bot * fy) * gain; + } + let [yy, cc, gg, mm] = v; + let r = (yy + mm - cc) * 0.5; + let g = (gg + (yy + cc - mm) * 0.5) * 0.5; + let b = (cc + mm - yy) * 0.5; + for (o, c) in px.iter_mut().zip([r, g, b]) { + *o = (c * CYGM_SCALE).round().clamp(0.0, 65535.0) as u16; + } + } + }); + Some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn malformed_dimensions_are_refused_before_work_or_allocation() { + for (w, h) in [(usize::MAX, 2), (usize::MAX - 1, 64), (crate::MAX_SAMPLES, 4)] { + assert!(deinterlace(&[], w, h, true).is_none()); + assert!(cygm_to_rgb(&[], w, h, CYGM_PATTERN).is_none()); + } + } + + #[test] + fn two_field_round_trip_for_both_parities() { + let (w, h) = (6usize, 8usize); + // sensor image whose every line is distinct + let img: Vec = (0..w * h).map(|i| (i * 7 % 4096) as u16).collect(); + for first_even in [false, true] { + let lines: Vec<&[u16]> = img.chunks_exact(w).collect(); + // fields as stored: A = first h/2 rows, B = the rest + let evens = lines.iter().step_by(2); + let odds = lines.iter().skip(1).step_by(2); + let stored: Vec = if first_even { + evens.chain(odds).flat_map(|l| l.iter().copied()).collect() + } else { + odds.chain(evens).flat_map(|l| l.iter().copied()).collect() + }; + assert_eq!(deinterlace(&stored, w, h, first_even).unwrap(), img, "first_even = {first_even}"); + } + // the two parities differ + let s: Vec = (0..w * h).map(|i| i as u16).collect(); + assert_ne!(deinterlace(&s, w, h, true), deinterlace(&s, w, h, false)); + } + + #[test] + fn deinterlace_refuses_bad_shapes() { + assert!(deinterlace(&[0; 12], 3, 5, true).is_none()); + assert!(deinterlace(&[0; 11], 3, 4, true).is_none()); + assert!(deinterlace(&[], 0, 0, true).is_none()); + } + + #[test] + fn field_order_is_per_model_and_only_for_measured_bodies() { + assert_eq!(field_order("E5700"), Some(false)); + assert_eq!(field_order("E5700 "), Some(false)); + for model in ["E5400", "E8400", "E8800"] { + assert_eq!(field_order(model), Some(true), "{model}"); + } + for model in ["E5000", "E8700", "D1X", "", "E57000"] { + assert_eq!(field_order(model), None, "{model}"); + } + } + + #[test] + fn white_level_follows_the_weakest_gain() { + let weakest = CYGM_GAINS[0].min(CYGM_GAINS[1]).min(CYGM_GAINS[3]); + assert!((CYGM_WHITE - 4095.0 * weakest * 0.5 * CYGM_SCALE).abs() < 1e-3); + } + + #[test] + fn cygm_neutral_surface_stays_neutral() { + let (w, h) = (16usize, 12usize); + // a neutral surface of level v on this sensor: each plane reads v / gain (G at half level) + let [gy, gc, gg, gm] = CYGM_GAINS; + for v in [400.0f32, 2000.0, 3500.0] { + let at = |i: usize| match ((i / w) % 2, i % 2) { + (0, 0) => v / gy, + (0, _) => v / gc, + (_, 0) => v / 2.0 / gg, + _ => v / gm, + }; + let m: Vec = (0..w * h).map(|i| at(i).round() as u16).collect(); + let rgb = cygm_to_rgb(&m, w, h, CYGM_PATTERN).unwrap(); + for px in rgb.as_chunks::<3>().0 { + let (lo, hi) = (px.iter().min().copied().unwrap_or(0), px.iter().max().copied().unwrap_or(0)); + assert!(lo > 0 && f32::from(hi - lo) <= f32::from(hi) * 0.01, "{px:?} at {v}"); + } + } + } + + #[test] + fn cygm_refuses_bad_input_without_panicking() { + assert!(cygm_to_rgb(&[0; 10], 4, 4, [5, 3, 1, 4]).is_none()); + assert!(cygm_to_rgb(&[], 0, 0, [5, 3, 1, 4]).is_none()); + assert!(cygm_to_rgb(&[0; 16], 4, 4, [5, 3, 1, 1]).is_none()); + assert!(cygm_to_rgb(&[0; 16], 4, 4, [2, 1, 1, 0]).is_none()); + assert!(cygm_to_rgb(&[0; 15], 5, 3, [5, 3, 1, 4]).is_none()); + // all-black input is fine + assert!(cygm_to_rgb(&[0; 16], 4, 4, [5, 3, 1, 4]).is_some()); + } +} diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index 83a1165ca..e12fe78ba 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -93,6 +93,9 @@ mod arw6_testenc; mod arw_lens; #[cfg(feature = "arw")] mod arw_lens_rm6; +/// Two-field Coolpix NEFs: field order and the CYGM mosaic. +#[cfg(feature = "nef")] +mod coolpix; /// Bounded DNG strip and tile sample reader. #[cfg(feature = "line-dng")] pub mod dng_lines; diff --git a/crates/raw/src/nef.rs b/crates/raw/src/nef.rs index 047d1ce56..b15320ce5 100644 --- a/crates/raw/src/nef.rs +++ b/crates/raw/src/nef.rs @@ -12,10 +12,10 @@ //! is exactly three bytes per pixel, Nikon small raw ([`small_raw`]); the D1X's genuinely Huffman-coded strip stays //! refused. -use crate::nefc; use crate::shared::white_from_data_sourced; use crate::tiffraw::{Packing, check_image, read_image}; use crate::{BlackLevel, Camera, Cfa, ColorData, Limits, Mode, OpcodeLists, Orientation, RawData, RawError, RawFormat, RawImage, Rect, Result}; +use crate::{coolpix, nefc}; use craft_tiff::image::ImageInfo; use craft_tiff::tags::{self as t, photometric}; use craft_tiff::{ByteOrder, Ifd, Tiff, makernote}; @@ -237,6 +237,19 @@ pub(crate) fn trailing_masked_columns(d: &[u16], w: usize, bits: u32) -> usize { aw & !1 } +/// The measured two-field Coolpix files use the binary maker-note version 0.2.0.0, compression 1 and a single +/// tight 12-bit strip. Together with the model list in [`coolpix::field_order`] this scopes the rearrangement; +/// it is a measured discriminator, not a TIFF declaration of field storage. +fn legacy_field_layout(info: &ImageInfo, mn: Option<&makernote::MakerNote>, file_len: usize) -> bool { + let legacy = mn.and_then(|m| m.ifd.bytes(0x0001)) == Some(&[0, 2, 0, 0]); + let expected = (info.width as u64).checked_mul(info.height as u64).and_then(|n| n.checked_mul(3)).map(|n| n / 2); + legacy + && info.compression == 1 + && info.samples_per_pixel == 1 + && info.bits() == 12 + && matches!(info.chunks(file_len as u64).as_slice(), [c] if Some(c.len) == expected) +} + 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("TIFF without IFDs".into()))?; @@ -255,11 +268,41 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result h, Mode::Header => h.min(MASK_ROWS), }; - let data = if info.compression == t::compression::NIKON { + let mut data = if info.compression == t::compression::NIKON { compressed(bytes, &info, mn.as_ref(), rows, limits)? } else { uncompressed(bytes, &info, tiff.order, mn.as_ref(), rows, limits)? }; + // Header probes inspect stored rows. Judge masked columns before rearranging the full + // image too, so the probe and full decoder use exactly the same prefix. + let stored_active_w = match &data { + RawData::U16(samples) => trailing_masked_columns(samples, w, bits), + _ => w, + }; + let model = ifd0.string(t::MODEL).unwrap_or_default(); + // Some CCD Coolpix bodies write two interlaced fields one after the other: the measured bodies, in their + // measured legacy layout, are interleaved in their model's field order (see `coolpix`). + if let (Mode::Full, RawData::U16(d)) = (mode, &mut data) + && let Some(first_even) = coolpix::field_order(&model) + && legacy_field_layout(&info, mn.as_ref(), bytes.len()) + && let Some(img) = coolpix::deinterlace(d, w, h, first_even) + { + *d = img; + } + // the E5700's four-colour (CYGM) filter becomes linear RGB (fixed measured gains, approximate colour) + let cygm = matches!( + (raw.u64s(t::CFA_REPEAT_PATTERN_DIM).as_deref(), raw.bytes(t::CFA_PATTERN_EP)), + (Some([2, 2]), Some(p)) if p == coolpix::CYGM_PATTERN + ) && info.compression != t::compression::NIKON + && info.samples_per_pixel == 1; + // Checked in every mode, so a CYGM NEF that `probe_info` accepts also decodes + if cygm && (w < 4 || h < 4 || !w.is_multiple_of(2) || !h.is_multiple_of(2)) { + return Err(RawError::Corrupt("Coolpix: bad CYGM mosaic".into())); + } + if cygm && let (Mode::Full, RawData::U16(d)) = (mode, &data) { + let rgb = coolpix::cygm_to_rgb(d, w, h, coolpix::CYGM_PATTERN).ok_or_else(|| RawError::Corrupt("Coolpix: bad CYGM mosaic".into()))?; + data = RawData::U16(rgb); + } let RawData::U16(ref samples) = data else { return Err(RawError::Unsupported("float NEF".into())) }; // Maker note 0x003d is in 14-bit units whatever the sample depth: 12-bit files from the D750, D780, D850, @@ -289,18 +332,21 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result= 2 && v[0] > 0.1 && v[1] > 0.1 && v[0] < 10.0 && v[1] < 10.0) .map(|v| [v[0] as f32, 1.0, v[1] as f32]); + // the converted CYGM data is already balanced + let wb = if cygm { Some([1.0; 3]) } else { wb }; let (cfa, assumed_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(), origin_x: 0, origin_y: 0 }, false) } _ => (Cfa::bayer_static("RGGB"), true), }; - let model = ifd0.string(t::MODEL).unwrap_or_default(); let body = measured_body(&model, w, h, bits); - let active_w = trailing_masked_columns(samples, w, bits); + let active_w = stored_active_w; // the white level is measured from the whole image (or known for a measured body); the probe (no samples in its // result) takes the nominal one let (white, white_source) = match (body.and_then(|b| b.white), mode) { + // fixed, so the header probe and the full decode agree + _ if cygm => (coolpix::CYGM_WHITE, crate::LevelSource::Fallback), (Some(white), _) => (white, crate::LevelSource::Fallback), (None, Mode::Full) => white_from_data_sourced(samples, bits), (None, Mode::Header) => (((1u32 << bits.clamp(1, 16)) - 1) as f32, crate::LevelSource::Fallback), @@ -314,12 +360,12 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result data, Mode::Header => RawData::U16(Vec::new()), }, - cfa: Some(cfa), + cfa: if cygm { None } else { Some(cfa) }, bits, black, white: vec![white], @@ -1137,6 +1183,153 @@ mod tests { assert_eq!(decode(Some(both)).black.values, vec![100.0, 101.0, 102.0, 103.0]); } + /// A Coolpix-style file: model `model`, `pattern` as the colour-filter tag, one strip of 12-bit MSB-first samples. + fn coolpix_file(model: &str, pattern: [u8; 4], w: usize, h: usize, strip_px: &[u16]) -> Vec { + coolpix_file_version(model, pattern, w, h, strip_px, &[0, 2, 0, 0]) + } + + fn coolpix_file_version(model: &str, pattern: [u8; 4], w: usize, h: usize, strip_px: &[u16], version: &[u8]) -> Vec { + let mut packed = Vec::new(); + for pair in strip_px.chunks(2) { + let v = (pair[0] as u32) << 12 | pair.get(1).copied().unwrap_or(0) as u32; + packed.extend_from_slice(&[(v >> 16) as u8, (v >> 8) as u8, v as u8]); + } + let mut raw = IfdBuilder::new(); + raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); + raw.set(t::IMAGE_WIDTH, Value::Long(vec![w as u32])); + raw.set(t::IMAGE_LENGTH, Value::Long(vec![h as u32])); + 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![photometric::CFA])); + raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); + raw.set(t::CFA_PATTERN_EP, Value::Byte(pattern.to_vec())); + raw.set_image(ImageData::Strips { rows_per_strip: h as u32, strips: vec![packed] }); + let mut ifd0 = IfdBuilder::new(); + ifd0.set(t::MAKE, Value::Ascii("NIKON".into())); + ifd0.set(t::MODEL, Value::Ascii(model.into())); + ifd0.set(t::ORIENTATION, Value::Short(vec![1])); + let mut note = IfdBuilder::new(); + note.set(0x0001, Value::Undefined(version.to_vec())); + let mut maker = b"Nikon\0\x02\0\0\0".to_vec(); + maker.extend(TiffWriter::new(ByteOrder::Little, false).write(&[note]).unwrap()); + let mut exif = IfdBuilder::new(); + exif.set(t::MAKER_NOTE, Value::Undefined(maker)); + ifd0.set_child(t::EXIF_IFD, exif); + ifd0.add_sub_ifd(raw); + TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap() + } + + /// The strip of a sensor image `img` with its even lines in the first (`first_even`) or the second field. + fn two_fields(img: &[u16], w: usize, h: usize, first_even: bool) -> Vec { + let lines = |start: usize| (start..h).step_by(2).flat_map(|y| img[y * w..(y + 1) * w].to_vec()).collect::>(); + let (even, odd) = (lines(0), lines(1)); + if first_even { [even, odd].concat() } else { [odd, even].concat() } + } + + /// A smooth scene with a little per-colour texture, sized like nothing in particular. + fn smooth_scene(w: usize, h: usize) -> Vec { + (0..w * h) + .map(|i| { + let (x, y) = ((i % w) as f64 / w as f64, (i / w) as f64 / h as f64); + (1800.0 + + 600.0 * (y * 6.0 * std::f64::consts::PI).sin() + + 300.0 * (x * 4.0 * std::f64::consts::PI).cos() * (y * 4.0 * std::f64::consts::PI).sin() + + 1800.0 * y + + (i % 2) as f64 * 40.0) as u16 + }) + .collect() + } + + #[test] + fn stacked_fields_are_interleaved_for_every_body_that_writes_them() { + let (w, h) = (96usize, 80usize); + let img = smooth_scene(w, h); + // E8400, E8800 and E5400 store the even lines first + for model in ["E8400", "E8800", "E5400"] { + let bytes = coolpix_file(model, [2, 1, 1, 0], w, h, &two_fields(&img, w, h, true)); + let r = crate::decode(&bytes).unwrap(); + assert_eq!((r.width, r.height, r.cpp), (w, h, 1), "{model}"); + assert_eq!(r.data, RawData::U16(img.clone()), "{model}"); + assert_eq!(r.cfa.as_ref().unwrap().name(), "BGGR", "{model}"); + } + } + + #[test] + fn other_models_and_layouts_keep_their_stored_rows() { + let (w, h) = (96usize, 80usize); + let stored = two_fields(&smooth_scene(w, h), w, h, true); + // an unmeasured model in the legacy layout + for model in ["E5000", "E99999", "D1X"] { + assert_eq!(crate::decode(&coolpix_file(model, [2, 1, 1, 0], w, h, &stored)).unwrap().data, RawData::U16(stored.clone()), "{model}"); + } + // a measured model outside its legacy maker-note dialect + for version in [b"0211".as_slice(), b"unknown".as_slice()] { + let bytes = coolpix_file_version("E8800", [2, 1, 1, 0], w, h, &stored, version); + assert_eq!(crate::decode(&bytes).unwrap().data, RawData::U16(stored.clone())); + } + // an odd height cannot hold two fields + let odd: Vec = (0..w * 79).map(|i| (i * 131 % 4096) as u16).collect(); + assert_eq!(crate::decode(&coolpix_file("E8400", [2, 1, 1, 0], w, 79, &odd)).unwrap().data, RawData::U16(odd)); + } + + #[test] + fn field_storage_does_not_depend_on_orientation() { + let (w, h) = (96usize, 80usize); + let img = smooth_scene(w, h); + let bytes = coolpix_file("E8400", [2, 1, 1, 0], w, h, &two_fields(&img, w, h, true)); + let tiff = Tiff::parse(&bytes).unwrap(); + let orientation = tiff.ifds.first().unwrap().get(t::ORIENTATION).unwrap().offset as usize; + for code in [3u16, 6, 8] { + let mut rotated = bytes.clone(); + rotated.get_mut(orientation..orientation + 2).unwrap().copy_from_slice(&code.to_le_bytes()); + let r = crate::decode(&rotated).unwrap(); + assert_eq!(r.orientation, Orientation::from_exif(code), "the rotated file reports orientation {code}"); + assert_eq!(r.data, RawData::U16(img.clone()), "orientation {code}"); + } + } + + #[test] + fn stacked_field_header_and_full_decode_agree() { + let (w, h) = (160usize, 256usize); + let mut img = smooth_scene(w, h); + for row in img.chunks_mut(w) { + row.iter_mut().skip(w - 8).for_each(|v| *v = 0); + } + for (model, pattern, first_even) in [("E8400", [2, 1, 1, 0], true), ("E5700", coolpix::CYGM_PATTERN, false)] { + let bytes = coolpix_file(model, pattern, w, h, &two_fields(&img, w, h, first_even)); + let header = decode(&bytes, Mode::Header, &Limits::default()).unwrap(); + let full = decode(&bytes, Mode::Full, &Limits::default()).unwrap(); + assert_eq!(header.info(), full.info(), "{model}"); + assert_eq!(header.black, full.black, "{model}"); + assert!(matches!(header.data, RawData::U16(ref d) if d.is_empty())); + if pattern == coolpix::CYGM_PATTERN { + assert_eq!((header.white.clone(), full.white.clone()), (vec![coolpix::CYGM_WHITE], vec![coolpix::CYGM_WHITE]), "{model}"); + } + } + } + + #[test] + fn coolpix_e5700_keeps_geometry_during_cygm_conversion() { + let (w, h) = (128usize, 96usize); + let img = smooth_scene(w, h); + // the E5700 stores the odd lines first + let r = crate::decode(&coolpix_file("E5700", [5, 3, 1, 4], w, h, &two_fields(&img, w, h, false))).unwrap(); + assert_eq!((r.width, r.height, r.cpp), (w, h, 3)); + assert!(r.cfa.is_none()); + let expected = coolpix::cygm_to_rgb(&img, w, h, coolpix::CYGM_PATTERN).unwrap(); + assert!(r.data == RawData::U16(expected), "full decode retains the intended sensor geometry"); + } + + #[test] + fn coolpix_short_input_is_an_error_not_a_panic() { + let (w, h) = (128usize, 96usize); + let mut file = coolpix_file("E5700", [5, 3, 1, 4], w, h, &vec![100u16; w * h]); + file.truncate(file.len() / 2); + let _ = crate::decode(&file); + file.truncate(200); + assert!(crate::decode(&file).is_err()); + } + #[test] fn compressed_without_table_is_unsupported() { let bytes = nef(34713, 14, vec![vec![0; 64]], 8, 8, 8);