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
//! Stage 0 — the JP2 file format (ISO/IEC 15444-1 Annex I).
//!
//! A JP2 file is a sequence of boxes around one codestream, and so is a JPH
//! file (ISO/IEC 15444-15 Annex D), which holds an HTJ2K codestream:
//!
//! ```text
//! jP   signature (12 bytes, first)
//! ftyp file type (second): `jp2 ` or `jph ` as brand or in the compatibility list
//! jp2h header superbox: ihdr, colr, bpcc, pclr, cmap, cdef, res
//! jp2c the codestream (the first one; later ones are ignored, I.5.4)
//! ```
//!
//! Other boxes are skipped without being descended into: the JPX boxes
//! (`jpch`, `jplh`, `asoc`, `lbl `, `ftbl`) and anything unknown. Only
//! `jp2h`, `res ` and `uinf` are entered. The top-level `xml `, `uuid` and
//! `jp2i` boxes are passed through verbatim, and the well-formed top-level
//! `uinf` boxes are read (see [`uuid_info`]), including those after the
//! codestream, as is the first top-level `rreq` (see [`rreq`]).
//!
//! [`parse`] walks the boxes up to the first `jp2c` and hands back the
//! codestream slice with the header boxes. The rest runs before any tile data
//! is read, so `read_header` shares it with `decode`: the codestream's main
//! header is parsed, [`check_against_siz`] holds `ihdr` to its SIZ,
//! [`ChannelPlans::plan`] plans the output channels (the palette, see
//! [`palette`], then the channel definitions, see [`channels`]), and
//! [`metadata()`] builds the [`Jp2Metadata`] that rides on the
//! [`Image`](crate::Image). When the caller asks for sRGB output,
//! [`plan_srgb`] plans that conversion too (see [`srgb`]). Only then are the
//! tiles decoded and the plans applied to their samples.
//!
//! For these ways a file can bend Annex I, the walk does what OpenJPEG 2.5.0
//! does: `ihdr` may sit anywhere in `jp2h`, a second `jp2h` before the
//! codestream is merged into the first, a header box misplaced at the top
//! level after `jp2h` is applied as if it were inside, and a `jp2c` that runs
//! past the end of the file is clamped to it. The walk stops at the first
//! `jp2c`. OpenJPEG does not use that box's length: the codestream ends where
//! its tile-parts end ([`after::codestream_end`]), and the boxes from there on
//! are walked and read as OpenJPEG reads them once it has decoded the
//! codestream ([`boxes::walk_after_codestream`], [`after::check`]). When the
//! last tile-part has `Psot = 0`, its length does not say where it ends, and
//! the box's end is used when that tile's packets end exactly there
//! ([`locate_codestream`]). The two
//! decoders still differ on some files, in both directions;
//! `docs/openjpeg-departures.md` and the reject matrix in `docs/roadmap-phase3.md`
//! list where.
//!
//! Every length is checked before use and nothing is allocated from one (see
//! [`boxes`]). Box-layer faults are [`Error::FileFormat`], and a file that
//! ends before its codestream's main header is whole is [`Error::Incomplete`]
//! (see [`parse`]); a file this decoder does not read (no `jp2 ` or `jph `
//! compatibility, or a palette mapping or column depth it does not decode) is
//! [`Error::Unsupported`].

mod after;
mod boxes;
mod channels;
mod color;
mod header;
mod lcms;
mod math;
mod math_data;
mod metadata;
mod palette;
mod resolution;
mod rreq;
mod srgb;
mod uuid_info;

#[cfg(test)]
mod color_tests;
#[cfg(test)]
mod math_tests;
#[cfg(test)]
mod srgb_tests;
#[cfg(test)]
mod tests;

