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
//! With `strict` off, under a window, a tile or a component subset, the
//! report describes what the decode returns: the tiles it reads, the
//! components it reconstructs, and the code-blocks the window's samples
//! depend on. Data the returned samples do not need does not make the image
//! look incomplete, and data they do need is still reported.

use std::collections::HashMap;
use std::path::PathBuf;

use rust_j2k::{DecodeOptions, Image, Region, ReportEntry, Window, decode_with, read_header};

fn read(path: &str) -> Vec<u8> {
    let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(path);
    std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()))
}

fn lenient() -> DecodeOptions {
    DecodeOptions::default().with_strict(false)
}

fn decode_ok(bytes: &[u8], options: &DecodeOptions, what: &str) -> Image {
    decode_with(bytes, options).unwrap_or_else(|e| panic!("{what}: {e}"))
}

/// A cut of `bytes` at `percent` of its length.
fn cut(bytes: &[u8], percent: usize) -> &[u8] {
    &bytes[..bytes.len() * percent / 100]
}

/// `precincts_cprl_lossless` is one tile of three components, no color
/// transform, in component-major order: by 70% of the file every packet of
/// component 0 is there. A decode of component 0 alone gives the uncut
/// samples, and the report says it is complete; the whole image's report
/// still has packets missing.
#[test]
fn a_component_whose_packets_are_all_there_is_complete() {
    let bytes = read("tests/fixtures/precincts_cprl_lossless.j2k");
    let first = lenient().with_components(Some(vec![0]));
    let uncut = decode_ok(&bytes, &first, "uncut");
    for percent in 70..=97 {
        let prefix = cut(&bytes, percent);
        let part = decode_ok(prefix, &first, "component 0");
        assert_eq!(part.components, uncut.components, "{percent}%");
        assert!(part.report.is_complete(), "{percent}%: {:?}", part.report);
        assert_eq!(part.report.complete_reduction, Some(0), "{percent}%");
        let whole = decode_ok(prefix, &lenient(), "the whole image");
        assert!(!whole.report.is_complete(), "{percent}%");
        // The components whose packets are cut are still reported.
        let last = lenient().with_components(Some(vec![2]));
        let part = decode_ok(prefix, &last, "component 2");
        assert!(!part.report.is_complete(), "{percent}%");
        assert_ne!(
            part.components,
            decode_ok(&bytes, &last, "uncut").components
        );
    }
    // Cut inside component 0's packets, its samples differ, and the report
    // says so.
    let prefix = cut(&bytes, 20);
    let part = decode_ok(prefix, &first, "component 0 at 20%");
    assert_ne!(part.components, uncut.components);
    assert!(!part.report.is_complete(), "{:?}", part.report);
}

/// A window of the top-left 8 x 8 samples of component 0 needs only the
/// first precinct of each resolution, which are the first packets of the
/// file: cut at 15%, the samples are the uncut ones and the report is
/// complete, at reduction 0 as at every coarser one. The whole of component
/// 0 is not.
#[test]
fn a_window_whose_code_blocks_are_all_there_is_complete() {
    let bytes = read("tests/fixtures/precincts_cprl_lossless.j2k");
    let prefix = cut(&bytes, 15);
    let first = lenient().with_components(Some(vec![0]));
    let window = first
        .clone()
        .with_region(Region::Window(Window::new(0, 0, 8, 8)));
    let part = decode_ok(prefix, &window, "the window");
    assert_eq!(
        part.components,
        decode_ok(&bytes, &window, "uncut").components
    );
    assert!(part.report.is_complete(), "{:?}", part.report);
    assert_eq!(part.report.complete_reduction, Some(0));
    let all = decode_ok(prefix, &first, "component 0");
    assert!(!all.report.is_complete());
    // A window over the bottom-right corner needs the last precincts of
    // component 0, which the cut leaves out.
    let far = first.with_region(Region::Window(Window::new(100, 80, 128, 96)));
    let part = decode_ok(prefix, &far, "the far window");
    assert!(!part.report.is_complete(), "{:?}", part.report);
    assert_ne!(part.components, decode_ok(&bytes, &far, "uncut").components);
}

