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
//! Conformance harness — the bar that defines "correct".
//!
//! Decode a corpus of real JPEG 2000 codestreams and compare against an oracle
//! produced by a trusted decoder (OpenJPEG, or eccodes' `grid_jpeg` decode for
//! the GRIB2-sourced ones). The agreement standard:
//!
//! - **reversible (5/3, lossless)** fixtures: bit-exact sample equality;
//! - **irreversible (9/7, lossy)** fixtures: within a stated absolute tolerance.
//!
//! Drop fixtures under `tests/fixtures/<name>.j2k` with a sibling
//! `<name>.expected.json` oracle (image area, tolerance, per-component
//! samples, provenance), and record each fixture's provenance (source file,
//! how the oracle was generated) so the corpus stays reproducible. Seed it from the GRIB2 §5.40 fixtures in the
//! fieldglass repo, plus a 9/7 re-encode for the irreversible path (no GRIB2
//! producer ships lossy 9/7). The `<name>.expected.json` schema lives in
//! [`support`].

mod support;

use std::path::PathBuf;

use support::{Outcome, discover, run_fixture};

/// The committed fixture corpus lives next to this test file.
fn fixtures_dir() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures")
}

/// How many top-level `tests/fixtures/*.j2k` codestreams are committed. Pinned
/// exactly so a deleted fixture cannot shrink the run silently; update it when
/// adding or removing one on purpose.
const TOP_LEVEL_FIXTURES: usize = 49;

/// Decode every committed fixture and grade it against its oracle snapshot.
///
/// Every fixture in this corpus is expected to decode: a rejection (including
/// `Unsupported`), an oracle disagreement, or a panic grades as
/// [`Outcome::Failed`], and a broken fixture as [`Outcome::LoadError`]; either
/// fails the gate.
#[test]
fn decodes_corpus_against_oracle() {
    let fixtures = discover(&fixtures_dir()).expect("read tests/fixtures");
    assert_eq!(
        fixtures.len(),
        TOP_LEVEL_FIXTURES,
        "the corpus changed size: a deleted fixture must fail, and an added one \
         must update TOP_LEVEL_FIXTURES",
    );

    let mut failures = Vec::new();
    for fixture in &fixtures {
        let outcome = run_fixture(fixture);
        match &outcome {
            Outcome::Passed => eprintln!("conformance: {} … ok", fixture.name),
            Outcome::Failed(m) => {
                eprintln!("conformance: {} … FAILED: {m}", fixture.name);
                failures.push(format!("{}: {m}", fixture.name));
            }
            Outcome::LoadError(e) => {
                eprintln!("conformance: {} … LOAD ERROR: {e}", fixture.name);
                failures.push(format!("{}: {e}", fixture.name));
            }
        }
    }

    assert!(
        failures.is_empty(),
        "{} fixture(s) failed the conformance gate:\n  {}",
        failures.len(),
        failures.join("\n  "),
    );
}

/// Harness behavior: discovery, the comparator, and outcome classification.
/// These exercise the harness with hand-built inputs so it is proven before
/// the real corpus (issue #4) and a working `decode` exist.
mod harness {
    use super::support::{
        ComponentSnapshot, Expected, Fixture, Geometry, ImageGeometry, Mismatch, Outcome,
        Provenance, Tolerance, classify, compare, discover, run_fixture,
    };
    use rust_j2k::{Component, Error, Image};
    use std::path::{Path, PathBuf};

    fn geometry(width: u32, height: u32) -> Geometry {
        Geometry {
            width,
            height,
            bit_depth: 16,
            signed: false,
        }
    }

    /// A one-component image at unit sub-sampling, so the image area and the
    /// component grid coincide — what the single-component snapshots describe.
    fn image(width: u32, height: u32, samples: Vec<i32>) -> Image {
        Image::new(
            width,
            height,
            vec![Component::new(width, height, 16, false, 1, 1, samples)],
        )
    }

