forge
Explore
Log in

Don't you dare go Hollow

Differential corpus, fuzz sweep and a real-library pass

Browse files at this commit

82499c0f4f83a2eab050285b0688724c98e50e10Ahmet Kaan GümüşParent: 22ac6ab
  • test
    • differential corpus, fuzz sweep and a real-library pass
Show full message
test(image): differential corpus, fuzz sweep and a real-library pass

Three bars, one per format, each the strictest the format allows:

- PNG and lossless WebP are pixel-exact against the incumbent `image`
  crate over every colour type, bit depth and interlace method, with the
  16-bit variants compared at 16 bits so neither side's narrowing rounds
  the comparison away.
- JPEG is measured, not asserted away: max sample delta 5 of 255 (1 on
  grayscale, 3 on 4:4:4), correlation above 0.9999 and 49-66 dB against
  the incumbent's own decode, all printed per file. T.81 leaves IDCT
  rounding to the implementation and both readings are legal.
- WebP lossy is measured against the *source picture*: 32.1-36.5 dB,
  within 0.05 dB of the incumbent everywhere, and the alpha plane, being
  lossless, must match exactly.

Ten thousand mutations per format — bit flips, truncations, injections and
noise behind each signature, with PNG chunk CRCs repaired so the mutations
reach the decoder instead of stopping at the checksum — must produce an
Ok or an Err, never a panic. A header claiming four gigapixels is refused
before anything is allocated from it.

