rust-j2k 0.5.0

Decodes JPEG 2000 images in pure Rust, for programs that need to read them without linking a C library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
//! Shared test support: the `<name>.expected.json` oracle-snapshot schema.
//!
//! Each fixture under `tests/fixtures/` ships a sibling `<name>.expected.json`
//! holding what a trusted decoder (OpenJPEG, or eccodes for GRIB2-sourced
//! files) produced for it: the decoded samples, their geometry, the agreement
//! tolerance, and the provenance that lets the snapshot be regenerated. The
//! conformance harness deserializes one of these and compares it against our
//! own `decode` output. See `tests/fixtures/README.md` for the documented
//! schema and `docs/correctness.md` for how the corpus is graded.
//!
//! This module owns the schema *and* the harness that runs it: fixture
//! discovery ([`discover`]), the sample comparator ([`compare`]), and the
//! decode-outcome classifier ([`classify`]) the corpus test drives.
//!
//! It also carries the shared machinery for the ISO/IEC 15444-4 conformance
//! corpus: the PGX reference reader ([`pgx`]) and the manifest schema, PAE/MSE
//! comparator, and ratchet driver ([`part4`]). Each `tests/*.rs` file is its own
//! crate, so any given test binary uses only a slice of this module; the
//! module-wide `#![allow(dead_code)]` keeps the unused-in-this-binary slice from
//! tripping the `dead_code` lint.

#![allow(dead_code)]

pub mod ht;
pub mod jp2;
pub mod part4;
pub mod pgx;
pub mod synth;

use std::fmt;
use std::panic;
use std::path::{Path, PathBuf};

use rust_j2k::{
    Association, ChannelType, ColorOutput, ColorSpace, Component, DecodeOptions, Error, Image,
    Jp2Metadata, Res,
};
use serde::{Deserialize, Serialize};

/// Default options with sRGB output.
pub fn srgb() -> DecodeOptions {
    DecodeOptions::default().with_color(ColorOutput::Srgb)
}

/// The hash `scripts/gen-icc-oracles.py` records: samples in raster order,
/// each a 4-byte big-endian signed integer.
pub fn plane_hash(component: &Component) -> String {
    let bytes: Vec<u8> = component
        .samples
        .iter()
        .flat_map(|s| s.to_be_bytes())
        .collect();
    jp2::sha256_hex(&bytes)
}

/// One fixture's oracle snapshot: the decode a trusted reference produced, plus
/// everything needed to grade our decode against it and to reproduce the file.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Expected {
    /// The reference-grid image area the components are registered against.
    pub image: ImageGeometry,
    /// How close our decode must be to count as correct.
    pub tolerance: Tolerance,
    /// One entry per component, in SIZ order.
    pub components: Vec<ComponentSnapshot>,
    /// Where the fixture came from and how to regenerate this snapshot.
    pub provenance: Provenance,
    /// For a JP2 fixture, what its header says; checked against
    /// [`Image::jp2`] when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub jp2: Option<Jp2Snapshot>,
    /// For a JP2 fixture with no `jp2` section, its `ftyp`, `ihdr`, `colr`
    /// and `rreq` fields; checked against [`Image::jp2`] when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub jp2_boxes: Option<Jp2Boxes>,
}

