forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8dbd683Tahinli3 months ago856 commits

differential.rs731 lines, 27.4 KiBHistoryRawDownload
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
11use image::GenericImageView;
12use std::path::{Path, PathBuf};
13
14fn 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.
19fn 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
36fn 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.
42fn 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
67fn 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]
85fn 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]
115fn 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]
143fn 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]
183fn 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]
234fn 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]
258fn 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.
274fn 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]
295fn 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]
314fn 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") || name.starts_with("anim-") {
321 continue; // an animation is not a still; the animation tests cover 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}
349
350#[test]
351fn gif_decodes_pixel_exactly() {
352 let files = corpus("gif");
353 if files.is_empty() && skip("gif") {
354 return;
355 }
356 for path in files {
357 let bytes = std::fs::read(&path).unwrap();
358 let ours = ec_image::decode(&bytes).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
359 let theirs = image::load_from_memory(&bytes).expect("incumbent decode");
360 assert_eq!(
361 (ours.width, ours.height),
362 theirs.dimensions(),
363 "{}",
364 path.display()
365 );
366 assert_eq!(
367 ours.to_rgba8(),
368 theirs.to_rgba8().into_raw(),
369 "{} (first frame)",
370 path.file_name().unwrap().to_string_lossy()
371 );
372 eprintln!(
373 "{:<22} {}x{} exact",
374 path.file_name().unwrap().to_string_lossy(),
375 ours.width,
376 ours.height
377 );
378 }
379}
380
381#[test]
382fn a_gif_animation_composites_frame_for_frame_like_the_incumbent() {
383 use image::AnimationDecoder;
384
385 let path = fixtures().join("animated.gif");
386 if !path.exists() && skip("animated.gif") {
387 return;
388 }
389 let bytes = std::fs::read(&path).unwrap();
390 let ours = ec_image::decode_animation(&bytes).expect("our animation decode");
391 let theirs: Vec<image::Frame> =
392 image::codecs::gif::GifDecoder::new(std::io::Cursor::new(&bytes))
393 .expect("incumbent decoder")
394 .into_frames()
395 .collect::<Result<Vec<_>, _>>()
396 .expect("incumbent frames");
397
398 assert_eq!(ours.len(), theirs.len(), "frame count");
399 assert!(ours.len() > 1, "the fixture is not an animation");
400 for (i, (ours, theirs)) in ours.iter().zip(&theirs).enumerate() {
401 let (num, den) = theirs.delay().numer_denom_ms();
402 // Both sides quote the delay in their own units; compare in
403 // milliseconds, which is what a renderer actually waits.
404 let ours_ms = f64::from(ours.delay_num) * 1000.0 / f64::from(ours.delay_den);
405 let theirs_ms = f64::from(num) / f64::from(den);
406 assert!(
407 (ours_ms - theirs_ms).abs() < 0.5,
408 "frame {i}: {ours_ms} ms against the incumbent's {theirs_ms} ms"
409 );
410 assert_eq!(
411 (ours.image.width, ours.image.height),
412 theirs.buffer().dimensions(),
413 "frame {i} is not the whole canvas"
414 );
415 assert_eq!(
416 ours.image.to_rgba8(),
417 theirs.buffer().as_raw().clone(),
418 "frame {i} samples"
419 );
420 eprintln!("frame {i}: {ours_ms:.0} ms, exact");
421 }
422}
423
424#[test]
425fn a_still_of_any_format_is_one_frame_of_animation() {
426 let path = fixtures().join("rgb8.png");
427 if !path.exists() && skip("rgb8.png") {
428 return;
429 }
430 let bytes = std::fs::read(&path).unwrap();
431 let frames = ec_image::decode_animation(&bytes).expect("decode");
432 assert_eq!(frames.len(), 1);
433 assert_eq!(frames[0].delay_num, 0);
434 assert_eq!(
435 frames[0].image.to_rgba8(),
436 ec_image::decode(&bytes).unwrap().to_rgba8()
437 );
438}
439
440#[test]
441fn an_animated_webp_composites_frame_for_frame_like_the_incumbent() {
442 one_animated_webp("animated.webp");
443}
444
445fn one_animated_webp(fixture: &str) {
446 use image::AnimationDecoder;
447
448 let path = fixtures().join(fixture);
449 let Ok(bytes) = std::fs::read(&path) else {
450 skip(fixture);
451 return;
452 };
453 assert!(
454 ec_image::webp::is_animated(&bytes),
455 "the fixture is not an animation"
456 );
457 let ours = ec_image::decode_animation(&bytes).expect("our animation decode");
458 let theirs: Vec<image::Frame> =
459 image::codecs::webp::WebPDecoder::new(std::io::Cursor::new(&bytes))
460 .expect("incumbent decoder")
461 .into_frames()
462 .collect::<Result<Vec<_>, _>>()
463 .expect("incumbent frames");
464
465 assert_eq!(ours.len(), theirs.len(), "frame count");
466 assert!(ours.len() > 1, "the fixture is not an animation");
467 for (i, (ours, theirs)) in ours.iter().zip(&theirs).enumerate() {
468 let (num, den) = theirs.delay().numer_denom_ms();
469 let ours_ms = f64::from(ours.delay_num) * 1000.0 / f64::from(ours.delay_den);
470 let theirs_ms = f64::from(num) / f64::from(den);
471 assert!(
472 (ours_ms - theirs_ms).abs() < 0.5,
473 "frame {i}: {ours_ms} ms against the incumbent's {theirs_ms} ms"
474 );
475 assert_eq!(
476 (ours.image.width, ours.image.height),
477 theirs.buffer().dimensions(),
478 "frame {i} is not the whole canvas"
479 );
480 // The frames are lossy VP8, so the payload is only as exact as the two
481 // VP8 decoders agree; the bar here is on the compositing, which is
482 // exact arithmetic over whatever the payload decoded to.
483 let a = ours.image.to_rgba8();
484 let b = theirs.buffer().as_raw();
485 let max = a
486 .iter()
487 .zip(b)
488 .map(|(&x, &y)| x.abs_diff(y))
489 .max()
490 .unwrap_or(0);
491 let psnr = psnr(&a, b);
492 eprintln!("{fixture} frame {i}: {ours_ms:.0} ms, max delta {max}, {psnr:.1} dB");
493 assert!(
494 max <= 5 && psnr > 48.0,
495 "{fixture} frame {i}: max delta {max}, {psnr:.1} dB"
496 );
497 }
498}
499
500/// Alpha blending and dispose-to-background, against libwebp itself.
501///
502/// The `image` crate is not the oracle here: it ignores the ANMF
503/// dispose-to-background flag, so the frame after a disposal keeps pixels
504/// libwebp clears -- 6912 of 6912 pixels differ on this fixture, and libwebp
505/// agrees with us on every one. The goldens are libwebp's own composited
506/// frames, written by `scripts/gen-still-fixtures.sh`.
507#[test]
508fn webp_disposal_and_blending_match_libwebp() {
509 let path = fixtures().join("anim-alpha.webp");
510 let Ok(bytes) = std::fs::read(&path) else {
511 skip("anim-alpha.webp");
512 return;
513 };
514 let goldens: Vec<PathBuf> = (0..)
515 .map(|i| fixtures().join(format!("anim-alpha-f{i}.png")))
516 .take_while(|p| p.exists())
517 .collect();
518 if goldens.is_empty() {
519 skip("anim-alpha-f0.png (libwebp goldens; Pillow not installed?)");
520 return;
521 }
522
523 let ours = ec_image::decode_animation(&bytes).expect("our animation decode");
524 assert_eq!(ours.len(), goldens.len(), "frame count against libwebp");
525 for (i, (ours, golden)) in ours.iter().zip(&goldens).enumerate() {
526 let want = ec_image::open(golden).expect("golden");
527 assert_eq!(
528 (ours.image.width, ours.image.height),
529 (want.width, want.height),
530 "frame {i} is not the whole canvas"
531 );
532 assert_eq!(ours.image.to_rgba8(), want.to_rgba8(), "frame {i} samples");
533 eprintln!(
534 "frame {i}: {} ms, exact against libwebp",
535 f64::from(ours.delay_num) * 1000.0 / f64::from(ours.delay_den)
536 );
537 }
538 // The delays come from the same headers, but a player that gets them wrong
539 // plays the animation at the wrong speed however exact the pixels are.
540 let delays: Vec<u32> = ours.iter().map(|f| f.delay_num).collect();
541 assert_eq!(delays, vec![60, 90, 30], "per-frame durations in ms");
542}
543
544/// BMP is a lossless container of raw samples, so the only question is whether
545/// the two decoders read the same header the same way.
546#[test]
547fn bmp_decodes_pixel_exactly() {
548 let files = corpus("bmp");
549 if files.is_empty() && skip("bmp") {
550 return;
551 }
552 for path in files {
553 let name = path.file_name().unwrap().to_string_lossy().to_string();
554 if name.starts_with("embedded-") || name == "os2v2.bmp" {
555 continue; // the incumbent refuses both; their own tests cover them
556 }
557 let data = std::fs::read(&path).unwrap();
558 let ours = ec_image::decode(&data).unwrap_or_else(|e| panic!("{name}: {e}"));
559 let theirs = image::load_from_memory(&data).unwrap_or_else(|e| panic!("{name}: {e}"));
560 assert_eq!(
561 (ours.width, ours.height),
562 theirs.dimensions(),
563 "{name}: dimensions differ"
564 );
565 let (max, corr) = compare(&ours.to_rgba8(), &theirs.to_rgba8().into_raw());
566 println!("{name:>16} max {max} corr {corr:.6}");
567 assert_eq!(max, 0, "{name}: samples differ from the incumbent");
568 }
569}
570
571/// `BI_PNG` and `BI_JPEG` are a BMP header wrapped around a whole file of
572/// another format. The incumbent refuses both, so the oracle is the incumbent
573/// decoding the *payload* directly: reading the wrapper must reach the same
574/// picture as reading what it wraps.
575#[test]
576fn a_bmp_wrapping_another_format_decodes_to_that_format() {
577 // The JPEG bar is the same 5 the plain JPEG comparison uses: the IDCT is
578 // implementation-defined, so the two decoders round differently.
579 for (fixture, bar) in [("embedded-png.bmp", 0u32), ("embedded-jpeg.bmp", 5)] {
580 let path = fixtures().join(fixture);
581 let Ok(data) = std::fs::read(&path) else {
582 if skip(fixture) {
583 return;
584 }
585 unreachable!()
586 };
587 // The payload starts where the file header says the pixels do.
588 let offset = u32::from_le_bytes([data[10], data[11], data[12], data[13]]) as usize;
589 let payload = &data[offset..];
590 let ours = ec_image::decode(&data).unwrap_or_else(|e| panic!("{fixture}: {e}"));
591 let theirs = image::load_from_memory(payload).unwrap();
592 assert_eq!(
593 (ours.width, ours.height),
594 theirs.dimensions(),
595 "{fixture}: dimensions differ"
596 );
597 let (max, corr) = compare(&ours.to_rgba8(), &theirs.to_rgba8().into_raw());
598 println!("{fixture:>20} max {max} corr {corr:.6}");
599 assert!(max <= bar, "{fixture}: max delta {max} over the bar {bar}");
600 assert_eq!(
601 ec_image::info(&data).unwrap().width,
602 theirs.dimensions().0,
603 "{fixture}: the header-only path disagrees with the pixels"
604 );
605 }
606}
607
608/// The 16-byte OS/2 v2 header, which the incumbent refuses outright
609/// ("Unknown bitmap header type (size=16)") and ffmpeg reads. The oracle is
610/// therefore the same picture in a header both decoders read: the two files
611/// carry identical rows, so the pixels must come out identical too.
612#[test]
613fn an_os2_v2_header_reads_as_the_same_picture() {
614 let short = fixtures().join("os2v2.bmp");
615 let long = fixtures().join("os2v1.bmp");
616 let (Ok(short), Ok(long)) = (std::fs::read(&short), std::fs::read(&long)) else {
617 skip("os2v2.bmp");
618 return;
619 };
620 assert!(
621 image::load_from_memory(&short).is_err(),
622 "the incumbent now reads a 16-byte header; this test's premise is stale"
623 );
624 let ours = ec_image::decode(&short).unwrap();
625 let reference = image::load_from_memory(&long).unwrap();
626 assert_eq!((ours.width, ours.height), reference.dimensions());
627 let (max, _) = compare(&ours.to_rgba8(), &reference.to_rgba8().into_raw());
628 assert_eq!(
629 max, 0,
630 "os2v2.bmp: samples differ from the same picture in a v1 header"
631 );
632}
633
634/// TIFF stores raw samples, so like BMP the only question is whether the two
635/// decoders read the same tags the same way. The corpus crosses every
636/// compression with both byte orders, strips against tiles, interleaved
637/// samples against planes, and five sample depths.
638#[test]
639fn tiff_decodes_pixel_exactly() {
640 let mut files = corpus("tiff");
641 files.extend(corpus("tif"));
642 files.sort();
643 if files.is_empty() && skip("tiff") {
644 return;
645 }
646 for path in files {
647 let name = path.file_name().unwrap().to_string_lossy().to_string();
648 if name == "palette4.tiff" {
649 continue; // the incumbent refuses a 4-bit palette; its own test covers it
650 }
651 if name == "rgba8-assoc.tiff" {
652 continue; // the incumbent ignores ExtraSamples; its own test covers it
653 }
654 let data = std::fs::read(&path).unwrap();
655 let ours = ec_image::decode(&data).unwrap_or_else(|e| panic!("{name}: {e}"));
656 let theirs = image::load_from_memory(&data).unwrap_or_else(|e| panic!("{name}: {e}"));
657 assert_eq!(
658 (ours.width, ours.height),
659 theirs.dimensions(),
660 "{name}: dimensions differ"
661 );
662 let (max, corr) = compare(&ours.to_rgba8(), &theirs.to_rgba8().into_raw());
663 println!("{name:>20} max {max} corr {corr:.6}");
664 assert_eq!(max, 0, "{name}: samples differ from the incumbent");
665 }
666}
667
668/// TIFF tags its alpha as either straight (ExtraSamples 1) or associated
669/// (ExtraSamples 2, premultiplied). The incumbent hands back the file's raw
670/// samples either way, so it cannot arbitrate the premultiplied one; the two
671/// fixtures carry the same picture at alpha 0 or 255, where premultiplying is
672/// lossless, so the associated file must decode to the straight one exactly.
673#[test]
674fn an_associated_alpha_tiff_reads_unpremultiplied() {
675 let (Ok(assoc), Ok(straight)) = (
676 std::fs::read(fixtures().join("rgba8-assoc.tiff")),
677 std::fs::read(fixtures().join("rgba8.tiff")),
678 ) else {
679 skip("rgba8-assoc.tiff");
680 return;
681 };
682 let ours = ec_image::decode(&assoc).expect("rgba8-assoc.tiff");
683 let reference = ec_image::decode(&straight).expect("rgba8.tiff");
684 // Under a zero alpha the colour is gone for good -- premultiplying by zero
685 // is not invertible -- so those pixels are compared on their alpha alone.
686 let (ours, reference) = (ours.to_rgba8(), reference.to_rgba8());
687 for (i, (a, b)) in ours.chunks(4).zip(reference.chunks(4)).enumerate() {
688 assert_eq!(a[3], b[3], "rgba8-assoc.tiff: alpha differs at pixel {i}");
689 if b[3] != 0 {
690 assert_eq!(
691 a[..3],
692 b[..3],
693 "rgba8-assoc.tiff: the premultiplication was not undone at pixel {i}"
694 );
695 }
696 }
697
698 // The incumbent ignores the tag, so its two decodes differ: were that to
699 // change, this test would be comparing against nothing.
700 let a = image::load_from_memory(&assoc).expect("incumbent rgba8-assoc.tiff");
701 let b = image::load_from_memory(&straight).expect("incumbent rgba8.tiff");
702 assert_ne!(
703 a.to_rgba8().into_raw(),
704 b.to_rgba8().into_raw(),
705 "the incumbent now honours ExtraSamples; use it as the oracle instead"
706 );
707}
708
709/// A 4-bit palette, which the incumbent refuses ("Photometric interpretation
710/// RGBPalette with bits per sample [4] is unsupported") and ffmpeg reads. The
711/// oracle is therefore ffmpeg's own decode of the same file, written to a PNG
712/// when the corpus was generated.
713#[test]
714fn a_four_bit_tiff_palette_reads_as_ffmpeg_reads_it() {
715 let (Ok(narrow), Ok(wide)) = (
716 std::fs::read(fixtures().join("palette4.tiff")),
717 std::fs::read(fixtures().join("palette4-golden.png")),
718 ) else {
719 skip("palette4.tiff");
720 return;
721 };
722 assert!(
723 image::load_from_memory(&narrow).is_err(),
724 "the incumbent now reads a 4-bit palette; this test's premise is stale"
725 );
726 let ours = ec_image::decode(&narrow).unwrap();
727 let reference = image::load_from_memory(&wide).unwrap();
728 assert_eq!((ours.width, ours.height), reference.dimensions());
729 let (max, _) = compare(&ours.to_rgba8(), &reference.to_rgba8().into_raw());
730 assert_eq!(max, 0, "palette4.tiff: samples differ from the same palette at 8 bits");
731}