    /// A single-component snapshot at unit sub-sampling, matching [`image`].
    fn snapshot(geometry: Geometry, tolerance: Tolerance, samples: Vec<i32>) -> Expected {
        Expected {
            image: ImageGeometry {
                width: geometry.width,
                height: geometry.height,
            },
            tolerance,
            components: vec![ComponentSnapshot {
                width: geometry.width,
                height: geometry.height,
                bit_depth: geometry.bit_depth,
                signed: geometry.signed,
                x_sampling: 1,
                y_sampling: 1,
                samples,
            }],
            provenance: Provenance {
                source: "test".into(),
                oracle_command: "n/a".into(),
                notes: None,
            },
            jp2: None,
            jp2_boxes: None,
        }
    }

    // --- comparator ---------------------------------------------------------

    #[test]
    fn exact_match_passes() {
        let want = snapshot(geometry(2, 2), Tolerance::Exact, vec![0, 1, 2, 3]);
        let got = image(2, 2, vec![0, 1, 2, 3]);
        assert_eq!(compare(&got, &want), Ok(()));
    }

    #[test]
    fn exact_reports_first_divergent_sample() {
        // Second row, second column (index 3) is the first divergence.
        let want = snapshot(geometry(2, 2), Tolerance::Exact, vec![0, 1, 2, 3]);
        let got = image(2, 2, vec![0, 1, 2, 9]);
        let err = compare(&got, &want).unwrap_err();
        assert_eq!(
            err,
            Mismatch::Sample {
                component: 0,
                index: 3,
                x: 1,
                y: 1,
                expected: 3,
                actual: 9,
                bound: 0.0,
            }
        );
    }

    #[test]
    fn absolute_within_bound_passes() {
        let want = snapshot(
            geometry(2, 1),
            Tolerance::Absolute { max_abs_error: 1.5 },
            vec![10, 20],
        );
        let got = image(2, 1, vec![11, 19]); // |diff| = 1 ≤ 1.5
        assert_eq!(compare(&got, &want), Ok(()));
    }

    #[test]
    fn absolute_outside_bound_fails() {
        let want = snapshot(
            geometry(2, 1),
            Tolerance::Absolute { max_abs_error: 1.5 },
            vec![10, 20],
        );
        let got = image(2, 1, vec![10, 23]); // |diff| = 3 > 1.5 at index 1
        let err = compare(&got, &want).unwrap_err();
        assert_eq!(
            err,
            Mismatch::Sample {
                component: 0,
                index: 1,
                x: 1,
                y: 0,
                expected: 20,
                actual: 23,
                bound: 1.5,
            }
        );
    }

    #[test]
    fn component_geometry_mismatch_fails_before_samples() {
        // Same image area and sample count; the component's declared depth is
        // what disagrees, so the samples are never reached.
        let mut want = snapshot(geometry(2, 2), Tolerance::Exact, vec![0, 0, 0, 0]);
        want.components[0].bit_depth = 8; // `image` decodes at depth 16
        let got = image(2, 2, vec![0, 0, 0, 0]);
        let err = compare(&got, &want).unwrap_err();
        assert!(
            matches!(err, Mismatch::Geometry { component: 0, .. }),
            "{err}"
        );
    }

    #[test]
    fn image_area_mismatch_is_reported_before_any_component() {
        let want = snapshot(geometry(2, 2), Tolerance::Exact, vec![0, 0, 0, 0]);
        let got = image(4, 1, vec![0, 0, 0, 0]); // same count, wrong shape
        let err = compare(&got, &want).unwrap_err();
        assert!(matches!(err, Mismatch::DecodeError(_)), "{err}");
    }

    #[test]
    fn component_count_mismatch_is_reported() {
        let mut want = snapshot(geometry(2, 2), Tolerance::Exact, vec![0, 0, 0, 0]);
        want.components.push(want.components[0].clone());
        let got = image(2, 2, vec![0, 0, 0, 0]);
        let err = compare(&got, &want).unwrap_err();
        assert!(matches!(err, Mismatch::DecodeError(_)), "{err}");
    }

    // --- classification -----------------------------------------------------

    #[test]
    fn panic_classifies_as_failed() {
        // `decode` promises a typed error for every input; a panic must fail
        // the gate, not slip through as anything softer.
        let want = snapshot(geometry(1, 1), Tolerance::Exact, vec![0]);
        let decoded =
            std::panic::catch_unwind(|| -> Result<Image, Error> { panic!("decoder bug") });
        assert!(matches!(
            classify(decoded, &want),
            Outcome::Failed(Mismatch::DecodeError(_))
        ));
    }