/// What a JP2 file's header says, in a form a box dump can be checked against
/// by hand: the optional `jp2` section of an [`Expected`] snapshot, and the
/// per-file record in `tests/fixtures/jp2_real/metadata.json`.
///
/// ```json
/// "jp2": {
///   "color": "srgb",
///   "channels": ["color/1", "color/2", "color/3"],
///   "palette_applied": false,
///   "resolution": { "capture": [10000, 254, 10000, 254, 0, 0], "display": null },
///   "xml": [431, 741],
///   "uuid": [["b14bf8bd083d4b43a5ae8cd7d5a6ce03", 300]],
///   "ipr": [120],
///   "uuid_info": [[["2b0d7e97aa2e317d9133e53161a2f7d0"], 24]],
///   "file_type": { "brand": "jp2 ", "minor_version": 0, "compatibility": ["jp2 "] },
///   "image_header": { "compression": 7, "unknown_color_space": 0, "ipr_flag": 0 },
///   "color_specifications": [{ "method": 1, "precedence": 0, "approximation": 0,
///     "payload_len": 4, "payload_sha256": "<hex>", "enum_cs": 16 }],
///   "reader_requirements": null
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Jp2Snapshot {
    /// `srgb`, `grayscale`, `sycc`, `icc:<profile bytes>`, `enumerated:<n>`
    /// or `unknown`.
    pub color: String,
    /// One `<type>/<association>` per output channel: `color/1`,
    /// `opacity/whole`, `unspecified/none`, `other(7)/other(9)`.
    pub channels: Vec<String>,
    pub palette_applied: bool,
    pub resolution: ResolutionSnapshot,
    /// The byte length of each top-level `xml ` box, in file order.
    pub xml: Vec<usize>,
    /// Each top-level `uuid` box's identifier (lowercase hex) and payload
    /// length, in file order.
    pub uuid: Vec<(String, usize)>,
    /// The byte length of each top-level `jp2i` box, in file order. Absent
    /// in a record means none.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub ipr: Vec<usize>,
    /// Each top-level `uinf` box: its UUIDs (lowercase hex) and its `url `
    /// location's byte length, in file order. Absent in a record means none.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub uuid_info: Vec<(Vec<String>, usize)>,
    /// The `ftyp` box.
    pub file_type: FileTypeSnapshot,
    /// The `ihdr` fields that are not taken from the codestream.
    pub image_header: ImageHeaderSnapshot,
    /// Every counted `colr` box, in file order.
    pub color_specifications: Vec<ColorSpecSnapshot>,
    /// The first well-formed top-level `rreq` box, if any.
    pub reader_requirements: Option<ReaderRequirementsSnapshot>,
}

/// The `ftyp`, `ihdr`, `colr` and `rreq` fields of a JP2 file, from a box dump
/// (`scripts/gen-jp2-box-snapshots.py`). The same four fields sit in
/// [`Jp2Snapshot`]; this is the record for a file that has no other snapshot.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Jp2Boxes {
    pub file_type: FileTypeSnapshot,
    pub image_header: ImageHeaderSnapshot,
    pub color_specifications: Vec<ColorSpecSnapshot>,
    pub reader_requirements: Option<ReaderRequirementsSnapshot>,
}

/// `ftyp`: each 4-byte code as text, `\xNN` for a byte outside printable ASCII.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FileTypeSnapshot {
    pub brand: String,
    pub minor_version: u32,
    pub compatibility: Vec<String>,
}

/// `ihdr`'s `C`, `UnkC` and `IPR`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ImageHeaderSnapshot {
    pub compression: u8,
    pub unknown_color_space: u8,
    pub ipr_flag: u8,
}

/// One `colr` box: `METH`, `PREC`, `APPROX`, the payload's length and SHA-256,
/// and `EnumCS` when `METH` is 1 with a 4-byte value.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ColorSpecSnapshot {
    pub method: u8,
    pub precedence: u8,
    pub approximation: u8,
    pub payload_len: usize,
    pub payload_sha256: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub enum_cs: Option<u32>,
}

/// `rreq`: `ML`, the masks as lowercase hex, `(SF, SM)` and `(VF, VM)` pairs.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ReaderRequirementsSnapshot {
    pub mask_length: u8,
    pub fully_understand: String,
    pub decode_completely: String,
    pub standard_features: Vec<(u16, String)>,
    pub vendor_features: Vec<(String, String)>,
}

