LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
Merge PR #1475
Brandon Thomas66a0cd826c30
diff --cc crates/merge/src/output.rsindex f8b7e7173,ed24e636e..3f2bb665e--- a/crates/merge/src/output.rs+++ b/crates/merge/src/output.rs@@@ -111,7 -107,8 +111,8 @@@ pub fn write_linear_dngcolor: cd,wb_multipliers: None,linearized: false,+ pixel_aspect: 1.0,- opcodes: OpcodeLists::default(),+ opcodes: OpcodeLists { list3: lens.to_vec(), ..Default::default() },metadata: meta,};let compression = DngCompression::Deflate { tile: 256, half: samples == DngSamples::Half };diff --cc crates/raw/examples/rawinfo.rsindex c1e05bedc,d5cc21b15..701b93d73--- a/crates/raw/examples/rawinfo.rs+++ b/crates/raw/examples/rawinfo.rs@@@ -150,87 -130,4 +150,88 @@@ fn inspect_files(args: &[String]) -> usNone => println!(" preview: none"),}}+ failures+}++fn main() -> ExitCode {+ let args: Vec<String> = std::env::args().skip(1).collect();+ if inspect_files(&args) == 0 { ExitCode::SUCCESS } else { ExitCode::FAILURE }+}++#[cfg(test)]+mod tests {+ use super::inspect_files;+ use lightcraft_raw::{BlackLevel, Cfa, ColorData, DngWriteOptions, OpcodeLists, Orientation, RawData, RawFormat, RawImage, Rect, write_dng};+ use std::path::PathBuf;+ use std::sync::atomic::{AtomicUsize, Ordering};++ struct TempDir(PathBuf);++ impl TempDir {+ fn new() -> Self {+ static NEXT: AtomicUsize = AtomicUsize::new(0);+ let path = std::env::temp_dir().join(format!("lightcraft-rawinfo-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));+ std::fs::create_dir(&path).expect("create test directory");+ Self(path)+ }++ fn path(&self, name: &str) -> String {+ self.0.join(name).to_string_lossy().into_owned()+ }+ }++ impl Drop for TempDir {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.0);+ }+ }++ #[test]+ fn unreadable_input_is_a_failure_without_panicking() {+ let dir = TempDir::new();+ assert_eq!(inspect_files(&[dir.path("absent.arw")]), 1);+ }++ #[test]+ fn invalid_inputs_are_counted_without_stopping_the_batch() {+ let dir = TempDir::new();+ let path = dir.path("invalid.arw");+ std::fs::write(&path, b"not a raw file").expect("write invalid fixture");+ assert_eq!(inspect_files(&[path.clone(), path]), 2);+ }++ #[test]+ fn input_paths_are_required() {+ assert_eq!(inspect_files(&[]), 1);+ assert_eq!(inspect_files(&["--tree".into()]), 1);+ }++ #[test]+ fn valid_generated_dng_succeeds_after_an_unreadable_input() {+ let dir = TempDir::new();+ let raw = RawImage {+ format: RawFormat::Dng,+ width: 16,+ height: 16,+ cpp: 1,+ data: RawData::U16(vec![2048; 16 * 16]),+ cfa: Some(Cfa::bayer("RGGB").expect("valid CFA")),+ bits: 14,+ black: BlackLevel::uniform(0.0),+ white: vec![16383.0],+ active_area: Rect::new(0, 0, 16, 16),+ crop: Rect::new(0, 0, 16, 16),+ orientation: Orientation::Normal,+ color: ColorData::default(),+ wb_multipliers: Some([1.0; 3]),+ linearized: false,+ opcodes: OpcodeLists::default(),+ metadata: Default::default(),++ pixel_aspect: 1.0,+ };+ let path = dir.path("valid.dng");+ std::fs::write(&path, write_dng(&raw, &DngWriteOptions::default()).expect("encode generated fixture")).expect("write fixture");+ assert_eq!(inspect_files(std::slice::from_ref(&path)), 0);+ assert_eq!(inspect_files(&[dir.path("absent.arw"), path]), 1);+ }}diff --cc crates/raw/src/lib.rsindex 3a7f04a95,98b29dbd8..0e3cfd98e--- a/crates/raw/src/lib.rs+++ b/crates/raw/src/lib.rs@@@ -816,10 -811,16 +836,13 @@@ impl RawImagepub fn finish_demosaiced(&self, mut rgb: Rgb32f) -> Rgb32f {opcodes::apply_list3(&self.opcodes.list3, &mut rgb);let c = self.develop_crop(rgb.width, rgb.height);- if c.x == 0 && c.y == 0 && c.width == rgb.width && c.height == rgb.height {- let rgb = if c.x == 0 && c.y == 0 && c.width == rgb.width && c.height == rgb.height {- rgb- } else {- rgb.into_crop(c.x, c.y, c.width, c.height)- };++ let rgb =++ if c.x == 0 && c.y == 0 && c.width == rgb.width && c.height == rgb.height { rgb } else { rgb.into_crop(c.x, c.y, c.width, c.height) };+ let h = stretched_height(rgb.height, self.pixel_aspect);+ if h == rgb.height {return rgb;}- rgb.into_crop(c.x, c.y, c.width, c.height)+ lightcraft_raster::resample::resize(&rgb, rgb.width, h, lightcraft_raster::resample::Filter::Mitchell)}/// The part of a `width × height` demosaiced picture (the active area) that [`Self::develop`] keeps: the default@@@ -894,39 -896,19 +918,51 @@@ mod tests// a crop that pokes out is clipped to the picturewhole.crop = Rect::new(6, 4, 10, 10);assert_eq!(whole.develop_crop(8, 6), Rect::new(6, 4, 2, 2));++ // tall pixels (D1X: 2.0) are stretched to square ones: the rows double, `developed_size` says so+ let mut tall = raw.clone();+ tall.pixel_aspect = 2.0;+ let d = tall.develop(Method::Bilinear).unwrap();+ assert_eq!((d.width, d.height), (5, 8));+ assert_eq!(tall.info().developed_size(), (5, 8));+ assert_eq!(raw.info().developed_size(), (5, 4));+ assert!(!tall.can_bin(2));+ assert_eq!(stretched_height(1324, 2.0), 2648);+ assert_eq!(stretched_height(1324, 1.0), 1324);}+ /// A maker-note crop (`PEF` AOC / `ORF` ImageProcessing) with an origin of `u64::MAX` used to+ /// pass the bounds check (`x + width` wraps to 0) and then index out of bounds in+ /// `normalized`. It must be a `Corrupt` error at validate time instead.+ #[test]+ fn an_active_area_that_wraps_past_the_image_is_corrupt() {+ let (w, h) = (12usize, 10usize);+ let mut raw = RawImage {+ format: RawFormat::Dng,+ width: w,+ height: h,+ cpp: 1,+ data: RawData::U16(vec![100; w * h]),+ cfa: Cfa::bayer("RGGB"),+ bits: 12,+ black: BlackLevel::uniform(64.0),+ white: vec![1023.0],+ active_area: Rect::new(usize::MAX, 0, 1, 1),+ crop: Rect::default(),+ orientation: Orientation::Normal,+ color: ColorData::default(),+ wb_multipliers: None,+ linearized: false,+ opcodes: OpcodeLists::default(),+ metadata: Metadata::default(),++ pixel_aspect: 1.0,+ };+ assert!(raw.validate().is_err(), "`x + width` wrapped: the area is outside the image");+ assert!(raw.normalized().is_err());+ raw.active_area = Rect::new(0, 0, w + 1, h);+ assert!(raw.validate().is_err(), "one past the last column is outside too");+ }+#[test]fn black_levels() {let b = BlackLevel { repeat_rows: 2, repeat_cols: 2, values: vec![1.0, 2.0, 3.0, 4.0], delta_h: vec![0.5, 0.0], delta_v: vec![0.0, 10.0] };diff --cc crates/raw/src/vendor/erf.rsindex fae120bcc,000000000..c585ad0ccmode 100644,000000..100644--- a/crates/raw/src/vendor/erf.rs+++ b/crates/raw/src/vendor/erf.rs@@@ -1,197 -1,0 +1,198 @@@+//! Epson ERF (R-D1, R-D1s, R-D1x): a big-endian TIFF whose `SubIFDs` child is a 12-bit CFA image in 16-byte blocks.+//!+//! Sources: TIFF 6.0 (container, `CFARepeatPatternDim` / `CFAPattern`) and our own black-box analysis of the three+//! CC0 ERF samples on raw.pixls.us (one per body); every number below was measured on them.+//!+//! - IFD0 is a 160 x 120 RGB thumbnail; its `SubIFDs` child is the raw: 3040 x 2024, 12 bits, `Compression` 32769,+//! photometric CFA, one strip of exactly `width * 8 / 5` bytes per row. Byte 15 of every 16 is zero in all rows:+//! a row is 16-byte blocks, each 15 bytes of ten 12-bit samples, most significant bits first (`b0 << 4 | b1 >> 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 it is measured from the+//! preview's neutral pixels ([`crate::wb_estimate`]); on the R-D1s sample (54,000 neutral preview pixels) that+//! gives red 2.68 and blue 1.31.+//! - 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, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result};+use lightcraft_geom::Orientation;+use lightcraft_tiff::image::chunk_bytes;+use lightcraft_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<Ifd> {+ 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 = lightcraft_tiff::ParseOptions { max_ifds: 1, max_depth: 0, follow_children: false, ..Default::default() };+ lightcraft_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) -> Result<RawImage> {+ 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 <= crate::MAX_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+ let chunks = info.chunks(bytes.len() as u64);+ let src = chunks.first().and_then(|c| chunk_bytes(bytes, c)).ok_or_else(|| RawError::Corrupt("Erf strip outside file".into()))?;+ let mut d = vec![0u16; n];+ unpack(src, &mut d);+ let white = super::white_from_data(&d, 12);+ let wb = crate::wb_estimate::as_shot(bytes, &crate::wb_estimate::Frame { data: &d, width: w, crop, cfa: &cfa, black: &black, white });+ let data = if mode == Mode::Full { RawData::U16(d) } else { RawData::U16(Vec::new()) };+ let mut metadata = lightcraft_meta::from_tiff(&tiff);+ metadata.width = Some(crop.width as u32);+ metadata.height = Some(crop.height as u32);+ 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: wb,+ linearized: false,+ opcodes: OpcodeLists::default(),+ metadata,++ pixel_aspect: 1.0,+ };+ img.validate_for(mode)?;+ Ok(img)+}++#[cfg(test)]+mod tests {+ use super::*;+ use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};++ /// Pack ten-sample groups into 16-byte blocks, MSB first, zero pad.+ fn pack(px: &[u16]) -> Vec<u8> {+ 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<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]));+ 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(lightcraft_tiff::ByteOrder::Big, false).write(&[ifd0]).unwrap()+ }++ #[test]+ fn decodes_the_block_layout() {+ let (w, h) = (20u32, 6u32);+ let px: Vec<u16> = (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!(r.wb_multipliers.is_some());+ assert_eq!(crate::probe_info(&f).unwrap(), r.info());+ }++ #[test]+ fn malformed_files_never_panic() {+ let px: Vec<u16> = (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);+ }+ }+ }+}diff --cc crates/raw/src/vendor/mef.rsindex 244245818,000000000..8298bd4f0mode 100644,000000..100644--- a/crates/raw/src/vendor/mef.rs+++ b/crates/raw/src/vendor/mef.rs@@@ -1,185 -1,0 +1,186 @@@+//! 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 our own 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 the as-shot gains are measured+//! from that preview's neutral pixels ([`crate::wb_estimate`]).+use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result};+use lightcraft_geom::Orientation;+use lightcraft_tiff::image::chunk_bytes;+use lightcraft_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) -> Result<RawImage> {+ 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 <= crate::MAX_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+ let chunks = info.chunks(bytes.len() as u64);+ let src = chunks.first().and_then(|c| chunk_bytes(bytes, c)).ok_or_else(|| RawError::Corrupt("Mef strip outside file".into()))?;+ let mut d = vec![0u16; n];+ crate::unpack::unpack_msb(src, 12, &mut d);+ let white = super::white_from_data(&d, 12);+ let black = BlackLevel::uniform(0.0);+ let frame = crate::wb_estimate::Frame { data: &d, width: w, crop, cfa: &cfa, black: &black, white };+ let wb = match preview {+ Some((px, pw, ph)) => crate::wb_estimate::as_shot_rgb(px, pw, ph, &frame),+ None => crate::wb_estimate::as_shot(bytes, &frame),+ };+ let data = if mode == Mode::Full { RawData::U16(d) } else { RawData::U16(Vec::new()) };+ let mut metadata = lightcraft_meta::from_tiff(&tiff);+ metadata.width = Some(crop.width as u32);+ metadata.height = Some(crop.height as u32);+ 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: wb,+ linearized: false,+ opcodes: OpcodeLists::default(),+ metadata,++ pixel_aspect: 1.0,+ };+ img.validate_for(mode)?;+ Ok(img)+}++#[cfg(test)]+mod tests {+ use super::*;+ use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};++ fn pack(px: &[u16]) -> Vec<u8> {+ 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<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]));+ 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![pack(px)] });+ 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()+ }++ #[test]+ fn decodes_packed_12_bit() {+ let px: Vec<u16> = (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<u16> = (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);+ }+ }+ }+}diff --cc crates/raw/src/vendor/nef.rsindex f4e568cb3,0b7a68e6a..20a917000--- a/crates/raw/src/vendor/nef.rs+++ b/crates/raw/src/vendor/nef.rs@@@ -188,21 -98,16 +188,31 @@@ fn measured_body(model: &str, w: usizeMEASURED_BODIES.iter().find(|b| b.model == model.trim() && b.size == (w, h) && b.bits == bits)}+/// The samples of the image area `crop`, every few rows (an odd step, so both rows of the CFA are in), for measuring+/// the white level where the picture is.+fn area_samples(d: &[u16], w: usize, crop: Rect) -> Vec<u16> {+ let step = (crop.width.saturating_mul(crop.height) / 2_000_000).max(1) | 1;+ (crop.y..crop.y.saturating_add(crop.height))+ .step_by(step)+ .filter_map(|y| {+ let at = y.checked_mul(w)?.checked_add(crop.x)?;+ d.get(at..at.checked_add(crop.width)?)+ })+ .flatten()+ .copied()+ .collect()+}++ /// Pixel height over width from the raw IFD's resolution tags: the D1X and D1H write 600 x 300 per inch for a+ /// 4028 x 1324 frame, rows twice as tall as the columns are wide. Only ratios from 1.5 to 4 count (a frame+ /// squashed 3:1 or 2:1), the rest is rounding or a stray tag.+ pub(crate) fn pixel_aspect_of(raw: &Ifd) -> f32 {+ match (raw.f64(t::X_RESOLUTION), raw.f64(t::Y_RESOLUTION)) {+ (Some(x), Some(y)) if x > 0.0 && y > 0.0 && (1.5..=4.0).contains(&(x / y)) => (x / y).round() as f32,+ _ => 1.0,+ }+ }+fn raw_ifd(tiff: &Tiff) -> Option<&Ifd> {tiff.all_ifds().into_iter()@@@ -283,25 -187,23 +293,26 @@@ pub(crate) fn decode(bytes: &[u8], mode(Some([2, 2]), Some(p)) if p.len() == 4 && p.iter().all(|&c| c <= 2) => Cfa { width: 2, height: 2, pattern: p.to_vec() },_ => Cfa::bayer_static("RGGB"),};- let body = measured_body(&ifd0.string(t::MODEL).unwrap_or_default(), w, h, bits);+ 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);- // 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 = match (body.and_then(|b| b.white), mode) {- (Some(white), _) => white,- (None, Mode::Full) => white_from_data(samples, bits),- (None, Mode::Header) => ((1u32 << bits.clamp(1, 16)) - 1) as f32,+ let measured = match body {+ Some(&MeasuredBody { crop: (x, y, cw, ch), .. }) if x + cw <= active_w && y + ch <= h => Some(Rect::new(x, y, cw, ch)),+ _ => None,};- let crop = match body {- Some(&MeasuredBody { crop: (x, y, cw, ch), .. }) if x + cw <= active_w && y + ch <= h => Rect::new(x, y, cw, ch),- _ => default_crop(mn.as_ref(), active_w, h),+ let crop = measured.unwrap_or_else(|| default_crop(mn.as_ref(), active_w, h));+ // the white level is measured from the whole image (only its measured area, for a body with one), or known for a+ // measured body; the probe (no samples in its result) takes the nominal one+ let white = match (body.and_then(|b| b.white), mode, measured) {+ (Some(white), _, _) => white,+ (None, Mode::Full, Some(area)) => white_from_data(&area_samples(samples, w, area), bits),+ (None, Mode::Full, None) => white_from_data(samples, bits),+ (None, Mode::Header, _) => ((1u32 << bits.clamp(1, 16)) - 1) as f32,};+ let pixel_aspect = pixel_aspect_of(raw);let mut metadata = lightcraft_meta::from_tiff(&tiff);metadata.width = Some(crop.width as u32);- metadata.height = Some(crop.height as u32);+ metadata.height = Some(crate::stretched_height(crop.height, pixel_aspect) as u32);let img = RawImage {format: RawFormat::Nef,width: w,@@@ -321,11 -223,8 +332,12 @@@color: ColorData::default(),wb_multipliers: wb,linearized: false,+ pixel_aspect,- opcodes: OpcodeLists::default(),+ // Nikon's in-file distortion correction, about the optical centre (which follows the sensor shift)+ opcodes: OpcodeLists {+ list3: super::nef_lens::distortion(&model, raw, Rect::new(0, 0, active_w, h), crop).into_iter().collect(),+ ..Default::default()+ },metadata,};img.validate_for(mode)?;diff --cc crates/raw/tests/lossy_dng.rsindex dd34b5158,000000000..818f02c0amode 100644,000000..100644--- a/crates/raw/tests/lossy_dng.rs+++ b/crates/raw/tests/lossy_dng.rs@@@ -1,95 -1,0 +1,96 @@@+//! Lossy DNG (compression 34892) round trip: write, decode, develop, compare with the source.++use lightcraft_raw::{+ BlackLevel, Cfa, ColorData, DngCompression, DngWriteOptions, Mat3, Method, OpcodeLists, Orientation, RawData, RawFormat, RawImage, Rect,+};++/// A smooth Bayer mosaic (12-bit, black 64) of `w × h` with a colour matrix and a white balance.+fn mosaic(w: usize, h: usize) -> RawImage {+ let data: Vec<u16> = (0..w * h)+ .map(|i| {+ let (x, y) = (i % w, i / w);+ let c = (x % 2) + (y % 2);+ (64.0 + 3000.0 * (x as f32 / w as f32) * (0.5 + c as f32 * 0.25) + 500.0 * (y as f32 / h as f32)) as u16+ })+ .collect();+ let color = ColorData {+ illuminant: [21, 0],+ color_matrix: [Some(Mat3([[0.7, -0.1, -0.05], [-0.4, 1.2, 0.2], [-0.1, 0.2, 0.6]])), None],+ as_shot_neutral: Some([0.5, 1.0, 0.7]),+ ..Default::default()+ };+ RawImage {+ format: RawFormat::Dng,+ width: w,+ height: h,+ cpp: 1,+ data: RawData::U16(data),+ cfa: Some(Cfa::bayer("RGGB").unwrap()),+ bits: 12,+ black: BlackLevel::uniform(64.0),+ white: vec![4095.0],+ active_area: Rect::new(0, 0, w, h),+ crop: Rect::new(2, 2, w - 4, h - 4),+ orientation: Orientation::Rotate90,+ color,+ wb_multipliers: None,+ linearized: false,+ opcodes: OpcodeLists::default(),+ metadata: Default::default(),++ pixel_aspect: 1.0,+ }+}++fn lossy(raw: &RawImage, long_edge: Option<u32>) -> Vec<u8> {+ let opts = DngWriteOptions { compression: DngCompression::LossyJpeg { tile: 32, quality: 95, long_edge }, ..Default::default() };+ lightcraft_raw::write_dng(raw, &opts).unwrap()+}++#[test]+fn lossy_dng_round_trips_close_to_the_source() {+ let raw = mosaic(80, 56);+ let bytes = lossy(&raw, None);+ let back = lightcraft_raw::decode(&bytes).unwrap();+ assert_eq!((back.width, back.height, back.cpp, back.cfa.is_none()), (76, 52, 3, true), "demosaiced, default crop applied");+ assert!(back.linearized);+ assert_eq!(back.orientation, raw.orientation);+ assert_eq!(back.color.color_matrix, raw.color.color_matrix);+ assert_eq!(back.color.as_shot_neutral, raw.color.as_shot_neutral);+ let a = raw.develop(Method::Ahd).unwrap();+ let b = back.develop(Method::Ahd).unwrap();+ assert_eq!((a.width, a.height), (b.width, b.height));+ let (mut sum, mut worst) = (0f64, 0f32);+ for (p, q) in a.data.iter().zip(&b.data) {+ for k in 0..3 {+ let d = (p[k].clamp(0.0, 1.0) - q[k]).abs();+ sum += d as f64;+ worst = worst.max(d);+ }+ }+ let mean = sum / (a.data.len() * 3) as f64;+ assert!(mean < 0.01 && worst < 0.08, "mean {mean} worst {worst}");+}++#[test]+fn lossy_dng_scales_to_the_long_edge_and_is_smaller() {+ let raw = mosaic(160, 96);+ let small = lossy(&raw, Some(78));+ let back = lightcraft_raw::decode(&small).unwrap();+ assert_eq!(back.width.max(back.height), 78);+ assert_eq!(back.width, 78);+ assert!(back.height == 46 || back.height == 47, "{}", back.height);+ let full = lightcraft_raw::write_dng(&raw, &DngWriteOptions { compression: DngCompression::Uncompressed, ..Default::default() }).unwrap();+ assert!(small.len() < full.len() / 2, "{} vs {}", small.len(), full.len());+}++#[test]+fn lossy_dng_of_linear_data_and_extreme_values() {+ // a 3-sample linear raw with values above white, negative and non-finite samples: no panic, clipped+ let (w, h) = (20usize, 12usize);+ let data: Vec<f32> = (0..w * h * 3).map(|i| [2.0, -1.0, f32::NAN, 0.5, f32::INFINITY][i % 5]).collect();+ let raw = RawImage { cpp: 3, cfa: None, data: RawData::F32(data), white: vec![1.0], black: BlackLevel::uniform(0.0), ..mosaic(w, h) };+ let back = lightcraft_raw::decode(&lossy(&raw, Some(4))).unwrap();+ assert_eq!(back.width.max(back.height), 4);+ let rgb = back.develop(Method::Bilinear).unwrap();+ assert!(rgb.data.iter().flatten().all(|v| v.is_finite() && (0.0..=1.0).contains(v)));+}diff --cc crates/raw/tests/robust.rsindex b6cd9ab9f,733b029b9..a54cb0238--- a/crates/raw/tests/robust.rs+++ b/crates/raw/tests/robust.rs@@@ -104,207 -103,3 +105,208 @@@ fn hostile_dimensions_are_rejected_quicassert!(lightcraft_raw::decode(&bytes).is_err());assert!(t0.elapsed().as_secs_f64() < 2.0);}++/// A Bayer DNG whose `BlackLevel` is a FLOAT holding NaN (or infinity), and a float CFA DNG with+/// NaN samples: every normalised sample came out NaN, and AHD's green estimate clamped between two+/// NaN neighbours, which panics (the 1:1 view and every export of such a file). Non-finite levels+/// read as 0 and non-finite samples as black: the photo develops to finite numbers.+#[test]+fn non_finite_black_levels_and_samples_develop() {+ use lightcraft_tiff::tags as t;+ use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};+ let (w, h) = (32u32, 16u32);+ for black in [Value::Float(vec![f32::NAN]), Value::Double(vec![f64::INFINITY]), Value::Float(vec![64.0, f32::NAN, 64.0, 64.0])] {+ let mut ifd = IfdBuilder::new();+ ifd.set(t::DNG_VERSION, Value::Byte(vec![1, 4, 0, 0]));+ ifd.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0]));+ ifd.set(t::IMAGE_WIDTH, Value::Long(vec![w]));+ ifd.set(t::IMAGE_LENGTH, Value::Long(vec![h]));+ ifd.set(t::BITS_PER_SAMPLE, Value::Short(vec![16]));+ ifd.set(t::COMPRESSION, Value::Short(vec![1]));+ ifd.set(t::PHOTOMETRIC, Value::Short(vec![t::photometric::CFA]));+ ifd.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2]));+ ifd.set(t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2]));+ ifd.set(t::BLACK_LEVEL_REPEAT_DIM, Value::Short(vec![2, 2]));+ ifd.set(t::BLACK_LEVEL, black.clone());+ ifd.set(t::WHITE_LEVEL, Value::Long(vec![4095]));+ let strip: Vec<u8> = (0..w * h).flat_map(|i| (100 + (i * 37 % 3000) as u16).to_le_bytes()).collect();+ ifd.set_image(ImageData::Strips { rows_per_strip: h, strips: vec![strip] });+ let bytes = TiffWriter::default().write(&[ifd]).unwrap();+ let img = lightcraft_raw::decode(&bytes).unwrap_or_else(|e| panic!("{black:?}: {e}"));+ let rgb = img.develop(Method::Ahd).unwrap();+ assert!(rgb.data.iter().flatten().all(|v| v.is_finite()), "{black:?}: finite output");+ let _ = img.develop(Method::Ppg);+ }+ // float samples: a block of NaN and infinities in the middle of the mosaic+ let (w, h) = (24usize, 16usize);+ let data: Vec<f32> = (0..w * h)+ .map(|i| match (i % w, i / w) {+ (8..=13, 5..=10) => f32::NAN,+ (2, _) => f32::INFINITY,+ _ => (i * 97 % 1000) as f32 / 1000.0,+ })+ .collect();+ let raw = RawImage {+ format: RawFormat::Dng,+ width: w,+ height: h,+ cpp: 1,+ data: RawData::F32(data),+ cfa: Some(Cfa::bayer("RGGB").unwrap()),+ bits: 32,+ black: BlackLevel::uniform(0.0),+ white: vec![1.0],+ active_area: Rect::new(0, 0, w, h),+ crop: Rect::new(0, 0, w, h),+ orientation: Orientation::Normal,+ color: ColorData::default(),+ wb_multipliers: None,+ linearized: false,+ opcodes: OpcodeLists::default(),+ metadata: Default::default(),++ pixel_aspect: 1.0,+ };+ for img in [raw.clone(), lightcraft_raw::decode(&lightcraft_raw::write_dng(&raw, &DngWriteOptions::default()).unwrap()).unwrap()] {+ let rgb = img.develop(Method::Ahd).unwrap();+ assert!(rgb.data.iter().flatten().all(|v| v.is_finite()), "float NaN samples: finite output");+ }+}++// --- CR3 containers (Canon CRX): structurally valid files whose every byte may be mutated ---++/// A CR3 with a single CRAW track carrying a CMP1 descriptor (and optional CDI1/IAD1) plus raw samples.+mod cr3 {+ pub(crate) fn box_bytes(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {+ let mut out = ((body.len() + 8) as u32).to_be_bytes().to_vec();+ out.extend_from_slice(kind);+ out.extend_from_slice(body);+ out+ }++ fn track(entry: &[u8], offset: u64, size: u32) -> Vec<u8> {+ let mut stsd = vec![0u8; 4];+ stsd.extend(1u32.to_be_bytes());+ stsd.extend_from_slice(entry);+ let mut stsz = vec![0u8; 4];+ stsz.extend(size.to_be_bytes());+ stsz.extend(1u32.to_be_bytes());+ let mut co64 = vec![0u8; 4];+ co64.extend(1u32.to_be_bytes());+ co64.extend(offset.to_be_bytes());+ let tables = [box_bytes(b"stsd", &stsd), box_bytes(b"stsz", &stsz), box_bytes(b"co64", &co64)].concat();+ box_bytes(b"trak", &box_bytes(b"mdia", &box_bytes(b"minf", &box_bytes(b"stbl", &tables))))+ }++ /// `CMP1` coding descriptor: 52 bytes, four planes, 14 bits, RGGB, `levels` wavelet levels.+ pub(crate) fn cmp1(width: u32, height: u32, tile_width: u32, tile_height: u32, levels: u8, header_size: u32) -> Vec<u8> {+ let mut coding = vec![0u8; 52];+ coding[0..2].copy_from_slice(&0xff00u16.to_be_bytes());+ coding[2..4].copy_from_slice(&48u16.to_be_bytes());+ coding[4..6].copy_from_slice(&0x100u16.to_be_bytes());+ coding[8..12].copy_from_slice(&width.to_be_bytes());+ coding[12..16].copy_from_slice(&height.to_be_bytes());+ coding[16..20].copy_from_slice(&tile_width.to_be_bytes());+ coding[20..24].copy_from_slice(&tile_height.to_be_bytes());+ coding[24] = 14;+ coding[25] = 0x40;+ coding[26] = levels;+ coding[28..32].copy_from_slice(&header_size.to_be_bytes());+ coding+ }++ pub(crate) fn file(coding: &[u8], width: u16, height: u16, sample: &[u8]) -> Vec<u8> {+ let mut craw = vec![0u8; 82];+ craw[24..26].copy_from_slice(&width.to_be_bytes());+ craw[26..28].copy_from_slice(&height.to_be_bytes());+ craw.extend(box_bytes(b"CMP1", coding));+ let entry = box_bytes(b"CRAW", &craw);+ let ftyp = box_bytes(b"ftyp", b"crx \0\0\0\x01crx isom");+ let track_len = track(&entry, 0, sample.len() as u32).len();+ let offset = (ftyp.len() + 8 + track_len + 7) & !7;+ let mut out = ftyp;+ out.extend(box_bytes(b"moov", &track(&entry, offset as u64, sample.len() as u32)));+ out.resize(offset, 0);+ out.extend_from_slice(sample);+ out+ }++ fn marker(out: &mut Vec<u8>, code: u16, size: u32, flags: u32) {+ out.extend(code.to_be_bytes());+ out.extend(8u16.to_be_bytes());+ out.extend(size.to_be_bytes());+ out.extend(flags.to_be_bytes());+ }++ /// A 4×4 lossless CRX stream: four 2×2 planes, each sample value 1 (sensor level 8193).+ pub(crate) fn lossless_sample() -> Vec<u8> {+ let mut sample = Vec::new();+ marker(&mut sample, 0xff01, 4, 0);+ for p in 0..4u32 {+ marker(&mut sample, 0xff02, 1, (p << 28) | 0x0800_0000);+ marker(&mut sample, 0xff03, 1, 4 << 19);+ }+ sample.extend([0x1e; 4]);+ sample+ }++ pub(crate) fn lossless_file() -> Vec<u8> {+ file(&cmp1(4, 4, 4, 4, 0, 108), 4, 4, &lossless_sample())+ }++ /// A 16×16 three-level C-RAW CRX stream of flat zero subbands (sensor level 8192).+ pub(crate) fn craw_sample() -> Vec<u8> {+ let mut sample = Vec::new();+ marker(&mut sample, 0xff01, 52, 0);+ for plane in 0..4u32 {+ marker(&mut sample, 0xff02, 13, (plane << 28) | 0x0800_0000);+ for band in 0..10u32 {+ marker(&mut sample, 0xff03, if band >= 7 { 2 } else { 1 }, (band << 28) | (4 << 19));+ }+ }+ for _ in 0..4 {+ sample.extend([0x80; 4]);+ sample.extend([0xf0; 3]);+ for _ in 0..3 {+ sample.extend([0xff, 0xf8]);+ }+ }+ sample+ }++ pub(crate) fn craw_file() -> Vec<u8> {+ file(&cmp1(16, 16, 16, 16, 3, 540), 16, 16, &craw_sample())+ }+}++/// Both fixtures decode as built, so the mutations below hit live decode paths.+#[test]+fn cr3_fixtures_decode() {+ let lossless = lightcraft_raw::decode(&cr3::lossless_file()).unwrap();+ assert_eq!((lossless.width, lossless.height, lossless.bits), (4, 4, 14));+ assert_eq!(lossless.data.get(0), 8193.0);+ let craw = lightcraft_raw::decode(&cr3::craw_file()).unwrap();+ assert_eq!((craw.width, craw.height, craw.bits), (16, 16, 14));+ assert_eq!(craw.data.get(0), 8192.0);+ assert_eq!(lightcraft_raw::probe_info(&cr3::craw_file()).unwrap(), craw.info());+}++proptest! {+ /// Mutating or truncating structurally valid CR3 containers exercises the CRX marker walker and+ /// entropy readers far deeper than random TIFF bytes: errors or clean decodes, never a panic.+ #[test]+ fn mutated_cr3_containers_never_panic(+ kind in 0usize..2,+ flips in proptest::collection::vec((any::<usize>(), any::<u8>()), 1..24),+ cut in any::<usize>(),+ ) {+ let mut data = if kind == 0 { cr3::lossless_file() } else { cr3::craw_file() };+ for (i, v) in flips {+ let n = data.len();+ data[i % n] = v;+ }+ let keep = if cut % 3 == 0 { cut % data.len() } else { data.len() };+ exercise(&data[..keep]);+ // The header-only description path (used when importing) must hold up against the same mutations.+ let _ = lightcraft_raw::probe_info(&data[..keep]);+ }+}