    #[test]
    fn ok_matching_classifies_as_passed() {
        let want = snapshot(geometry(1, 1), Tolerance::Exact, vec![42]);
        let decoded = Ok(Ok(image(1, 1, vec![42])));
        assert_eq!(classify(decoded, &want), Outcome::Passed);
    }

    #[test]
    fn ok_mismatch_classifies_as_failed() {
        let want = snapshot(geometry(1, 1), Tolerance::Exact, vec![42]);
        let decoded = Ok(Ok(image(1, 1, vec![7])));
        assert!(matches!(classify(decoded, &want), Outcome::Failed(_)));
    }

    #[test]
    fn decode_error_classifies_as_failed() {
        let want = snapshot(geometry(1, 1), Tolerance::Exact, vec![42]);
        let decoded = Ok(Err(rust_j2k::decode(b"nope").unwrap_err()));
        assert!(matches!(
            classify(decoded, &want),
            Outcome::Failed(Mismatch::DecodeError(_))
        ));
    }

    // --- discovery ----------------------------------------------------------

    /// A unique scratch directory under the test binary's temp dir, so discovery
    /// can be exercised against synthetic fixtures without a committed corpus.
    fn scratch(tag: &str) -> PathBuf {
        let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!("discover-{tag}"));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    fn write(dir: &Path, name: &str, contents: &str) {
        std::fs::write(dir.join(name), contents).unwrap();
    }

    const VALID_SNAPSHOT: &str = r#"{
  "image": { "width": 1, "height": 1 },
  "tolerance": { "mode": "exact" },
  "components": [
    { "width": 1, "height": 1, "bit_depth": 8, "signed": false,
      "x_sampling": 1, "y_sampling": 1, "samples": [0] }
  ],
  "provenance": { "source": "s", "oracle_command": "c" }
}"#;

    #[test]
    fn discovers_paired_fixture() {
        let dir = scratch("paired");
        // Not a real codestream, so end to end it classifies as Failed
        // (the decoder rightly rejects non-codestream bytes). What is under
        // test here is discovery: the `.j2k` is paired with its snapshot and
        // run end to end. The panic path is covered by `panic_classifies_as_failed`.
        write(&dir, "alpha.j2k", "\x00not-a-codestream");
        write(&dir, "alpha.expected.json", VALID_SNAPSHOT);

        let found = discover(&dir).unwrap();
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].name, "alpha");
        assert!(found[0].expected.is_ok());
        assert!(matches!(
            run_fixture(&found[0]),
            Outcome::Failed(Mismatch::DecodeError(_))
        ));
    }

    #[test]
    fn missing_snapshot_is_a_load_error() {
        let dir = scratch("orphan-codestream");
        write(&dir, "lonely.j2k", "bytes");
        // no sibling .expected.json

        let found = discover(&dir).unwrap();
        assert_eq!(found.len(), 1);
        assert!(found[0].expected.is_err());
        assert!(matches!(run_fixture(&found[0]), Outcome::LoadError(_)));
    }

    #[test]
    fn malformed_snapshot_is_a_load_error() {
        let dir = scratch("malformed-snapshot");
        write(&dir, "broken.j2k", "bytes");
        write(&dir, "broken.expected.json", "{ not valid json");

        let found = discover(&dir).unwrap();
        assert_eq!(found.len(), 1);
        assert!(found[0].expected.is_err());
        assert!(matches!(run_fixture(&found[0]), Outcome::LoadError(_)));
    }

    #[test]
    fn snapshot_with_wrong_sample_count_is_a_load_error() {
        let dir = scratch("wrong-count");
        write(&dir, "bad.j2k", "bytes");
        // The component declares 2x2 = 4 samples, but only 3 are listed. The
        // JSON itself is well-formed, so this must fail the consistency check,
        // not deserialization.
        write(
            &dir,
            "bad.expected.json",
            r#"{
  "image": { "width": 2, "height": 2 },
  "tolerance": { "mode": "exact" },
  "components": [
    { "width": 2, "height": 2, "bit_depth": 8, "signed": false,
      "x_sampling": 1, "y_sampling": 1, "samples": [0, 1, 2] }
  ],
  "provenance": { "source": "s", "oracle_command": "c" }
}"#,
        );

        let found = discover(&dir).unwrap();
        assert_eq!(found.len(), 1);
        let reason = found[0].expected.as_ref().expect_err("must not load");
        assert!(
            reason.contains("4 samples but the array has 3"),
            "must fail the sample-count check, not parsing: {reason}"
        );
        assert!(matches!(run_fixture(&found[0]), Outcome::LoadError(_)));
    }

    #[test]
    fn discovery_is_sorted_and_ignores_other_files() {
        let dir = scratch("sorted");
        write(&dir, "beta.j2k", "bytes");
        write(&dir, "beta.expected.json", VALID_SNAPSHOT);
        write(&dir, "alpha.j2k", "bytes");
        write(&dir, "alpha.expected.json", VALID_SNAPSHOT);
        write(&dir, "notes.txt", "ignore me");

        let names: Vec<_> = discover(&dir)
            .unwrap()
            .into_iter()
            .map(|f| f.name)
            .collect();
        assert_eq!(names, vec!["alpha", "beta"]);
    }

    #[test]
    fn missing_directory_is_an_error() {
        let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("does-not-exist-xyz");
        let _ = std::fs::remove_dir_all(&dir);
        assert!(discover(&dir).is_err());
    }

    // Touch `Fixture` directly so the type is exercised by name.
    #[test]
    fn fixture_load_error_short_circuits_run() {
        let fixture = Fixture {
            name: "x".into(),
            codestream: PathBuf::from("/nonexistent/x.j2k"),
            expected: Err("synthetic load error".into()),
        };
        assert!(matches!(run_fixture(&fixture), Outcome::LoadError(_)));
    }
}