fn hex_bytes(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

fn code_text(code: &[u8; 4]) -> String {
    code.iter()
        .map(|&b| {
            if (0x20..=0x7e).contains(&b) {
                char::from(b).to_string()
            } else {
                format!("\\x{b:02x}")
            }
        })
        .collect()
}

impl Jp2Boxes {
    /// The snapshot of decoded metadata, to compare against a recorded one.
    pub fn of(metadata: &Jp2Metadata) -> Self {
        let file_type = &metadata.file_type;
        let header = metadata.image_header;
        Jp2Boxes {
            file_type: FileTypeSnapshot {
                brand: code_text(&file_type.brand),
                minor_version: file_type.minor_version,
                compatibility: file_type.compatibility.iter().map(code_text).collect(),
            },
            image_header: ImageHeaderSnapshot {
                compression: header.compression,
                unknown_color_space: header.unknown_color_space,
                ipr_flag: header.ipr_flag,
            },
            color_specifications: metadata
                .color_specifications
                .iter()
                .map(|c| ColorSpecSnapshot {
                    method: c.method,
                    precedence: c.precedence,
                    approximation: c.approximation,
                    payload_len: c.payload.len(),
                    payload_sha256: jp2::sha256_hex(&c.payload),
                    enum_cs: <[u8; 4]>::try_from(c.payload.as_slice())
                        .ok()
                        .filter(|_| c.method == 1)
                        .map(u32::from_be_bytes),
                })
                .collect(),
            reader_requirements: metadata.reader_requirements.as_ref().map(|r| {
                ReaderRequirementsSnapshot {
                    mask_length: r.mask_length,
                    fully_understand: hex_bytes(&r.fully_understand),
                    decode_completely: hex_bytes(&r.decode_completely),
                    standard_features: r
                        .standard_features
                        .iter()
                        .map(|f| (f.feature, hex_bytes(&f.mask)))
                        .collect(),
                    vendor_features: r
                        .vendor_features
                        .iter()
                        .map(|f| (hex_bytes(&f.id), hex_bytes(&f.mask)))
                        .collect(),
                }
            }),
        }
    }
}

/// `resc` and `resd` as the box stores them: `VRN, VRD, HRN, HRD, VRE, HRE`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ResolutionSnapshot {
    pub capture: Option<[i32; 6]>,
    pub display: Option<[i32; 6]>,
}

impl Jp2Snapshot {
    /// The snapshot of decoded metadata, to compare against a recorded one.
    pub fn of(metadata: &Jp2Metadata) -> Self {
        let color = match &metadata.color {
            ColorSpace::Srgb => "srgb".to_string(),
            ColorSpace::Grayscale => "grayscale".to_string(),
            ColorSpace::Sycc => "sycc".to_string(),
            ColorSpace::RestrictedIcc(profile) => format!("icc:{}", profile.len()),
            ColorSpace::Enumerated(n) => format!("enumerated:{n}"),
            ColorSpace::Unknown => "unknown".to_string(),
            // `ColorSpace` is non-exhaustive: a new variant needs a snapshot name.
            other => panic!("no snapshot name for {other:?}"),
        };
        let kind = |k: ChannelType| match k {
            ChannelType::Color => "color".to_string(),
            ChannelType::Opacity => "opacity".to_string(),
            ChannelType::PremultipliedOpacity => "premultiplied".to_string(),
            ChannelType::ApplicationDefined => "application".to_string(),
            ChannelType::Unspecified => "unspecified".to_string(),
            ChannelType::Other(n) => format!("other({n})"),
            other => panic!("no snapshot name for {other:?}"),
        };
        let association = |a: Association| match a {
            Association::WholeImage => "whole".to_string(),
            Association::Color(n) => n.to_string(),
            Association::None => "none".to_string(),
            Association::ApplicationDefined(n) => format!("application({n})"),
            other => panic!("no snapshot name for {other:?}"),
        };
        let hex = |id: &[u8; 16]| id.iter().map(|b| format!("{b:02x}")).collect::<String>();
        let res = |r: Option<Res>| {
            r.map(|r| {
                let (v, h) = (r.vertical, r.horizontal);
                [
                    i32::from(v.numerator),
                    i32::from(v.denominator),
                    i32::from(h.numerator),
                    i32::from(h.denominator),
                    i32::from(v.exponent),
                    i32::from(h.exponent),
                ]
            })
        };
        let boxes = Jp2Boxes::of(metadata);
        Jp2Snapshot {
            file_type: boxes.file_type,
            image_header: boxes.image_header,
            color_specifications: boxes.color_specifications,
            reader_requirements: boxes.reader_requirements,
            color,
            channels: metadata
                .channels
                .iter()
                .map(|c| format!("{}/{}", kind(c.kind), association(c.association)))
                .collect(),
            palette_applied: metadata.palette_applied,
            resolution: ResolutionSnapshot {
                capture: res(metadata.resolution.capture),
                display: res(metadata.resolution.display),
            },
            xml: metadata.xml.iter().map(|x| x.payload.len()).collect(),
            uuid: metadata
                .uuid
                .iter()
                .map(|u| (hex(&u.id), u.payload.len()))
                .collect(),
            ipr: metadata.ipr.iter().map(|b| b.payload.len()).collect(),
            uuid_info: metadata
                .uuid_info
                .iter()
                .map(|u| (u.ids.iter().map(hex).collect(), u.location.len()))
                .collect(),
        }
    }
}