pub(crate) use after::check as check_after_codestream;
pub use metadata::{
    Association, ChannelDefinition, ChannelDefinitionEntry, ChannelType, ColorSpace,
    ColorSpecification, FileType, ImageHeader, IprBox, Jp2Metadata, Ratio, ReaderRequirements, Res,
    Resolution, StandardFeature, UuidBox, UuidInfo, VendorFeature, XmlBox,
};
pub use palette::{ChannelMapping, MappingKind, Palette, PaletteColumn};

use crate::codestream::markers::Siz;
use crate::{Component, ComponentInfo, Error, Result, WorkLimit};
use after::End;
use boxes::{Boxes, Jp2Box, type_name, walk_after_codestream};
use channels::ChannelPlan;
pub(crate) use header::is_jph;
use header::{Jp2Header, check_file_type};
use palette::PalettePlan;
pub(crate) use srgb::SrgbPlan;

/// The JP2 signature box (I.5.1): length 12, type `jP  `, contents
/// `0D 0A 87 0A`.
pub(crate) const SIGNATURE: [u8; 12] = [
    0x00, 0x00, 0x00, 0x0C, b'j', b'P', b' ', b' ', 0x0D, 0x0A, 0x87, 0x0A,
];

/// Whether `bytes` open with a box of the signature box's type. Such input is
/// read as a JP2 file, so a damaged signature box is reported as one
/// ([`Error::FileFormat`]) rather than as a codestream missing its `SOC`.
/// Input of 1 to 7 bytes that starts the signature box is read as a JP2 file
/// too, so it is [`Error::Incomplete`].
pub(crate) fn looks_like_jp2(bytes: &[u8]) -> bool {
    match bytes.get(4..8) {
        Some(kind) => kind == &SIGNATURE[4..8],
        None => !bytes.is_empty() && SIGNATURE.starts_with(bytes),
    }
}

/// A JP2 file's boxes up to and including its first `jp2c`.
#[derive(Debug, Clone)]
pub(crate) struct Jp2File<'a> {
    /// The `ftyp` box's fields.
    pub(crate) file_type: FileType,
    /// The `jp2h` contents, merged over every `jp2h` box and every header box
    /// misplaced at the top level after the first `jp2h`.
    pub(crate) header: Jp2Header<'a>,
    /// The color space the header declares (see [`color::read`]).
    pub(crate) color: ColorSpace,
    /// The codestream: from the start of the first `jp2c` box's contents to
    /// the end of its last tile-part, or the box's contents when that end
    /// cannot be found from the tile-part lengths (see [`after::codestream_end`]
    /// and [`locate_codestream`]).
    pub(crate) codestream: &'a [u8],
    /// The other top-level boxes before the codestream (`xml `, `uuid`, `rreq`
    /// and the like, and header boxes misplaced before `jp2h`, which OpenJPEG
    /// ignores), in file order.
    pub(crate) other: Vec<Jp2Box<'a>>,
    /// The whole boxes after the codestream, from just after its last
    /// tile-part, as far as OpenJPEG's walk there follows them (see
    /// [`walk_after_codestream`]). When [`Jp2File::after_read`] is set,
    /// [`after::check`] reads the header boxes among them.
    pub(crate) after_codestream: Vec<Jp2Box<'a>>,
    /// The whole boxes after both the codestream and the `jp2c` box, walked
    /// the same way. Their `xml `, `uuid`, `jp2i` and `uinf` boxes are
    /// reported, like those in `other`. This differs from `after_codestream`
    /// when the box is longer than its codestream: padding inside the box is
    /// skipped by its length here.
    pub(crate) after_box: Vec<Jp2Box<'a>>,
    /// Whether OpenJPEG reads the boxes after the codestream: true when the
    /// codestream's end was found from its tile-part lengths. When the last
    /// tile-part has `Psot = 0`, OpenJPEG runs it to the end of the file and
    /// its walk there finds nothing, even when the codestream ends at the
    /// `jp2c` box's end; when the end cannot be found, the codestream does
    /// not decode.
    pub(crate) after_read: bool,
    /// The length fault that ended the walk after the codestream, reported by
    /// [`after::check`] after the boxes before it.
    pub(crate) after_fault: Option<Error>,
}

