Skip to main content

webp/dec/
idec_dec.rs

1// libwebp v1.6.0, src/dec/idec_dec.c:
2//
3// Copyright 2011 Google Inc. All Rights Reserved.
4//
5// Use of this source code is governed by a BSD-style license
6// that can be found in the COPYING file in the root of the source
7// tree. An additional intellectual property rights grant can be found
8// in the file PATENTS. All contributing project authors may
9// be found in the AUTHORS file in the root of the source tree.
10// -----------------------------------------------------------------------------
11//
12// Incremental decoding
13//
14// Author: somnath@google.com (Somnath Banerjee)
15
16//! Translation of `src/dec/idec_dec.c` from libwebp v1.6.0.
17//!
18//! Work package: WP12 (decoder integration).
19//!
20//! The decoder keeps `io`, `params`, the VP8 or VP8L decoder, `mem` and its
21//! output buffers as plain fields and passes disjoint borrows of them to each
22//! call (ADR 0003, "Decoding context per call"). The input of a decoding step is
23//! the memory buffer: in append mode the decoder's own `mem.buf`, in map mode the
24//! caller's buffer, which `WebPIUpdate` passes and which the decoder does not
25//! keep between calls. Every C pointer into that input is an index of it: the
26//! readers of the VP8 decoder (`VP8GetHeaders` sets them up at `mem.start`), the
27//! alpha chunk and the token partitions; `DoRemap` moves them by the index
28//! delta that C adds to its pointers, which is 0 in map mode, where the bytes
29//! keep their positions in the caller's growing buffer. Partition #0 is read
30//! from `mem.part0_buf` once `CopyParts0Data` copied it in append mode. The VP8L
31//! reader reads the input from `mem.start` on.
32//!
33//! The io hooks are the custom ones of `WebPInitCustomIo` over `params` and the
34//! output buffer, or the caller's from `WebPISetIOHooks`; they are made for
35//! each call. C's `params.output` is the decoder's own `output` or the caller's
36//! buffer (`user_output`). For slow external memory the caller's buffer is
37//! `final_output` until `FinishDecoding` copies the samples into it; C then
38//! copies the caller's buffer structure into its own `output`, which here
39//! becomes `params.output = user_output` (see `# Deviations from upstream`,
40//! item 1).
41//!
42//! # Representation
43//!
44//! 1. **Incremental decoder.** `WebPIDecoder<'a, 'b>` keeps `io`, `params`, the
45//!    decoder (`enum` of a boxed `VP8Decoder` and `VP8LDecoder`), `mem` and its
46//!    own output buffer as plain fields. `'a` is what the caller lends for the
47//!    decoder's life (the options and output buffer of a `WebPDecoderConfig`,
48//!    the output buffer of `WebPINewDecoder`, the hooks of `WebPISetIOHooks`);
49//!    `'b` is the caller memory that an output buffer borrows. C's
50//!    `params.output` is the caller's buffer (`user_output`) or the decoder's
51//!    own. Two lifetimes are needed because a mutable borrow is invariant: one
52//!    lifetime would keep the configuration borrowed for its whole existence.
53//!    Dropping the decoder is `WebPIDelete`.
54//!
55//! # Deviations from upstream
56//!
57//! Changes of representation that the ADRs allow, or behavior that the Rust
58//! side cannot reproduce exactly. Each records the reason.
59//!
60//! 1. **The slow copy of the incremental decoder.** After `FinishDecoding`
61//!    copies into the caller's buffer, C copies the caller's buffer structure
62//!    into its own `output` (`*output = *idec->final_output`), which
63//!    `params.output` points at. Safe Rust cannot hold a second view of the
64//!    caller's memory, so `params.output` becomes the caller's buffer, which
65//!    has the same contents; the C ABI returns C's copy of the structure from
66//!    `WebPIDecodedArea`, as C does. In the C ABI the decoder's own block stays
67//!    allocated until `WebPIDelete` (C frees it at the copy).
68//! 2. **Allocation sizes.** `CopyParts0Data` tests `WebPSafeMalloc(1, size)` as
69//!    `size` elements of one byte (the same outcome). `NewDecoder`, `VP8New`
70//!    and `VP8LNew` cannot fail; a refused host allocation of a fixed-size
71//!    object aborts.
72//!
73//! # Calling the VP8 decoder
74//!
75//! How `WebPIDecoder` drives the VP8 decoder:
76//!
77//! 1. `WebPIDecoder` keeps `io`, `params`, `dec`, `mem` and the output side by
78//!    side and passes disjoint borrows: `vp8_enter_critical(dec, io, hooks)`,
79//!    `vp8_init_frame(dec, io, alpha_data)`, then per row
80//!    `vp8_parse_intra_mode_row`, `vp8_decode_mb(dec, token_br, data)` for each
81//!    macroblock, `vp8_init_scanline` and `vp8_process_row(dec, io, alpha_data,
82//!    hooks)`, and `vp8_exit_critical`.
83//! 2. The same `data` and `alpha_data` must reach every call of one decoding;
84//!    `alpha_data` is the bytes in `mem`, so `DoRemap` needs no alpha update (C
85//!    moves `dec->alpha_data`), and `NeedCompressedAlpha` tests
86//!    `alpha_data.is_some()` and `!dec.is_alpha_decoded`.
87//! 3. `DoRemap` remaps `dec.br` and `dec.parts` with index deltas (the bit
88//!    readers store positions). `RestoreContext` copies `dec.br` and
89//!    `dec.parts[token_br]` field by field (the bit reader has no `Clone`).
90//! 4. `VP8Clear` before an `End` with a pending row is never needed: call
91//!    `vp8_exit_critical` first, as `IDecError` does.
92//!
93//! # Excluded undefined behavior
94//!
95//! Inputs that are undefined behavior (or assertion failures) in C and are
96//! therefore excluded from the oracle comparison (PORTING rule 8):
97//!
98//! 1. **`WebPIAppend` of zero bytes before any data**: C asserts
99//!    `mem->buf != NULL` and calls `memcpy` with a `NULL` destination.
100//! 2. **`WebPISetIOHooks` with a lossless image**: C's `VP8LDecodeImage` reads
101//!    the caller's user data as `WebPDecParams`; Rust uses the decoder's
102//!    parameters (ADR 0003).
103
104use crate::dec::buffer_dec::{
105    is_null_plane, webp_allocate_dec_buffer, webp_avoid_slow_memory, webp_copy_dec_buffer_pixels,
106    webp_flip_buffer, webp_free_dec_buffer,
107};
108use crate::dec::frame_dec::{
109    vp8_enter_critical, vp8_exit_critical, vp8_get_thread_method, vp8_init_dithering,
110    vp8_init_frame, vp8_process_row, vp8_sync_rows,
111};
112use crate::dec::io_dec::{CustomIo, webp_init_custom_io};
113use crate::dec::tree_dec::vp8_parse_intra_mode_row;
114use crate::dec::vp8_dec::{
115    VP8Io, VP8IoHooks, vp8_decode_mb, vp8_get_headers_at, vp8_get_info, vp8_init_io,
116    vp8_init_scanline, vp8_new,
117};
118use crate::dec::vp8i_dec::{VP8Decoder, VP8MB};
119use crate::dec::vp8l_dec::{vp8l_decode_header, vp8l_decode_image, vp8l_new};
120use crate::dec::vp8li_dec::VP8LDecoder;
121use crate::dec::webp_dec::{webp_parse_headers, webp_reset_dec_params};
122use crate::dec::webpi_dec::{WebPDecParams, WebPHeaderStructure};
123use crate::utils::bit_reader_utils::{
124    VP8BitReader, vp8_bit_reader_set_buffer, vp8_remap_bit_reader, vp8l_bit_reader_set_buffer,
125};
126use crate::utils::utils::webp_safe_malloc;
127use crate::webp::decode::{
128    VP8StatusCode, WEBP_CSP_MODE, WebPBitstreamFeatures, WebPDecBuffer, WebPDecBufferPlanes,
129    WebPDecoderConfig, WebPDecoderOptions, WebPRGBABuffer, WebPYUVABuffer, webp_get_features,
130    webp_init_dec_buffer,
131};
132use crate::webp::format_constants::{
133    ALPHA_HEADER_LEN, ALPHA_LOSSLESS_COMPRESSION, MAX_CHUNK_PAYLOAD, VP8_FRAME_HEADER_SIZE,
134};
135use crate::webp::types::{PlaneOffset, PlaneStorage};
136
137// upstream: src/dec/idec_dec.c CHUNK_SIZE
138/// In append mode, buffer allocations increase as multiples of this value.
139/// Needs to be a power of 2.
140const CHUNK_SIZE: u64 = 4096;
141// upstream: src/dec/idec_dec.c MAX_MB_SIZE
142const MAX_MB_SIZE: usize = 4096;
143
144//------------------------------------------------------------------------------
145// Data structures for memory and states
146
147// upstream: src/dec/idec_dec.c DecState
148/// Decoding states. State normally flows as:
149/// `WEBP_HEADER->VP8_HEADER->VP8_PARTS0->VP8_DATA->DONE` for a lossy image, and
150/// `WEBP_HEADER->VP8L_HEADER->VP8L_DATA->DONE` for a lossless image.
151/// If there is any error the decoder goes into state `ERROR`.
152#[repr(transparent)]
153#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
154struct DecState(u32);
155
156impl DecState {
157    // upstream: src/dec/idec_dec.c STATE_WEBP_HEADER
158    /// All the data before that of the VP8/VP8L chunk.
159    const STATE_WEBP_HEADER: Self = Self(0);
160    // upstream: src/dec/idec_dec.c STATE_VP8_HEADER
161    /// The VP8 Frame header (within the VP8 chunk).
162    const STATE_VP8_HEADER: Self = Self(1);
163    // upstream: src/dec/idec_dec.c STATE_VP8_PARTS0
164    const STATE_VP8_PARTS0: Self = Self(2);
165    // upstream: src/dec/idec_dec.c STATE_VP8_DATA
166    const STATE_VP8_DATA: Self = Self(3);
167    // upstream: src/dec/idec_dec.c STATE_VP8L_HEADER
168    const STATE_VP8L_HEADER: Self = Self(4);
169    // upstream: src/dec/idec_dec.c STATE_VP8L_DATA
170    const STATE_VP8L_DATA: Self = Self(5);
171    // upstream: src/dec/idec_dec.c STATE_DONE
172    const STATE_DONE: Self = Self(6);
173    // upstream: src/dec/idec_dec.c STATE_ERROR
174    const STATE_ERROR: Self = Self(7);
175}
176
177// upstream: src/dec/idec_dec.c MemBufferMode
178/// Operating state for the `MemBuffer`.
179#[repr(transparent)]
180#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
181struct MemBufferMode(u32);
182
183impl MemBufferMode {
184    // upstream: src/dec/idec_dec.c MEM_MODE_NONE
185    const MEM_MODE_NONE: Self = Self(0);
186    // upstream: src/dec/idec_dec.c MEM_MODE_APPEND
187    const MEM_MODE_APPEND: Self = Self(1);
188    // upstream: src/dec/idec_dec.c MEM_MODE_MAP
189    const MEM_MODE_MAP: Self = Self(2);
190}
191
192// upstream: src/dec/idec_dec.c MemBuffer
193/// Storage for partition #0 and partial data (in a rolling fashion).
194///
195/// `buf` is the decoder's own memory in append mode (`buf_size` bytes, empty
196/// where C has `NULL`). In map mode C points `buf` at the caller's buffer; here
197/// the caller passes it to each `WebPIUpdate`, and `buf` stays empty.
198/// `part0_buf` is empty where C has `NULL`.
199#[derive(Debug, Default)]
200struct MemBuffer {
201    /// Operation mode.
202    mode: MemBufferMode,
203    /// Start location of the data to be decoded.
204    start: usize,
205    /// End location.
206    end: usize,
207    /// Size of the allocated buffer.
208    buf_size: usize,
209    /// The data in append mode.
210    buf: Vec<u8>,
211    /// Size of partition #0.
212    part0_size: usize,
213    /// Buffer to store partition #0.
214    part0_buf: Vec<u8>,
215}
216
217/// C's `void* dec`, which `is_lossless` down-casts: either a `VP8Decoder` or a
218/// `VP8LDecoder` instance. This type has no C counterpart.
219enum IDecDecoder {
220    /// The lossy decoder.
221    VP8(Box<VP8Decoder>),
222    /// The lossless decoder.
223    VP8L(Box<VP8LDecoder>),
224}
225
226// upstream: src/dec/idec_dec.c WebPIDecoder
227/// The incremental decoder.
228///
229/// `'a` is the lifetime of what the caller lends to the decoder for its whole
230/// life: the decoding options and output buffer of a `WebPDecoderConfig`, or
231/// the output buffer of `WebPINewDecoder`, and the hooks of `WebPISetIOHooks`.
232/// `'b` is the lifetime of the caller's memory that an output buffer borrows.
233/// C's `params.output` is `user_output` when the caller supplied a buffer and
234/// `output` otherwise. C keeps the alpha chunk in the VP8 decoder
235/// (`dec->alpha_data`); here it is a position in the input, kept by its owner.
236pub struct WebPIDecoder<'a, 'b> {
237    /// Current decoding state.
238    state: DecState,
239    /// Params to store output info.
240    params: WebPDecParams<'a>,
241    /// For down-casting `dec`.
242    is_lossless: bool,
243    /// Either a `VP8Decoder` or a `VP8LDecoder` instance; `None` is `NULL`.
244    dec: Option<IDecDecoder>,
245    io: VP8Io,
246
247    /// Input memory buffer.
248    mem: MemBuffer,
249    /// Output buffer (when no external one is supplied, or if the external
250    /// one has slow-memory).
251    output: WebPDecBuffer<'b>,
252    /// The caller's output buffer, which C's `params.output` points at when
253    /// one was supplied without slow memory, or after the slow copy.
254    user_output: Option<&'a mut WebPDecBuffer<'b>>,
255    /// Slow-memory output to copy to eventually.
256    final_output: Option<&'a mut WebPDecBuffer<'b>>,
257    /// Set when `NewDecoder` chose a `final_output` (no C counterpart: C's
258    /// `params.output` then stays `&idec->output`, which the C ABI reproduces).
259    slow_copy: bool,
260    /// Compressed VP8/VP8L size extracted from Header.
261    chunk_size: usize,
262
263    /// Last row reached for intra-mode decoding.
264    last_mb_y: i32,
265
266    /// The alpha chunk of the VP8 decoder, as a position in the input (C:
267    /// `dec->alpha_data`, `NULL` is `None`).
268    alpha_data: Option<usize>,
269    /// Its size (C: `dec->alpha_data_size`).
270    alpha_data_size: usize,
271    /// The hooks of `WebPISetIOHooks` with their user data; `None` stands for
272    /// the custom hooks of `WebPInitCustomIo`.
273    hooks: Option<Box<dyn VP8IoHooks + 'a>>,
274}
275
276// upstream: src/dec/idec_dec.c MBContext
277/// MB context to restore in case `VP8DecodeMB()` fails.
278struct MBContext {
279    left: VP8MB,
280    info: VP8MB,
281    token_br: VP8BitReader,
282}
283
284/// The lossy decoder of `dec`.
285///
286/// # Panics
287///
288/// Panics when the decoder is not a VP8 decoder, where C would down-cast the
289/// wrong object.
290fn vp8_dec(dec: &mut Option<IDecDecoder>) -> &mut VP8Decoder {
291    match dec {
292        Some(IDecDecoder::VP8(dec)) => dec,
293        _ => panic!("the decoder is a VP8 decoder"),
294    }
295}
296
297/// The lossless decoder of `dec`; see [`vp8_dec`].
298fn vp8l_dec(dec: &mut Option<IDecDecoder>) -> &mut VP8LDecoder {
299    match dec {
300        Some(IDecDecoder::VP8L(dec)) => dec,
301        _ => panic!("the decoder is a VP8L decoder"),
302    }
303}
304
305/// The status code of a `Result`, as C stores it in `dec->status`.
306fn status_code(result: Result<(), VP8StatusCode>) -> VP8StatusCode {
307    result.err().unwrap_or(VP8StatusCode::VP8_STATUS_OK)
308}
309
310/// C's `params.output`: the caller's buffer, or the decoder's own.
311fn params_output<'s, 'b>(
312    output: &'s mut WebPDecBuffer<'b>,
313    user_output: &'s mut Option<&'_ mut WebPDecBuffer<'b>>,
314) -> &'s mut WebPDecBuffer<'b> {
315    match user_output {
316        Some(user_output) => user_output,
317        None => output,
318    }
319}
320
321/// The io hooks of one call: the caller's, or the custom hooks of
322/// `WebPInitCustomIo` over the parameters and the output buffer (C:
323/// `io->put`, `io->setup`, `io->teardown` and `io->opaque`). This type has no C
324/// counterpart.
325enum IoHooks<'s, 'a, 'b> {
326    /// The hooks of `WebPISetIOHooks`.
327    User(&'s mut (dyn VP8IoHooks + 'a)),
328    /// The hooks of `WebPInitCustomIo`.
329    Custom(CustomIo<'s, 'a, 'b>),
330}
331
332impl IoHooks<'_, '_, '_> {
333    /// The hooks as the decoding functions take them.
334    fn get(&mut self) -> &mut dyn VP8IoHooks {
335        match self {
336            Self::User(hooks) => &mut **hooks,
337            Self::Custom(hooks) => hooks,
338        }
339    }
340}
341
342/// The io hooks of one call; see [`IoHooks`].
343fn io_hooks<'s, 'a, 'b>(
344    hooks: &'s mut Option<Box<dyn VP8IoHooks + 'a>>,
345    params: &'s mut WebPDecParams<'a>,
346    output: &'s mut WebPDecBuffer<'b>,
347    user_output: &'s mut Option<&'a mut WebPDecBuffer<'b>>,
348    io: &mut VP8Io,
349) -> IoHooks<'s, 'a, 'b> {
350    match hooks {
351        Some(hooks) => IoHooks::User(hooks.as_mut()),
352        None => IoHooks::Custom(webp_init_custom_io(
353            params,
354            params_output(output, user_output),
355            io,
356        )),
357    }
358}
359
360/// The alpha chunk in the input (C: `dec->alpha_data[..alpha_data_size]`).
361/// Once the alpha plane is decoded, C no longer moves `alpha_data` with the
362/// input and never reads it again; the stale position then gives the bytes that
363/// happen to be there, or none.
364fn alpha_slice(input: &[u8], alpha_data: Option<usize>, alpha_data_size: usize) -> Option<&[u8]> {
365    alpha_data.map(|alpha| {
366        input
367            .get(alpha..alpha + alpha_data_size)
368            .unwrap_or_default()
369    })
370}
371
372/// A copy of a reader (WP2's reader has no `Clone`): C copies the structure.
373fn copy_bit_reader(br: &VP8BitReader) -> VP8BitReader {
374    VP8BitReader {
375        value: br.value,
376        range: br.range,
377        bits: br.bits,
378        has_buf: br.has_buf,
379        buf: br.buf,
380        buf_end: br.buf_end,
381        buf_max: br.buf_max,
382        eof: br.eof,
383    }
384}
385
386/// `pointer += offset` for an index.
387///
388/// # Panics
389///
390/// Panics when the index would become negative, which means that `offset` does
391/// not describe a move of the input's bytes.
392fn add_offset(index: usize, offset: isize) -> usize {
393    index
394        .checked_add_signed(offset)
395        .expect("the moved position stays in the input")
396}
397
398/// An index as the signed difference C computes between pointers.
399fn signed(index: usize) -> isize {
400    isize::try_from(index).expect("a position in the input fits in isize")
401}
402
403//------------------------------------------------------------------------------
404// MemBuffer: incoming data handling
405
406// upstream: src/dec/idec_dec.c MemDataSize
407fn mem_data_size(mem: &MemBuffer) -> usize {
408    mem.end - mem.start
409}
410
411// upstream: src/dec/idec_dec.c NeedCompressedAlpha
412/// Checks if we need to preserve the compressed alpha data, as it may not have
413/// been decoded yet.
414fn need_compressed_alpha(idec: &WebPIDecoder<'_, '_>) -> bool {
415    if idec.state == DecState::STATE_WEBP_HEADER {
416        // We haven't parsed the headers yet, so we don't know whether the image is
417        // lossy or lossless. This also means that we haven't parsed the ALPH chunk.
418        return false;
419    }
420    if idec.is_lossless {
421        false // ALPH chunk is not present for lossless images.
422    } else {
423        // Must be a decoder as idec->state != STATE_WEBP_HEADER.
424        let Some(IDecDecoder::VP8(dec)) = &idec.dec else {
425            panic!("a lossy decoding past the headers has a VP8 decoder")
426        };
427        idec.alpha_data.is_some() && !dec.is_alpha_decoded
428    }
429}
430
431// upstream: src/dec/idec_dec.c DoRemap
432/// Moves the positions into the input by `offset`, the index delta of the
433/// input's bytes (see the module documentation), and gives the last partition
434/// and the lossless reader the input up to `mem.end`. C also points `io.data`
435/// at the new input; here the input is passed per call.
436#[allow(clippy::needless_range_loop, reason = "the C index loops")]
437fn do_remap(idec: &mut WebPIDecoder<'_, '_>, offset: isize) {
438    let need_compressed_alpha = need_compressed_alpha(idec);
439    let mem = &idec.mem;
440    // note: for VP8, setting up idec->io is only really needed at the beginning
441    // of the decoding, till partition #0 is complete.
442
443    match &mut idec.dec {
444        None => {}
445        Some(IDecDecoder::VP8(dec)) => {
446            let last_part = dec.num_parts_minus_one as usize;
447            if offset != 0 {
448                for p in 0..last_part {
449                    vp8_remap_bit_reader(&mut dec.parts[p], offset);
450                }
451                // C moves the three pointers of the last partition too. Its end
452                // and limit can then lie before the new buffer: with one
453                // partition, `mem.start` follows the reader, which can be past its
454                // limit near the end of the input. The buffer reset below
455                // replaces both, so only the position moves here, which keeps
456                // the positions non-negative.
457                let last = &mut dec.parts[last_part];
458                if last.has_buf {
459                    last.buf = add_offset(last.buf, offset);
460                }
461                // Remap partition #0 data pointer to new offset, but only in MAP
462                // mode (in APPEND mode, partition #0 is copied into a fixed memory).
463                if mem.mode == MemBufferMode::MEM_MODE_MAP {
464                    vp8_remap_bit_reader(&mut dec.br, offset);
465                }
466            }
467            {
468                let last = &mut dec.parts[last_part];
469                // 'last_start' will be NULL when 'idec->state' is < STATE_VP8_PARTS0
470                // and through a portion of that state (when there isn't enough data to
471                // parse the partitions). The bitreader is only used meaningfully when
472                // there is enough data to begin parsing partition 0.
473                if last.has_buf {
474                    let last_start = last.buf;
475                    // C: VP8BitReaderSetBuffer(last, last_start, end - last_start).
476                    vp8_bit_reader_set_buffer(last, mem.end - last_start);
477                    vp8_remap_bit_reader(last, signed(last_start));
478                }
479            }
480            if need_compressed_alpha {
481                let alpha_data = add_offset(
482                    idec.alpha_data
483                        .expect("compressed alpha needs the alpha chunk"),
484                    offset,
485                );
486                idec.alpha_data = Some(alpha_data);
487                if let Some(alph_dec) = dec.alph_dec.as_deref_mut()
488                    && let Some(alph_vp8l_dec) = alph_dec.vp8l_dec.as_deref_mut()
489                {
490                    if alph_dec.method == ALPHA_LOSSLESS_COMPRESSION {
491                        let header_len = ALPHA_HEADER_LEN.unsigned_abs() as usize;
492                        debug_assert!(idec.alpha_data_size >= header_len);
493                        // C: VP8LBitReaderSetBuffer(&alph_vp8l_dec->br,
494                        //   dec->alpha_data + ALPHA_HEADER_LEN, size - ALPHA_HEADER_LEN);
495                        // the reader's positions are in the moved chunk.
496                        vp8l_bit_reader_set_buffer(
497                            &mut alph_vp8l_dec.br,
498                            idec.alpha_data_size - header_len,
499                        );
500                    } else {
501                        // alph_dec->method == ALPHA_NO_COMPRESSION
502                        // Nothing special to do in this case.
503                    }
504                }
505            }
506        }
507        Some(IDecDecoder::VP8L(dec)) => {
508            // Resize lossless bitreader
509            vp8l_bit_reader_set_buffer(&mut dec.br, mem_data_size(mem));
510        }
511    }
512}
513
514// upstream: src/dec/idec_dec.c AppendToMemBuffer
515/// Appends data to the end of `MemBuffer->buf`. It expands the allocated memory
516/// size if required and also updates the readers if new memory is allocated.
517/// Returns false when the data is too large or the allocation fails.
518#[expect(
519    clippy::cast_possible_truncation,
520    reason = "C converts the uint64_t size to size_t, which holds it after WebPSafeMalloc"
521)]
522fn append_to_mem_buffer(idec: &mut WebPIDecoder<'_, '_>, data: &[u8]) -> bool {
523    let need_compressed_alpha = need_compressed_alpha(idec);
524    let mem = &mut idec.mem;
525    // C: old_start is NULL without a buffer, where start is 0 (asserted below).
526    let old_start = mem.start;
527    let old_base = if need_compressed_alpha {
528        idec.alpha_data
529            .expect("compressed alpha needs the alpha chunk")
530    } else {
531        old_start
532    };
533    debug_assert!(!mem.buf.is_empty() || mem.start == 0);
534    debug_assert_eq!(mem.mode, MemBufferMode::MEM_MODE_APPEND);
535    if data.len() as u64 > u64::from(MAX_CHUNK_PAYLOAD) {
536        // security safeguard: trying to allocate more than what the format
537        // allows for a chunk should be considered a smoke smell.
538        return false;
539    }
540
541    if mem.end + data.len() > mem.buf_size {
542        // Need some free memory
543        let new_mem_start = old_start - old_base;
544        let current_size = mem_data_size(mem) + new_mem_start;
545        let new_size = current_size as u64 + data.len() as u64;
546        let extra_size = (new_size + CHUNK_SIZE - 1) & !(CHUNK_SIZE - 1);
547        let Some(mut new_buf) = webp_safe_malloc::<u8>(extra_size, 1) else {
548            return false;
549        };
550        // Rust initializes the allocation (ADR 0003, allocation limits).
551        new_buf.resize(extra_size as usize, 0);
552        if !mem.buf.is_empty() {
553            // C: if (old_base != NULL)
554            new_buf[..current_size].copy_from_slice(&mem.buf[old_base..old_base + current_size]);
555        }
556        // C: WebPSafeFree(mem->buf).
557        mem.buf = new_buf;
558        mem.buf_size = extra_size as usize;
559        mem.start = new_mem_start;
560        mem.end = current_size;
561    }
562
563    debug_assert_ne!(mem.buf.len(), 0);
564    mem.buf[mem.end..mem.end + data.len()].copy_from_slice(data);
565    mem.end += data.len();
566    debug_assert!(mem.end <= mem.buf_size);
567
568    let offset = signed(mem.start) - signed(old_start);
569    do_remap(idec, offset);
570    true
571}
572
573// upstream: src/dec/idec_dec.c RemapMemBuffer
574/// Makes the memory buffer the caller's `data`, which holds the data so far
575/// at the same positions. C points `mem->buf` at `data` and moves its pointers
576/// by the distance between the old and the new buffer; the positions here are
577/// indexes of the caller's buffer, which do not change. Returns false for a
578/// shorter buffer.
579fn remap_mem_buffer(idec: &mut WebPIDecoder<'_, '_>, data: &[u8]) -> bool {
580    let mem = &mut idec.mem;
581    let old_start = mem.start;
582    debug_assert_eq!(mem.mode, MemBufferMode::MEM_MODE_MAP);
583
584    if data.len() < mem.buf_size {
585        return false; // can't remap to a shorter buffer!
586    }
587
588    // C: mem->buf = (uint8_t*)data; the caller passes it to each call.
589    mem.end = data.len();
590    mem.buf_size = data.len();
591
592    let offset = signed(mem.start) - signed(old_start);
593    do_remap(idec, offset);
594    true
595}
596
597// upstream: src/dec/idec_dec.c InitMemBuffer
598fn init_mem_buffer(mem: &mut MemBuffer) {
599    mem.mode = MemBufferMode::MEM_MODE_NONE;
600    mem.buf = Vec::new();
601    mem.buf_size = 0;
602    mem.part0_buf = Vec::new();
603    mem.part0_size = 0;
604}
605
606// upstream: src/dec/idec_dec.c ClearMemBuffer
607fn clear_mem_buffer(mem: &mut MemBuffer) {
608    if mem.mode == MemBufferMode::MEM_MODE_APPEND {
609        mem.buf = Vec::new();
610        mem.part0_buf = Vec::new();
611    }
612}
613
614// upstream: src/dec/idec_dec.c CheckMemBufferMode
615/// Returns false when the calls mix the modes.
616fn check_mem_buffer_mode(mem: &mut MemBuffer, expected: MemBufferMode) -> bool {
617    if mem.mode == MemBufferMode::MEM_MODE_NONE {
618        mem.mode = expected; // switch to the expected mode
619    } else if mem.mode != expected {
620        return false; // we mixed the modes => error
621    }
622    debug_assert_eq!(mem.mode, expected); // mode is ok
623    true
624}
625
626// upstream: src/dec/idec_dec.c FinishDecoding
627/// To be called last. After the slow copy, C copies the structure of
628/// `final_output` into its own `output`, which `params.output` points at; here
629/// `params.output` becomes the caller's buffer itself.
630fn finish_decoding(idec: &mut WebPIDecoder<'_, '_>) -> Result<(), VP8StatusCode> {
631    let options = idec.params.options;
632    let output = params_output(&mut idec.output, &mut idec.user_output);
633
634    idec.state = DecState::STATE_DONE;
635    if options.is_some_and(|options| options.flip != 0) {
636        webp_flip_buffer(output)?;
637    }
638    if let Some(final_output) = idec.final_output.as_deref_mut() {
639        // do the slow-copy
640        let status = webp_copy_dec_buffer_pixels(&idec.output, final_output);
641        webp_free_dec_buffer(&mut idec.output);
642        status?;
643        // C: *output = *idec->final_output; idec->final_output = NULL.
644        idec.user_output = idec.final_output.take();
645    }
646    Ok(())
647}
648
649//------------------------------------------------------------------------------
650// Macroblock-decoding contexts
651
652// upstream: src/dec/idec_dec.c SaveContext
653/// C takes the token reader as a pointer; here it is its index in `dec.parts`.
654fn save_context(dec: &VP8Decoder, token_br: usize) -> MBContext {
655    let mb_x = usize::try_from(dec.mb_x).expect("a non-negative position");
656    MBContext {
657        left: dec.mb_info[0],        // C: dec->mb_info[-1]
658        info: dec.mb_info[mb_x + 1], // C: dec->mb_info[dec->mb_x]
659        token_br: copy_bit_reader(&dec.parts[token_br]),
660    }
661}
662
663// upstream: src/dec/idec_dec.c RestoreContext
664fn restore_context(context: &MBContext, dec: &mut VP8Decoder, token_br: usize) {
665    let mb_x = usize::try_from(dec.mb_x).expect("a non-negative position");
666    dec.mb_info[0] = context.left;
667    dec.mb_info[mb_x + 1] = context.info;
668    dec.parts[token_br] = copy_bit_reader(&context.token_br);
669}
670
671//------------------------------------------------------------------------------
672
673// upstream: src/dec/idec_dec.c IDecError
674/// Enters the error state and returns `error`. `input` is the input of the
675/// call, which the synchronization reads for a row's alpha.
676fn i_dec_error(
677    idec: &mut WebPIDecoder<'_, '_>,
678    input: &[u8],
679    error: VP8StatusCode,
680) -> VP8StatusCode {
681    if idec.state == DecState::STATE_VP8_DATA {
682        // Synchronize the thread, clean-up and check for errors.
683        let WebPIDecoder {
684            dec,
685            io,
686            params,
687            output,
688            user_output,
689            hooks,
690            alpha_data,
691            alpha_data_size,
692            ..
693        } = idec;
694        let alpha = alpha_slice(input, *alpha_data, *alpha_data_size);
695        let mut hooks = io_hooks(hooks, params, output, user_output, io);
696        let _ = vp8_exit_critical(vp8_dec(dec), io, alpha, Some(hooks.get()));
697    }
698    idec.state = DecState::STATE_ERROR;
699    error
700}
701
702// upstream: src/dec/idec_dec.c ChangeState
703/// C also points `io.data` at the remaining input; here it is passed per call.
704fn change_state(idec: &mut WebPIDecoder<'_, '_>, new_state: DecState, consumed_bytes: usize) {
705    let mem = &mut idec.mem;
706    idec.state = new_state;
707    mem.start += consumed_bytes;
708    debug_assert!(mem.start <= mem.end);
709}
710
711// upstream: src/dec/idec_dec.c DecodeWebPHeaders
712/// Headers.
713fn decode_webp_headers(idec: &mut WebPIDecoder<'_, '_>, input: &[u8]) -> Result<(), VP8StatusCode> {
714    let mem = &idec.mem;
715    let data = &input[mem.start..mem.end];
716    let start = mem.start;
717    let mut headers = WebPHeaderStructure {
718        data,
719        have_all_data: false,
720        ..WebPHeaderStructure::default()
721    };
722
723    match webp_parse_headers(&mut headers) {
724        Ok(()) => {}
725        Err(VP8StatusCode::VP8_STATUS_NOT_ENOUGH_DATA) => {
726            return Err(VP8StatusCode::VP8_STATUS_SUSPENDED); // We haven't found a VP8 chunk yet.
727        }
728        Err(status) => return Err(i_dec_error(idec, input, status)),
729    }
730
731    idec.chunk_size = headers.compressed_size;
732    idec.is_lossless = headers.is_lossless;
733    if idec.is_lossless {
734        // C: VP8LNew() returns NULL when the allocation fails.
735        let dec = vp8l_new();
736        idec.dec = Some(IDecDecoder::VP8L(dec));
737        change_state(idec, DecState::STATE_VP8L_HEADER, headers.offset);
738    } else {
739        // C: VP8New() returns NULL when the allocation fails.
740        let mut dec = vp8_new();
741        dec.incremental = true;
742        idec.dec = Some(IDecDecoder::VP8(dec));
743        idec.alpha_data = headers.alpha_data.map(|alpha| start + alpha);
744        idec.alpha_data_size = headers.alpha_data_size;
745        change_state(idec, DecState::STATE_VP8_HEADER, headers.offset);
746    }
747    Ok(())
748}
749
750// upstream: src/dec/idec_dec.c DecodeVP8FrameHeader
751fn decode_vp8_frame_header(
752    idec: &mut WebPIDecoder<'_, '_>,
753    input: &[u8],
754) -> Result<(), VP8StatusCode> {
755    let data = &input[idec.mem.start..idec.mem.end];
756    let curr_size = mem_data_size(&idec.mem);
757
758    if curr_size < VP8_FRAME_HEADER_SIZE.unsigned_abs() as usize {
759        // Not enough data bytes to extract VP8 Frame Header.
760        return Err(VP8StatusCode::VP8_STATUS_SUSPENDED);
761    }
762    if vp8_get_info(data, idec.chunk_size).is_none() {
763        return Err(i_dec_error(
764            idec,
765            input,
766            VP8StatusCode::VP8_STATUS_BITSTREAM_ERROR,
767        ));
768    }
769
770    let bits = u32::from(data[0]) | (u32::from(data[1]) << 8) | (u32::from(data[2]) << 16);
771    idec.mem.part0_size = (bits >> 5) as usize + VP8_FRAME_HEADER_SIZE.unsigned_abs() as usize;
772
773    // C: idec->io.data = data; idec->io.data_size = curr_size.
774    idec.state = DecState::STATE_VP8_PARTS0;
775    Ok(())
776}
777
778// upstream: src/dec/idec_dec.c CopyParts0Data
779/// Partition #0.
780fn copy_parts0_data(idec: &mut WebPIDecoder<'_, '_>, input: &[u8]) -> Result<(), VP8StatusCode> {
781    debug_assert!(!idec.is_lossless);
782    let dec = vp8_dec(&mut idec.dec);
783    let br = &mut dec.br;
784    let part_size = br.buf_end - br.buf;
785    let mem = &mut idec.mem;
786    debug_assert_eq!(mem.part0_buf.len(), 0);
787    // the following is a format limitation, no need for runtime check:
788    debug_assert!(part_size <= mem.part0_size);
789    if part_size == 0 {
790        // can't have zero-size partition #0
791        return Err(VP8StatusCode::VP8_STATUS_BITSTREAM_ERROR);
792    }
793    if mem.mode == MemBufferMode::MEM_MODE_APPEND {
794        // We copy and grab ownership of the partition #0 data. C tests
795        // WebPSafeMalloc(1ULL, part_size); the test of part_size elements of
796        // one byte makes the same decision.
797        let Some(mut part0_buf) = webp_safe_malloc::<u8>(part_size as u64, 1) else {
798            return Err(VP8StatusCode::VP8_STATUS_OUT_OF_MEMORY);
799        };
800        part0_buf.extend_from_slice(&input[br.buf..br.buf + part_size]);
801        mem.part0_buf = part0_buf;
802        vp8_bit_reader_set_buffer(br, part_size);
803    } else {
804        // Else: just keep pointers to the partition #0's data in dec->br.
805    }
806    mem.start += part_size;
807    Ok(())
808}
809
810// upstream: src/dec/idec_dec.c DecodePartition0
811fn decode_partition0(idec: &mut WebPIDecoder<'_, '_>, input: &[u8]) -> Result<(), VP8StatusCode> {
812    // Wait till we have enough data for the whole partition #0
813    if mem_data_size(&idec.mem) < idec.mem.part0_size {
814        return Err(VP8StatusCode::VP8_STATUS_SUSPENDED);
815    }
816
817    {
818        let dec = vp8_dec(&mut idec.dec);
819        // C: io->data, which points mem.start bytes into the input.
820        if vp8_get_headers_at(dec, &mut idec.io, &input[..idec.mem.end], idec.mem.start).is_err() {
821            let status = dec.status;
822            if status == VP8StatusCode::VP8_STATUS_SUSPENDED
823                || status == VP8StatusCode::VP8_STATUS_NOT_ENOUGH_DATA
824            {
825                // treating NOT_ENOUGH_DATA as SUSPENDED state
826                return Err(VP8StatusCode::VP8_STATUS_SUSPENDED);
827            }
828            return Err(i_dec_error(idec, input, status));
829        }
830    }
831
832    // Allocate/Verify output buffer now
833    let status = {
834        let WebPIDecoder {
835            dec,
836            io,
837            params,
838            output,
839            user_output,
840            ..
841        } = idec;
842        let dec = vp8_dec(dec);
843        dec.status = status_code(webp_allocate_dec_buffer(
844            io.width,
845            io.height,
846            params.options,
847            params_output(output, user_output),
848        ));
849        dec.status
850    };
851    if status != VP8StatusCode::VP8_STATUS_OK {
852        return Err(i_dec_error(idec, input, status));
853    }
854    {
855        let WebPIDecoder {
856            dec, io, params, ..
857        } = idec;
858        let dec = vp8_dec(dec);
859        // This change must be done before calling VP8InitFrame(). C passes no
860        // headers to VP8GetThreadMethod.
861        dec.mt_method = vp8_get_thread_method(params.options, io.width, io.height);
862        vp8_init_dithering(params.options, dec);
863    }
864
865    let status = status_code(copy_parts0_data(idec, input));
866    vp8_dec(&mut idec.dec).status = status;
867    if status != VP8StatusCode::VP8_STATUS_OK {
868        return Err(i_dec_error(idec, input, status));
869    }
870
871    // Finish setting up the decoding parameters. Will call io->setup().
872    let entered = {
873        let WebPIDecoder {
874            dec,
875            io,
876            params,
877            output,
878            user_output,
879            hooks,
880            ..
881        } = idec;
882        let dec = vp8_dec(dec);
883        let mut hooks = io_hooks(hooks, params, output, user_output, io);
884        vp8_enter_critical(dec, io, Some(hooks.get())).map_err(|_| dec.status)
885    };
886    if let Err(status) = entered {
887        return Err(i_dec_error(idec, input, status));
888    }
889
890    // Note: past this point, teardown() must always be called
891    // in case of error.
892    idec.state = DecState::STATE_VP8_DATA;
893    // Allocate memory and prepare everything.
894    let alpha = alpha_slice(input, idec.alpha_data, idec.alpha_data_size);
895    let dec = vp8_dec(&mut idec.dec);
896    if !vp8_init_frame(dec, &mut idec.io, alpha) {
897        let status = dec.status;
898        return Err(i_dec_error(idec, input, status));
899    }
900    Ok(())
901}
902
903/// How the row loop of `DecodeRemaining` ends. This type has no C counterpart.
904enum RowsEnd {
905    /// The loop ran through every row.
906    Done,
907    /// A macroblock needs more data: return `VP8_STATUS_SUSPENDED`.
908    Suspended,
909    /// `IDecError` with this status.
910    Error(VP8StatusCode),
911}
912
913// upstream: src/dec/idec_dec.c DecodeRemaining
914/// Remaining partitions.
915fn decode_remaining(idec: &mut WebPIDecoder<'_, '_>, input: &[u8]) -> Result<(), VP8StatusCode> {
916    // Make sure partition #0 has been read before, to set dec to ready.
917    if !vp8_dec(&mut idec.dec).ready {
918        return Err(i_dec_error(
919            idec,
920            input,
921            VP8StatusCode::VP8_STATUS_BITSTREAM_ERROR,
922        ));
923    }
924    let rows_end = {
925        let WebPIDecoder {
926            dec,
927            io,
928            params,
929            mem,
930            output,
931            user_output,
932            last_mb_y,
933            alpha_data,
934            alpha_data_size,
935            hooks,
936            ..
937        } = idec;
938        let dec = vp8_dec(dec);
939        let data = &input[..mem.end];
940        let alpha = alpha_slice(input, *alpha_data, *alpha_data_size);
941        let mut hooks = io_hooks(hooks, params, output, user_output, io);
942        'rows: {
943            while dec.mb_y < dec.mb_h {
944                if *last_mb_y != dec.mb_y {
945                    // Partition #0: its copy in append mode, the input in map mode.
946                    let part0 = if mem.mode == MemBufferMode::MEM_MODE_APPEND {
947                        mem.part0_buf.as_slice()
948                    } else {
949                        data
950                    };
951                    if !vp8_parse_intra_mode_row(dec, part0) {
952                        // note: normally, error shouldn't occur since we already have the whole
953                        // partition0 available here in DecodeRemaining(). Reaching EOF while
954                        // reading intra modes really means a BITSTREAM_ERROR.
955                        break 'rows RowsEnd::Error(VP8StatusCode::VP8_STATUS_BITSTREAM_ERROR);
956                    }
957                    *last_mb_y = dec.mb_y;
958                }
959                while dec.mb_x < dec.mb_w {
960                    let token_br = (dec.mb_y.cast_unsigned() & dec.num_parts_minus_one) as usize;
961                    let context = save_context(dec, token_br);
962                    if !vp8_decode_mb(dec, token_br, data) {
963                        // We shouldn't fail when MAX_MB data was available
964                        if dec.num_parts_minus_one == 0 && mem_data_size(mem) > MAX_MB_SIZE {
965                            break 'rows RowsEnd::Error(VP8StatusCode::VP8_STATUS_BITSTREAM_ERROR);
966                        }
967                        // Synchronize the threads.
968                        if dec.mt_method > 0 && !vp8_sync_rows(dec, alpha, Some(hooks.get())) {
969                            break 'rows RowsEnd::Error(VP8StatusCode::VP8_STATUS_BITSTREAM_ERROR);
970                        }
971                        restore_context(&context, dec, token_br);
972                        break 'rows RowsEnd::Suspended;
973                    }
974                    // Release buffer only if there is only one partition
975                    if dec.num_parts_minus_one == 0 {
976                        mem.start = dec.parts[token_br].buf;
977                        debug_assert!(mem.start <= mem.end);
978                    }
979                    dec.mb_x += 1;
980                }
981                vp8_init_scanline(dec); // Prepare for next scanline
982
983                // Reconstruct, filter and emit the row.
984                if !vp8_process_row(dec, io, alpha, Some(hooks.get())) {
985                    break 'rows RowsEnd::Error(VP8StatusCode::VP8_STATUS_USER_ABORT);
986                }
987                dec.mb_y += 1;
988            }
989            RowsEnd::Done
990        }
991    };
992    match rows_end {
993        RowsEnd::Done => {}
994        RowsEnd::Suspended => return Err(VP8StatusCode::VP8_STATUS_SUSPENDED),
995        RowsEnd::Error(status) => return Err(i_dec_error(idec, input, status)),
996    }
997    // Synchronize the thread and check for errors.
998    let exited = {
999        let WebPIDecoder {
1000            dec,
1001            io,
1002            params,
1003            output,
1004            user_output,
1005            alpha_data,
1006            alpha_data_size,
1007            hooks,
1008            ..
1009        } = idec;
1010        let alpha = alpha_slice(input, *alpha_data, *alpha_data_size);
1011        let mut hooks = io_hooks(hooks, params, output, user_output, io);
1012        vp8_exit_critical(vp8_dec(dec), io, alpha, Some(hooks.get()))
1013    };
1014    if !exited {
1015        idec.state = DecState::STATE_ERROR; // prevent re-entry in IDecError
1016        return Err(i_dec_error(
1017            idec,
1018            input,
1019            VP8StatusCode::VP8_STATUS_USER_ABORT,
1020        ));
1021    }
1022    vp8_dec(&mut idec.dec).ready = false;
1023    finish_decoding(idec)
1024}
1025
1026// upstream: src/dec/idec_dec.c ErrorStatusLossless
1027fn error_status_lossless(
1028    idec: &mut WebPIDecoder<'_, '_>,
1029    input: &[u8],
1030    status: VP8StatusCode,
1031) -> VP8StatusCode {
1032    if status == VP8StatusCode::VP8_STATUS_SUSPENDED
1033        || status == VP8StatusCode::VP8_STATUS_NOT_ENOUGH_DATA
1034    {
1035        return VP8StatusCode::VP8_STATUS_SUSPENDED;
1036    }
1037    i_dec_error(idec, input, status)
1038}
1039
1040// upstream: src/dec/idec_dec.c DecodeVP8LHeader
1041fn decode_vp8l_header(idec: &mut WebPIDecoder<'_, '_>, input: &[u8]) -> Result<(), VP8StatusCode> {
1042    let curr_size = mem_data_size(&idec.mem);
1043    debug_assert!(idec.is_lossless);
1044
1045    // Wait until there's enough data for decoding header.
1046    if curr_size < (idec.chunk_size >> 3) {
1047        let dec = vp8l_dec(&mut idec.dec);
1048        dec.status = VP8StatusCode::VP8_STATUS_SUSPENDED;
1049        let status = dec.status;
1050        return Err(error_status_lossless(idec, input, status));
1051    }
1052
1053    {
1054        let dec = vp8l_dec(&mut idec.dec);
1055        let data = &input[idec.mem.start..idec.mem.end];
1056        if vp8l_decode_header(dec, &mut idec.io, data).is_err() {
1057            if dec.status == VP8StatusCode::VP8_STATUS_BITSTREAM_ERROR
1058                && curr_size < idec.chunk_size
1059            {
1060                dec.status = VP8StatusCode::VP8_STATUS_SUSPENDED;
1061            }
1062            let status = dec.status;
1063            return Err(error_status_lossless(idec, input, status));
1064        }
1065    }
1066    // Allocate/verify output buffer now.
1067    let status = {
1068        let WebPIDecoder {
1069            dec,
1070            io,
1071            params,
1072            output,
1073            user_output,
1074            ..
1075        } = idec;
1076        let dec = vp8l_dec(dec);
1077        dec.status = status_code(webp_allocate_dec_buffer(
1078            io.width,
1079            io.height,
1080            params.options,
1081            params_output(output, user_output),
1082        ));
1083        dec.status
1084    };
1085    if status != VP8StatusCode::VP8_STATUS_OK {
1086        return Err(i_dec_error(idec, input, status));
1087    }
1088
1089    idec.state = DecState::STATE_VP8L_DATA;
1090    Ok(())
1091}
1092
1093// upstream: src/dec/idec_dec.c DecodeVP8LData
1094/// `VP8LDecodeImage` takes the decoder's parameters and output buffer. C reads
1095/// the parameters through `io->opaque`, which is the caller's user data after
1096/// `WebPISetIOHooks`: undefined, and excluded (`# Excluded undefined behavior`,
1097/// item 2, in the module documentation).
1098fn decode_vp8l_data(idec: &mut WebPIDecoder<'_, '_>, input: &[u8]) -> Result<(), VP8StatusCode> {
1099    let curr_size = mem_data_size(&idec.mem);
1100    debug_assert!(idec.is_lossless);
1101
1102    let status = {
1103        let WebPIDecoder {
1104            dec,
1105            io,
1106            params,
1107            mem,
1108            output,
1109            user_output,
1110            chunk_size,
1111            ..
1112        } = idec;
1113        let dec = vp8l_dec(dec);
1114        // Switch to incremental decoding if we don't have all the bytes available.
1115        dec.incremental = curr_size < *chunk_size;
1116
1117        let data = &input[mem.start..mem.end];
1118        if vp8l_decode_image(dec, io, data, params, params_output(output, user_output)).is_err() {
1119            Err(dec.status)
1120        } else {
1121            debug_assert!(
1122                dec.status == VP8StatusCode::VP8_STATUS_OK
1123                    || dec.status == VP8StatusCode::VP8_STATUS_SUSPENDED
1124            );
1125            Ok(dec.status)
1126        }
1127    };
1128    match status {
1129        Err(status) => Err(error_status_lossless(idec, input, status)),
1130        Ok(VP8StatusCode::VP8_STATUS_SUSPENDED) => Err(VP8StatusCode::VP8_STATUS_SUSPENDED),
1131        Ok(_) => finish_decoding(idec),
1132    }
1133}
1134
1135// upstream: src/dec/idec_dec.c IDecode
1136/// Main decoding loop. `input` is the memory buffer (see the module
1137/// documentation).
1138fn i_decode(idec: &mut WebPIDecoder<'_, '_>, input: &[u8]) -> Result<(), VP8StatusCode> {
1139    let mut status = Err(VP8StatusCode::VP8_STATUS_SUSPENDED);
1140
1141    if idec.state == DecState::STATE_WEBP_HEADER {
1142        status = decode_webp_headers(idec, input);
1143    } else if idec.dec.is_none() {
1144        return Err(VP8StatusCode::VP8_STATUS_SUSPENDED); // can't continue if we have no decoder.
1145    }
1146    if idec.state == DecState::STATE_VP8_HEADER {
1147        status = decode_vp8_frame_header(idec, input);
1148    }
1149    if idec.state == DecState::STATE_VP8_PARTS0 {
1150        status = decode_partition0(idec, input);
1151    }
1152    if idec.state == DecState::STATE_VP8_DATA {
1153        if idec.dec.is_none() {
1154            return Err(VP8StatusCode::VP8_STATUS_SUSPENDED); // can't continue if we have no decoder.
1155        }
1156        status = decode_remaining(idec, input);
1157    }
1158    if idec.state == DecState::STATE_VP8L_HEADER {
1159        status = decode_vp8l_header(idec, input);
1160    }
1161    if idec.state == DecState::STATE_VP8L_DATA {
1162        status = decode_vp8l_data(idec, input);
1163    }
1164    status
1165}
1166
1167//------------------------------------------------------------------------------
1168// Internal constructor
1169
1170// upstream: src/dec/idec_dec.c NewDecoder
1171/// Creates the decoder over the caller's `output_buffer`, or over its own
1172/// output buffer for `None` or for slow memory, which receives the samples at
1173/// the end. C returns `NULL` when its allocation fails; here a refused host
1174/// allocation aborts.
1175fn new_decoder<'a, 'b>(
1176    output_buffer: Option<&'a mut WebPDecBuffer<'b>>,
1177    features: Option<&WebPBitstreamFeatures>,
1178) -> Option<WebPIDecoder<'a, 'b>> {
1179    let mut idec = WebPIDecoder {
1180        state: DecState::STATE_WEBP_HEADER,
1181        params: WebPDecParams::default(),
1182        is_lossless: false,
1183        dec: None,
1184        io: VP8Io::default(),
1185        mem: MemBuffer::default(),
1186        output: WebPDecBuffer::default(),
1187        user_output: None,
1188        final_output: None,
1189        slow_copy: false,
1190        chunk_size: 0,
1191        last_mb_y: -1,
1192        alpha_data: None,
1193        alpha_data_size: 0,
1194        hooks: None,
1195    };
1196
1197    init_mem_buffer(&mut idec.mem);
1198    if !webp_init_dec_buffer(&mut idec.output) || !vp8_init_io(&mut idec.io) {
1199        return None;
1200    }
1201
1202    webp_reset_dec_params(&mut idec.params);
1203    match output_buffer {
1204        Some(output_buffer) if !webp_avoid_slow_memory(output_buffer, features) => {
1205            // C: idec->params.output = output_buffer; final_output = NULL.
1206            idec.user_output = Some(output_buffer);
1207        }
1208        output_buffer => {
1209            // C: idec->params.output = &idec->output.
1210            if let Some(output_buffer) = &output_buffer {
1211                idec.output.colorspace = output_buffer.colorspace;
1212            }
1213            idec.slow_copy = output_buffer.is_some();
1214            idec.final_output = output_buffer;
1215        }
1216    }
1217    // C: WebPInitCustomIo(&idec->params, &idec->io); the hooks are made for each
1218    // call (`io_hooks`).
1219
1220    Some(idec)
1221}
1222
1223//------------------------------------------------------------------------------
1224// Public functions
1225
1226// upstream: src/dec/idec_dec.c WebPINewDecoder
1227/// Creates a new incremental decoder with the supplied buffer parameter. This
1228/// `output_buffer` can be passed `None`, in which case a default output buffer
1229/// is used (with `MODE_RGB`). Otherwise, an internal reference to
1230/// `output_buffer` is kept, which means that the lifetime of `output_buffer`
1231/// must be larger than that of the returned decoder. The decoder is a value;
1232/// dropping it is `WebPIDelete()`.
1233#[must_use]
1234pub fn webp_i_new_decoder<'a, 'b>(
1235    output_buffer: Option<&'a mut WebPDecBuffer<'b>>,
1236) -> Option<WebPIDecoder<'a, 'b>> {
1237    new_decoder(output_buffer, None)
1238}
1239
1240// upstream: src/dec/idec_dec.c WebPIDecode
1241/// Instantiates a new incremental decoder object with the requested
1242/// configuration. The bitstream can be passed in `data` to retrieve the
1243/// features into `config.input` (or into a temporary when `config` is `None`);
1244/// `data` is not consumed, only parsed. Returns `None` in case of error, for
1245/// instance when the features cannot be retrieved from a non-empty `data`. The
1246/// options and the output buffer of `config` stay borrowed by the decoder. C
1247/// tests `data != NULL && data_size > 0`; a `NULL` `data` is an empty slice
1248/// here.
1249#[must_use]
1250pub fn webp_i_decode<'a, 'b>(
1251    data: &[u8],
1252    config: Option<&'a mut WebPDecoderConfig<'b>>,
1253) -> Option<WebPIDecoder<'a, 'b>> {
1254    let mut tmp_features = WebPBitstreamFeatures::default();
1255    let (features, output, options) = match config {
1256        Some(config) => {
1257            let WebPDecoderConfig {
1258                input,
1259                output,
1260                options,
1261            } = config;
1262            (input, Some(output), Some(&*options))
1263        }
1264        None => (&mut tmp_features, None, None),
1265    };
1266
1267    // Parse the bitstream's features, if requested:
1268    if !data.is_empty() && webp_get_features(data, features).is_err() {
1269        return None;
1270    }
1271
1272    // Create an instance of the incremental decoder
1273    let mut idec = new_decoder(output, Some(features))?;
1274    // Finish initialization
1275    if options.is_some() {
1276        idec.params.options = options;
1277    }
1278    Some(idec)
1279}
1280
1281// upstream: src/dec/idec_dec.c WebPIDelete
1282/// Deletes the decoder: dropping it does what `WebPIDelete()` does (see
1283/// [`Drop`] for [`WebPIDecoder`]).
1284pub fn webp_i_delete(idec: WebPIDecoder<'_, '_>) {
1285    drop(idec);
1286}
1287
1288impl Drop for WebPIDecoder<'_, '_> {
1289    // upstream: src/dec/idec_dec.c WebPIDelete
1290    /// Synchronizes the thread and tears the io down for a lossy decoding in
1291    /// progress, then releases the decoder, the memory buffer and the
1292    /// decoder's own output buffer. No row is pending at this point, because
1293    /// every call ends with the worker synchronized; in map mode the caller's
1294    /// buffer is gone, so the alpha chunk is not passed.
1295    fn drop(&mut self) {
1296        if let Some(dec) = &mut self.dec {
1297            match dec {
1298                IDecDecoder::VP8(dec) => {
1299                    if self.state == DecState::STATE_VP8_DATA {
1300                        debug_assert!(!dec.put_pending);
1301                        let alpha = if self.mem.mode == MemBufferMode::MEM_MODE_APPEND {
1302                            alpha_slice(&self.mem.buf, self.alpha_data, self.alpha_data_size)
1303                        } else {
1304                            None
1305                        };
1306                        let mut hooks = io_hooks(
1307                            &mut self.hooks,
1308                            &mut self.params,
1309                            &mut self.output,
1310                            &mut self.user_output,
1311                            &mut self.io,
1312                        );
1313                        // Synchronize the thread, clean-up and check for errors.
1314                        // C does not use the result either.
1315                        let _ = vp8_exit_critical(dec, &mut self.io, alpha, Some(hooks.get()));
1316                    }
1317                    // C: VP8Delete((VP8Decoder*)idec->dec).
1318                }
1319                IDecDecoder::VP8L(_) => {
1320                    // C: VP8LDelete((VP8LDecoder*)idec->dec).
1321                }
1322            }
1323        }
1324        self.dec = None;
1325        clear_mem_buffer(&mut self.mem);
1326        webp_free_dec_buffer(&mut self.output);
1327    }
1328}
1329
1330//------------------------------------------------------------------------------
1331// Wrapper toward WebPINewDecoder
1332
1333// upstream: src/dec/idec_dec.c WebPINewRGB
1334/// Creates a decoder that outputs RGB samples in `csp`: into the caller's
1335/// `output_buffer` with `output_stride` (C: the pointer and its size), or, for
1336/// `None`, into memory that the decoder allocates, in which case the stride is
1337/// ignored. Returns `None` for a YUV colorspace, or for a zero stride or an
1338/// empty buffer.
1339#[must_use]
1340pub fn webp_i_new_rgb<'a>(
1341    csp: WEBP_CSP_MODE,
1342    output_buffer: Option<&mut [u8]>,
1343    output_stride: i32,
1344) -> Option<WebPIDecoder<'a, '_>> {
1345    let is_external_memory = output_buffer.is_some();
1346    let mut output_buffer_size = output_buffer.as_ref().map_or(0, |buffer| buffer.len());
1347    let mut output_stride = output_stride;
1348
1349    if csp >= WEBP_CSP_MODE::MODE_YUV {
1350        return None;
1351    }
1352    if is_external_memory {
1353        // A buffer was passed. Validate the other params.
1354        if output_stride == 0 || output_buffer_size == 0 {
1355            return None; // invalid parameter.
1356        }
1357    } else {
1358        // Overwrite parameters to sane values.
1359        output_buffer_size = 0;
1360        output_stride = 0;
1361    }
1362    let mut idec = webp_i_new_decoder(None)?;
1363    idec.output.colorspace = csp;
1364    // C: idec->output.is_external_memory = is_external_memory.
1365    idec.output.storage = match output_buffer {
1366        Some(buffer) => PlaneStorage::External(vec![buffer]),
1367        None => PlaneStorage::Internal(Vec::new()),
1368    };
1369    idec.output.u = WebPDecBufferPlanes::RGBA(WebPRGBABuffer {
1370        rgba: PlaneOffset::default(),
1371        stride: output_stride,
1372        size: output_buffer_size,
1373    });
1374    Some(idec)
1375}
1376
1377// upstream: src/dec/idec_dec.c WebPINewYUVA
1378/// Creates a decoder that outputs YUV samples, with alpha when `a` is given:
1379/// into the caller's `luma`, `u`, `v` and `a` with their strides (C: each
1380/// pointer with its size), or, for a `None` luma, into memory that the decoder
1381/// allocates (`MODE_YUVA`), in which case the other arguments are ignored.
1382/// Returns `None` when a luma buffer is passed without U or V, or with an empty
1383/// buffer or a zero stride.
1384#[expect(
1385    clippy::too_many_arguments,
1386    reason = "the four planes and strides of the C function"
1387)]
1388#[must_use]
1389pub fn webp_i_new_yuva<'a, 'b>(
1390    luma: Option<&'b mut [u8]>,
1391    luma_stride: i32,
1392    u: Option<&'b mut [u8]>,
1393    u_stride: i32,
1394    v: Option<&'b mut [u8]>,
1395    v_stride: i32,
1396    a: Option<&'b mut [u8]>,
1397    a_stride: i32,
1398) -> Option<WebPIDecoder<'a, 'b>> {
1399    let size = |plane: &Option<&'b mut [u8]>| plane.as_ref().map_or(0, |plane| plane.len());
1400    let (mut luma_size, mut u_size, mut v_size, mut a_size) =
1401        (size(&luma), size(&u), size(&v), size(&a));
1402    let (mut luma_stride, mut u_stride, mut v_stride, mut a_stride) =
1403        (luma_stride, u_stride, v_stride, a_stride);
1404    let colorspace;
1405    let storage;
1406
1407    if let Some(luma) = luma {
1408        // A luma buffer was passed. Validate the other parameters.
1409        let (Some(u), Some(v)) = (u, v) else {
1410            return None;
1411        };
1412        if luma_size == 0 || u_size == 0 || v_size == 0 {
1413            return None;
1414        }
1415        if luma_stride == 0 || u_stride == 0 || v_stride == 0 {
1416            return None;
1417        }
1418        if a.is_some() && (a_size == 0 || a_stride == 0) {
1419            return None;
1420        }
1421        colorspace = if a.is_none() {
1422            WEBP_CSP_MODE::MODE_YUV
1423        } else {
1424            WEBP_CSP_MODE::MODE_YUVA
1425        };
1426        // C: is_external_memory = 1.
1427        let mut slices = vec![luma, u, v];
1428        slices.extend(a);
1429        storage = PlaneStorage::External(slices);
1430    } else {
1431        // Overwrite parameters to sane values.
1432        luma_size = 0;
1433        u_size = 0;
1434        v_size = 0;
1435        a_size = 0;
1436        luma_stride = 0;
1437        u_stride = 0;
1438        v_stride = 0;
1439        a_stride = 0;
1440        colorspace = WEBP_CSP_MODE::MODE_YUVA;
1441        storage = PlaneStorage::Internal(Vec::new());
1442    }
1443    let has_a = matches!(&storage, PlaneStorage::External(slices) if slices.len() == 4);
1444
1445    let mut idec = webp_i_new_decoder(None)?;
1446
1447    idec.output.colorspace = colorspace;
1448    idec.output.storage = storage;
1449    let plane = |region| PlaneOffset { region, offset: 0 };
1450    idec.output.u = WebPDecBufferPlanes::YUVA(WebPYUVABuffer {
1451        y: plane(0),
1452        y_stride: luma_stride,
1453        y_size: luma_size,
1454        u: plane(1),
1455        u_stride,
1456        u_size,
1457        v: plane(2),
1458        v_stride,
1459        v_size,
1460        a: has_a.then(|| plane(3)),
1461        a_stride,
1462        a_size,
1463    });
1464    Some(idec)
1465}
1466
1467// upstream: src/dec/idec_dec.c WebPINewYUV
1468/// Deprecated version of [`webp_i_new_yuva`], without the alpha plane.
1469#[must_use]
1470pub fn webp_i_new_yuv<'a, 'b>(
1471    luma: Option<&'b mut [u8]>,
1472    luma_stride: i32,
1473    u: Option<&'b mut [u8]>,
1474    u_stride: i32,
1475    v: Option<&'b mut [u8]>,
1476    v_stride: i32,
1477) -> Option<WebPIDecoder<'a, 'b>> {
1478    webp_i_new_yuva(luma, luma_stride, u, u_stride, v, v_stride, None, 0)
1479}
1480
1481//------------------------------------------------------------------------------
1482
1483// upstream: src/dec/idec_dec.c IDecCheckStatus
1484fn i_dec_check_status(idec: &WebPIDecoder<'_, '_>) -> Result<(), VP8StatusCode> {
1485    if idec.state == DecState::STATE_ERROR {
1486        return Err(VP8StatusCode::VP8_STATUS_BITSTREAM_ERROR);
1487    }
1488    if idec.state == DecState::STATE_DONE {
1489        return Ok(());
1490    }
1491    Err(VP8StatusCode::VP8_STATUS_SUSPENDED)
1492}
1493
1494// upstream: src/dec/idec_dec.c WebPIAppend
1495/// Copies and decodes the next available data.
1496///
1497/// # Errors
1498///
1499/// `VP8_STATUS_SUSPENDED` when more data is expected, the decoding error
1500/// otherwise; `Ok` when the image is successfully decoded.
1501/// `VP8_STATUS_INVALID_PARAM` after calls of `WebPIUpdate`, and
1502/// `VP8_STATUS_OUT_OF_MEMORY` when the data cannot be stored. C returns
1503/// `VP8_STATUS_INVALID_PARAM` for a `NULL` decoder or data, which exist only at
1504/// the C ABI.
1505pub fn webp_i_append(idec: &mut WebPIDecoder<'_, '_>, data: &[u8]) -> Result<(), VP8StatusCode> {
1506    let status = i_dec_check_status(idec);
1507    if status != Err(VP8StatusCode::VP8_STATUS_SUSPENDED) {
1508        return status;
1509    }
1510    // Check mixed calls between RemapMemBuffer and AppendToMemBuffer.
1511    if !check_mem_buffer_mode(&mut idec.mem, MemBufferMode::MEM_MODE_APPEND) {
1512        return Err(VP8StatusCode::VP8_STATUS_INVALID_PARAM);
1513    }
1514    // Append data to memory buffer
1515    if !append_to_mem_buffer(idec, data) {
1516        return Err(VP8StatusCode::VP8_STATUS_OUT_OF_MEMORY);
1517    }
1518    // The memory buffer is the input of the decoding step.
1519    let input = std::mem::take(&mut idec.mem.buf);
1520    let status = i_decode(idec, &input);
1521    idec.mem.buf = input;
1522    status
1523}
1524
1525// upstream: src/dec/idec_dec.c WebPIUpdate
1526/// A variant of [`webp_i_append`] for a `data` buffer that contains partial
1527/// data from the beginning. The data is not copied; the caller passes the
1528/// whole buffer so far to each call, which may move between calls.
1529///
1530/// # Errors
1531///
1532/// As [`webp_i_append`]; `VP8_STATUS_INVALID_PARAM` also for a buffer shorter
1533/// than the previous one.
1534pub fn webp_i_update(idec: &mut WebPIDecoder<'_, '_>, data: &[u8]) -> Result<(), VP8StatusCode> {
1535    let status = i_dec_check_status(idec);
1536    if status != Err(VP8StatusCode::VP8_STATUS_SUSPENDED) {
1537        return status;
1538    }
1539    // Check mixed calls between RemapMemBuffer and AppendToMemBuffer.
1540    if !check_mem_buffer_mode(&mut idec.mem, MemBufferMode::MEM_MODE_MAP) {
1541        return Err(VP8StatusCode::VP8_STATUS_INVALID_PARAM);
1542    }
1543    // Make the memory buffer point to the new buffer
1544    if !remap_mem_buffer(idec, data) {
1545        return Err(VP8StatusCode::VP8_STATUS_INVALID_PARAM);
1546    }
1547    i_decode(idec, data)
1548}
1549
1550//------------------------------------------------------------------------------
1551
1552// upstream: src/dec/idec_dec.c GetOutputBuffer
1553/// C returns `NULL` for a `NULL` decoder, which exists only at the C ABI.
1554fn get_output_buffer<'s, 'b>(idec: &'s WebPIDecoder<'_, 'b>) -> Option<&'s WebPDecBuffer<'b>> {
1555    idec.dec.as_ref()?;
1556    if idec.state <= DecState::STATE_VP8_PARTS0 {
1557        return None;
1558    }
1559    if idec.final_output.is_some() {
1560        return None; // not yet slow-copied
1561    }
1562    Some(match &idec.user_output {
1563        Some(user_output) => user_output,
1564        None => &idec.output,
1565    })
1566}
1567
1568/// The region and offset of a plane, or `None` where C's pointer is `NULL`
1569/// (`src/dec/buffer_dec.rs` describes when it is).
1570fn plane_rows<'s>(
1571    storage: &'s PlaneStorage<'_, u8>,
1572    plane: PlaneOffset,
1573) -> Option<(&'s [u8], usize)> {
1574    if is_null_plane(storage, plane) {
1575        return None;
1576    }
1577    storage
1578        .region(plane.region)
1579        .map(|region| (region, plane.offset))
1580}
1581
1582// upstream: src/dec/idec_dec.c WebPIDecodedArea
1583/// Generic call to retrieve information about the displayable area. If
1584/// non-`None`, `left`, `top`, `width` and `height` receive the visible
1585/// rectangular area so far (`left` and `top` are always 0). Returns `None` in
1586/// case the incremental decoder object is in an invalid state, otherwise the
1587/// output buffer, which is still owned by the decoder and lives as long as it.
1588#[must_use]
1589pub fn webp_i_decoded_area<'s, 'b>(
1590    idec: &'s WebPIDecoder<'_, 'b>,
1591    left: Option<&mut i32>,
1592    top: Option<&mut i32>,
1593    width: Option<&mut i32>,
1594    height: Option<&mut i32>,
1595) -> Option<&'s WebPDecBuffer<'b>> {
1596    let src = get_output_buffer(idec);
1597    if let Some(left) = left {
1598        *left = 0;
1599    }
1600    if let Some(top) = top {
1601        *top = 0;
1602    }
1603    if let Some(src) = src {
1604        if let Some(width) = width {
1605            *width = src.width;
1606        }
1607        if let Some(height) = height {
1608            *height = idec.params.last_y;
1609        }
1610    } else {
1611        if let Some(width) = width {
1612            *width = 0;
1613        }
1614        if let Some(height) = height {
1615            *height = 0;
1616        }
1617    }
1618    src
1619}
1620
1621// upstream: src/dec/idec_dec.c WebPIDecGetRGB
1622/// Returns the RGB/A image decoded so far: the region that holds the samples
1623/// and the position of the first row in it, where C returns the pointer (the
1624/// rows follow at `stride`, which is negative for a flipped output). Returns
1625/// `None` if the output is not RGB or not allocated yet. `last_y` receives the
1626/// index of the row after the last decoded one; `width`, `height` and `stride`
1627/// describe the output.
1628#[must_use]
1629pub fn webp_i_dec_get_rgb<'s>(
1630    idec: &'s WebPIDecoder<'_, '_>,
1631    last_y: Option<&mut i32>,
1632    width: Option<&mut i32>,
1633    height: Option<&mut i32>,
1634    stride: Option<&mut i32>,
1635) -> Option<(&'s [u8], usize)> {
1636    let src = get_output_buffer(idec)?;
1637    if src.colorspace >= WEBP_CSP_MODE::MODE_YUV {
1638        return None;
1639    }
1640    // The RGBA member, which the colorspace selects. A buffer that was not
1641    // allocated yet may hold the other member, zeroed, which C reads as a
1642    // zeroed RGBA member (see `src/dec/buffer_dec.rs`).
1643    let (buf, rows) = match &src.u {
1644        WebPDecBufferPlanes::RGBA(buf) => (*buf, plane_rows(&src.storage, buf.rgba)),
1645        WebPDecBufferPlanes::YUVA(_) => (WebPRGBABuffer::default(), None),
1646    };
1647
1648    if let Some(last_y) = last_y {
1649        *last_y = idec.params.last_y;
1650    }
1651    if let Some(width) = width {
1652        *width = src.width;
1653    }
1654    if let Some(height) = height {
1655        *height = src.height;
1656    }
1657    if let Some(stride) = stride {
1658        *stride = buf.stride;
1659    }
1660
1661    rows
1662}
1663
1664/// The rows of one plane, as [`webp_i_dec_get_yuva`] returns them: the region
1665/// and the position of the first row in it, or `None` for C's `NULL`.
1666pub type PlaneRows<'s> = Option<(&'s [u8], usize)>;
1667
1668// upstream: src/dec/idec_dec.c WebPIDecGetYUVA
1669/// Same as [`webp_i_dec_get_rgb`] but to retrieve the Y, U, V and alpha planes:
1670/// returns the luma plane and writes the U, V and alpha planes (`None` for no
1671/// alpha plane), with `stride` for luma, `uv_stride` for chroma and `a_stride`
1672/// for alpha. Returns `None` if the output is not YUV or not allocated yet.
1673#[expect(
1674    clippy::too_many_arguments,
1675    reason = "the output parameters of the C function"
1676)]
1677#[must_use]
1678pub fn webp_i_dec_get_yuva<'s>(
1679    idec: &'s WebPIDecoder<'_, '_>,
1680    last_y: Option<&mut i32>,
1681    u: Option<&mut PlaneRows<'s>>,
1682    v: Option<&mut PlaneRows<'s>>,
1683    a: Option<&mut PlaneRows<'s>>,
1684    width: Option<&mut i32>,
1685    height: Option<&mut i32>,
1686    stride: Option<&mut i32>,
1687    uv_stride: Option<&mut i32>,
1688    a_stride: Option<&mut i32>,
1689) -> PlaneRows<'s> {
1690    let src = get_output_buffer(idec)?;
1691    if src.colorspace < WEBP_CSP_MODE::MODE_YUV {
1692        return None;
1693    }
1694    // The YUVA member, which the colorspace selects. A buffer that was not
1695    // allocated yet may hold the other member, zeroed, which C reads as a
1696    // zeroed YUVA member with no planes (see `src/dec/buffer_dec.rs`).
1697    let (buf, planes) = match &src.u {
1698        WebPDecBufferPlanes::YUVA(buf) => (*buf, true),
1699        WebPDecBufferPlanes::RGBA(_) => (WebPYUVABuffer::default(), false),
1700    };
1701    let rows = |plane: Option<PlaneOffset>| {
1702        plane
1703            .filter(|_| planes)
1704            .and_then(|plane| plane_rows(&src.storage, plane))
1705    };
1706
1707    if let Some(last_y) = last_y {
1708        *last_y = idec.params.last_y;
1709    }
1710    if let Some(u) = u {
1711        *u = rows(Some(buf.u));
1712    }
1713    if let Some(v) = v {
1714        *v = rows(Some(buf.v));
1715    }
1716    if let Some(a) = a {
1717        *a = rows(buf.a);
1718    }
1719    if let Some(width) = width {
1720        *width = src.width;
1721    }
1722    if let Some(height) = height {
1723        *height = src.height;
1724    }
1725    if let Some(stride) = stride {
1726        *stride = buf.y_stride;
1727    }
1728    if let Some(uv_stride) = uv_stride {
1729        *uv_stride = buf.u_stride;
1730    }
1731    if let Some(a_stride) = a_stride {
1732        *a_stride = buf.a_stride;
1733    }
1734
1735    rows(Some(buf.y))
1736}
1737
1738// upstream: src/dec/idec_dec.c WebPISetIOHooks
1739/// Sets the custom IO functions and their user data (C: `put`, `setup`,
1740/// `teardown` and `user_data`, ADR 0003). Returns false when the decoding has
1741/// gone past the headers. In C, a lossless image then makes `VP8LDecodeImage`
1742/// read the user data as `WebPDecParams`, which is undefined; here it uses the
1743/// decoder's parameters (`# Excluded undefined behavior`, item 2, in the module
1744/// documentation). C returns 0 for a `NULL` decoder, which exists only at the C
1745/// ABI.
1746#[must_use]
1747pub fn webp_i_set_io_hooks<'a>(
1748    idec: &mut WebPIDecoder<'a, '_>,
1749    hooks: Box<dyn VP8IoHooks + 'a>,
1750) -> bool {
1751    if idec.state > DecState::STATE_WEBP_HEADER {
1752        return false;
1753    }
1754
1755    idec.hooks = Some(hooks);
1756
1757    true
1758}
1759
1760//------------------------------------------------------------------------------
1761// Access for the C ABI (no C counterpart). The C ABI (`src/abi/decode.rs`)
1762// lends caller memory to the output buffers for the duration of each call and
1763// reads their planes after each call.
1764
1765impl<'b> WebPIDecoder<'_, 'b> {
1766    /// Whether C's `params.output` is the caller's buffer.
1767    pub(crate) fn has_user_output(&self) -> bool {
1768        self.user_output.is_some()
1769    }
1770
1771    /// The decoder's own output buffer (C: `idec->output`).
1772    pub(crate) fn own_output_mut(&mut self) -> &mut WebPDecBuffer<'b> {
1773        &mut self.output
1774    }
1775
1776    /// Whether the decoder copies into the caller's buffer at the end (C: a
1777    /// `final_output` was set by `NewDecoder`, slow memory).
1778    pub(crate) fn was_slow(&self) -> bool {
1779        self.slow_copy
1780    }
1781
1782    /// The caller's output buffer: C's `params.output` or `final_output`.
1783    pub(crate) fn caller_output_mut(&mut self) -> Option<&mut WebPDecBuffer<'b>> {
1784        match (&mut self.user_output, &mut self.final_output) {
1785            (Some(output), _) | (None, Some(output)) => Some(&mut **output),
1786            (None, None) => None,
1787        }
1788    }
1789}
1790
1791//------------------------------------------------------------------------------
1792// Access for the safe API (no C counterpart). `src/api/decode.rs` (WP16)
1793// creates a decoder over its own output buffer and sets the options as
1794// `WebPIDecode` does, so that it borrows the options without the output buffer
1795// of a `WebPDecoderConfig`.
1796
1797impl<'a> WebPIDecoder<'a, '_> {
1798    /// Sets the decoding options, as `WebPIDecode` does with
1799    /// `idec->params.options = &config->options`, for a decoder that
1800    /// `webp_i_new_decoder`, `webp_i_new_rgb` or `webp_i_new_yuva` created. Call
1801    /// it before the first `webp_i_append` or `webp_i_update`, as C sets the
1802    /// options before the decoder sees any data.
1803    pub(crate) fn set_options(&mut self, options: &'a WebPDecoderOptions) {
1804        self.params.options = Some(options);
1805    }
1806}