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