/// Walk a JP2 file's top-level boxes to the first `jp2c`. `packet_work` is
/// the caller's tier-2 work limit, which also bounds the walk of a
/// `Psot = 0` tile that finds where the codestream ends
/// ([`packets_end_at`]).
///
/// Input that ends before the `jp2c` box's header is whole is
/// [`Error::Incomplete`]: inside the signature box, after it, between boxes
/// or inside one. Every box the input holds in full is read first, and a box
/// cut short whose type is already wrong (not `ftyp` second, or `jp2c` with
/// no `jp2h` before it) is the whole file's [`Error::FileFormat`].
pub(crate) fn parse<'a>(bytes: &'a [u8], packet_work: &WorkLimit) -> Result<Jp2File<'a>> {
    if SIGNATURE.starts_with(bytes) && bytes.len() < SIGNATURE.len() {
        return Err(Error::incomplete(
            "the input ends inside the JP2 signature box",
        ));
    }
    if !bytes.starts_with(&SIGNATURE) {
        return Err(Error::file_format(
            "the file must open with the 12-byte JP2 signature box (`jP  ` holding \
             0D 0A 87 0A)",
        ));
    }

    let mut boxes = Boxes::top_level(bytes, SIGNATURE.len());
    let not_ftyp = |kind: [u8; 4]| {
        Error::file_format(format!(
            "the `ftyp` box must follow the signature, not `{}`",
            type_name(kind)
        ))
    };
    let file_type = match boxes.next() {
        Some(Ok(ftyp)) if &ftyp.kind == b"ftyp" => check_file_type(&ftyp)?,
        Some(Ok(other)) => return Err(not_ftyp(other.kind)),
        // A box cut short is judged on its type once that has arrived.
        Some(Err(error @ Error::Incomplete(_))) => match boxes.cut_kind() {
            Some(kind) if &kind != b"ftyp" => return Err(not_ftyp(kind)),
            _ => return Err(error),
        },
        Some(Err(error)) => return Err(error),
        None => {
            return Err(Error::incomplete(
                "the input ends after the JP2 signature box",
            ));
        }
    };

    let mut header: Option<Jp2Header<'_>> = None;
    let mut other = Vec::new();
    // Whether a box with length 0 ("to the end of the file") was read, for the
    // message when it swallowed the boxes meant to follow it.
    let mut open_ended = boxes.last_was_open_ended();
    while let Some(item) = boxes.next() {
        let item = match item {
            // A `jp2c` cut inside its 16-byte header still needs a `jp2h`
            // before it.
            Err(Error::Incomplete(_)) if header.is_none() && boxes.cut_kind() == Some(*b"jp2c") => {
                return Err(no_jp2h());
            }
            item => item?,
        };
        open_ended = boxes.last_was_open_ended();
        match &item.kind {
            b"jp2h" => {
                header = Some(match header {
                    None => Jp2Header::parse(item.payload)?,
                    Some(first) => first.merge(item.payload)?,
                });
            }
            b"jp2c" => {
                let Some(header) = header else {
                    return Err(no_jp2h());
                };
                color::check_bpcc(&header)?;
                let color = color::read(&header)?;
                let (codestream, rest, after_read) =
                    locate_codestream(bytes, item.payload, boxes.rest(), packet_work);
                let after = walk_after_codestream(rest);
                // Both are ends of the file; the shorter starts later.
                let past_box = boxes.rest();
                let after_box = if past_box.len() < rest.len() {
                    walk_after_codestream(past_box).boxes
                } else {
                    after.boxes.clone()
                };
                return Ok(Jp2File {
                    file_type,
                    header,
                    color,
                    codestream,
                    other,
                    after_codestream: after.boxes,
                    after_box,
                    after_read,
                    after_fault: after.fault,
                });
            }
            _ => {
                let taken = header
                    .as_mut()
                    .is_some_and(|header| header.add_misplaced(item));
                if !taken {
                    other.push(item);
                }
            }
        }
    }
    // Every box read was whole, so the input ends between boxes: more may
    // follow, unless a box of length 0 claimed the rest of the file.
    if !open_ended {
        return Err(Error::incomplete(
            "the input ends before the `jp2c` codestream box",
        ));
    }
    let missing = match header {
        None => "the file has no `jp2h` header box and no `jp2c` codestream box",
        Some(_) => "the file has no `jp2c` codestream box",
    };
    Err(Error::file_format(format!(
        "{missing}: a box of length 0 (to the end of the file) swallowed the rest"
    )))
}

