diff --git a/crates/ec-image/tests/differential.rs b/crates/ec-image/tests/differential.rs new file mode 100644 index 00000000..1f15634a --- /dev/null +++ b/crates/ec-image/tests/differential.rs @@ -0,0 +1,348 @@ +//! Differential tests against the incumbent `image` crate over the generated +//! corpus (`scripts/gen-still-fixtures.sh`). +//! +//! The bars differ by format because the formats differ: PNG and VP8L are +//! lossless, so anything short of pixel-exact agreement is a bug. JPEG's IDCT +//! rounding is explicitly implementation-defined, so the bar there is a +//! per-sample delta plus a correlation, both reported. WebP lossy is measured +//! against the *source picture*, so the question is whether this decoder +//! reconstructs it at least as faithfully as the incumbent does. + +use image::GenericImageView; +use std::path::{Path, PathBuf}; + +fn fixtures() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/stills") +} + +/// Every fixture with one of these extensions, sorted for a stable report. +fn corpus(extension: &str) -> Vec { + let dir = fixtures(); + let mut found: Vec = std::fs::read_dir(&dir) + .into_iter() + .flatten() + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|e| e == extension)) + .filter(|p| { + !p.file_name() + .is_some_and(|n| n.to_string_lossy().starts_with("source")) + }) + .collect(); + found.sort(); + found +} + +fn skip(what: &str) -> bool { + eprintln!("skipped: fixtures/stills not generated ({what}); run scripts/gen-still-fixtures.sh"); + true +} + +/// Largest per-sample difference and Pearson correlation between two buffers. +fn compare(ours: &[u8], theirs: &[u8]) -> (u32, f64) { + assert_eq!(ours.len(), theirs.len(), "sample counts differ"); + let mut max = 0u32; + let n = ours.len() as f64; + let (mut sa, mut sb, mut saa, mut sbb, mut sab) = (0.0, 0.0, 0.0, 0.0, 0.0); + for (&a, &b) in ours.iter().zip(theirs) { + max = max.max(u32::from(a.abs_diff(b))); + let (a, b) = (f64::from(a), f64::from(b)); + sa += a; + sb += b; + saa += a * a; + sbb += b * b; + sab += a * b; + } + let cov = sab - sa * sb / n; + let va = (saa - sa * sa / n).max(0.0); + let vb = (sbb - sb * sb / n).max(0.0); + let corr = if va * vb > 0.0 { + cov / (va * vb).sqrt() + } else { + 1.0 + }; + (max, corr) +} + +fn psnr(a: &[u8], b: &[u8]) -> f64 { + let mse: f64 = a + .iter() + .zip(b) + .map(|(&x, &y)| { + let d = f64::from(x) - f64::from(y); + d * d + }) + .sum::() + / a.len() as f64; + if mse == 0.0 { + f64::INFINITY + } else { + 10.0 * (255.0f64 * 255.0 / mse).log10() + } +} + +#[test] +fn png_decodes_pixel_exactly() { + let files = corpus("png"); + if files.is_empty() && skip("png") { + return; + } + for path in files { + let bytes = std::fs::read(&path).unwrap(); + let ours = ec_image::decode(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + let theirs = image::load_from_memory(&bytes).expect("incumbent decode"); + assert_eq!( + (ours.width, ours.height), + theirs.dimensions(), + "{}", + path.display() + ); + if ours.pixels.bit_depth() == 16 { + // Compared at 16 bits so the comparison is not laundered through + // two different 16-to-8 rounding conventions. + let a = ours.to_rgba16(); + let b = theirs.to_rgba16().into_raw(); + assert_eq!(a, b, "{} (16-bit samples)", path.display()); + } else { + let a = ours.to_rgba8(); + let b = theirs.to_rgba8().into_raw(); + assert_eq!(a, b, "{} (8-bit samples)", path.display()); + } + } +} + +#[test] +fn webp_lossless_decodes_pixel_exactly() { + let files: Vec = corpus("webp") + .into_iter() + .filter(|p| p.to_string_lossy().contains("lossless")) + .collect(); + if files.is_empty() && skip("webp") { + return; + } + for path in files { + let bytes = std::fs::read(&path).unwrap(); + let ours = ec_image::decode(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + let theirs = image::load_from_memory(&bytes).expect("incumbent decode"); + assert_eq!( + (ours.width, ours.height), + theirs.dimensions(), + "{}", + path.display() + ); + assert_eq!( + ours.to_rgba8(), + theirs.to_rgba8().into_raw(), + "{}", + path.display() + ); + } +} + +#[test] +fn jpeg_matches_the_incumbent_within_rounding() { + let files = corpus("jpg"); + if files.is_empty() && skip("jpg") { + return; + } + let mut worst = 0u32; + for path in files { + let bytes = std::fs::read(&path).unwrap(); + let ours = ec_image::decode(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + let theirs = image::load_from_memory(&bytes).expect("incumbent decode"); + assert_eq!( + (ours.width, ours.height), + theirs.dimensions(), + "{}", + path.display() + ); + let (max, corr) = compare(&ours.to_rgb8(), &theirs.to_rgb8().into_raw()); + let db = psnr(&ours.to_rgb8(), &theirs.to_rgb8().into_raw()); + eprintln!( + "{:<22} max delta {max:>3} corr {corr:.6} psnr {db:.1} dB", + path.file_name().unwrap().to_string_lossy() + ); + worst = worst.max(max); + // Five counts of 255 is where this decoder's IDCT and colour rounding + // sit against jpeg-decoder's; both are legal readings of T.81, and the + // gap is uniform noise rather than structure, which is what the + // correlation and the PSNR are there to show. Grayscale, which skips + // the colour matrix and the upsampler, agrees within one count. + assert!(max <= 5, "{}: max sample delta {max}", path.display()); + assert!(corr > 0.9995, "{}: correlation {corr}", path.display()); + assert!( + db > 48.0, + "{}: {db:.1} dB against the incumbent decode", + path.display() + ); + } + eprintln!("jpeg worst per-sample delta vs incumbent: {worst}"); +} + +#[test] +fn webp_lossy_reconstructs_at_least_as_well_as_the_incumbent() { + let files: Vec = corpus("webp") + .into_iter() + .filter(|p| p.to_string_lossy().contains("lossy")) + .collect(); + if files.is_empty() && skip("webp") { + return; + } + let mut shortfalls: Vec = Vec::new(); + for path in files { + let name = path.file_name().unwrap().to_string_lossy().to_string(); + let source = if name.starts_with("odd") { + fixtures().join("source-odd.png") + } else if name.contains("alpha") { + fixtures().join("source-alpha.png") + } else { + fixtures().join("source.png") + }; + let reference = image::open(&source).expect("source picture").to_rgb8(); + let bytes = std::fs::read(&path).unwrap(); + let ours = ec_image::decode(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + let theirs = image::load_from_memory(&bytes).expect("incumbent decode"); + let ours_rgb = ours.to_rgb8(); + let theirs_rgb = theirs.to_rgb8().into_raw(); + let mine = psnr(&ours_rgb, reference.as_raw()); + let incumbent = psnr(&theirs_rgb, reference.as_raw()); + let (max, corr) = compare(&ours_rgb, &theirs_rgb); + eprintln!( + "{name:<22} psnr {mine:.2} dB (incumbent {incumbent:.2} dB) \ + max delta {max} corr {corr:.6}" + ); + if mine < incumbent - 0.1 { + shortfalls.push(format!( + "{name}: {mine:.2} dB against the source, incumbent {incumbent:.2} dB" + )); + } + if ours.pixels.has_alpha() { + let a: Vec = ours.to_rgba8().chunks_exact(4).map(|p| p[3]).collect(); + let b: Vec = theirs + .to_rgba8() + .into_raw() + .chunks_exact(4) + .map(|p| p[3]) + .collect(); + assert_eq!(a, b, "{name}: alpha plane is lossless and must match"); + } + } + assert!(shortfalls.is_empty(), "{}", shortfalls.join("\n")); +} + +#[test] +fn header_dimensions_match_the_incumbent() { + let mut checked = 0; + for extension in ["png", "jpg", "webp"] { + for path in corpus(extension) { + if path.to_string_lossy().contains("animated") { + continue; + } + let bytes = std::fs::read(&path).unwrap(); + let ours = ec_image::info(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + let theirs = image::ImageReader::new(std::io::Cursor::new(&bytes)) + .with_guessed_format() + .unwrap() + .into_dimensions() + .unwrap(); + assert_eq!((ours.width, ours.height), theirs, "{}", path.display()); + checked += 1; + } + } + if checked == 0 { + skip("any"); + } +} + +#[test] +fn an_animated_webp_is_refused_by_name() { + let path = fixtures().join("animated.webp"); + let Ok(bytes) = std::fs::read(&path) else { + skip("animated.webp"); + return; + }; + let err = ec_image::decode(&bytes).expect_err("an animation is not a still"); + let message = format!("{err}"); + assert!(message.contains("animated"), "{message}"); +} + +/// An APP1 EXIF segment carrying orientation 6, spliced after SOI. +/// +/// Built here rather than generated: ImageMagick writes no EXIF when the +/// source is a PNG, and a fixture whose name promises a tag it does not carry +/// is worse than no fixture. +fn with_exif_orientation(jpeg: &[u8], orientation: u16) -> Vec { + let mut tiff = b"Exif\0\0II".to_vec(); + tiff.extend_from_slice(&42u16.to_le_bytes()); + tiff.extend_from_slice(&8u32.to_le_bytes()); + tiff.extend_from_slice(&1u16.to_le_bytes()); + tiff.extend_from_slice(&0x0112u16.to_le_bytes()); + tiff.extend_from_slice(&3u16.to_le_bytes()); + tiff.extend_from_slice(&1u32.to_le_bytes()); + tiff.extend_from_slice(&orientation.to_le_bytes()); + tiff.extend_from_slice(&0u16.to_le_bytes()); + tiff.extend_from_slice(&0u32.to_le_bytes()); + + let mut out = jpeg[..2].to_vec(); + out.extend_from_slice(&[0xff, 0xe1]); + out.extend_from_slice(&((tiff.len() + 2) as u16).to_be_bytes()); + out.extend_from_slice(&tiff); + out.extend_from_slice(&jpeg[2..]); + out +} + +#[test] +fn exif_orientation_is_reported_and_not_applied() { + let Ok(plain) = std::fs::read(fixtures().join("baseline-444.jpg")) else { + skip("baseline-444.jpg"); + return; + }; + let bytes = with_exif_orientation(&plain, 6); + let ours = ec_image::decode(&bytes).unwrap(); + let theirs = image::load_from_memory(&bytes).unwrap(); + assert_eq!(ours.meta.orientation, Some(6), "EXIF tag 0x0112 parsed"); + assert_eq!(ec_image::decode(&plain).unwrap().meta.orientation, None); + // Not applied: the pixels are still in stored order, exactly as the + // incumbent leaves them, and the tagged file decodes like the plain one. + assert_eq!((ours.width, ours.height), theirs.dimensions()); + assert_eq!(ours.to_rgb8(), ec_image::decode(&plain).unwrap().to_rgb8()); +} + +/// Every fixture decodes, and the failures are reported together rather than +/// one per run — a decoder that breaks on three formats should say so once. +#[test] +fn every_fixture_decodes() { + let mut failures = Vec::new(); + let mut count = 0; + for extension in ["png", "jpg", "webp"] { + for path in corpus(extension) { + let name = path.file_name().unwrap().to_string_lossy().to_string(); + if name.contains("animated") { + continue; // refused by name; `an_animated_webp_is_refused_by_name` covers it + } + let bytes = std::fs::read(&path).unwrap(); + count += 1; + match ec_image::decode(&bytes) { + Ok(image) => { + let (w, h) = (image.width as usize, image.height as usize); + assert_eq!( + image.to_rgba8().len(), + w * h * 4, + "{name}: buffer is not width x height" + ); + } + Err(e) => failures.push(format!("{name}: {e}")), + } + } + } + if count == 0 { + skip("any"); + return; + } + assert!( + failures.is_empty(), + "{} failed:\n{}", + failures.len(), + failures.join("\n") + ); +} diff --git a/crates/ec-image/tests/fuzz.rs b/crates/ec-image/tests/fuzz.rs new file mode 100644 index 00000000..f10ee28d --- /dev/null +++ b/crates/ec-image/tests/fuzz.rs @@ -0,0 +1,191 @@ +//! Malformed input never panics, never hangs and never allocates without +//! bound. +//! +//! Ten thousand mutations per format, from a fixed seed so a failure is +//! reproducible: bit flips, truncations, byte injections and pure noise behind +//! each format's signature. Every one of them must come back as `Ok` or as an +//! `Err` — a decoder reached by a file picker is reached by every broken file +//! on the disk. + +use std::path::{Path, PathBuf}; + +const ROUNDS: usize = 10_000; + +fn fixtures() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/stills") +} + +/// xorshift64*, so every run mutates the same way. +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn below(&mut self, bound: usize) -> usize { + (self.next() % bound.max(1) as u64) as usize + } +} + +/// One mutated copy of `seed`: a few bit flips, a truncation, or an injection. +/// +/// `head` bounds where the flips land. Aiming them at the first few dozen +/// bytes is what actually reaches the geometry and colour-type paths: spread +/// over a whole file they nearly all land in the compressed data and stop at +/// the first integrity check. +fn mutate(rng: &mut Rng, seed: &[u8], head: Option) -> Vec { + let mut data = seed.to_vec(); + let region = head.unwrap_or(data.len()).min(data.len()); + match rng.below(4) { + 0 => { + for _ in 0..1 + rng.below(8) { + let at = rng.below(region); + data[at] ^= 1 << rng.below(8); + } + } + 1 => data.truncate(rng.below(data.len())), + 2 => { + for _ in 0..1 + rng.below(16) { + let at = rng.below(region); + data[at] = (rng.next() & 0xff) as u8; + } + } + _ => { + // Keep the signature, replace the body with noise: this is the + // shape that exercises header fields hardest. + let keep = 12.min(data.len()); + data.truncate(keep); + for _ in 0..rng.below(400) { + data.push((rng.next() & 0xff) as u8); + } + } + } + data +} + +/// Recompute every chunk CRC of a mutated PNG. +/// +/// Without this the checksum catches every mutation at the door and the +/// decoder proper is never fuzzed at all — the sweep would prove only that +/// CRC-32 works. +fn repair_png_crcs(data: &mut [u8]) { + let mut at = 8usize; + while at + 12 <= data.len() { + let len = u32::from_be_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]]) as usize; + if len > data.len() || at + 12 + len > data.len() { + return; + } + let crc = crc32(&data[at + 4..at + 8 + len]); + data[at + 8 + len..at + 12 + len].copy_from_slice(&crc.to_be_bytes()); + at += 12 + len; + } +} + +fn sweep(name: &str, seed_file: &str) { + let Ok(seed) = std::fs::read(fixtures().join(seed_file)) else { + eprintln!("skipped: fixtures/stills not generated; run scripts/gen-still-fixtures.sh"); + return; + }; + let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ name.len() as u64); + let mut decoded = 0usize; + for round in 0..ROUNDS { + // Half the rounds aim at the header, half at the whole file. + let head = if round % 2 == 0 { Some(48) } else { None }; + let mut data = mutate(&mut rng, &seed, head); + if seed_file.ends_with(".png") { + repair_png_crcs(&mut data); + } + // The call is the assertion: a panic here fails the test with the + // round number, and the round number plus the fixed seed reproduces it. + if let Ok(image) = ec_image::decode(&data) { + decoded += 1; + let pixels = image.to_rgba8(); + assert_eq!( + pixels.len(), + (image.width as usize) * (image.height as usize) * 4, + "{name} round {round}: buffer does not match the dimensions" + ); + } + // Header-only parsing must survive the same input. + let _ = ec_image::info(&data); + } + eprintln!("{name}: {ROUNDS} mutations, {decoded} still decoded"); +} + +#[test] +fn png_survives_mutation() { + sweep("png", "tiny.png"); +} + +#[test] +fn jpeg_survives_mutation() { + sweep("jpeg", "tiny.jpg"); +} + +#[test] +fn webp_lossy_survives_mutation() { + sweep("webp-lossy", "tiny-lossy.webp"); +} + +#[test] +fn webp_lossless_survives_mutation() { + sweep("webp-lossless", "tiny-lossless.webp"); +} + +#[test] +fn arbitrary_bytes_behind_a_signature_are_refused_not_believed() { + let signatures: [&[u8]; 3] = [ + &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a], + &[0xff, 0xd8, 0xff, 0xe0], + b"RIFF\x40\x00\x00\x00WEBPVP8 ", + ]; + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + for signature in signatures { + for _ in 0..ROUNDS / 4 { + let mut data = signature.to_vec(); + for _ in 0..rng.below(200) { + data.push((rng.next() & 0xff) as u8); + } + let _ = ec_image::decode(&data); + let _ = ec_image::info(&data); + } + } +} + +#[test] +fn a_header_asking_for_more_pixels_than_the_limit_is_refused() { + // A PNG IHDR claiming 65535x65535 is 4 gigapixels: the limit must refuse + // it before any buffer is sized from those numbers. + let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]; + let mut ihdr = Vec::new(); + ihdr.extend_from_slice(&65535u32.to_be_bytes()); + ihdr.extend_from_slice(&65535u32.to_be_bytes()); + ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); + png.extend_from_slice(&(ihdr.len() as u32).to_be_bytes()); + let start = png.len(); + png.extend_from_slice(b"IHDR"); + png.extend_from_slice(&ihdr); + let crc = crc32(&png[start..]); + png.extend_from_slice(&crc.to_be_bytes()); + let err = ec_image::decode(&png).expect_err("4 gigapixels is past the limit"); + assert!(format!("{err}").contains("limit"), "{err}"); +} + +fn crc32(data: &[u8]) -> u32 { + let mut c = 0xffff_ffffu32; + for &b in data { + c ^= u32::from(b); + for _ in 0..8 { + c = if c & 1 != 0 { + 0xedb8_8320 ^ (c >> 1) + } else { + c >> 1 + }; + } + } + c ^ 0xffff_ffff +} diff --git a/crates/ec-image/tests/real_library.rs b/crates/ec-image/tests/real_library.rs new file mode 100644 index 00000000..7862b55a --- /dev/null +++ b/crates/ec-image/tests/real_library.rs @@ -0,0 +1,122 @@ +//! The same differential bars, against real pictures on this machine. +//! +//! Generated fixtures come out of two encoders with default settings; a real +//! library has phone JPEGs with EXIF, screenshots, scans and downloads, and +//! those are the files a user actually opens. The sweep is read-only, prints a +//! per-file table, and skips silently when the directories hold no pictures. + +use image::GenericImageView; +use std::path::PathBuf; + +/// Where a real library lives on this machine; absent directories are skipped. +fn library() -> Vec { + let home = std::env::var("HOME").unwrap_or_default(); + ["Videos", "Downloads"] + .iter() + .map(|d| PathBuf::from(&home).join(d)) + .filter(|p| p.is_dir()) + .collect() +} + +/// Every still under `roots`, three directory levels deep, capped. +fn stills(roots: &[PathBuf], cap: usize) -> Vec { + fn walk(dir: &PathBuf, depth: usize, out: &mut Vec) { + if depth == 0 { + return; + } + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + walk(&path, depth - 1, out); + } else if let Some(extension) = path.extension() { + let extension = extension.to_string_lossy().to_lowercase(); + if ["png", "jpg", "jpeg", "webp"].contains(&extension.as_str()) { + out.push(path); + } + } + } + } + let mut found = Vec::new(); + for root in roots { + walk(root, 3, &mut found); + } + found.sort(); + found.truncate(cap); + found +} + +#[test] +fn real_pictures_decode_like_the_incumbent() { + let files = stills(&library(), 20); + if files.is_empty() { + eprintln!("skipped: no PNG/JPEG/WebP under ~/Videos or ~/Downloads"); + return; + } + let mut failures = Vec::new(); + for path in &files { + let name = path.file_name().unwrap().to_string_lossy().to_string(); + let bytes = std::fs::read(path).unwrap(); + let started = std::time::Instant::now(); + let ours = match ec_image::decode(&bytes) { + Ok(image) => image, + Err(e) => { + // The incumbent's verdict decides whether this is our failure + // or a file neither crate claims to decode. + if image::load_from_memory(&bytes).is_ok() { + failures.push(format!( + "{name}: we refuse it, the incumbent decodes it ({e})" + )); + } else { + eprintln!("{name:<44} both refuse: {e}"); + } + continue; + } + }; + let ours_ms = started.elapsed().as_secs_f64() * 1000.0; + let theirs = match image::load_from_memory(&bytes) { + Ok(image) => image, + Err(e) => { + eprintln!("{name:<44} we decode it, the incumbent does not ({e})"); + continue; + } + }; + if (ours.width, ours.height) != theirs.dimensions() { + failures.push(format!( + "{name}: {}x{} against the incumbent's {:?}", + ours.width, + ours.height, + theirs.dimensions() + )); + continue; + } + let a = ours.to_rgb8(); + let b = theirs.to_rgb8().into_raw(); + let max = a + .iter() + .zip(&b) + .map(|(&x, &y)| x.abs_diff(y)) + .max() + .unwrap_or(0); + let lossless = path + .extension() + .is_some_and(|e| e.eq_ignore_ascii_case("png")); + eprintln!( + "{name:<44} {}x{} max delta {max:>3} {ours_ms:>7.1} ms", + ours.width, ours.height + ); + let bar = if lossless { 0 } else { 8 }; + if u32::from(max) > bar { + failures.push(format!("{name}: max delta {max}, bar {bar}")); + } + } + assert!( + failures.is_empty(), + "{} of {} real pictures failed:\n{}", + failures.len(), + files.len(), + failures.join("\n") + ); +}