/// A decode at reduction 1 reports the reduction-0 decode's
/// `complete_reduction`, counted at reduction 0 over the code-blocks the
/// window needs there, which reach finer resolutions than at reduction 1.
#[test]
fn complete_reduction_is_counted_with_the_finer_reductions_footprint() {
    let bytes = read("tests/fixtures/precincts_cprl_lossless.j2k");
    let prefix = &bytes[..32340];
    let options = lenient()
        .with_region(Region::Window(Window::new(38, 67, 40, 85)))
        .with_components(Some(vec![2, 0]));
    let fine = decode_ok(prefix, &options, "-r 0");
    let coarse = decode_ok(
        prefix,
        &options.clone().with_resolution_reduction(1),
        "-r 1",
    );
    assert!(!fine.report.is_complete(), "{:?}", fine.report);
    assert_eq!(
        coarse.report.complete_reduction,
        fine.report.complete_reduction
    );
    assert_ne!(coarse.report.complete_reduction, Some(0));
}

/// Under a layer cap, a code-block missing a packet of a layer the cap keeps
/// is missing, whatever later layers it also lacks.
#[test]
fn a_layer_cap_counts_the_first_layer_missing() {
    let bytes = read("tests/fixtures/precincts_cprl_lossless.j2k");
    let prefix = &bytes[..133];
    let options = lenient()
        .with_max_quality_layers(Some(1))
        .with_components(Some(vec![2]));
    let part = decode_ok(prefix, &options, "cut");
    let uncut = decode_ok(&bytes, &options, "uncut");
    assert_ne!(part.components, uncut.components);
    assert!(!part.report.is_complete(), "{:?}", part.report);
}

/// A splitmix64 stream: small, and the same on every platform.
struct Rng(u64);

impl Rng {
    fn next(&mut self) -> u64 {
        self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
        let mut z = self.0;
        z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
        z ^ (z >> 31)
    }

    /// A value in `0..n`.
    fn below(&mut self, n: u32) -> u32 {
        (self.next() % u64::from(n.max(1))) as u32
    }
}

/// The tile grid of a raw codestream, from its SIZ marker, which follows
/// SOC: the image area `XOsiz..Xsiz` by `YOsiz..Ysiz`, the tile size and the
/// tile grid's origin.
struct Grid {
    image: (u32, u32, u32, u32),
    tile: (u32, u32),
    origin: (u32, u32),
}

impl Grid {
    fn of(bytes: &[u8]) -> Self {
        assert_eq!(&bytes[..4], &[0xff, 0x4f, 0xff, 0x51], "SOC then SIZ");
        let word = |at: usize| u32::from_be_bytes(bytes[at..at + 4].try_into().unwrap());
        Grid {
            image: (word(16), word(20), word(8), word(12)),
            tile: (word(24), word(28)),
            origin: (word(32), word(36)),
        }
    }

    /// The tiles across.
    fn across(&self) -> u32 {
        (self.image.2 - self.origin.0).div_ceil(self.tile.0)
    }

    /// The indices of the tiles that hold part of `window`.
    fn tiles(&self, window: Window) -> Vec<u32> {
        let (ix0, iy0, ix1, iy1) = self.image;
        let (x0, y0) = (window.x0.max(ix0), window.y0.max(iy0));
        let (x1, y1) = (window.x1.min(ix1), window.y1.min(iy1));
        let (tw, th) = self.tile;
        let (ox, oy) = self.origin;
        let mut out = Vec::new();
        for ty in (y0 - oy) / th..(y1 - oy).div_ceil(th) {
            for tx in (x0 - ox) / tw..(x1 - ox).div_ceil(tw) {
                out.push(ty * self.across() + tx);
            }
        }
        out
    }
}