/// The reference-grid image area (`Xsiz - XOsiz` by `Ysiz - YOsiz`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ImageGeometry {
    pub width: u32,
    pub height: u32,
}

/// One component's oracle samples and the geometry they are laid out against.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ComponentSnapshot {
    pub width: u32,
    pub height: u32,
    /// Bits per sample as declared in SIZ.
    pub bit_depth: u8,
    /// Whether samples are signed (SIZ component sign bit).
    pub signed: bool,
    /// Sub-sampling factors (SIZ `XRsiz`/`YRsiz`); `1` means unit sampling.
    pub x_sampling: u8,
    pub y_sampling: u8,
    /// `width * height` reference samples, row-major. `i32` mirrors
    /// [`rust_j2k::Component::samples`], so the harness compares like-for-like.
    pub samples: Vec<i32>,
}

/// Sample-grid geometry, matching the SIZ-declared component shape.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Geometry {
    pub width: u32,
    pub height: u32,
    /// Bits per sample as declared in SIZ.
    pub bit_depth: u8,
    /// Whether samples are signed (SIZ component sign bit).
    pub signed: bool,
}

impl ComponentSnapshot {
    /// This component's geometry, for comparing against a decoded component.
    pub fn geometry(&self) -> Geometry {
        Geometry {
            width: self.width,
            height: self.height,
            bit_depth: self.bit_depth,
            signed: self.signed,
        }
    }
}

/// How exactly a decode must match the oracle.
///
/// Serializes as a tagged object so both arms read the same in JSON:
///
/// ```json
/// "tolerance": { "mode": "exact" }
/// "tolerance": { "mode": "absolute", "max_abs_error": 1.0 }
/// ```
///
/// Reversible (5/3, lossless) fixtures use [`Tolerance::Exact`]; irreversible
/// (9/7, lossy) fixtures use [`Tolerance::Absolute`] with a per-sample bound.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(tag = "mode", rename_all = "snake_case")]
pub enum Tolerance {
    /// Every sample must equal the oracle exactly (bit-exact lossless).
    Exact,
    /// Each sample may differ from the oracle by at most `max_abs_error` in
    /// absolute value.
    Absolute { max_abs_error: f64 },
}

/// Where a fixture came from and the exact command that regenerates its oracle,
/// so the corpus stays reproducible without the reference decoder installed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Provenance {
    /// The source the codestream was taken from, e.g.
    /// `"fieldglass/jpeg2000_regular_latlon.grib2"`.
    pub source: String,
    /// The exact command that regenerates this snapshot, e.g. an
    /// `opj_decompress …` or eccodes invocation.
    pub oracle_command: String,
    /// Optional free-form note (how the source was obtained, caveats).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub notes: Option<String>,
}

