Skip to main content

rust_j2k/
report.rs

1//! What a decode with [`DecodeOptions::strict`](crate::DecodeOptions::strict)
2//! off found missing or skipped: the [`DecodeReport`] on
3//! [`Image::report`](crate::Image::report).
4
5use core::fmt;
6use core::ops::Range;
7
8/// What a decode left out, and how far the data reached.
9///
10/// A strict decode (the default) returns an image only when nothing is
11/// missing, so its report is always the complete one: no entries and a
12/// [`complete_reduction`](Self::complete_reduction) of `Some(0)`. That is also
13/// [`DecodeReport::default`]. With
14/// [`strict`](crate::DecodeOptions::strict) off, the decode returns the image
15/// it could make and says here what it left out.
16///
17/// ```
18/// use rust_j2k::{DecodeOptions, decode_with, read_header};
19///
20/// let bytes = include_bytes!(concat!(
21///     env!("CARGO_MANIFEST_DIR"),
22///     "/tests/fixtures/jpeg2000_regular_latlon.j2k"
23/// ));
24/// // Only the first part of the codestream has arrived.
25/// let prefix = &bytes[..bytes.len() * 3 / 4];
26/// let options = DecodeOptions::default().with_strict(false);
27/// let image = decode_with(prefix, &options).expect("the main header is there");
28/// let report = &image.report;
29/// if !report.is_complete() {
30///     for entry in &report.entries {
31///         println!("{entry}");
32///     }
33///     // The finest level the data already holds in full, if any, and if a
34///     // decode may ask for it.
35///     let max = read_header(prefix).expect("the main header is there").max_reduction;
36///     if let Some(reduction) = report.complete_reduction.filter(|&r| r <= max) {
37///         let options = options.with_resolution_reduction(reduction);
38///         let coarse = decode_with(prefix, &options).expect("decodes");
39///         assert!(coarse.report.is_complete());
40///     }
41/// }
42/// ```
43#[derive(Debug, Clone, PartialEq, Eq)]
44#[non_exhaustive]
45pub struct DecodeReport {
46    /// What was missing, skipped or irregular, in the order the decoder met
47    /// them. Empty when the codestream was whole.
48    ///
49    /// The list is bounded by the input: at most five entries per tile-part
50    /// the codestream carries, plus two. A run of missing tiles is one
51    /// [`ReportEntry::MissingTiles`] entry, however many tiles it spans.
52    pub entries: Vec<ReportEntry>,
53    /// The smallest [`resolution_reduction`](crate::DecodeOptions::resolution_reduction)
54    /// at which every tile has every packet: a decode at this reduction, or
55    /// any larger one the file allows, gives the same samples as a decode of
56    /// the whole codestream. It is counted over all of the data, whatever
57    /// reduction this decode used, so one cheap decode at a coarse level says
58    /// which finer level the data can already give. It can be larger than
59    /// [`Header::max_reduction`](crate::Header::max_reduction), the largest
60    /// reduction a decode may ask for.
61    ///
62    /// `None` when no reduction is complete: even the coarsest resolution has
63    /// a packet missing, a tile is missing, or a tile has bytes left over (see
64    /// [`ReportEntry::LeftoverBytes`]).
65    pub complete_reduction: Option<u8>,
66    /// The reduction the decode used, which [`Self::is_complete`] compares
67    /// against.
68    reduction: u8,
69}
70
71impl Default for DecodeReport {
72    /// The report of a whole codestream: no entries, complete at reduction 0.
73    fn default() -> Self {
74        DecodeReport {
75            entries: Vec::new(),
76            complete_reduction: Some(0),
77            reduction: 0,
78        }
79    }
80}
81
82impl DecodeReport {
83    /// A report of `entries`, complete at `complete_reduction`, for a decode
84    /// at `reduction`. Nothing missing at any reduction is the default report,
85    /// whatever the reduction, so it compares equal to a strict decode's.
86    pub(crate) fn new(
87        entries: Vec<ReportEntry>,
88        complete_reduction: Option<u8>,
89        reduction: u8,
90    ) -> Self {
91        if entries.is_empty() && complete_reduction == Some(0) {
92            return DecodeReport::default();
93        }
94        DecodeReport {
95            entries,
96            complete_reduction,
97            reduction,
98        }
99    }
100
101    /// Whether the samples are what the whole codestream gives at the
102    /// reduction this decode used.
103    ///
104    /// That holds when [`complete_reduction`](Self::complete_reduction) is at
105    /// most that reduction, no tile is missing and no tile has bytes left
106    /// over. A missing `EOC` marker, a tile-part count that disagrees with the
107    /// parts found ([`ReportEntry::TilePartCountMismatch`]), and packets
108    /// missing only from the resolutions the reduction drops leave it true.
109    #[must_use]
110    pub fn is_complete(&self) -> bool {
111        self.complete_reduction
112            .is_some_and(|complete| complete <= self.reduction)
113            && !self.entries.iter().any(|entry| {
114                matches!(
115                    entry,
116                    ReportEntry::MissingTiles { .. } | ReportEntry::LeftoverBytes { .. }
117                )
118            })
119    }
120}
121
122/// One thing a decode with [`strict`](crate::DecodeOptions::strict) off left
123/// out or skipped, on [`DecodeReport::entries`].
124///
125/// The enum and each of its variants are `#[non_exhaustive]`: a later version
126/// can add variants and fields, so match with a `_` arm and with
127/// `{ field, .. }`, and [`MissingEoc`](Self::MissingEoc) as `MissingEoc { .. }`.
128///
129/// Tiles are numbered in raster order from 0, as the codestream's `Isot`
130/// numbers them, and a tile's tile-parts from 0, as its `TPsot` does.
131///
132/// The [`Display`](fmt::Display) text is a diagnostic for a log, not a stable
133/// format: do not parse it.
134#[derive(Debug, Clone, PartialEq, Eq)]
135#[non_exhaustive]
136pub enum ReportEntry {
137    /// No tile-part of these tiles was found. Their samples are 0 in the
138    /// output, after the DC level shift, as `opj_decompress -allow-partial`
139    /// writes them: 0 for an unsigned component, not its mid-gray, and 0 for
140    /// a signed one. A JP2 palette then maps them as any other index 0.
141    #[non_exhaustive]
142    MissingTiles {
143        /// The tiles, a run of consecutive tile indices.
144        tiles: Range<u32>,
145    },
146    /// Packets of this tile that the decode keeps were never read: the data
147    /// ended first, or the `POC` volumes leave them out. A missing packet
148    /// adds nothing to its code-blocks, so they decode from the layers that
149    /// were read, as a codestream truncated after those layers would.
150    ///
151    /// A packet cut short keeps each code-block whose data is all there, and
152    /// the rest of its code-blocks keep only their earlier layers. A packet
153    /// whose header is cut adds nothing.
154    #[non_exhaustive]
155    MissingPackets {
156        /// The tile.
157        tile: u32,
158        /// How many of the leading quality layers are whole, counted over
159        /// the resolutions this decode keeps.
160        complete_layers: u16,
161        /// The smallest reduction at which this tile has every packet, as
162        /// [`DecodeReport::complete_reduction`] counts it, or `None` when even
163        /// the coarsest resolution of this tile has a packet missing.
164        complete_reduction: Option<u8>,
165    },
166    /// The input ends inside this tile-part: its `Psot` declares more bytes
167    /// than remain. The bytes that are there are read.
168    #[non_exhaustive]
169    TruncatedTilePart {
170        /// The tile.
171        tile: u32,
172        /// The tile-part, as its `TPsot` numbers it.
173        tile_part: u8,
174        /// The tile-part's length as its `Psot` declares it, from its `SOT`
175        /// marker on.
176        declared: u64,
177        /// The bytes of it the input holds.
178        present: u64,
179    },
180    /// The tile's `SOT` markers declare a number of tile-parts (`TNsot`, after
181    /// OpenJPEG's `TPsot == TNsot` correction when that applies) other than
182    /// the number found. The tile decodes from the parts found; any packets
183    /// they lack are reported as [`MissingPackets`](Self::MissingPackets).
184    #[non_exhaustive]
185    TilePartCountMismatch {
186        /// The tile.
187        tile: u32,
188        /// The count the markers declare.
189        declared: u16,
190        /// The tile-parts found.
191        found: u16,
192    },
193    /// Bytes of this tile were not read: every packet the tile's progression
194    /// holds was read, and bytes were left after the last one.
195    ///
196    /// The tile's samples may be wrong: leftover bytes can mean the packets
197    /// were misread. Two encoder bugs leave them in valid tiles. OpenJPEG's
198    /// encoder writes duplicate packets under overlapping progression changes,
199    /// which decode right, and a phantom packet under `-TP R` or `-TP C` with
200    /// empty resolutions, which does not. So the tile counts as incomplete at
201    /// every reduction.
202    #[non_exhaustive]
203    LeftoverBytes {
204        /// The tile.
205        tile: u32,
206        /// The tile-part the leftover bytes start in.
207        tile_part: u8,
208        /// How many bytes were left.
209        bytes: u64,
210        /// Whether the bytes are packet headers packed in `PPT` or `PPM`
211        /// markers rather than tile data.
212        in_packed_headers: bool,
213    },
214    /// The codestream ends without its `EOC` marker. On its own this changes
215    /// no sample.
216    #[non_exhaustive]
217    MissingEoc,
218}
219
220impl fmt::Display for ReportEntry {
221    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222        match self {
223            ReportEntry::MissingTiles { tiles } if tiles.len() == 1 => {
224                write!(f, "tile {} is missing; its samples are 0", tiles.start)
225            }
226            ReportEntry::MissingTiles { tiles } => write!(
227                f,
228                "tiles {} to {} are missing; their samples are 0",
229                tiles.start,
230                tiles.end.saturating_sub(1)
231            ),
232            ReportEntry::MissingPackets {
233                tile,
234                complete_layers,
235                complete_reduction,
236            } => {
237                write!(
238                    f,
239                    "tile {tile} has packets missing; {complete_layers} layer(s) are whole"
240                )?;
241                match complete_reduction {
242                    Some(r) => write!(f, ", and every packet is there at reduction {r}"),
243                    None => write!(f, ", and no reduction has every packet"),
244                }
245            }
246            ReportEntry::TruncatedTilePart {
247                tile,
248                tile_part,
249                declared,
250                present,
251            } => write!(
252                f,
253                "tile {tile} tile-part {tile_part} is cut short: {present} of its {declared} \
254                 bytes are there"
255            ),
256            ReportEntry::TilePartCountMismatch {
257                tile,
258                declared,
259                found,
260            } => write!(
261                f,
262                "tile {tile} declares {declared} tile-part(s) and {found} were found"
263            ),
264            ReportEntry::LeftoverBytes {
265                tile,
266                tile_part,
267                bytes,
268                in_packed_headers,
269            } => {
270                let place = if *in_packed_headers {
271                    "packed packet header"
272                } else {
273                    "tile data"
274                };
275                write!(
276                    f,
277                    "tile {tile} has {bytes} byte(s) of {place} left from tile-part \
278                     {tile_part} on, not read; its samples may be wrong"
279                )
280            }
281            ReportEntry::MissingEoc => write!(f, "the codestream ends without its `EOC` marker"),
282        }
283    }
284}