/// Where each tile's data ends in `bytes`: the end of its last tile-part,
/// found by stepping from the first `SOT` by each `Psot`.
fn tile_ends(bytes: &[u8]) -> Vec<usize> {
    let mut at = bytes
        .windows(2)
        .position(|w| w == [0xFF, 0x90])
        .expect("an SOT");
    let mut ends = Vec::new();
    while bytes[at..at + 2] == [0xFF, 0x90] {
        let tile = usize::from(u16::from_be_bytes([bytes[at + 4], bytes[at + 5]]));
        let psot = u32::from_be_bytes(bytes[at + 6..at + 10].try_into().unwrap()) as usize;
        assert_ne!(psot, 0, "the fixtures give every Psot");
        if ends.len() <= tile {
            ends.resize(tile + 1, 0);
        }
        ends[tile] = at + psot;
        at += psot;
    }
    ends
}

/// The samples of `whole`'s component `c` inside `window` cut to `image`,
/// at reduction `r`.
fn crop(whole: &Image, c: usize, image: (u32, u32, u32, u32), window: Window, r: u8) -> Vec<i32> {
    let at = |v: u32, d: u32| v.div_ceil(d).div_ceil(1 << r);
    let plane = &whole.components[c];
    let (dx, dy) = (u32::from(plane.x_sampling), u32::from(plane.y_sampling));
    let (x0, y0) = (window.x0.max(image.0), window.y0.max(image.1));
    let (x1, y1) = (window.x1.min(image.2), window.y1.min(image.3));
    let (ox, oy) = (at(image.0, dx), at(image.1, dy));
    let mut out = Vec::new();
    for y in at(y0, dy)..at(y1, dy) {
        for x in at(x0, dx)..at(x1, dx) {
            out.push(plane.samples[((y - oy) * plane.width + (x - ox)) as usize]);
        }
    }
    out
}

/// A random window on the image area: mostly small, so it falls inside a
/// tile and a few of its precincts, sometimes wide.
fn window(rng: &mut Rng, image: (u32, u32, u32, u32)) -> Window {
    let (x0, y0, x1, y1) = image;
    let mut axis = |lo: u32, hi: u32| {
        let start = lo + rng.below(hi - lo);
        let reach = [4, 16, 48, hi - lo][rng.below(4) as usize];
        (start, (start + 1 + rng.below(reach)).min(hi))
    };
    let (wx0, wx1) = axis(x0, x1);
    let (wy0, wy1) = axis(y0, y1);
    Window::new(wx0, wy0, wx1, wy1)
}

/// The uncut decode and, per cut, whether the whole image's report is
/// complete.
type Whole = (Image, HashMap<usize, bool>);

/// One decode of a cut: its `complete_reduction`, whether it is complete,
/// and whether its samples are the uncut ones.
type Outcome = (Option<u8>, bool, bool);

/// How the decodes of [`check`] came out.
struct Counts {
    /// Reported complete. The counts leave out the decodes of the whole
    /// image.
    complete: usize,
    /// Reported incomplete, with samples other than the uncut ones.
    incomplete: usize,
    /// Reported incomplete, with the uncut samples.
    same_incomplete: usize,
}