mod expected_schema {
    use super::support::{Expected, Geometry, Provenance, Tolerance};

    /// A reversible (lossless) snapshot: one 2x2 component, exact agreement.
    /// Kept in sync with the documented example in `tests/fixtures/README.md`.
    const EXACT_JSON: &str = r#"{
  "image": { "width": 2, "height": 2 },
  "tolerance": { "mode": "exact" },
  "components": [
    { "width": 2, "height": 2, "bit_depth": 16, "signed": false,
      "x_sampling": 1, "y_sampling": 1, "samples": [0, 1, 2, 3] }
  ],
  "provenance": {
    "source": "fieldglass/jpeg2000_regular_latlon.grib2",
    "oracle_command": "opj_decompress -i sample.j2k -o sample.pgx"
  }
}"#;

    /// An irreversible (lossy) snapshot: bounded absolute error, plus an
    /// optional provenance note.
    const ABSOLUTE_JSON: &str = r#"{
  "image": { "width": 2, "height": 1 },
  "tolerance": { "mode": "absolute", "max_abs_error": 1.5 },
  "components": [
    { "width": 2, "height": 1, "bit_depth": 12, "signed": true,
      "x_sampling": 1, "y_sampling": 1, "samples": [-2, 7] }
  ],
  "provenance": {
    "source": "hrrr/sample.grib2",
    "oracle_command": "grib_to_jpeg ...",
    "notes": "9/7 lossy path"
  }
}"#;

    /// A sub-sampled two-component snapshot: the components sit on smaller grids
    /// than the reference-grid image area.
    const SUBSAMPLED_JSON: &str = r#"{
  "image": { "width": 3, "height": 3 },
  "tolerance": { "mode": "exact" },
  "components": [
    { "width": 3, "height": 3, "bit_depth": 8, "signed": false,
      "x_sampling": 1, "y_sampling": 1, "samples": [1,2,3,4,5,6,7,8,9] },
    { "width": 2, "height": 2, "bit_depth": 8, "signed": false,
      "x_sampling": 2, "y_sampling": 2, "samples": [1,2,3,4] }
  ],
  "provenance": { "source": "s", "oracle_command": "c" }
}"#;

    #[test]
    fn parses_exact_reversible_snapshot() {
        let expected = Expected::from_json(EXACT_JSON).expect("parse exact snapshot");

        assert_eq!(expected.image.width, 2);
        assert_eq!(expected.image.height, 2);
        assert_eq!(expected.components.len(), 1);
        let component = &expected.components[0];
        assert_eq!(
            component.geometry(),
            Geometry {
                width: 2,
                height: 2,
                bit_depth: 16,
                signed: false,
            }
        );
        assert_eq!(expected.tolerance, Tolerance::Exact);
        assert_eq!(component.samples, vec![0, 1, 2, 3]);
        assert_eq!(component.samples.len(), component.geometry().sample_count());
        assert_eq!(expected.provenance.notes, None);
    }

    #[test]
    fn parses_absolute_irreversible_snapshot() {
        let expected = Expected::from_json(ABSOLUTE_JSON).expect("parse absolute snapshot");

        assert_eq!(
            expected.tolerance,
            Tolerance::Absolute { max_abs_error: 1.5 }
        );
        let component = &expected.components[0];
        assert_eq!(component.samples, vec![-2, 7]);
        assert_eq!(component.samples.len(), component.geometry().sample_count());
        assert_eq!(expected.provenance.source, "hrrr/sample.grib2");
        assert_eq!(expected.provenance.notes.as_deref(), Some("9/7 lossy path"));
    }

    /// A sub-sampled component sits on a smaller grid than the image area, and
    /// the snapshot records both.
    #[test]
    fn parses_subsampled_multi_component_snapshot() {
        let expected = Expected::from_json(SUBSAMPLED_JSON).expect("parse subsampled snapshot");
        assert_eq!((expected.image.width, expected.image.height), (3, 3));
        assert_eq!(expected.components.len(), 2);

        let luma = &expected.components[0];
        assert_eq!((luma.width, luma.height), (3, 3));
        assert_eq!((luma.x_sampling, luma.y_sampling), (1, 1));

        let chroma = &expected.components[1];
        assert_eq!((chroma.width, chroma.height), (2, 2));
        assert_eq!((chroma.x_sampling, chroma.y_sampling), (2, 2));
        assert_eq!(chroma.samples.len(), chroma.geometry().sample_count());
    }

    #[test]
    fn round_trips_through_serde() {
        // Deserialize -> serialize -> deserialize must be a fixed point, so the
        // committed JSON and the schema can never silently drift apart.
        let parsed = Expected::from_json(EXACT_JSON).expect("parse");
        let reserialized = serde_json::to_string(&parsed).expect("serialize");
        let reparsed = Expected::from_json(&reserialized).expect("reparse");
        assert_eq!(parsed, reparsed);
    }

    #[test]
    fn omitted_optional_note_defaults_to_none() {
        let json = r#"{
  "image": { "width": 1, "height": 1 },
  "tolerance": { "mode": "exact" },
  "components": [
    { "width": 1, "height": 1, "bit_depth": 8, "signed": false,
      "x_sampling": 1, "y_sampling": 1, "samples": [42] }
  ],
  "provenance": { "source": "s", "oracle_command": "c" }
}"#;
        let expected = Expected::from_json(json).expect("parse without notes");
        assert_eq!(
            expected.provenance,
            Provenance {
                source: "s".to_string(),
                oracle_command: "c".to_string(),
                notes: None,
            }
        );
    }

    #[test]
    fn rejects_unknown_field() {
        // A typo'd key (here `sample` instead of `samples`) must fail loudly
        // rather than silently deserialize to an empty grid.
        let json = r#"{
  "image": { "width": 1, "height": 1 },
  "tolerance": { "mode": "exact" },
  "components": [
    { "width": 1, "height": 1, "bit_depth": 8, "signed": false,
      "x_sampling": 1, "y_sampling": 1, "sample": [0] }
  ],
  "provenance": { "source": "s", "oracle_command": "c" }
}"#;
        let error = Expected::from_json(json).expect_err("a typo'd key must not parse");
        assert!(
            error.to_string().contains("unknown field `sample`"),
            "must fail on the typo'd key: {error}"
        );
    }

    #[test]
    fn rejects_unknown_tolerance_mode() {
        let json = r#"{
  "image": { "width": 1, "height": 1 },
  "tolerance": { "mode": "relative", "max_abs_error": 1.0 },
  "components": [
    { "width": 1, "height": 1, "bit_depth": 8, "signed": false,
      "x_sampling": 1, "y_sampling": 1, "samples": [0] }
  ],
  "provenance": { "source": "s", "oracle_command": "c" }
}"#;
        let error = Expected::from_json(json).expect_err("an unknown mode must not parse");
        assert!(
            error.to_string().contains("unknown variant `relative`"),
            "must fail on the tolerance mode: {error}"
        );
    }
}