/// A `jp2c` codestream box with no `jp2h` before it.
fn no_jp2h() -> Error {
    Error::file_format("the file has no `jp2h` header box before its `jp2c` codestream box")
}

/// Find the codestream that starts with the `jp2c` box's contents `payload`,
/// the box being followed by `rest` in `file`. Returns the codestream, the
/// bytes after it, and whether OpenJPEG reads those bytes as boxes.
///
/// OpenJPEG reads the codestream from the start of the box to wherever its
/// tile-parts end, whatever the box's length says. When every tile-part has a
/// length, that is just after `EOC`, and the boxes from there on are walked.
/// A last tile-part of `Psot = 0` runs to the end of the file and nothing
/// after it is walked. Its length does not say where the codestream ends, so
/// the box's end is used when the box shows it is the end:
///
/// - The box's contents end in `EOC`: they are the codestream.
/// - The box ends at least two bytes before the end of the file, it holds
///   every tile-part's `SOT`, and the packets of the `Psot = 0` tile-part's
///   tile end exactly at the box's end ([`packets_end_at`]). The boxes after
///   the box are walked for their metadata.
///
/// Otherwise the codestream runs to the end of the file, and any bytes after
/// its last packet are refused as for a raw codestream. When the tile-part
/// chain is broken, the box's contents go to the codestream parser to be
/// rejected (or to `read_header`, which reads only the main header).
fn locate_codestream<'a>(
    file: &'a [u8],
    payload: &'a [u8],
    rest: &'a [u8],
    packet_work: &WorkLimit,
) -> (&'a [u8], &'a [u8], bool) {
    // `payload` and `rest` are the end of `file`, back to back.
    let tail = file
        .len()
        .checked_sub(rest.len() + payload.len())
        .and_then(|start| file.get(start..));
    let Some(tail) = tail else {
        return (payload, rest, false);
    };
    match after::codestream_end(tail) {
        End::At(end) => (&tail[..end], &tail[end..], true),
        End::OpenLastPart(_) if payload.ends_with(&[0xFF, 0xD9]) => (payload, rest, false),
        // The codestream parser gives a `Psot = 0` tile-part all but the last
        // two bytes of its slice, the room for an `EOC`, so a slice two bytes
        // past the box ends the tile-part at the box's end. `rest` under two
        // bytes leaves no room for it.
        End::OpenLastPart(tile)
            if matches!(after::codestream_end(payload), End::OpenLastPart(_)) =>
        {
            match tail.get(..payload.len() + 2) {
                Some(cut) if packets_end_at(cut, tile, packet_work) => (cut, rest, false),
                _ => (tail, &[], false),
            }
        }
        End::OpenLastPart(_) => (tail, &[], false),
        End::Unknown => (payload, rest, false),
    }
}

/// The most code-blocks, and the most precincts, [`packets_end_at`] builds the
/// packet geometry for. Each costs a few hundred bytes of geometry and decode
/// state, so the geometry stays at a few MB. A larger tile is not walked. A
/// POC marker of more than one volume adds a bit per packet they reach, as
/// the decode's does: at most 2 MB, or 4 bytes per byte of tile data when
/// that is more, so for a file of several MB this part grows with the file.
/// A tile whose volumes reach more packets than that, where the decode would
/// keep per-precinct counts, is not walked (see `tier2::progression`).
const PROBE_GEOMETRY: usize = 1 << 14;