/// For random windows, component subsets and layer caps of `name`, each
/// decoded from a series of cuts at reductions 0 and 1:
///
/// - the report is complete only when the samples are the uncut ones;
/// - it is complete whenever the whole image's report at that cut is;
/// - it is complete whenever every tile the window reads is wholly there;
/// - once complete at a cut, it stays complete at every longer one;
/// - its `complete_reduction` is the same at both reductions, and a
///   reduction-1 decode that names reduction 0 is borne out by the
///   reduction-0 decode;
/// - few decodes that give the uncut samples are reported incomplete.
///
/// Returns how the decodes came out, so the caller can check each outcome
/// happened, and how often the report missed data the samples did not need.
fn check(name: &str, draws: usize, seed: u64) -> Counts {
    let bytes = read(name);
    let grid = Grid::of(&bytes);
    let ends = tile_ends(&bytes);
    let header = read_header(&bytes).unwrap();
    let components = header.components.len() as u16;
    let start = bytes.windows(2).position(|w| w == [0xFF, 0x90]).unwrap() + 14;
    let mut rng = Rng(seed);
    let mut counts = Counts {
        complete: 0,
        incomplete: 0,
        same_incomplete: 0,
    };
    // The uncut decode and, per cut, whether the whole image is complete,
    // for each reduction and layer cap.
    let mut wholes: HashMap<(u8, Option<u16>), Whole> = HashMap::new();
    for draw in 0..draws {
        // Twelve cuts spread over the tile data, three of them in its first
        // part, where the coarsest packets are, and the whole file.
        let mut cuts: Vec<usize> = (0..9)
            .map(|i| start + (bytes.len() - start) * i / 9)
            .chain((0..3).map(|_| start + rng.below(((bytes.len() - start) / 8) as u32) as usize))
            .chain([bytes.len()])
            .collect();
        cuts.sort_unstable();
        cuts.dedup();
        let window = (rng.below(4) != 0).then(|| window(&mut rng, grid.image));
        let subset = match rng.below(3) {
            0 => None,
            1 => Some(vec![rng.below(u32::from(components)) as u16]),
            _ => Some(vec![components - 1, 0]),
        };
        let cap = [None, Some(1), Some(2)][draw % 3];
        let returned: Vec<usize> = subset.as_ref().map_or_else(
            || (0..usize::from(components)).collect(),
            |s| s.iter().map(|&c| usize::from(c)).collect(),
        );
        // Per reduction, per cut: the report's `complete_reduction`, whether
        // it is complete, and whether the samples are the uncut ones. `None`
        // where the window holds no sample at that reduction.
        let mut outcomes: Vec<Option<Vec<Outcome>>> = Vec::new();
        for r in 0..2u8 {
            let base = lenient()
                .with_resolution_reduction(r)
                .with_max_quality_layers(cap);
            let (uncut, whole) = wholes
                .entry((r, cap))
                .or_insert_with(|| (decode_ok(&bytes, &base, name), HashMap::new()));
            let options = base
                .clone()
                .with_region(window.map_or(Region::Whole, Region::Window))
                .with_components(subset.clone());
            let what = format!("{name} -r {r} -l {cap:?} {window:?} {subset:?}");
            let expected: Vec<Vec<i32>> = returned
                .iter()
                .map(|&c| match window {
                    Some(w) => crop(uncut, c, grid.image, w, r),
                    None => uncut.components[c].samples.clone(),
                })
                .collect();
            // Where the last tile read ends.
            let read_end = match window {
                Some(w) => grid
                    .tiles(w)
                    .iter()
                    .map(|&t| ends[t as usize])
                    .max()
                    .unwrap(),
                None => *ends.iter().max().unwrap(),
            };
            let mut was_complete = false;
            let mut seen = Some(Vec::new());
            for &at in &cuts {
                let whole_complete = *whole
                    .entry(at)
                    .or_insert_with(|| decode_ok(&bytes[..at], &base, name).report.is_complete());
                let part = match decode_with(&bytes[..at], &options) {
                    Ok(part) => part,
                    // A window holding no sample of a component at this
                    // reduction is refused, whatever the cut.
                    Err(rust_j2k::Error::InvalidOptions(_)) => {
                        seen = None;
                        break;
                    }
                    Err(e) => panic!("{what} at {at}: {e}"),
                };
                let samples: Vec<&Vec<i32>> = part.components.iter().map(|c| &c.samples).collect();
                let same = samples.iter().zip(&expected).all(|(a, b)| *a == b);
                let is = part.report.is_complete();
                let report = &part.report;
                assert!(
                    !is || same,
                    "{what} at {at}: complete, but differs: {report:?}"
                );
                assert!(
                    !whole_complete || is,
                    "{what} at {at}: the whole is complete: {report:?}"
                );
                assert!(
                    at < read_end || is,
                    "{what} at {at}: every tile read is there: {report:?}"
                );
                assert!(
                    !was_complete || is,
                    "{what} at {at}: was complete at a shorter cut"
                );
                was_complete = is;
                // The whole image's report is not this test's to grade.
                if window.is_none() && subset.is_none() {
                } else if is {
                    counts.complete += 1;
                } else if same {
                    counts.same_incomplete += 1;
                } else {
                    counts.incomplete += 1;
                }
                if let Some(seen) = &mut seen {
                    seen.push((report.complete_reduction, is, same));
                }
            }
            outcomes.push(seen);
        }
        if let [Some(fine), Some(coarse)] = &outcomes[..] {
            let what = format!("{name} -l {cap:?} {window:?} {subset:?}");
            for ((at, f), c) in cuts.iter().zip(fine).zip(coarse) {
                assert_eq!(
                    f.0, c.0,
                    "{what} at {at}: complete_reduction at -r 0 and -r 1"
                );
                if c.0 == Some(0) {
                    assert!(f.1 && f.2, "{what} at {at}: -r 1 names reduction 0");
                }
            }
        }
    }
    counts
}

