rust_j2k/incremental.rs
1//! A decoder fed a file as it arrives, which gives a refined image as
2//! more of it comes in (see [`IncrementalDecoder`]).
3
4use std::cell::{Cell, RefCell};
5use std::fmt;
6
7use crate::codestream::{MainHeader, Tile};
8use crate::tier2::resume::Walks;
9use crate::tier2::{CodedData, Meter, Reach, Refused};
10use crate::{DecodeOptions, Error, Image, Result, check_options, decode_metered, decode_with, jp2};
11
12/// A decoder for a file that arrives a piece at a time, from a network or a
13/// slow disk.
14///
15/// [`feed`](Self::feed) appends bytes as they come in, and
16/// [`refine`](Self::refine) decodes what has come in so far. Each image
17/// `refine` returns is the image [`decode_with`] gives with
18/// [`strict`](DecodeOptions::strict) off on the bytes fed so far, with its
19/// [`report`](Image::report) saying what those bytes do not hold yet: the
20/// quality layers and resolutions that are complete, and the tiles still
21/// missing. [`bytes_decoded`](Self::bytes_decoded) is how many bytes that
22/// image is the decode of. Once the input ends, [`finish`](Self::finish)
23/// decodes all of it under the decoder's options.
24///
25/// `refine` does not have to decode every time it is called, so a caller
26/// can call it after every read, however small. It decodes at least each
27/// time the bytes fed have doubled since it last decoded or tried to, and
28/// may decode more often; when it does not decode, it returns `Ok(None)`.
29/// The first refine called with at least one byte fed tries; one called
30/// with none fed returns `Ok(None)` and is not a try. A try that a work
31/// bound refuses counts, so the next refine waits for twice its bytes.
32///
33/// The decoder keeps each tile's packet walk (what it has read of the
34/// tile's packet headers so far) between refines, so a refine reads only
35/// the packets that have come in since the last one. Over all
36/// the refines, the packet headers are read about once, as one decode reads
37/// them; a packet the data cuts is read again by each refine ([the packets
38/// a refine reads
39/// again](https://github.com/D0ubleD0uble/rust-j2k/blob/v0.5.0/docs/incremental-decoding.md)).
40/// Each refine is held to the packet bound of a decode of its bytes on its
41/// own: it is charged the packet visits that decode would spend, and a
42/// refine that decode is refused for returns `Ok(None)`.
43///
44/// The code-block work is done again by each refine that decodes, so the
45/// code-block work every `refine` has spent is held to the bound one decode
46/// of the bytes fed has, raised as the options say. A refine the rest of
47/// that bound cannot cover returns `Ok(None)`, so a file whose code-blocks
48/// cost a lot may give no image before `finish`, which is a decode of its
49/// own, under its own bound. Each refine that returns an image also builds
50/// the whole image, as one decode does: it allocates the samples and runs
51/// the inverse wavelet and color transforms over them, outside the work
52/// bounds. Under the doubling cadence a file of `n` bytes gives at most
53/// about `log2(n)` images, so a large image fed in small pieces costs up to
54/// that many reconstructions.
55///
56/// Between calls the decoder keeps the bytes fed and the tiles' packet
57/// walks. The walks kept hold at most twice what one decode holds at its
58/// peak: twice the image's samples, plus twice the packet walk of the
59/// largest tile. A tile whose walk would pass that is walked from the start
60/// by each refine instead. Each refine also holds what [`decode_with`]
61/// holds for the same bytes, so the decoder holds at most about three
62/// times one decode's peak memory, plus the bytes fed.
63///
64/// That memory follows the image size the file declares, not the bytes fed:
65/// a file of 1228 bytes that declares a 16384 x 16384 image holds about
66/// 640 MB between calls, until the decoder is dropped. A server that keeps
67/// many slow streams open should check the size that
68/// [`read_header`](crate::read_header) reports before it feeds the rest of
69/// a file, or drop the decoders it is not refining.
70///
71/// ```
72/// use rust_j2k::{DecodeOptions, IncrementalDecoder};
73///
74/// # let file = include_bytes!(concat!(
75/// # env!("CARGO_MANIFEST_DIR"),
76/// # "/tests/fixtures/layers/lrcp.j2k"
77/// # )).to_vec();
78/// # /*
79/// let file = std::fs::read("image.j2k")?;
80/// # */
81/// let mut decoder = IncrementalDecoder::new(DecodeOptions::default())?;
82/// // The file arrives 500 bytes at a time.
83/// for piece in file.chunks(500) {
84/// decoder.feed(piece);
85/// if let Some(image) = decoder.refine()? {
86/// // Show the image of what has arrived so far. Its report says
87/// // what is still missing.
88/// println!(
89/// "{} bytes: {}x{}, complete: {}",
90/// decoder.bytes_decoded(),
91/// image.width,
92/// image.height,
93/// image.report.is_complete()
94/// );
95/// }
96/// }
97/// // The input has ended: decode all of it, under the decoder's options
98/// // (strict here).
99/// let image = decoder.finish()?;
100/// assert!(image.report.is_complete());
101/// # Ok::<(), Box<dyn std::error::Error>>(())
102/// ```
103///
104/// An error from `refine` is the error [`decode_with`] gives with `strict`
105/// off on the same bytes, such as a marker segment with an invalid field,
106/// or an [`Error::Limit`] that does not depend on how many bytes there are:
107/// an image past the sample limit, too many precincts or code-blocks, too
108/// many `POC` volumes, or too many bit-planes. More bytes do not undo
109/// these, so once `refine` returns an error, every later `refine` returns
110/// the same error without decoding. Two refusals are not final while bytes
111/// may still come, so `refine` returns `Ok(None)` for them and only
112/// `finish` reports them: a main header cut short ([`Error::Incomplete`]),
113/// and a refusal by the packet or code-block work bound, which more bytes
114/// raise.
115///
116/// The decoder is [`Send`] and [`Sync`].
117pub struct IncrementalDecoder {
118 /// The options `finish` decodes under.
119 options: DecodeOptions,
120 /// The same options with `strict` off, which `refine` decodes under.
121 lenient: DecodeOptions,
122 /// The bytes fed so far.
123 bytes: Vec<u8>,
124 /// How many bytes had been fed at the last refine that decoded, or
125 /// tried to: the next one waits for twice as many.
126 tried: usize,
127 /// How many bytes the last image `refine` returned is the decode of.
128 decoded: usize,
129 /// The work the refines have spent, and the packet walks they keep.
130 spent: Spent,
131 /// Whether a work bound refused the last refine.
132 refused: bool,
133 /// The error a refine returned, which every later call returns.
134 failed: Option<Error>,
135}
136
137impl IncrementalDecoder {
138 /// A decoder with no bytes fed yet, which decodes under `options`.
139 ///
140 /// Options that are invalid whatever the input, which
141 /// [`decode_with`] refuses before it reads a byte, are
142 /// [`Error::InvalidOptions`] here. Options that do not fit the file,
143 /// such as a reduction past its levels, are found by the first decode
144 /// that reads its header.
145 pub fn new(options: DecodeOptions) -> Result<Self> {
146 check_options(&options)?;
147 let lenient = options.clone().with_strict(false);
148 Ok(IncrementalDecoder {
149 options,
150 lenient,
151 bytes: Vec::new(),
152 tried: 0,
153 decoded: 0,
154 spent: Spent::default(),
155 refused: false,
156 failed: None,
157 })
158 }
159
160 /// Append `bytes` to the input. This only copies them; the decoding is
161 /// done by [`refine`](Self::refine) and [`finish`](Self::finish).
162 pub fn feed(&mut self, bytes: &[u8]) {
163 self.bytes.extend_from_slice(bytes);
164 }
165
166 /// How many bytes have been fed.
167 pub fn bytes_fed(&self) -> usize {
168 self.bytes.len()
169 }
170
171 /// How many bytes the last image [`refine`](Self::refine) returned is
172 /// the decode of, or 0 before it has returned one.
173 pub fn bytes_decoded(&self) -> usize {
174 self.decoded
175 }
176
177 /// Decode the bytes fed so far. This decodes at least each time they
178 /// have doubled since it last decoded or tried to, and may decode more
179 /// often.
180 ///
181 /// The image is the one [`decode_with`] gives with
182 /// [`strict`](DecodeOptions::strict) off on all the bytes fed, and its
183 /// [`report`](Image::report) lists what they do not hold yet.
184 /// `Ok(None)` means there is no new image yet: too few bytes have come
185 /// in since the last decode, the main header is not whole, or a work
186 /// bound refused the decode. Any error is the one `decode_with` gives
187 /// on those bytes, and more bytes will not clear it: each later call
188 /// returns it again.
189 pub fn refine(&mut self) -> Result<Option<Image>> {
190 if let Some(error) = &self.failed {
191 return Err(error.clone());
192 }
193 let fed = self.bytes.len();
194 if fed == 0 || fed < self.tried.saturating_mul(2) {
195 return Ok(None);
196 }
197 self.tried = fed;
198 // The ledger lives for the decode alone, so the decoder holds no
199 // `Cell` between calls. Only the walks move into it: if the decode
200 // panics, the code-block work spent stays, and the walks start
201 // again.
202 let walks = std::mem::take(&mut self.spent.walks);
203 let ledger = Ledger::over(walks, self.spent.blocks);
204 let decoded = decode_metered(&self.bytes, &self.lenient, Some(&ledger));
205 self.refused = ledger.work_refused.get();
206 self.spent = ledger.into_spent();
207 match decoded {
208 Ok(image) => {
209 self.decoded = fed;
210 Ok(Some(image))
211 }
212 // More bytes can complete the header, and raise the work
213 // bounds.
214 Err(Error::Incomplete(_)) => Ok(None),
215 Err(Error::Limit(_)) if self.refused => Ok(None),
216 Err(error) => {
217 self.failed = Some(error.clone());
218 Err(error)
219 }
220 }
221 }
222
223 /// The input has ended: decode all of it under the decoder's options,
224 /// as [`decode_with`] does.
225 ///
226 /// With [`strict`](DecodeOptions::strict) on, the default, a file cut
227 /// short is refused as `decode_with` refuses it. With `strict` off, it
228 /// gives the image the bytes hold, with a report of what is missing. In
229 /// both cases, a file that ends before its main header is whole, which
230 /// [`refine`](Self::refine) waits on, is truncated now:
231 /// [`Error::FileFormat`] when it ends inside the boxes of a JP2 file
232 /// before its codestream, and [`Error::Codestream`] when it ends inside
233 /// the codestream's main header.
234 ///
235 /// This is a decode of its own, also after a `refine` has returned an
236 /// error: under strict options it may refuse the bytes for an earlier
237 /// fault, such as the data ending, than the one `refine` found.
238 ///
239 /// `finish` borrows the decoder and keeps nothing from the call, so it
240 /// can be called again and gives the same result. When it refuses a
241 /// work limit, [`into_bytes`](Self::into_bytes) gives the bytes back to
242 /// decode with the limit raised.
243 pub fn finish(&self) -> Result<Image> {
244 match decode_with(&self.bytes, &self.options) {
245 Err(Error::Incomplete(why)) => {
246 let in_boxes = !self.bytes.starts_with(&[0xFF, 0x4F])
247 && jp2::looks_like_jp2(&self.bytes)
248 && matches!(
249 jp2::parse(&self.bytes, &self.options.packet_work_limit),
250 Err(Error::Incomplete(_))
251 );
252 let why = format!("the input is truncated: {why}");
253 Err(if in_boxes {
254 Error::file_format(why)
255 } else {
256 Error::codestream(why)
257 })
258 }
259 decoded => decoded,
260 }
261 }
262
263 /// A decoder whose earlier refines spent `blocks` of the code-block
264 /// work, as the unit tests set it up (see [`crate::fuzz`]).
265 pub(crate) fn with_code_block_work_spent(options: DecodeOptions, blocks: u64) -> Result<Self> {
266 let mut decoder = Self::new(options)?;
267 decoder.spent.blocks = blocks;
268 Ok(decoder)
269 }
270
271 /// The code-block work the refines have spent, and the code-block
272 /// bound of the last decode a refine tried, when that decode read the
273 /// main header and has a bound (see [`crate::fuzz`]).
274 pub(crate) fn code_block_work(&self) -> (u64, Option<u64>) {
275 (self.spent.blocks, self.spent.bound)
276 }
277
278 /// Consumes the decoder and returns the bytes fed.
279 ///
280 /// After [`finish`](Self::finish) refuses a work limit, decode these
281 /// with [`decode_with`], or feed them to a new decoder, under options
282 /// with the limit raised.
283 #[must_use]
284 pub fn into_bytes(self) -> Vec<u8> {
285 self.bytes
286 }
287}
288
289impl fmt::Debug for IncrementalDecoder {
290 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
291 f.debug_struct("IncrementalDecoder")
292 .field("options", &self.options)
293 .field("bytes_fed", &self.bytes.len())
294 .field("bytes_decoded", &self.decoded)
295 .finish_non_exhaustive()
296 }
297}
298
299// The decoder can be shared and sent between threads, and a panic in one
300// of its calls leaves nothing half-borrowed.
301const _: () = {
302 const fn holds<T: Send + Sync + std::panic::UnwindSafe + std::panic::RefUnwindSafe>() {}
303 holds::<IncrementalDecoder>();
304};
305
306/// What the decodes of an [`IncrementalDecoder`] keep between them (see
307/// [`Ledger`]).
308#[derive(Default)]
309struct Spent {
310 walks: Walks,
311 /// The code-block work spent.
312 blocks: u64,
313 /// The code-block bound of the last decode, when it had one.
314 bound: Option<u64>,
315}
316
317/// What the decodes of an [`IncrementalDecoder`] keep between them, so
318/// that all of them together stay within the work bounds one decode of the
319/// same bytes has. It is built from [`Spent`] for the length of one decode.
320///
321/// Each tile's packet walk is kept (see [`Walks`]): a decode goes on from
322/// where the last one stopped, and reads each packet once, however many
323/// decodes there are. It is charged what the walk of a decode of its bytes
324/// on its own would spend, and refused where that walk is refused, so the
325/// packet bound is not cut. The code-block work is done again by each
326/// decode, so the code-block bound of each is cut by what the earlier ones
327/// spent.
328pub(crate) struct Ledger {
329 /// The tiles' packet walks.
330 walks: RefCell<Walks>,
331 /// The code-block work spent.
332 blocks: Cell<u64>,
333 /// The code-block bound of this decode, once it is known.
334 bound: Cell<Option<u64>>,
335 /// Whether a work bound refused the last decode.
336 work_refused: Cell<bool>,
337}
338
339impl fmt::Debug for Ledger {
340 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
341 f.debug_struct("Ledger")
342 .field("blocks", &self.blocks)
343 .field("bound", &self.bound)
344 .field("work_refused", &self.work_refused)
345 .finish_non_exhaustive()
346 }
347}
348
349impl Ledger {
350 /// A ledger over the walks and the code-block work of the earlier
351 /// decodes.
352 fn over(walks: Walks, blocks: u64) -> Self {
353 Ledger {
354 walks: RefCell::new(walks),
355 blocks: Cell::new(blocks),
356 bound: Cell::new(None),
357 work_refused: Cell::new(false),
358 }
359 }
360
361 /// What the decodes have spent, this one included.
362 fn into_spent(self) -> Spent {
363 Spent {
364 walks: self.walks.into_inner(),
365 blocks: self.blocks.get(),
366 bound: self.bound.get(),
367 }
368 }
369
370 /// The code-block work a decode whose own bound is `bound` may spend:
371 /// what is left of it after the earlier decodes. No bound
372 /// ([`WorkLimit::Unlimited`](crate::WorkLimit::Unlimited)) stays none.
373 /// The ledger keeps `bound` as this decode's.
374 pub(crate) fn blocks_left(&self, bound: u64) -> u64 {
375 self.bound.set(Some(bound));
376 if bound == u64::MAX {
377 return bound;
378 }
379 bound.saturating_sub(self.blocks.get())
380 }
381
382 /// Tile `tile`'s packets, as a walk with `strict` off of the bytes it
383 /// holds gives them (see [`Walks::walk`]), going on from the walk the
384 /// earlier decodes left.
385 #[allow(clippy::too_many_arguments)]
386 pub(crate) fn walk<'t>(
387 &self,
388 header: &MainHeader,
389 tile: &'t Tile<'t>,
390 meter: &Meter,
391 poc_bitmap: u64,
392 reduction: u8,
393 layers: Option<u16>,
394 image: u64,
395 ) -> std::result::Result<(CodedData<'t>, Reach), Refused> {
396 self.walks
397 .borrow_mut()
398 .walk(header, tile, meter, poc_bitmap, reduction, layers, image)
399 }
400
401 /// Record that a work bound refused a decode: the packet walk, the
402 /// code-block work or the charge for missing tiles. The bounds grow
403 /// with the bytes and the missing tiles shrink, so more bytes may
404 /// clear it.
405 pub(crate) fn refuse(&self) {
406 self.work_refused.set(true);
407 }
408
409 /// Add `work` to the code-block work spent.
410 pub(crate) fn spend_blocks(&self, work: u64) {
411 self.blocks.set(self.blocks.get().saturating_add(work));
412 }
413}
414
415#[cfg(test)]
416mod tests;