/// The most tiles, and the most components, a codestream may have for
/// [`packets_end_at`] to walk it. The tile list and the walked tile's header
/// cost a few hundred bytes per tile and per component, so these keep them
/// to about 2 MB.
const PROBE_TILES: usize = 1 << 12;
const PROBE_COMPONENTS: usize = 1 << 10;

/// The fewest visits [`packets_end_at`] may spend: packets read, steps over
/// code-blocks a packet header names no bit for, and points of the
/// progression order's loops (see [`crate::tier2::Meter`]). A
/// code-block entry that reads a bit is paid for by the header's bytes and
/// is not counted.
const PROBE_VISITS_MIN: u64 = 1 << 22;

/// The visits [`packets_end_at`] may spend per byte of the tile's data, when
/// that comes to more than [`PROBE_VISITS_MIN`].
const PROBE_VISITS_PER_BYTE: u64 = 8;

/// The visits [`packets_end_at`] may spend on a tile of `bytes` bytes of data.
fn probe_visits(bytes: u64) -> u64 {
    PROBE_VISITS_MIN.max(bytes.saturating_mul(PROBE_VISITS_PER_BYTE))
}

/// Whether the packets of `tile`, the tile of the `Psot = 0` tile-part, end
/// exactly at the end of `codestream`: its main header and tile-parts parse
/// and tier-2 walks the tile's packets (no tier-1). Tier-2 refuses bytes left
/// after the last packet and a tile-part that ends before its last packet, so
/// this holds only when the packets end exactly at the box's end.
///
/// That makes the box's end safe to use. OpenJPEG reads the tile-part on to
/// the end of the file, past the box: the same packets when the tile has 999
/// layers or fewer, then bytes it ignores (docs/openjpeg-departures.md,
/// "More than 999 layers"). Read that way here, the same
/// packets are followed by bytes left
/// after the last packet, which are refused, so reading to the end of the file
/// could never decode instead; a fault in tier-1 would be the same fault
/// either way. When the packets do not end there, the box ends inside the
/// codestream, and the bytes after it are tile data, not boxes.
///
/// The walk does not check that a POC sequence covers the tile: packets its
/// volumes leave out are not in the codestream, so they do not move where
/// the others end. The decode refuses such a tile wherever it ends.
///
/// The walk is bounded in every step, because `read_header` runs it too. A
/// codestream of more than [`PROBE_TILES`] (4096) tiles or
/// [`PROBE_COMPONENTS`] (1024) components, or of fewer than 14 bytes per
/// tile, is not walked, nor is a tile of more than [`PROBE_GEOMETRY`] (16384)
/// code-blocks or precincts. The walk stops after `max(2^22, 8 × the tile's
/// data bytes)` visits, counted as the decode's bound counts them (see
/// `tier2::decode_visits`). A packet header of one byte can step over each
/// row of code-blocks of its precinct, and a sweep can check
/// millions of positions that hold no packet, so without the bound a small
/// file could make this walk run for minutes. Only that tile's header is
/// resolved, not every tile's, which would cost `tiles × components`. Past
/// any bound the answer is `false`, so the codestream runs to the end of the
/// file, the rule for a `Psot = 0` tile-part that this check does not apply
/// to.
fn packets_end_at(codestream: &[u8], tile: u16, packet_work: &WorkLimit) -> bool {
    probe_packets(codestream, tile, packet_work).0
}