/// The randomized check on fixtures with precincts and layers, with tiles,
/// with a color transform, on 9/7 with sub-sampled components, and with
/// more layers and smaller precincts and code-blocks.
#[test]
fn random_windows_and_subsets_of_cut_codestreams_report_what_they_return() {
    for (seed, (name, draws)) in [
        ("tests/fixtures/precincts_cprl_lossless.j2k", 12),
        ("tests/fixtures/precincts_lrcp_lossless.j2k", 6),
        ("tests/fixtures/precincts_tiled_cprl_lossless.j2k", 6),
        ("tests/fixtures/window/tiled_53.j2k", 6),
        ("tests/fixtures/window/sub_97.j2k", 6),
        ("tests/fixtures/layers/precincts_pterm.j2k", 6),
    ]
    .into_iter()
    .enumerate()
    {
        let Counts {
            complete,
            incomplete,
            same_incomplete,
        } = check(name, draws, 500 + seed as u64);
        assert!(
            complete > 0 && incomplete > 0,
            "{name}: {complete} complete, {incomplete} not"
        );
        // Data the samples do not need can still be reported missing: a
        // packet that adds nothing, or a code-block of the footprint's
        // margin whose samples the window drops in the end. That is rare;
        // a report of whole tiles or every component makes it common.
        assert!(
            same_incomplete * 10 <= complete + same_incomplete,
            "{name}: {same_incomplete} of {} decodes with the uncut samples are reported \
             incomplete",
            complete + same_incomplete
        );
    }
}

/// The runs of missing tiles on `image`'s report.
fn missing_tiles(image: &Image) -> Vec<(u32, u32)> {
    image
        .report
        .entries
        .iter()
        .filter_map(|e| match e {
            ReportEntry::MissingTiles { tiles, .. } => Some((tiles.start, tiles.end)),
            _ => None,
        })
        .collect()
}

/// A window down the first column of `tiled_53`'s 3 x 3 tiles, cut before
/// tile 3, reads tiles 3 and 6 of the missing run 3..9: the report names
/// those two alone, not the tiles between them it does not read.
#[test]
fn a_run_of_missing_tiles_is_split_at_the_tiles_a_window_does_not_read() {
    let bytes = read("tests/fixtures/window/tiled_53.j2k");
    let ends = tile_ends(&bytes);
    let prefix = &bytes[..ends[2]];
    let window = lenient().with_region(Region::Window(Window::new(5, 4, 20, 58)));
    let part = decode_ok(prefix, &window, "the first column");
    assert_eq!(missing_tiles(&part), [(3, 4), (6, 7)]);
    assert!(!part.report.is_complete());
}