impl Expected {
    /// Parse an `<name>.expected.json` snapshot from its JSON text.
    pub fn from_json(text: &str) -> serde_json::Result<Self> {
        serde_json::from_str(text)
    }
}

impl Geometry {
    /// Number of samples a correct snapshot must carry (`width * height`).
    pub fn sample_count(self) -> usize {
        self.width as usize * self.height as usize
    }
}

// ---------------------------------------------------------------------------
// Harness: discovery, comparison, and outcome classification.
// ---------------------------------------------------------------------------

/// One discovered fixture: a `<name>.j2k` codestream and the snapshot loaded
/// from its sibling `<name>.expected.json`.
///
/// `expected` is itself a `Result` so a fixture with a missing or malformed
/// snapshot is surfaced loudly (as a [`Outcome::LoadError`]) rather than
/// silently skipped — a broken corpus is a test failure, not a no-op.
#[derive(Debug)]
pub struct Fixture {
    /// Fixture stem (the file name without the `.j2k` extension).
    pub name: String,
    /// Path to the codestream passed to [`rust_j2k::decode`].
    pub codestream: PathBuf,
    /// The parsed oracle snapshot, or why it could not be loaded.
    pub expected: Result<Expected, String>,
}

/// The result of running one fixture through the decoder and comparator.
#[derive(Debug, Clone, PartialEq)]
pub enum Outcome {
    /// Decode produced an image that agrees with the oracle.
    Passed,
    /// Decode ran but disagreed with the oracle, the decoder rejected a
    /// known-good fixture, or the decode panicked (a contract violation:
    /// `decode` promises a typed error for every input). The [`Mismatch`]
    /// carries a readable diff.
    Failed(Mismatch),
    /// The fixture itself is broken: its snapshot is missing, unreadable, or
    /// does not parse. Distinct from `Failed` so a corpus bug is not mistaken
    /// for a decoder bug.
    LoadError(String),
}

/// A readable account of why a decode disagreed with its oracle: either the
/// geometry differs, or the first sample that falls outside tolerance.
#[derive(Debug, Clone, PartialEq)]
pub enum Mismatch {
    /// A component's decoded geometry differs from the oracle's.
    Geometry {
        component: usize,
        expected: Geometry,
        actual: Geometry,
    },
    /// A sample differs by more than the allowed bound. Reports the *first*
    /// such sample in row-major order so a failure points at one coordinate.
    Sample {
        component: usize,
        index: usize,
        x: u32,
        y: u32,
        expected: i32,
        actual: i32,
        /// Allowed absolute error (`0.0` for an exact/reversible fixture).
        bound: f64,
    },
    /// The decode produced an error instead of an image, or disagreed with the
    /// oracle about the image's shape rather than its samples.
    DecodeError(String),
}

impl fmt::Display for Mismatch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Mismatch::Geometry {
                component,
                expected,
                actual,
            } => write!(
                f,
                "component {component} geometry mismatch: expected {}x{} (depth {}, signed {}), \
                 got {}x{} (depth {}, signed {})",
                expected.width,
                expected.height,
                expected.bit_depth,
                expected.signed,
                actual.width,
                actual.height,
                actual.bit_depth,
                actual.signed,
            ),
            Mismatch::Sample {
                component,
                index,
                x,
                y,
                expected,
                actual,
                bound,
            } => write!(
                f,
                "component {component} sample #{index} at ({x},{y}): expected {expected}, \
                 got {actual} (|diff| = {} exceeds bound {bound})",
                (*actual as i64 - *expected as i64).abs(),
            ),
            Mismatch::DecodeError(msg) => {
                write!(f, "decoder rejected a known-good fixture: {msg}")
            }
        }
    }
}

