Skip to main content

rust_j2k/jp2/
metadata.rs

1//! What a JP2 file says about its samples, as public plain data on
2//! [`Image::jp2`](crate::Image::jp2).
3
4/// What the JP2 wrapper said about the decoded samples.
5///
6/// `None` on [`Image::jp2`](crate::Image::jp2) for a raw codestream. The
7/// struct is `#[non_exhaustive]`, so more of the file's metadata can be added
8/// without a breaking change.
9#[derive(Debug, Clone, PartialEq, Eq)]
10#[non_exhaustive]
11pub struct Jp2Metadata {
12    /// The color space of the color channels.
13    pub color: ColorSpace,
14    /// One entry per [`Image::components`](crate::Image::components) entry,
15    /// saying what that channel is: its entry in the file's channel
16    /// definition (`cdef`) box, or, without one, color `i + 1` for channel
17    /// `i` while `i` is below the color space's number of colors (3 for
18    /// sRGB and sYCC, 1 for grayscale, the profile's for an ICC profile). A
19    /// channel past that has no meaning in I.5.3.6 and is
20    /// [`ChannelType::Unspecified`] with [`Association::None`]. When the count is
21    /// unknown (the file gives no color space, the enumerated value is not
22    /// one this decoder knows, or an ICC profile is too short to name its
23    /// color space) every channel is a color.
24    pub channels: Vec<ChannelDefinition>,
25    /// Whether the samples went through the file's palette. `false` when the
26    /// file has no palette (or a `pclr` without a `cmap`), or the caller set
27    /// [`DecodeOptions::raw_channels`](crate::DecodeOptions::raw_channels).
28    pub palette_applied: bool,
29    /// The file's channel definition box (`cdef`) as written, in file order:
30    /// `Some` whenever the file has one, whatever the options, and `None`
31    /// without one. The entries are checked only when the decode applies them,
32    /// so under [`raw_channels`](crate::DecodeOptions::raw_channels) a `cn`
33    /// may name a channel the file does not have.
34    ///
35    /// The channels an entry's [`channel`](ChannelDefinitionEntry::channel)
36    /// counts are the file's components after the palette is expanded, in the
37    /// order [`channel_mapping`](Self::channel_mapping) gives (the components
38    /// as coded for a file without a palette). The decode puts them in color
39    /// order like this. Start with the channels in that order, so channel `c`
40    /// is at position `c`. For each entry in file order whose type is
41    /// [`ChannelType::Color`] and whose association is
42    /// [`Association::Color`]`(n)`, find where its channel is now (earlier
43    /// swaps may have moved it) and swap it with whatever is at position
44    /// `n - 1`. Every other entry moves nothing. The channel a swap moves out
45    /// of the way keeps its place in later lookups: it is found where it went.
46    ///
47    /// For example, three color entries `(channel 0, color 3)`,
48    /// `(channel 1, color 2)`, `(channel 2, color 1)` give the order
49    /// `[2, 1, 0]`: the first swap gives `[2, 1, 0]`, the second finds channel
50    /// 1 already at position 1, and the third finds channel 2 already at
51    /// position 0. Reading `Cn` as a position instead would swap 0 and 2, then
52    /// 1 with itself, then 2 and 0 back, and give `[0, 1, 2]`, which is wrong.
53    ///
54    /// A file with exactly those entries decodes as this example shows: it
55    /// applies the rule above to the entries the decoder reports, and the
56    /// default decode is the raw one in that order.
57    ///
58    /// ```
59    /// use rust_j2k::{Association, ChannelType, DecodeOptions, decode_with};
60    ///
61    /// # let path = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/jp2_cdef_reversed.jp2");
62    /// # let bytes = std::fs::read(path)?;
63    /// let decoded = decode_with(&bytes, &DecodeOptions::default())?;
64    /// let coded = decode_with(&bytes, &DecodeOptions::default().with_raw_channels(true))?;
65    /// let entries = decoded.jp2.as_ref().unwrap().channel_definitions.as_ref().unwrap();
66    ///
67    /// // The rule: swap each color entry's channel into position `n - 1`.
68    /// let mut order: Vec<usize> = (0..coded.components.len()).collect();
69    /// for entry in entries {
70    ///     if let (ChannelType::Color, Association::Color(n)) =
71    ///         (entry.definition.kind, entry.definition.association)
72    ///     {
73    ///         let at = order.iter().position(|&c| c == usize::from(entry.channel)).unwrap();
74    ///         order.swap(at, usize::from(n) - 1);
75    ///     }
76    /// }
77    /// assert_eq!(order, [2, 1, 0]);
78    ///
79    /// // Output position `p` holds the coded channel `order[p]`, and the
80    /// // coded channels differ, so the check is not vacuous.
81    /// assert_ne!(coded.components[0].samples, coded.components[2].samples);
82    /// for (p, &c) in order.iter().enumerate() {
83    ///     assert_eq!(decoded.components[p].samples, coded.components[c].samples);
84    /// }
85    /// # Ok::<(), Box<dyn std::error::Error>>(())
86    /// ```
87    ///
88    /// A channel's label on [`channels`](Self::channels) is that of the last
89    /// entry naming it.
90    ///
91    /// [`channels`](Self::channels) itself is only relabeled when the `cdef`
92    /// applies: under `raw_channels` every channel keeps its default label.
93    pub channel_definitions: Option<Vec<ChannelDefinitionEntry>>,
94    /// The file's palette, from its `pclr` box. Present when the palette
95    /// applies, and also when
96    /// [`raw_channels`](crate::DecodeOptions::raw_channels) left it unapplied
97    /// (then [`palette_applied`](Self::palette_applied) is `false`). `None`
98    /// without a `pclr`. `None` too for a `pclr` without a `cmap`: the
99    /// standard requires both or neither, so the file is invalid, and OpenJPEG
100    /// ignores the palette in that case, as this decoder does.
101    pub palette: Option<Palette>,
102    /// The file's component mapping, set whenever [`palette`](Self::palette)
103    /// is: one entry per output channel of a palettized decode, in the order
104    /// before any `cdef` reordering. An entry is
105    /// [`Direct`](crate::MappingKind::Direct) for a component used as coded.
106    ///
107    /// It is the mapping the default decode applies, in either mode, including
108    /// OpenJPEG's correction for a single-component file (which turns every
109    /// entry into a lookup in its own column, so it can differ from the box).
110    /// Only a `cmap` the default decode refuses is reported as written, and
111    /// only under `raw_channels`, which does not check it; an `MTYP` other
112    /// than 0 or 1 is then [`Reserved`](crate::MappingKind::Reserved).
113    pub channel_mapping: Option<Vec<ChannelMapping>>,
114    /// The capture and default display resolutions from the header's `res `
115    /// box, each `None` when the file does not give it.
116    pub resolution: Resolution,
117    /// Every top-level `xml ` box, verbatim and in file order, including
118    /// those after the codestream. Not parsed.
119    pub xml: Vec<XmlBox>,
120    /// Every top-level `uuid` box, in file order, including those after the
121    /// codestream. Not interpreted.
122    pub uuid: Vec<UuidBox>,
123    /// Every top-level intellectual property box (`jp2i`), verbatim and in
124    /// file order, including those after the codestream. The standard leaves
125    /// the format of these bytes open, so they are not parsed.
126    /// `jp2i` boxes inside other superboxes are not collected.
127    pub ipr: Vec<IprBox>,
128    /// Every well-formed top-level UUID info box (`uinf`), in file order,
129    /// including those after the codestream: a list of UUIDs and a URL where
130    /// more about them can be found. The URL is not fetched. A malformed
131    /// `uinf` is left out and never fails a decode, as OpenJPEG skips the box
132    /// (see [`UuidInfo`]).
133    pub uuid_info: Vec<UuidInfo>,
134    /// The Image Header box's (I.5.3.1) flags `C`, `UnkC` and `IPR`.
135    pub image_header: ImageHeader,
136    /// Every Colour Specification box (`colr`, I.5.3.3) in file order, the
137    /// ignored ones too: those in every `jp2h` box and those misplaced at the
138    /// top level after the first `jp2h`, before the codestream. A `colr` after
139    /// the codestream is not reported. Only the first whose method is 1 or 2
140    /// sets [`color`](Self::color); the others are reported here and not
141    /// applied.
142    ///
143    /// The boxes are reported as stored in the file, whatever
144    /// [`DecodeOptions::color`](crate::DecodeOptions::color) is. Under
145    /// [`ColorOutput::Srgb`](crate::ColorOutput::Srgb) the first usable one
146    /// (`METH` 1 or 2, not always the first listed) may still hold the
147    /// original ICC profile while [`color`](Self::color) is
148    /// [`ColorSpace::Srgb`].
149    pub color_specifications: Vec<ColorSpecification>,
150    /// The File Type box (`ftyp`, I.5.2).
151    pub file_type: FileType,
152    /// The first top-level Reader Requirements box (`rreq`, ISO/IEC 15444-2
153    /// M.11.1), before or after the codestream. `None` without one, and when
154    /// the first is malformed (see [`ReaderRequirements`]).
155    pub reader_requirements: Option<ReaderRequirements>,
156}
157
158/// The Image Header box's (`ihdr`, I.5.3.1) flags `C`, `UnkC` and `IPR`, as
159/// stored. None of them changes the decode. The codestream's SIZ decides the
160/// image size, the component count and the depths, so `ihdr`'s `HEIGHT`,
161/// `WIDTH`, `NC` and `BPC`, and the `bpcc` box, are not reported.
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163#[non_exhaustive]
164pub struct ImageHeader {
165    /// `C`: the compression type. The standard requires 7 (JPEG 2000).
166    pub compression: u8,
167    /// `UnkC`: 1 when the file does not know the color space, 0 when its
168    /// color specification boxes give it accurately. Not consulted for
169    /// [`Jp2Metadata::color`].
170    pub unknown_color_space: u8,
171    /// `IPR`: 1 when the file claims to hold intellectual property rights
172    /// boxes, 0 when it does not. The flag is stored as-is, so it can hold
173    /// the values I.5.3.1 reserves (only 0 and 1 are defined). It is not
174    /// checked against the boxes present, so it may disagree with
175    /// [`Jp2Metadata::ipr`], which holds the top-level `jp2i` boxes.
176    pub ipr_flag: u8,
177}
178
179/// One Colour Specification box (`colr`, I.5.3.3), as stored.
180#[derive(Debug, Clone, PartialEq, Eq)]
181#[non_exhaustive]
182#[doc(alias = "ColourSpecification")]
183pub struct ColorSpecification {
184    /// `METH`: 1 for an enumerated color space, 2 for a restricted ICC
185    /// profile. Other values are reserved by this standard (ISO/IEC 15444-2
186    /// defines more), and such a box is ignored.
187    pub method: u8,
188    /// `PREC`: the precedence. The standard reserves it and requires 0, and
189    /// a reader ignores it. ISO/IEC 15444-2 reads the byte as a signed value.
190    pub precedence: u8,
191    /// `APPROX`: the color space approximation. The standard requires 0, and
192    /// a reader ignores it.
193    pub approximation: u8,
194    /// The bytes after `APPROX`, verbatim: `EnumCS` (four bytes, big-endian)
195    /// for `METH` 1, the ICC profile for `METH` 2.
196    pub payload: Vec<u8>,
197}
198
199/// The File Type box (`ftyp`, I.5.2), as stored. A file is read when `jp2 `
200/// is its brand or in its compatibility list.
201#[derive(Debug, Clone, PartialEq, Eq)]
202#[non_exhaustive]
203pub struct FileType {
204    /// `BR`: the brand, `jp2 ` for a JP2 file.
205    pub brand: [u8; 4],
206    /// `MinV`: the minor version. The standard requires 0, and a reader
207    /// ignores it.
208    pub minor_version: u32,
209    /// `CLi`: the compatibility list, in box order.
210    pub compatibility: Vec<[u8; 4]>,
211}
212
213/// A Reader Requirements box (`rreq`, ISO/IEC 15444-2 M.11.1): the features
214/// a reader must support to use the file, each with a mask saying which of
215/// the file's requirement expressions it belongs to.
216///
217/// Every mask is `ML` bytes, as stored (big-endian). A box is reported when it
218/// holds exactly the fields its counts give: `ML`, the two masks, `NSF` and
219/// its standard features, `NVF` and its vendor features, and nothing after.
220/// One that is cut short or has bytes left over is malformed: it is left out
221/// of [`Jp2Metadata::reader_requirements`] and never fails a decode, as
222/// OpenJPEG skips the box. The values are not checked (ISO/IEC 15444-2 allows
223/// `ML` of 1, 2, 4 or 8) and nothing in the box changes the decode.
224#[derive(Debug, Clone, PartialEq, Eq)]
225#[non_exhaustive]
226pub struct ReaderRequirements {
227    /// `ML`: the length of each mask in bytes.
228    pub mask_length: u8,
229    /// `FUAM`: the fully-understand-aspects mask.
230    pub fully_understand: Vec<u8>,
231    /// `DCM`: the decode-completely mask.
232    pub decode_completely: Vec<u8>,
233    /// The `NSF` standard features (`SF` and `SM`), in box order.
234    pub standard_features: Vec<StandardFeature>,
235    /// The `NVF` vendor features (`VF` and `VM`), in box order.
236    pub vendor_features: Vec<VendorFeature>,
237}
238
239/// One standard feature of a Reader Requirements box: `SF` and its `SM`.
240#[derive(Debug, Clone, PartialEq, Eq)]
241#[non_exhaustive]
242pub struct StandardFeature {
243    /// `SF`: the feature, numbered as in ISO/IEC 15444-2.
244    pub feature: u16,
245    /// `SM`: the feature's mask.
246    pub mask: Vec<u8>,
247}
248
249/// One vendor feature of a Reader Requirements box: `VF` and its `VM`.
250#[derive(Debug, Clone, PartialEq, Eq)]
251#[non_exhaustive]
252pub struct VendorFeature {
253    /// `VF`: the feature's UUID.
254    pub id: [u8; 16],
255    /// `VM`: the feature's mask.
256    pub mask: Vec<u8>,
257}
258
259use super::palette::{ChannelMapping, Palette};
260
261/// The resolutions a JP2 file's `res ` box gives, in grid points per meter.
262///
263/// The capture resolution (`resc`) is the one the image was digitized at; the
264/// default display resolution (`resd`) is the one it should be shown at. A
265/// box that is missing, or that does not hold exactly its ten bytes, leaves
266/// its field `None`: OpenJPEG does not read `res ` at all, so a malformed one
267/// never fails a decode. When more than one is present, the first counts.
268#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
269#[non_exhaustive]
270pub struct Resolution {
271    /// The capture resolution (`resc`).
272    pub capture: Option<Res>,
273    /// The default display resolution (`resd`).
274    pub display: Option<Res>,
275}
276
277/// One resolution: grid points per meter in each direction.
278#[derive(Debug, Clone, Copy, PartialEq, Eq)]
279#[non_exhaustive]
280pub struct Res {
281    /// Vertical grid points per meter (`VRN`, `VRD`, `VRE`).
282    pub vertical: Ratio,
283    /// Horizontal grid points per meter (`HRN`, `HRD`, `HRE`).
284    pub horizontal: Ratio,
285}
286
287/// A resolution as the file stores it: `numerator / denominator × 10^exponent`
288/// grid points per meter. Kept as integers, so the value is exact;
289/// [`Ratio::grid_points_per_meter`] gives it as a float.
290#[derive(Debug, Clone, Copy, PartialEq, Eq)]
291#[non_exhaustive]
292pub struct Ratio {
293    /// `N`.
294    pub numerator: u16,
295    /// `D`.
296    pub denominator: u16,
297    /// `E`, a power of ten.
298    pub exponent: i8,
299}
300
301impl Ratio {
302    /// The resolution in grid points per meter, or `None` when the
303    /// denominator is 0.
304    ///
305    /// ```
306    /// use rust_j2k::read_header;
307    ///
308    /// # fn jp2_with_resolution(codestream: &[u8]) -> Result<Vec<u8>, rust_j2k::Error> {
309    /// #     fn boxed(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {
310    /// #         let mut out = (8 + payload.len() as u32).to_be_bytes().to_vec();
311    /// #         out.extend_from_slice(kind);
312    /// #         out.extend_from_slice(payload);
313    /// #         out
314    /// #     }
315    /// #     let header = read_header(codestream)?;
316    /// #     let mut ihdr = header.height.to_be_bytes().to_vec();
317    /// #     ihdr.extend_from_slice(&header.width.to_be_bytes());
318    /// #     ihdr.extend_from_slice(&(header.components.len() as u16).to_be_bytes());
319    /// #     ihdr.extend_from_slice(&[header.components[0].bit_depth - 1, 7, 0, 0]);
320    /// #     // Capture resolution 10000 / 254 points per meter, both ways.
321    /// #     let mut resc = Vec::new();
322    /// #     for value in [10000u16, 254, 10000, 254] {
323    /// #         resc.extend_from_slice(&value.to_be_bytes());
324    /// #     }
325    /// #     resc.extend_from_slice(&[0, 0]);
326    /// #     let mut file = boxed(b"jP  ", &[0x0D, 0x0A, 0x87, 0x0A]);
327    /// #     file.extend(boxed(b"ftyp", b"jp2 \0\0\0\0jp2 "));
328    /// #     let colr = boxed(b"colr", &[1, 0, 0, 0, 0, 0, 17]);
329    /// #     let res = boxed(b"res ", &boxed(b"resc", &resc));
330    /// #     file.extend(boxed(b"jp2h", &[boxed(b"ihdr", &ihdr), colr, res].concat()));
331    /// #     file.extend(boxed(b"jp2c", codestream));
332    /// #     Ok(file)
333    /// # }
334    /// # fn main() -> Result<(), rust_j2k::Error> {
335    /// # let codestream = std::fs::read("tests/fixtures/derived_quant_lossy.j2k").unwrap();
336    /// let bytes = jp2_with_resolution(&codestream)?;
337    /// let jp2 = read_header(&bytes)?.jp2.expect("a JP2 file");
338    /// let capture = jp2.resolution.capture.expect("a capture resolution");
339    /// // 10000 / 254 is about 39.37 grid points per meter.
340    /// let per_meter = capture.horizontal.grid_points_per_meter().unwrap();
341    /// assert!((per_meter - 10000.0 / 254.0).abs() < 1e-9);
342    /// # Ok(())
343    /// # }
344    /// ```
345    #[must_use]
346    pub fn grid_points_per_meter(self) -> Option<f64> {
347        if self.denominator == 0 {
348            return None;
349        }
350        Some(
351            f64::from(self.numerator) / f64::from(self.denominator)
352                * 10f64.powi(i32::from(self.exponent)),
353        )
354    }
355}
356
357/// An `xml ` box: XML text the file carries, which is not parsed.
358///
359/// The payload is the bytes after the box header, not checked as UTF-8 or XML.
360#[derive(Debug, Clone, PartialEq, Eq)]
361#[non_exhaustive]
362pub struct XmlBox {
363    /// The box contents, verbatim.
364    pub payload: Vec<u8>,
365}
366
367/// An intellectual property box (`jp2i`). The standard leaves the format of
368/// its contents open, so they are not parsed.
369///
370/// The payload is the bytes after the box header, not checked in any way.
371#[derive(Debug, Clone, PartialEq, Eq)]
372#[non_exhaustive]
373pub struct IprBox {
374    /// The box contents, verbatim.
375    pub payload: Vec<u8>,
376}
377
378/// A `uuid` box: a 16-byte identifier and the data it labels.
379///
380/// GeoJP2 georeferencing and XMP are carried this way. A `uuid` box shorter
381/// than its 16-byte identifier is skipped.
382#[derive(Debug, Clone, PartialEq, Eq)]
383#[non_exhaustive]
384pub struct UuidBox {
385    /// The identifier, as stored.
386    pub id: [u8; 16],
387    /// The box contents after the identifier, verbatim.
388    pub payload: Vec<u8>,
389}
390
391/// A UUID info box (`uinf`): the UUIDs its UUID list box (`ulst`) names and
392/// its data entry URL box (`url `), which says where more about them can be
393/// found.
394///
395/// A `uinf` is reported when it is well formed: its contents are whole boxes,
396/// exactly one `ulst` and exactly one `url ` in either order (other boxes
397/// inside it are ignored), the `ulst` holds exactly the `NU` UUIDs its count
398/// gives, and the `url ` holds at least its 4-byte version and flags. A `uinf`
399/// that breaks any of these is left out of
400/// [`Jp2Metadata::uuid_info`] as a whole; the decode goes on. The version,
401/// flags and location are reported as stored, so a version or flags other
402/// than 0 and a location that is not valid UTF-8 or lacks its terminating NUL
403/// are kept.
404#[derive(Debug, Clone, PartialEq, Eq)]
405#[non_exhaustive]
406pub struct UuidInfo {
407    /// The UUIDs from the `ulst` box (`ID0` to `ID(NU-1)`), in box order.
408    pub ids: Vec<[u8; 16]>,
409    /// `VERS` from the `url ` box; the standard requires 0.
410    pub version: u8,
411    /// `FLAG` from the `url ` box, as stored (big-endian); the standard
412    /// requires 0.
413    pub flags: [u8; 3],
414    /// `LOC` from the `url ` box: the bytes after the version and flags,
415    /// verbatim, including any terminating NUL. See
416    /// [`location_str`](Self::location_str) for the URL as text.
417    pub location: Vec<u8>,
418}
419
420impl UuidInfo {
421    /// The location as a UTF-8 string, without its terminating NUL: `None`
422    /// when the bytes are not valid UTF-8 or hold a NUL before the last byte.
423    /// A location with no terminating NUL is read to its end.
424    ///
425    /// ```
426    /// use rust_j2k::read_header;
427    ///
428    /// # fn jp2_with_uuid_info(codestream: &[u8]) -> Result<Vec<u8>, rust_j2k::Error> {
429    /// #     fn boxed(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {
430    /// #         let mut out = (8 + payload.len() as u32).to_be_bytes().to_vec();
431    /// #         out.extend_from_slice(kind);
432    /// #         out.extend_from_slice(payload);
433    /// #         out
434    /// #     }
435    /// #     let header = read_header(codestream)?;
436    /// #     let mut ihdr = header.height.to_be_bytes().to_vec();
437    /// #     ihdr.extend_from_slice(&header.width.to_be_bytes());
438    /// #     ihdr.extend_from_slice(&(header.components.len() as u16).to_be_bytes());
439    /// #     ihdr.extend_from_slice(&[header.components[0].bit_depth - 1, 7, 0, 0]);
440    /// #     let mut file = boxed(b"jP  ", &[0x0D, 0x0A, 0x87, 0x0A]);
441    /// #     file.extend(boxed(b"ftyp", b"jp2 \0\0\0\0jp2 "));
442    /// #     let colr = boxed(b"colr", &[1, 0, 0, 0, 0, 0, 17]);
443    /// #     file.extend(boxed(b"jp2h", &[boxed(b"ihdr", &ihdr), colr].concat()));
444    /// #     // One UUID, and a URL with its terminating NUL.
445    /// #     let ulst = boxed(b"ulst", &[&[0, 1][..], &[0x42; 16]].concat());
446    /// #     let url = boxed(b"url ", b"\0\0\0\0https://example.com/ids\0");
447    /// #     file.extend(boxed(b"uinf", &[ulst, url].concat()));
448    /// #     file.extend(boxed(b"jp2c", codestream));
449    /// #     Ok(file)
450    /// # }
451    /// # fn main() -> Result<(), rust_j2k::Error> {
452    /// # let codestream = std::fs::read("tests/fixtures/derived_quant_lossy.j2k").unwrap();
453    /// let bytes = jp2_with_uuid_info(&codestream)?;
454    /// let jp2 = read_header(&bytes)?.jp2.expect("a JP2 file");
455    /// let info = &jp2.uuid_info[0];
456    /// assert_eq!(info.ids, [[0x42; 16]]);
457    /// assert_eq!(info.location_str(), Some("https://example.com/ids"));
458    /// # Ok(())
459    /// # }
460    /// ```
461    #[must_use]
462    pub fn location_str(&self) -> Option<&str> {
463        let text = self.location.strip_suffix(&[0]).unwrap_or(&self.location);
464        if text.contains(&0) {
465            return None;
466        }
467        std::str::from_utf8(text).ok()
468    }
469}
470
471/// The color space a JP2 file declares for its color channels.
472///
473/// It comes from the first usable Colour Specification (`colr`) box, the way
474/// OpenJPEG reads it: a box whose method is neither 1 (enumerated) nor 2
475/// (restricted ICC) is skipped and does not count as the first, and every
476/// later usable box is ignored. Boxes placed after `jp2h` at the top level
477/// count in file order with the ones inside `jp2h`. This is what the file
478/// declares. Decoding returns the samples as coded unless the caller asks for
479/// [`ColorOutput::Srgb`](crate::ColorOutput::Srgb); then the color channels
480/// are converted and [`Jp2Metadata::color`] reports the converted space.
481#[derive(Debug, Clone, PartialEq, Eq)]
482#[non_exhaustive]
483#[doc(alias = "ColourSpace")]
484pub enum ColorSpace {
485    /// sRGB (enumerated color space 16).
486    Srgb,
487    /// Grayscale (enumerated color space 17).
488    Grayscale,
489    /// sYCC (enumerated color space 18).
490    Sycc,
491    /// A `METH` 2 box's ICC profile: the box's bytes after its three header
492    /// bytes, verbatim. The standard restricts it to a monochrome or
493    /// three-component matrix/TRC input profile, but that is not checked
494    /// here: it holds whatever the box contains.
495    /// Applied to the samples only under
496    /// [`ColorOutput::Srgb`](crate::ColorOutput::Srgb), which then reports
497    /// the converted color space instead. The same bytes are also in that
498    /// box's [`ColorSpecification::payload`] on
499    /// [`Jp2Metadata::color_specifications`], so the profile is held twice.
500    RestrictedIcc(Vec<u8>),
501    /// Another enumerated color space value from the first usable box,
502    /// reported but not interpreted.
503    Enumerated(u32),
504    /// The file gives no color space: no usable `colr` box. The image
505    /// header's unknown-color-space flag
506    /// ([`ImageHeader::unknown_color_space`]) does not change this.
507    Unknown,
508}
509
510/// What one output channel is: its type and the color it belongs to.
511///
512/// It mirrors a `cdef` entry's `Typ` and `Asoc`, and both enums already hold
513/// every 16-bit value, so the struct and its enums are not
514/// `#[non_exhaustive]`: a caller may build one, and match on both enums
515/// without a catch-all arm.
516#[derive(Debug, Clone, Copy, PartialEq, Eq)]
517pub struct ChannelDefinition {
518    /// The channel's type.
519    pub kind: ChannelType,
520    /// Which color, if any, the channel is associated with.
521    pub association: Association,
522}
523
524/// One entry of a file's channel definition box (`cdef`), as written: the
525/// channel it describes and that channel's definition.
526///
527/// [`Jp2Metadata::channels`] has the labels of the output channels in output
528/// order; these entries are indexed by `Cn`, the channel's position before
529/// the `cdef` box reorders anything.
530#[derive(Debug, Clone, PartialEq, Eq)]
531#[non_exhaustive]
532pub struct ChannelDefinitionEntry {
533    /// `Cn`: the channel described, counting the components after palette
534    /// expansion (the codestream's components for a file without a palette).
535    pub channel: u16,
536    /// `Typ` and `Asoc`.
537    pub definition: ChannelDefinition,
538}
539
540/// A channel's type, from a channel definition (`Typ`).
541#[derive(Debug, Clone, Copy, PartialEq, Eq)]
542pub enum ChannelType {
543    /// A color channel (`Typ` 0).
544    Color,
545    /// An opacity channel (`Typ` 1).
546    Opacity,
547    /// A premultiplied opacity channel (`Typ` 2).
548    PremultipliedOpacity,
549    /// The type is not specified (`Typ` 65535).
550    Unspecified,
551    /// A reserved `Typ` value, reported as is.
552    Other(u16),
553}
554
555/// The color a channel is associated with, from a channel definition
556/// (`Asoc`).
557#[derive(Debug, Clone, Copy, PartialEq, Eq)]
558pub enum Association {
559    /// The channel applies to the whole image (`Asoc` 0), as an opacity
560    /// channel usually does.
561    WholeImage,
562    /// The channel is color `n` of the color space, counting from 1 (for
563    /// sRGB, 1 is red, 2 green, 3 blue).
564    Color(u16),
565    /// No association (`Asoc` 65535).
566    None,
567}