/// [`packets_end_at`], and the visits the walk spent.
fn probe_packets(codestream: &[u8], tile: u16, packet_work: &WorkLimit) -> (bool, u64) {
    let Ok(parsed) = crate::codestream::parse_header(codestream) else {
        return (false, 0);
    };
    // Every tile needs a tile-part, of at least an SOT segment and an SOD
    // (14 bytes), so a codestream shorter than that is missing tiles and
    // fails either way. Only the walked tile's header is resolved: a fault in
    // another one is found by the decode, the same whichever end is used.
    let siz = &parsed.header.siz;
    let tiles = siz.num_tiles() as usize;
    if tiles > PROBE_TILES
        || siz.components.len() > PROBE_COMPONENTS
        || tiles.saturating_mul(14) > codestream.len()
    {
        return (false, 0);
    }
    let Ok(cs) = crate::codestream::split_tiles(codestream, parsed) else {
        return (false, 0);
    };
    let index = usize::from(tile);
    let (Some(data), Ok(header)) = (cs.tiles.get(index), cs.tile_header(index)) else {
        return (false, 0);
    };
    let bytes = (data.data.len() + data.packed_headers.len()) as u64;
    let meter = crate::tier2::Meter::new(packet_work.apply(probe_visits(bytes)));
    let mut budget = crate::tier2::Budget {
        precincts: PROBE_GEOMETRY,
        blocks: PROBE_GEOMETRY,
        // A POC sequence holds a bitmap wherever the decode could, sized by
        // the decode's bound for the same tile data, and past it gives up
        // rather than keep a set.
        poc_bitmap: crate::tier2::decode_visits(crate::tile_bytes(&cs)),
        poc_counts: false,
        // Volumes that leave out packets do not move where the packets they
        // reach end; the decode refuses them.
        poc_coverage: false,
        // Where the codestream ends must not depend on the decode options,
        // so the walk is the same at every reduction. Its geometry is held to
        // PROBE_GEOMETRY, so no dropped resolutions need charging here.
        reduction: 0,
        // Nor on the layer cap: every layer's packets are read either way.
        layers: None,
    };
    let ends = crate::tier2::decode_packets_within(&header, data, &mut budget, &meter).is_ok();
    (ends, meter.spent())
}

/// Hold `ihdr` to the codestream: `HEIGHT` and `WIDTH` must equal the SIZ image
/// area (I.5.3.1), as OpenJPEG requires. `NC` is not held to `Csiz`: OpenJPEG
/// lets the codestream decide the image, and the palette's `cmap` and the
/// channel definitions are checked against the codestream's components.
pub(crate) fn check_against_siz(header: &Jp2Header<'_>, siz: &Siz) -> Result<()> {
    let ihdr = &header.ihdr;
    let (width, height) = siz.image_extent_at(0);
    if (ihdr.width, ihdr.height) != (width, height) {
        return Err(Error::file_format(format!(
            "`ihdr` declares a {}x{} image but the codestream's `SIZ` declares {width}x{height}",
            ihdr.width, ihdr.height
        )));
    }
    Ok(())
}

/// What the header boxes do to a file's channels, worked out from the boxes
/// and the codestream's main header before any tile is decoded: the palette,
/// then the channel definitions over the palette's output channels.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ChannelPlans {
    palette: PalettePlan,
    channels: ChannelPlan,
}

impl ChannelPlans {
    /// Plan the channels for a decode at `reduction` resolution levels down,
    /// holding a palette's expanded channels to `cap` samples. `siz` is the
    /// codestream's SIZ with its image area cut to what the decode returns
    /// (the selection's area), as the expansion covers only that.
    /// The palette is planned first, so a malformed palette reports its fault
    /// before a malformed `cdef` does, as OpenJPEG reads them. `jph` says
    /// whether the file is a JPH file ([`is_jph`]).
    pub(crate) fn plan(
        header: &Jp2Header<'_>,
        siz: &Siz,
        reduction: u8,
        cap: u64,
        raw_channels: bool,
        jph: bool,
    ) -> Result<Self> {
        let palette = palette::plan(header, siz, reduction, cap, raw_channels)?;
        let count = palette.output_channels(siz, reduction).len();
        let channels = channels::plan(header, count, raw_channels, jph)?;
        Ok(ChannelPlans { palette, channels })
    }