/// Discover every `<name>.j2k` fixture in `dir`, pairing each with the snapshot
/// from its sibling `<name>.expected.json`.
///
/// Fixtures are returned sorted by name for deterministic test output. A
/// directory that cannot be read is an error, not an empty corpus; a
/// codestream whose snapshot is missing or unparseable is still returned, with
/// the reason captured in [`Fixture::expected`].
pub fn discover(dir: &Path) -> std::io::Result<Vec<Fixture>> {
    let mut fixtures: Vec<Fixture> = std::fs::read_dir(dir)?
        .filter_map(|e| e.ok().map(|e| e.path()))
        .filter(|p| p.extension().is_some_and(|ext| ext == "j2k"))
        .map(|codestream| {
            let name = codestream
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("<non-utf8>")
                .to_string();
            let snapshot = codestream.with_extension("expected.json");
            let expected = load_snapshot(&snapshot);
            Fixture {
                name,
                codestream,
                expected,
            }
        })
        .collect();
    fixtures.sort_by(|a, b| a.name.cmp(&b.name));
    Ok(fixtures)
}

/// Read and parse one `<name>.expected.json`, mapping every failure to a
/// human-readable reason string.
///
/// Also checks the snapshot is internally consistent — `samples.len()` must
/// equal the declared `width * height` — so a malformed oracle is caught here
/// (as a [`Outcome::LoadError`]) rather than silently under-comparing later.
fn load_snapshot(path: &Path) -> Result<Expected, String> {
    let text = std::fs::read_to_string(path)
        .map_err(|e| format!("cannot read {}: {e}", path.display()))?;
    let expected =
        Expected::from_json(&text).map_err(|e| format!("cannot parse {}: {e}", path.display()))?;
    if expected.components.is_empty() {
        return Err(format!("malformed {}: no components", path.display()));
    }
    for (index, component) in expected.components.iter().enumerate() {
        let want = component.geometry().sample_count();
        if component.samples.len() != want {
            return Err(format!(
                "malformed {}: component {index} is {}x{} = {want} samples but the array has {}",
                path.display(),
                component.width,
                component.height,
                component.samples.len(),
            ));
        }
    }
    Ok(expected)
}

/// Compare a decoded [`Image`] against an oracle snapshot.
///
/// The image area, the component count, and each component's geometry must match
/// exactly; then each sample must agree within the snapshot's tolerance —
/// bit-exact for [`Tolerance::Exact`], within an absolute bound for
/// [`Tolerance::Absolute`]. Returns the first divergence so a failure localizes
/// to a single cause.
pub fn compare(actual: &Image, expected: &Expected) -> Result<(), Mismatch> {
    let actual_image = ImageGeometry {
        width: actual.width,
        height: actual.height,
    };
    if actual_image != expected.image {
        return Err(Mismatch::DecodeError(format!(
            "image area is {}x{} but the snapshot says {}x{}",
            actual.width, actual.height, expected.image.width, expected.image.height,
        )));
    }
    if actual.components.len() != expected.components.len() {
        return Err(Mismatch::DecodeError(format!(
            "decoded {} components but the snapshot has {}",
            actual.components.len(),
            expected.components.len(),
        )));
    }

    if let Some(want) = &expected.jp2 {
        let got = actual.jp2.as_ref().map(Jp2Snapshot::of);
        if got.as_ref() != Some(want) {
            return Err(Mismatch::DecodeError(format!(
                "JP2 metadata is {got:?} but the snapshot says {want:?}"
            )));
        }
    }

    if let Some(want) = &expected.jp2_boxes {
        let got = actual.jp2.as_ref().map(Jp2Boxes::of);
        if got.as_ref() != Some(want) {
            return Err(Mismatch::DecodeError(format!(
                "JP2 box fields are {got:?} but the snapshot says {want:?}"
            )));
        }
    }

    for (component_index, (component, want)) in actual
        .components
        .iter()
        .zip(&expected.components)
        .enumerate()
    {
        compare_component(component_index, component, want, expected.tolerance)?;
    }
    Ok(())
}