The real-library sweep decodes the PNGs and JPEGs actually on this machine
and prints a per-file table: 13 files, PNGs pixel-exact, JPEGs within four
counts, 33 Mpx in 568 ms and a 12.6 Mpx phone JPEG in 247 ms in release.
crates/ec-image/tests/differential.rsadded+348 -0
@@ -0,0 +1,348 @@
1+//! Differential tests against the incumbent `image` crate over the generated
2+//! corpus (`scripts/gen-still-fixtures.sh`).
3+//!
4+//! The bars differ by format because the formats differ: PNG and VP8L are
5+//! lossless, so anything short of pixel-exact agreement is a bug. JPEG's IDCT
6+//! rounding is explicitly implementation-defined, so the bar there is a
7+//! per-sample delta plus a correlation, both reported. WebP lossy is measured
8+//! against the *source picture*, so the question is whether this decoder
9+//! reconstructs it at least as faithfully as the incumbent does.
10+
11+use image::GenericImageView;
12+use std::path::{Path, PathBuf};
13+
14+fn fixtures() -> PathBuf {
15+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/stills")
16+}
17+
18+/// Every fixture with one of these extensions, sorted for a stable report.
19+fn corpus(extension: &str) -> Vec<PathBuf> {
20+ let dir = fixtures();
21+ let mut found: Vec<PathBuf> = std::fs::read_dir(&dir)
22+ .into_iter()
23+ .flatten()
24+ .flatten()
25+ .map(|e| e.path())
26+ .filter(|p| p.extension().is_some_and(|e| e == extension))
27+ .filter(|p| {
28+ !p.file_name()
29+ .is_some_and(|n| n.to_string_lossy().starts_with("source"))
30+ })
31+ .collect();
32+ found.sort();
33+ found
34+}
35+
36+fn skip(what: &str) -> bool {
37+ eprintln!("skipped: fixtures/stills not generated ({what}); run scripts/gen-still-fixtures.sh");
38+ true
39+}
40+
41+/// Largest per-sample difference and Pearson correlation between two buffers.
42+fn compare(ours: &[u8], theirs: &[u8]) -> (u32, f64) {
43+ assert_eq!(ours.len(), theirs.len(), "sample counts differ");
44+ let mut max = 0u32;
45+ let n = ours.len() as f64;
46+ let (mut sa, mut sb, mut saa, mut sbb, mut sab) = (0.0, 0.0, 0.0, 0.0, 0.0);
47+ for (&a, &b) in ours.iter().zip(theirs) {
48+ max = max.max(u32::from(a.abs_diff(b)));
49+ let (a, b) = (f64::from(a), f64::from(b));
50+ sa += a;
51+ sb += b;
52+ saa += a * a;
53+ sbb += b * b;
54+ sab += a * b;
55+ }
56+ let cov = sab - sa * sb / n;
57+ let va = (saa - sa * sa / n).max(0.0);
58+ let vb = (sbb - sb * sb / n).max(0.0);
59+ let corr = if va * vb > 0.0 {
60+ cov / (va * vb).sqrt()
61+ } else {
62+ 1.0
63+ };
64+ (max, corr)
65+}
66+
67+fn psnr(a: &[u8], b: &[u8]) -> f64 {
68+ let mse: f64 = a
69+ .iter()
70+ .zip(b)
71+ .map(|(&x, &y)| {
72+ let d = f64::from(x) - f64::from(y);
73+ d * d
74+ })
75+ .sum::<f64>()
76+ / a.len() as f64;
77+ if mse == 0.0 {
78+ f64::INFINITY
79+ } else {
80+ 10.0 * (255.0f64 * 255.0 / mse).log10()
81+ }
82+}
83+
84+#[test]
85+fn png_decodes_pixel_exactly() {
86+ let files = corpus("png");
87+ if files.is_empty() && skip("png") {
88+ return;
89+ }
90+ for path in files {
91+ let bytes = std::fs::read(&path).unwrap();
92+ let ours = ec_image::decode(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
93+ let theirs = image::load_from_memory(&bytes).expect("incumbent decode");
94+ assert_eq!(
95+ (ours.width, ours.height),
96+ theirs.dimensions(),
97+ "{}",
98+ path.display()
99+ );
100+ if ours.pixels.bit_depth() == 16 {
101+ // Compared at 16 bits so the comparison is not laundered through
102+ // two different 16-to-8 rounding conventions.
103+ let a = ours.to_rgba16();
104+ let b = theirs.to_rgba16().into_raw();
105+ assert_eq!(a, b, "{} (16-bit samples)", path.display());
106+ } else {
107+ let a = ours.to_rgba8();
108+ let b = theirs.to_rgba8().into_raw();
109+ assert_eq!(a, b, "{} (8-bit samples)", path.display());
110+ }
111+ }
112+}
113+
114+#[test]
115+fn webp_lossless_decodes_pixel_exactly() {
116+ let files: Vec<PathBuf> = corpus("webp")
117+ .into_iter()
118+ .filter(|p| p.to_string_lossy().contains("lossless"))
119+ .collect();
120+ if files.is_empty() && skip("webp") {
121+ return;
122+ }
123+ for path in files {
124+ let bytes = std::fs::read(&path).unwrap();
125+ let ours = ec_image::decode(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
126+ let theirs = image::load_from_memory(&bytes).expect("incumbent decode");
127+ assert_eq!(
128+ (ours.width, ours.height),
129+ theirs.dimensions(),
130+ "{}",
131+ path.display()
132+ );
133+ assert_eq!(
134+ ours.to_rgba8(),
135+ theirs.to_rgba8().into_raw(),
136+ "{}",
137+ path.display()
138+ );
139+ }
140+}
141+
142+#[test]
143+fn jpeg_matches_the_incumbent_within_rounding() {
144+ let files = corpus("jpg");
145+ if files.is_empty() && skip("jpg") {
146+ return;
147+ }
148+ let mut worst = 0u32;
149+ for path in files {
150+ let bytes = std::fs::read(&path).unwrap();
151+ let ours = ec_image::decode(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
152+ let theirs = image::load_from_memory(&bytes).expect("incumbent decode");
153+ assert_eq!(
154+ (ours.width, ours.height),
155+ theirs.dimensions(),
156+ "{}",
157+ path.display()
158+ );
159+ let (max, corr) = compare(&ours.to_rgb8(), &theirs.to_rgb8().into_raw());
160+ let db = psnr(&ours.to_rgb8(), &theirs.to_rgb8().into_raw());
161+ eprintln!(
162+ "{:<22} max delta {max:>3} corr {corr:.6} psnr {db:.1} dB",
163+ path.file_name().unwrap().to_string_lossy()
164+ );
165+ worst = worst.max(max);
166+ // Five counts of 255 is where this decoder's IDCT and colour rounding
167+ // sit against jpeg-decoder's; both are legal readings of T.81, and the
168+ // gap is uniform noise rather than structure, which is what the
169+ // correlation and the PSNR are there to show. Grayscale, which skips
170+ // the colour matrix and the upsampler, agrees within one count.
171+ assert!(max <= 5, "{}: max sample delta {max}", path.display());
172+ assert!(corr > 0.9995, "{}: correlation {corr}", path.display());
173+ assert!(
174+ db > 48.0,
175+ "{}: {db:.1} dB against the incumbent decode",
176+ path.display()
177+ );
178+ }
179+ eprintln!("jpeg worst per-sample delta vs incumbent: {worst}");
180+}
181+
182+#[test]
183+fn webp_lossy_reconstructs_at_least_as_well_as_the_incumbent() {
184+ let files: Vec<PathBuf> = corpus("webp")
185+ .into_iter()
186+ .filter(|p| p.to_string_lossy().contains("lossy"))
187+ .collect();
188+ if files.is_empty() && skip("webp") {
189+ return;
190+ }
191+ let mut shortfalls: Vec<String> = Vec::new();
192+ for path in files {
193+ let name = path.file_name().unwrap().to_string_lossy().to_string();
194+ let source = if name.starts_with("odd") {
195+ fixtures().join("source-odd.png")
196+ } else if name.contains("alpha") {
197+ fixtures().join("source-alpha.png")
198+ } else {
199+ fixtures().join("source.png")
200+ };
201+ let reference = image::open(&source).expect("source picture").to_rgb8();
202+ let bytes = std::fs::read(&path).unwrap();
203+ let ours = ec_image::decode(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
204+ let theirs = image::load_from_memory(&bytes).expect("incumbent decode");
205+ let ours_rgb = ours.to_rgb8();
206+ let theirs_rgb = theirs.to_rgb8().into_raw();
207+ let mine = psnr(&ours_rgb, reference.as_raw());
208+ let incumbent = psnr(&theirs_rgb, reference.as_raw());
209+ let (max, corr) = compare(&ours_rgb, &theirs_rgb);
210+ eprintln!(
211+ "{name:<22} psnr {mine:.2} dB (incumbent {incumbent:.2} dB) \
212+ max delta {max} corr {corr:.6}"
213+ );
214+ if mine < incumbent - 0.1 {
215+ shortfalls.push(format!(
216+ "{name}: {mine:.2} dB against the source, incumbent {incumbent:.2} dB"
217+ ));
218+ }
219+ if ours.pixels.has_alpha() {
220+ let a: Vec<u8> = ours.to_rgba8().chunks_exact(4).map(|p| p[3]).collect();
221+ let b: Vec<u8> = theirs
222+ .to_rgba8()
223+ .into_raw()
224+ .chunks_exact(4)
225+ .map(|p| p[3])
226+ .collect();
227+ assert_eq!(a, b, "{name}: alpha plane is lossless and must match");
228+ }
229+ }
230+ assert!(shortfalls.is_empty(), "{}", shortfalls.join("\n"));
231+}
232+
233+#[test]
234+fn header_dimensions_match_the_incumbent() {
235+ let mut checked = 0;
236+ for extension in ["png", "jpg", "webp"] {
237+ for path in corpus(extension) {
238+ if path.to_string_lossy().contains("animated") {
239+ continue;
240+ }
241+ let bytes = std::fs::read(&path).unwrap();
242+ let ours = ec_image::info(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
243+ let theirs = image::ImageReader::new(std::io::Cursor::new(&bytes))
244+ .with_guessed_format()
245+ .unwrap()
246+ .into_dimensions()
247+ .unwrap();
248+ assert_eq!((ours.width, ours.height), theirs, "{}", path.display());
249+ checked += 1;
250+ }
251+ }
252+ if checked == 0 {
253+ skip("any");
254+ }
255+}
256+
257+#[test]
258+fn an_animated_webp_is_refused_by_name() {
259+ let path = fixtures().join("animated.webp");
260+ let Ok(bytes) = std::fs::read(&path) else {
261+ skip("animated.webp");
262+ return;
263+ };
264+ let err = ec_image::decode(&bytes).expect_err("an animation is not a still");
265+ let message = format!("{err}");
266+ assert!(message.contains("animated"), "{message}");
267+}
268+
269+/// An APP1 EXIF segment carrying orientation 6, spliced after SOI.
270+///
271+/// Built here rather than generated: ImageMagick writes no EXIF when the
272+/// source is a PNG, and a fixture whose name promises a tag it does not carry
273+/// is worse than no fixture.
274+fn with_exif_orientation(jpeg: &[u8], orientation: u16) -> Vec<u8> {
275+ let mut tiff = b"Exif\0\0II".to_vec();
276+ tiff.extend_from_slice(&42u16.to_le_bytes());
277+ tiff.extend_from_slice(&8u32.to_le_bytes());
278+ tiff.extend_from_slice(&1u16.to_le_bytes());
279+ tiff.extend_from_slice(&0x0112u16.to_le_bytes());
280+ tiff.extend_from_slice(&3u16.to_le_bytes());
281+ tiff.extend_from_slice(&1u32.to_le_bytes());
282+ tiff.extend_from_slice(&orientation.to_le_bytes());
283+ tiff.extend_from_slice(&0u16.to_le_bytes());
284+ tiff.extend_from_slice(&0u32.to_le_bytes());
285+
286+ let mut out = jpeg[..2].to_vec();
287+ out.extend_from_slice(&[0xff, 0xe1]);
288+ out.extend_from_slice(&((tiff.len() + 2) as u16).to_be_bytes());
289+ out.extend_from_slice(&tiff);
290+ out.extend_from_slice(&jpeg[2..]);
291+ out
292+}
293+
294+#[test]
295+fn exif_orientation_is_reported_and_not_applied() {
296+ let Ok(plain) = std::fs::read(fixtures().join("baseline-444.jpg")) else {
297+ skip("baseline-444.jpg");
298+ return;
299+ };
300+ let bytes = with_exif_orientation(&plain, 6);
301+ let ours = ec_image::decode(&bytes).unwrap();
302+ let theirs = image::load_from_memory(&bytes).unwrap();
303+ assert_eq!(ours.meta.orientation, Some(6), "EXIF tag 0x0112 parsed");
304+ assert_eq!(ec_image::decode(&plain).unwrap().meta.orientation, None);
305+ // Not applied: the pixels are still in stored order, exactly as the
306+ // incumbent leaves them, and the tagged file decodes like the plain one.
307+ assert_eq!((ours.width, ours.height), theirs.dimensions());
308+ assert_eq!(ours.to_rgb8(), ec_image::decode(&plain).unwrap().to_rgb8());
309+}
310+
311+/// Every fixture decodes, and the failures are reported together rather than
312+/// one per run — a decoder that breaks on three formats should say so once.
313+#[test]
314+fn every_fixture_decodes() {
315+ let mut failures = Vec::new();
316+ let mut count = 0;
317+ for extension in ["png", "jpg", "webp"] {
318+ for path in corpus(extension) {
319+ let name = path.file_name().unwrap().to_string_lossy().to_string();
320+ if name.contains("animated") {
321+ continue; // refused by name; `an_animated_webp_is_refused_by_name` covers it
322+ }
323+ let bytes = std::fs::read(&path).unwrap();
324+ count += 1;
325+ match ec_image::decode(&bytes) {
326+ Ok(image) => {
327+ let (w, h) = (image.width as usize, image.height as usize);
328+ assert_eq!(
329+ image.to_rgba8().len(),
330+ w * h * 4,
331+ "{name}: buffer is not width x height"
332+ );
333+ }
334+ Err(e) => failures.push(format!("{name}: {e}")),
335+ }
336+ }
337+ }
338+ if count == 0 {
339+ skip("any");
340+ return;
341+ }
342+ assert!(
343+ failures.is_empty(),
344+ "{} failed:\n{}",
345+ failures.len(),
346+ failures.join("\n")
347+ );
348+}
crates/ec-image/tests/fuzz.rsadded+191 -0
@@ -0,0 +1,191 @@
1+//! Malformed input never panics, never hangs and never allocates without
2+//! bound.
3+//!
4+//! Ten thousand mutations per format, from a fixed seed so a failure is
5+//! reproducible: bit flips, truncations, byte injections and pure noise behind
6+//! each format's signature. Every one of them must come back as `Ok` or as an
7+//! `Err` — a decoder reached by a file picker is reached by every broken file
8+//! on the disk.
9+
10+use std::path::{Path, PathBuf};
11+
12+const ROUNDS: usize = 10_000;
13+
14+fn fixtures() -> PathBuf {
15+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/stills")
16+}
17+
18+/// xorshift64*, so every run mutates the same way.
19+struct Rng(u64);
20+
21+impl Rng {
22+ fn next(&mut self) -> u64 {
23+ self.0 ^= self.0 << 13;
24+ self.0 ^= self.0 >> 7;
25+ self.0 ^= self.0 << 17;
26+ self.0
27+ }
28+
29+ fn below(&mut self, bound: usize) -> usize {
30+ (self.next() % bound.max(1) as u64) as usize
31+ }
32+}
33+
34+/// One mutated copy of `seed`: a few bit flips, a truncation, or an injection.
35+///
36+/// `head` bounds where the flips land. Aiming them at the first few dozen
37+/// bytes is what actually reaches the geometry and colour-type paths: spread
38+/// over a whole file they nearly all land in the compressed data and stop at
39+/// the first integrity check.
40+fn mutate(rng: &mut Rng, seed: &[u8], head: Option<usize>) -> Vec<u8> {
41+ let mut data = seed.to_vec();
42+ let region = head.unwrap_or(data.len()).min(data.len());
43+ match rng.below(4) {
44+ 0 => {
45+ for _ in 0..1 + rng.below(8) {
46+ let at = rng.below(region);
47+ data[at] ^= 1 << rng.below(8);
48+ }
49+ }
50+ 1 => data.truncate(rng.below(data.len())),
51+ 2 => {
52+ for _ in 0..1 + rng.below(16) {
53+ let at = rng.below(region);
54+ data[at] = (rng.next() & 0xff) as u8;
55+ }
56+ }
57+ _ => {
58+ // Keep the signature, replace the body with noise: this is the
59+ // shape that exercises header fields hardest.
60+ let keep = 12.min(data.len());
61+ data.truncate(keep);
62+ for _ in 0..rng.below(400) {
63+ data.push((rng.next() & 0xff) as u8);
64+ }
65+ }
66+ }
67+ data
68+}
69+
70+/// Recompute every chunk CRC of a mutated PNG.
71+///
72+/// Without this the checksum catches every mutation at the door and the
73+/// decoder proper is never fuzzed at all — the sweep would prove only that
74+/// CRC-32 works.
75+fn repair_png_crcs(data: &mut [u8]) {
76+ let mut at = 8usize;
77+ while at + 12 <= data.len() {
78+ let len = u32::from_be_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]]) as usize;
79+ if len > data.len() || at + 12 + len > data.len() {
80+ return;
81+ }
82+ let crc = crc32(&data[at + 4..at + 8 + len]);
83+ data[at + 8 + len..at + 12 + len].copy_from_slice(&crc.to_be_bytes());
84+ at += 12 + len;
85+ }
86+}
87+
88+fn sweep(name: &str, seed_file: &str) {
89+ let Ok(seed) = std::fs::read(fixtures().join(seed_file)) else {
90+ eprintln!("skipped: fixtures/stills not generated; run scripts/gen-still-fixtures.sh");
91+ return;
92+ };
93+ let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ name.len() as u64);
94+ let mut decoded = 0usize;
95+ for round in 0..ROUNDS {
96+ // Half the rounds aim at the header, half at the whole file.
97+ let head = if round % 2 == 0 { Some(48) } else { None };
98+ let mut data = mutate(&mut rng, &seed, head);
99+ if seed_file.ends_with(".png") {
100+ repair_png_crcs(&mut data);
101+ }
102+ // The call is the assertion: a panic here fails the test with the
103+ // round number, and the round number plus the fixed seed reproduces it.
104+ if let Ok(image) = ec_image::decode(&data) {
105+ decoded += 1;
106+ let pixels = image.to_rgba8();
107+ assert_eq!(
108+ pixels.len(),
109+ (image.width as usize) * (image.height as usize) * 4,
110+ "{name} round {round}: buffer does not match the dimensions"
111+ );
112+ }
113+ // Header-only parsing must survive the same input.
114+ let _ = ec_image::info(&data);
115+ }
116+ eprintln!("{name}: {ROUNDS} mutations, {decoded} still decoded");
117+}
118+
119+#[test]
120+fn png_survives_mutation() {
121+ sweep("png", "tiny.png");
122+}
123+
124+#[test]
125+fn jpeg_survives_mutation() {
126+ sweep("jpeg", "tiny.jpg");
127+}
128+
129+#[test]
130+fn webp_lossy_survives_mutation() {
131+ sweep("webp-lossy", "tiny-lossy.webp");
132+}
133+
134+#[test]
135+fn webp_lossless_survives_mutation() {
136+ sweep("webp-lossless", "tiny-lossless.webp");
137+}
138+
139+#[test]
140+fn arbitrary_bytes_behind_a_signature_are_refused_not_believed() {
141+ let signatures: [&[u8]; 3] = [
142+ &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a],
143+ &[0xff, 0xd8, 0xff, 0xe0],
144+ b"RIFF\x40\x00\x00\x00WEBPVP8 ",
145+ ];
146+ let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
147+ for signature in signatures {
148+ for _ in 0..ROUNDS / 4 {
149+ let mut data = signature.to_vec();
150+ for _ in 0..rng.below(200) {
151+ data.push((rng.next() & 0xff) as u8);
152+ }
153+ let _ = ec_image::decode(&data);
154+ let _ = ec_image::info(&data);
155+ }
156+ }
157+}
158+
159+#[test]
160+fn a_header_asking_for_more_pixels_than_the_limit_is_refused() {
161+ // A PNG IHDR claiming 65535x65535 is 4 gigapixels: the limit must refuse
162+ // it before any buffer is sized from those numbers.
163+ let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
164+ let mut ihdr = Vec::new();
165+ ihdr.extend_from_slice(&65535u32.to_be_bytes());
166+ ihdr.extend_from_slice(&65535u32.to_be_bytes());
167+ ihdr.extend_from_slice(&[8, 6, 0, 0, 0]);
168+ png.extend_from_slice(&(ihdr.len() as u32).to_be_bytes());
169+ let start = png.len();
170+ png.extend_from_slice(b"IHDR");
171+ png.extend_from_slice(&ihdr);
172+ let crc = crc32(&png[start..]);
173+ png.extend_from_slice(&crc.to_be_bytes());
174+ let err = ec_image::decode(&png).expect_err("4 gigapixels is past the limit");
175+ assert!(format!("{err}").contains("limit"), "{err}");
176+}
177+
178+fn crc32(data: &[u8]) -> u32 {
179+ let mut c = 0xffff_ffffu32;
180+ for &b in data {
181+ c ^= u32::from(b);
182+ for _ in 0..8 {
183+ c = if c & 1 != 0 {
184+ 0xedb8_8320 ^ (c >> 1)
185+ } else {
186+ c >> 1
187+ };
188+ }
189+ }
190+ c ^ 0xffff_ffff
191+}
crates/ec-image/tests/real_library.rsadded+122 -0
@@ -0,0 +1,122 @@
1+//! The same differential bars, against real pictures on this machine.
2+//!
3+//! Generated fixtures come out of two encoders with default settings; a real
4+//! library has phone JPEGs with EXIF, screenshots, scans and downloads, and
5+//! those are the files a user actually opens. The sweep is read-only, prints a
6+//! per-file table, and skips silently when the directories hold no pictures.
7+
8+use image::GenericImageView;
9+use std::path::PathBuf;
10+
11+/// Where a real library lives on this machine; absent directories are skipped.
12+fn library() -> Vec<PathBuf> {
13+ let home = std::env::var("HOME").unwrap_or_default();
14+ ["Videos", "Downloads"]
15+ .iter()
16+ .map(|d| PathBuf::from(&home).join(d))
17+ .filter(|p| p.is_dir())
18+ .collect()
19+}
20+
21+/// Every still under `roots`, three directory levels deep, capped.
22+fn stills(roots: &[PathBuf], cap: usize) -> Vec<PathBuf> {
23+ fn walk(dir: &PathBuf, depth: usize, out: &mut Vec<PathBuf>) {
24+ if depth == 0 {
25+ return;
26+ }
27+ let Ok(entries) = std::fs::read_dir(dir) else {
28+ return;
29+ };
30+ for entry in entries.flatten() {
31+ let path = entry.path();
32+ if path.is_dir() {
33+ walk(&path, depth - 1, out);
34+ } else if let Some(extension) = path.extension() {
35+ let extension = extension.to_string_lossy().to_lowercase();
36+ if ["png", "jpg", "jpeg", "webp"].contains(&extension.as_str()) {
37+ out.push(path);
38+ }
39+ }
40+ }
41+ }
42+ let mut found = Vec::new();
43+ for root in roots {
44+ walk(root, 3, &mut found);
45+ }
46+ found.sort();
47+ found.truncate(cap);
48+ found
49+}
50+
51+#[test]
52+fn real_pictures_decode_like_the_incumbent() {
53+ let files = stills(&library(), 20);
54+ if files.is_empty() {
55+ eprintln!("skipped: no PNG/JPEG/WebP under ~/Videos or ~/Downloads");
56+ return;
57+ }
58+ let mut failures = Vec::new();
59+ for path in &files {
60+ let name = path.file_name().unwrap().to_string_lossy().to_string();
61+ let bytes = std::fs::read(path).unwrap();
62+ let started = std::time::Instant::now();
63+ let ours = match ec_image::decode(&bytes) {
64+ Ok(image) => image,
65+ Err(e) => {
66+ // The incumbent's verdict decides whether this is our failure
67+ // or a file neither crate claims to decode.
68+ if image::load_from_memory(&bytes).is_ok() {
69+ failures.push(format!(
70+ "{name}: we refuse it, the incumbent decodes it ({e})"
71+ ));
72+ } else {
73+ eprintln!("{name:<44} both refuse: {e}");
74+ }
75+ continue;
76+ }
77+ };
78+ let ours_ms = started.elapsed().as_secs_f64() * 1000.0;
79+ let theirs = match image::load_from_memory(&bytes) {
80+ Ok(image) => image,
81+ Err(e) => {
82+ eprintln!("{name:<44} we decode it, the incumbent does not ({e})");
83+ continue;
84+ }
85+ };
86+ if (ours.width, ours.height) != theirs.dimensions() {
87+ failures.push(format!(
88+ "{name}: {}x{} against the incumbent's {:?}",
89+ ours.width,
90+ ours.height,
91+ theirs.dimensions()
92+ ));
93+ continue;
94+ }
95+ let a = ours.to_rgb8();
96+ let b = theirs.to_rgb8().into_raw();
97+ let max = a
98+ .iter()
99+ .zip(&b)
100+ .map(|(&x, &y)| x.abs_diff(y))
101+ .max()
102+ .unwrap_or(0);
103+ let lossless = path
104+ .extension()
105+ .is_some_and(|e| e.eq_ignore_ascii_case("png"));
106+ eprintln!(
107+ "{name:<44} {}x{} max delta {max:>3} {ours_ms:>7.1} ms",
108+ ours.width, ours.height
109+ );
110+ let bar = if lossless { 0 } else { 8 };
111+ if u32::from(max) > bar {
112+ failures.push(format!("{name}: max delta {max}, bar {bar}"));
113+ }
114+ }
115+ assert!(
116+ failures.is_empty(),
117+ "{} of {} real pictures failed:\n{}",
118+ failures.len(),
119+ files.len(),
120+ failures.join("\n")
121+ );
122+}