    /// The output channels' formats, in output order: the palette's output,
    /// then placed by the channel definitions.
    pub(crate) fn outputs(&self, siz: &Siz, reduction: u8) -> Result<Vec<ComponentInfo>> {
        self.channels
            .apply(self.palette.output_channels(siz, reduction))
    }

    /// Build the output channels from the decoded components.
    pub(crate) fn apply(&self, components: Vec<Component>) -> Result<Vec<Component>> {
        self.channels.apply(self.palette.apply(components)?)
    }
}

/// The file's metadata, from its boxes and the channel plans alone: no
/// sample is needed. Without a `cdef`, the color space's channels start as
/// colors `1..=N` and the rest as unspecified; the palette and channel plans
/// relabel them. `siz` is the codestream's.
pub(crate) fn metadata(file: &Jp2File<'_>, plans: &ChannelPlans, siz: &Siz) -> Result<Jp2Metadata> {
    let passed = passthrough(file);
    let ihdr = &file.header.ihdr;
    let mut metadata = Jp2Metadata {
        color: file.color.clone(),
        channels: color_channels(plans.outputs(siz, 0)?.len(), &file.color)?,
        palette_applied: false,
        palette: None,
        channel_mapping: None,
        channel_definitions: channels::definitions(&file.header, is_jph(&file.file_type)),
        resolution: resolution::read(&file.header),
        xml: passed.xml,
        uuid: passed.uuid,
        ipr: passed.ipr,
        uuid_info: passed.uuid_info,
        image_header: ImageHeader {
            compression: ihdr.compression,
            unknown_color_space: ihdr.unknown_colorspace,
            ipr_flag: ihdr.ipr,
        },
        color_specifications: color_specifications(&file.header),
        file_type: file.file_type.clone(),
        reader_requirements: passed.reader_requirements,
    };
    plans.palette.describe(&mut metadata);
    plans.channels.describe(&mut metadata);
    Ok(metadata)
}

/// The metadata boxes [`passthrough`] collects.
#[derive(Default)]
struct Passthrough {
    xml: Vec<XmlBox>,
    uuid: Vec<UuidBox>,
    ipr: Vec<IprBox>,
    uuid_info: Vec<UuidInfo>,
    reader_requirements: Option<ReaderRequirements>,
}

/// The top-level `xml `, `uuid`, `jp2i` and `uinf` boxes, each kind in file
/// order: those before the codestream, then those after it, and the first
/// top-level `rreq`. A `uuid` box too short for its 16-byte identifier is
/// skipped, and so is a malformed `uinf` (see [`uuid_info`]); a malformed
/// first `rreq` gives `None` (see [`rreq`]). Every copy is of bytes in the
/// input, so together they are bounded by its length.
fn passthrough(file: &Jp2File<'_>) -> Passthrough {
    let mut out = Passthrough::default();
    let mut rreq_seen = false;
    for item in file.other.iter().chain(&file.after_box) {
        match &item.kind {
            b"xml " => out.xml.push(XmlBox {
                payload: item.payload.to_vec(),
            }),
            b"uuid" => {
                if let Some((id, payload)) = item.payload.split_first_chunk::<16>() {
                    out.uuid.push(UuidBox {
                        id: *id,
                        payload: payload.to_vec(),
                    });
                }
            }
            b"jp2i" => out.ipr.push(IprBox {
                payload: item.payload.to_vec(),
            }),
            b"uinf" => out.uuid_info.extend(uuid_info::parse(item.payload)),
            b"rreq" if !rreq_seen => {
                rreq_seen = true;
                out.reader_requirements = rreq::parse(item.payload);
            }
            _ => {}
        }
    }
    out
}

/// Every `colr` the header holds, in read order, split into its three header
/// bytes and the rest. [`color::read`] has refused a box under 3 bytes, so
/// none is dropped.
fn color_specifications(header: &Jp2Header<'_>) -> Vec<ColorSpecification> {
    header
        .colr()
        .into_iter()
        .filter_map(|body| {
            let (&[method, precedence, approximation], payload) = body.split_first_chunk()?;
            Some(ColorSpecification {
                method,
                precedence,
                approximation,
                payload: payload.to_vec(),
            })
        })
        .collect()
}