/// Compare one decoded component against its snapshot.
fn compare_component(
    component: usize,
    actual: &rust_j2k::Component,
    expected: &ComponentSnapshot,
    tolerance: Tolerance,
) -> Result<(), Mismatch> {
    let actual_geometry = Geometry {
        width: actual.width,
        height: actual.height,
        bit_depth: actual.bit_depth,
        signed: actual.signed,
    };
    if actual_geometry != expected.geometry() {
        return Err(Mismatch::Geometry {
            component,
            expected: expected.geometry(),
            actual: actual_geometry,
        });
    }
    if (actual.x_sampling, actual.y_sampling) != (expected.x_sampling, expected.y_sampling) {
        return Err(Mismatch::DecodeError(format!(
            "component {component} sub-samples ({}, {}) but the snapshot says ({}, {})",
            actual.x_sampling, actual.y_sampling, expected.x_sampling, expected.y_sampling,
        )));
    }
    // Matching geometry already implies matching sample counts, but the loop
    // below zips the two vectors: a short one would compare only its prefix.
    if actual.samples.len() != expected.samples.len() {
        return Err(Mismatch::DecodeError(format!(
            "component {component} decoded {} samples but the snapshot has {}",
            actual.samples.len(),
            expected.samples.len(),
        )));
    }

    let bound = match tolerance {
        Tolerance::Exact => 0.0,
        Tolerance::Absolute { max_abs_error } => max_abs_error,
    };
    let width = expected.width;
    for (index, (&got, &want)) in actual.samples.iter().zip(&expected.samples).enumerate() {
        // i64 so the subtraction cannot overflow at the i32 extremes.
        let diff = (got as i64 - want as i64).abs() as f64;
        if diff > bound {
            return Err(Mismatch::Sample {
                component,
                index,
                x: (index as u32) % width,
                y: (index as u32) / width,
                expected: want,
                actual: got,
                bound,
            });
        }
    }
    Ok(())
}

/// Map the result of a (panic-guarded) decode to an [`Outcome`].
///
/// - a panic ⇒ `Failed`: `decode` promises a typed error for every input, so
///   a panic is a contract violation, not a not-yet-implemented feature;
/// - `Ok(image)` ⇒ compared against the oracle ⇒ `Passed` or `Failed`;
/// - `Err(e)` ⇒ `Failed`, since the decoder rejected a fixture the oracle decoded.
pub fn classify(
    decoded: std::thread::Result<Result<Image, Error>>,
    expected: &Expected,
) -> Outcome {
    match decoded {
        Err(_) => Outcome::Failed(Mismatch::DecodeError(
            "panicked (decode must return a typed error for every input)".into(),
        )),
        Ok(Ok(image)) => match compare(&image, expected) {
            Ok(()) => Outcome::Passed,
            Err(mismatch) => Outcome::Failed(mismatch),
        },
        Ok(Err(e)) => Outcome::Failed(Mismatch::DecodeError(e.to_string())),
    }
}

/// Run one fixture end to end: load its bytes, decode under a panic guard, and
/// classify the result against its snapshot.
pub fn run_fixture(fixture: &Fixture) -> Outcome {
    let expected = match &fixture.expected {
        Ok(expected) => expected,
        Err(reason) => return Outcome::LoadError(reason.clone()),
    };
    let bytes = match std::fs::read(&fixture.codestream) {
        Ok(bytes) => bytes,
        Err(e) => {
            return Outcome::LoadError(format!(
                "cannot read {}: {e}",
                fixture.codestream.display()
            ));
        }
    };

    // Catch a panic so one bad fixture reports as Failed instead of aborting
    // the whole suite. We deliberately leave the default panic hook in place —
    // the panic still prints one informative line to stderr — rather than
    // swapping the process-global hook, which races with other tests running
    // in parallel and could swallow a genuine panic's message.
    let decoded = panic::catch_unwind(panic::AssertUnwindSafe(|| rust_j2k::decode(&bytes)));

    classify(decoded, expected)
}