/// The number of colors in a color space: the colors a channel can be
/// associated with in I.5.3.6. Part 1 (Table I.10) defines enumerated values
/// 16, 17 and 18; the others are those of ISO/IEC 15444-2 Table M.25. `None`
/// when the space is unknown, the enumerated value is not listed, or the ICC
/// profile is too short to name its color space, so the count cannot be
/// given.
fn color_count(color: &ColorSpace) -> Option<usize> {
    match color {
        // `color.rs` maps enumerated 16, 17 and 18 to `Srgb`, `Grayscale`
        // and `Sycc`, so they never reach the `Enumerated` arm.
        ColorSpace::Grayscale => Some(1),
        ColorSpace::Srgb | ColorSpace::Sycc => Some(3),
        ColorSpace::Enumerated(value) => match value {
            // Bi-level (0, 15).
            0 | 15 => Some(1),
            // YCbCr (1, 3, 4), PhotoYCC, CMY, CIELab, CIEJab, e-sRGB,
            // ROMM-RGB, YPbPr (22, 23) and e-sYCC.
            1 | 3 | 4 | 9 | 11 | 14 | 19..=24 => Some(3),
            // CMYK, YCCK.
            12 | 13 => Some(4),
            _ => None,
        },
        ColorSpace::RestrictedIcc(profile) => {
            // The data color space is the signature at byte 16 of the header.
            match profile.get(16..20)? {
                b"GRAY" => Some(1),
                b"RGB " | b"YCbr" | b"Lab " | b"Luv " | b"XYZ " | b"Yxy " | b"HSV " | b"HLS "
                | b"CMY " => Some(3),
                b"CMYK" => Some(4),
                // `nCLR`: n colors for n in 2 to 15, as one upper-case hex
                // digit (ICC.1 Table 19).
                [d @ (b'2'..=b'9' | b'A'..=b'F'), b'C', b'L', b'R'] => {
                    char::from(*d).to_digit(16).map(|n| n as usize)
                }
                _ => None,
            }
        }
        ColorSpace::Unknown => None,
    }
}

/// The channel definitions of a file without `cdef`. With no `cdef`, I.5.3.6
/// takes the channels to be the color space's colors in order (channel `i`
/// is color `i + 1`). The first [`color_count`] channels are labeled so; a
/// file with more channels than colors breaks that, so the channels past
/// them have no defined meaning and are `Unspecified` with no association.
/// When the count is unknown every channel is labeled a color.
fn color_channels(count: usize, color: &ColorSpace) -> Result<Vec<ChannelDefinition>> {
    let colors = color_count(color).unwrap_or(count);
    (0..count)
        .map(|i| {
            if i >= colors {
                return Ok(ChannelDefinition {
                    kind: ChannelType::Unspecified,
                    association: Association::None,
                });
            }
            let color = u16::try_from(i + 1).map_err(|_| {
                Error::inconsistent(format!("{count} channels exceed the `u16` color index"))
            })?;
            Ok(ChannelDefinition {
                kind: ChannelType::Color,
                association: Association::Color(color),
            })
        })
        .collect()
}

/// Plan the sRGB output step ([`ColorOutput::Srgb`](crate::ColorOutput::Srgb))
/// from the file's color space and the planned output channels, before any
/// tile is decoded. The output is held to `cap` samples.
pub(crate) fn plan_srgb(
    metadata: &Jp2Metadata,
    plans: &ChannelPlans,
    siz: &Siz,
    reduction: u8,
    cap: u64,
) -> Result<SrgbPlan> {
    srgb::plan(
        &metadata.color,
        &metadata.channels,
        &plans.outputs(siz, reduction)?,
        siz,
        reduction,
        cap,
    )
}