Skip to main content

webp/api/
decode.rs

1//! Safe Rust API over the decoder of the translation; no upstream unit.
2//!
3//! Wraps the translated types and functions in validated Rust types and adds
4//! no codec behavior of its own; see `docs/adr/`.
5//!
6//! Work package: WP16 (safe decoder API).
7//!
8//! The decision record is `docs/adr/0007-safe-decoder-api.md`. Every decoding
9//! calls the translation with the stored options: [`decode`] and
10//! [`decode_into`] call the translated `WebPDecode` ([`webp_decode`]),
11//! [`IncrementalDecoder`] the translated incremental decoder and
12//! [`AnimationDecoder`] the translated `WebPAnimDecoder`, so the samples are
13//! those of libwebp v1.6.0 with the same options. The API validates crops,
14//! scales, strides and buffer lengths first, so that caller input never
15//! reaches a panic of the translation, and reports failures as
16//! [`DecodeError`].
17//!
18//! # Example
19//!
20//! ```
21//! use webp::api::decode::{decode, ColorMode, Config, Features, Format};
22//! # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
23//! # let rgba = [200_u8, 100, 50, 255].repeat(6 * 4);
24//! # let rows = PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 6, height: 4, stride: 24 };
25//! # let file = encode_lossless(rows)?;
26//!
27//! // `file` holds a lossless 6 by 4 WebP image.
28//! let features = Features::parse(&file)?;
29//! assert_eq!((features.width, features.height, features.format), (6, 4, Some(Format::Lossless)));
30//!
31//! let config = Config::new(ColorMode::Rgba).crop(2, 0, 4, 4);
32//! let image = decode(&file, &config)?;
33//! let rows = image.rows().expect("an RGB mode");
34//! assert_eq!((image.width(), image.height(), rows.len()), (4, 4, 4));
35//! assert_eq!(rows.row(0), Some(&[200_u8, 100, 50, 255].repeat(4)[..]));
36//! # Ok::<(), Box<dyn std::error::Error>>(())
37//! ```
38//!
39//! # Memory
40//!
41//! [`decode`] returns an [`Image`] in memory that libwebp allocates; the image
42//! owns it and hands it over without a copy ([`Image::into_samples`]).
43//! [`decode_into`] and [`IncrementalDecoder::with_output`] write into the
44//! caller's rows or planes ([`Output`]), so that the caller can budget that
45//! memory; every stride counts bytes. [`Config::output_size`] gives the size
46//! of the output before decoding. [`AnimationDecoder::new`] allocates two
47//! canvases of `4 * canvas_width * canvas_height` bytes and zeroes them.
48//!
49//! # Semantics
50//!
51//! - **Lossy color.** A `VP8 ` bitstream holds `Y'CbCr` 4:2:0 after ITU-R BT.601
52//!   in limited range (Y 16 to 235, Cb and Cr 16 to 240). The RGB modes convert
53//!   with the fixed-point matrix of libwebp's `src/dsp/yuv.h` (`VP8YUVToR`,
54//!   `VP8YUVToG`, `VP8YUVToB`), with fancy upsampling of the chroma unless
55//!   [`Config::fancy_upsampling`] is off or the output is scaled (the rescaler
56//!   then upsamples). The in-loop filter runs unless
57//!   [`Config::bypass_filtering`] is set or the output is scaled below 3/4 in
58//!   both directions. [`ColorMode::Yuv`] and [`ColorMode::Yuva`] return the
59//!   decoded planes as stored, so their caller converts with the same
60//!   limited-range matrix. [`Config::dithering`] adds libwebp's dither to
61//!   lossy output.
62//! - **Lossless color.** A `VP8L` bitstream stores ARGB exactly; the RGB modes
63//!   reorder its bytes (the 16-bit modes keep the high bits), and the YUV
64//!   modes convert it with `WebPConvertARGBToY` and `WebPConvertARGBToUV` (the
65//!   same limited-range matrix, chroma from 2 by 2 averages).
66//! - **Alpha** is straight in [`ColorMode::Rgba`], [`ColorMode::Bgra`],
67//!   [`ColorMode::Argb`], [`ColorMode::Rgba4444`] and the alpha plane of
68//!   [`ColorMode::Yuva`], and premultiplied in the four `Premultiplied` modes.
69//!   The alpha of a lossy image comes from its `ALPH` chunk;
70//!   [`Config::alpha_dithering`] smooths quantized alpha. Modes without alpha
71//!   drop it.
72//! - **Precision.** Every mode has 8 bits per channel at most;
73//!   [`ColorMode::Rgba4444`] and [`ColorMode::Rgb565`] pack 4 or 5 and 6 bits
74//!   per channel into two bytes, red first.
75//! - **Color signal and orientation.** WebP carries no color signal besides an
76//!   `ICCP` chunk and no orientation besides an `EXIF` chunk. [`Container`]
77//!   returns the raw payloads and parses neither; without a profile, readers
78//!   assume sRGB.
79//! - **Animation.** Full canvases after blending and disposal, premultiplied
80//!   blending in the premultiplied modes, a transparent black start, the
81//!   background color reported and not applied, timestamps as end times in
82//!   milliseconds.
83//!
84//! # Cropping
85//!
86//! A crop decodes the rows from the top of the image down to the crop's
87//! bottom (with 2 or 8 rows of filter margin for lossy images), so it saves
88//! the rows below the crop and nothing above it; a horizontal crop saves
89//! nothing, and the incremental decoder parses every macroblock row of a lossy
90//! image whatever the crop. Scaling runs after decoding at full resolution.
91//! `tests/wp12_crop_rows.rs` has the counts.
92//!
93//! # Deviations from upstream
94//!
95//! Changes of representation that the ADRs allow, or behavior that the Rust
96//! side cannot reproduce exactly. Each records the reason.
97//!
98//! 1. **Odd crop offsets** are refused with `InvalidCrop`. libwebp moves an odd
99//!    `crop_left` or `crop_top` of a lossy image to the even position below it
100//!    (`WebPIoInitFromOptions` snaps when the source is YUV) and crops a
101//!    lossless image exactly.
102//! 2. **Scales** need both sides, each 1 to 16383. libwebp derives a side given
103//!    as 0 and accepts outputs up to `i32::MAX / 2`, for which it reserves and
104//!    zeroes up to 16 GiB of library memory.
105//! 3. **Dithering strengths above 100** are refused with `InvalidParameter`, as
106//!    `WebPValidateDecoderConfig` refuses them; `WebPDecode`, which does not
107//!    validate, clamps them.
108//! 4. **Order of errors.** `decode` and `decode_into` check the configuration
109//!    first, then the features, then the crop, scale and caller memory against
110//!    them, and call `webp_decode` last. C reports a bitstream error in a frame
111//!    header before the `VP8_STATUS_INVALID_PARAM` of a crop, scale or buffer
112//!    that does not fit, and a features error before any configuration error.
113//!    The samples of every accepted decoding are libwebp's.
114//! 5. **Caller memory** has one stride for both chroma planes, and the API
115//!    refuses an alpha plane for `Yuv` (`OutputMismatch`); C takes separate U
116//!    and V strides and ignores an alpha plane in `MODE_YUV`.
117//! 6. **An empty `append` before any data** returns `NeedsMoreData` without
118//!    calling the decoder. C asserts against it (see
119//!    `# Excluded undefined behavior` in `src/dec/idec_dec.rs`), and the
120//!    translation's `debug_assert` panics in the dev and `checked` profiles;
121//!    release builds of both return `SUSPENDED`. An `append` that fails with
122//!    `OutOfMemory` does not count as data, since a first piece above
123//!    `MAX_CHUNK_PAYLOAD` or a failed reservation stores nothing; if that
124//!    failure came from decoding a stored first piece instead, C would answer
125//!    the empty call with `BITSTREAM_ERROR`.
126//! 7. **The incremental decoder owns its output buffer** (C's `WebPINewRGB`,
127//!    `WebPINewYUVA` and `WebPINewDecoder` buffers) and takes the options as
128//!    `WebPIDecode` does; C's `WebPIDecode` decodes into the configuration's
129//!    buffer, which keeps the memory after `WebPIDelete`. The samples are equal
130//!    (`tests/wp16_incremental.rs` compares them); `into_image` moves the
131//!    library memory out. Slow memory is not offered.
132//! 8. **Errors without a C status.** `AnimationDecoder::new` and
133//!    `Container::new` classify a failure by running `Features::parse` and the
134//!    partial demuxer on the data; C returns `NULL` and the demuxer reports a
135//!    non-WebP file as a header in progress. A failed `next_frame` is
136//!    `FrameFailed`. On failure `Features::parse` returns no features, where C
137//!    writes what it parsed.
138//! 9. **`IncrementalDecoder::output_size`** is `None` while libwebp's decoded
139//!    area exists with a width of 0 (between a lossless header and the
140//!    allocation of the output); `rows` then lends the caller's memory with 0
141//!    rows, as C's getter returns the caller's pointer.
142//! 10. **The canvas of a failed frame** is not exposed: the borrow of the
143//!     previous frame ends at the next call (see the deviation on the canvas
144//!     after a failure in `src/demux/anim_decode.rs`).
145//!
146//! # Upstream behavior preserved
147//!
148//! Behavior of the C code that a reader might take for a defect, which the
149//! translation keeps:
150//!
151//! 1. **A whole-image decoding of a truncated file returns libwebp's status:**
152//!    `BitstreamError` when the file ends before the image's dimensions (C maps
153//!    the features' `NOT_ENOUGH_DATA`), and the decoder's `NotEnoughData` or
154//!    `BitstreamError` later; caller memory then holds the rows decoded so far.
155//! 2. **The incremental getters follow libwebp's pointer and stride:** while a
156//!    flipped decoding runs, row 0 is the bottom row of the output and the
157//!    stride is negative; once complete, the stride is positive. With a scale,
158//!    chroma and alpha rows lag behind the luma rows.
159//! 3. **After a failed incremental step** every later step returns
160//!    `BitstreamError`.
161//! 4. **A still image through the animation decoder** is one frame with
162//!    timestamp 0, loop count 1 and background `0xFFFFFFFF`.
163//!
164//! # Checks not applicable
165//!
166//! These checks do not apply, or cannot be made, with the reason:
167//!
168//! 1. **Source correspondence.** This module translates no upstream unit, so
169//!    there are no `// upstream:` markers, no `tools/rust_name.py` names and no
170//!    probe of its own.
171//! 2. **`NULL` arguments** do not exist in the API (references and slices).
172//! 3. **Callbacks.** The API takes no callbacks, so a panicking callback (the
173//!    test of the encoder API in `tests/wp17_misuse.rs`) cannot occur.
174//! 4. **I/O hooks, slow memory, `WebPCopyDecBuffer`, `WebPGrabDecBuffer`, the
175//!    demuxer's frame iterators, `WebPGetInfo` and the simple functions** are
176//!    not in the API (ADR 0007); the simple functions are compared through
177//!    `decode`. The `fconfig` commands of the probe
178//!    `tools/oracle/probes/wp12/decode.c` (features first, which matters only
179//!    for slow memory) and its constructor cases that the API cannot express
180//!    (`WebPINewRGB` with a YUV mode, YUVA memory without a V plane) are not
181//!    replayed.
182//! 5. **Undefined behavior in C.** The exclusions of the decoder translation
183//!    hold. The API passes the bitstream to the translation, so crafted lossy
184//!    streams whose coefficients overflow `int` in `TransformOne_C` (see
185//!    `# Excluded undefined behavior` in `src/dsp/dec.rs`) still panic in the
186//!    dev and `checked` profiles and wrap in release; the API cannot detect
187//!    them before decoding. `WebPIAppend` of zero bytes before any data (see
188//!    `# Excluded undefined behavior` in `src/dec/idec_dec.rs`) no longer
189//!    reaches the translation (item 6 of `# Deviations from upstream`).
190//!    Negative strides and overlapping input and output memory, which the
191//!    decoder translation also excludes, cannot be expressed.
192//! 6. **Allocation failures** are not injected; `OutOfMemory` is reached only
193//!    through the translation's fallible reservations.
194//! 7. **32-bit targets** are not run; the `usize` overflow of a plane's extent
195//!    maps to `InvalidStride` and is reachable there only.
196
197use std::borrow::Cow;
198use std::fmt;
199
200use crate::dec::idec_dec::{
201    WebPIDecoder, webp_i_append, webp_i_dec_get_rgb, webp_i_dec_get_yuva, webp_i_decoded_area,
202    webp_i_new_decoder, webp_i_new_rgb, webp_i_new_yuva, webp_i_update,
203};
204use crate::dec::webp_dec::{webp_check_crop_dimensions, webp_decode, webp_validate_decoder_config};
205use crate::demux::anim_decode::{
206    WebPAnimDecoder, anim_decoder_new_bytes, webp_anim_decoder_get_info,
207    webp_anim_decoder_get_next, webp_anim_decoder_has_more_frames, webp_anim_decoder_reset,
208};
209use crate::demux::demux::{
210    WebPDemuxer, demux_bytes, webp_demux_get_chunk, webp_demux_get_i, webp_demux_next_chunk,
211};
212use crate::webp::decode::{
213    VP8StatusCode, WEBP_CSP_MODE, WebPBitstreamFeatures, WebPDecBuffer, WebPDecBufferPlanes,
214    WebPDecoderConfig, WebPDecoderOptions, WebPRGBABuffer, WebPYUVABuffer, webp_get_features,
215    webp_init_decoder_config,
216};
217use crate::webp::demux::{
218    WEBP_DEMUX_ABI_VERSION, WebPAnimDecoderOptions, WebPChunkIterator, WebPDemuxState,
219    WebPFormatFeature, webp_anim_decoder_options_init,
220};
221use crate::webp::mux_types::WebPFeatureFlags;
222use crate::webp::types::{PlaneOffset, PlaneStorage};
223
224/// The largest scaled width or height that the API accepts: libwebp's
225/// `WEBP_MAX_DIMENSION`.
226const MAX_SCALED_DIMENSION: u32 = 16383;
227
228//------------------------------------------------------------------------------
229// Errors
230
231/// Which output a stride or buffer error is about.
232///
233/// # Examples
234///
235/// ```
236/// use webp::api::decode::{decode_into, ColorMode, Config, DecodeError, Output, Plane};
237/// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
238/// # let rgba = [1_u8, 2, 3, 255].repeat(4);
239/// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 2, height: 2, stride: 8 })?;
240///
241/// // A 2 by 2 image needs 8 + 8 bytes of RGBA rows.
242/// let mut rows = [0_u8; 15];
243/// let output = Output::Rows { data: &mut rows, stride: 8 };
244/// let error = decode_into(&file, &Config::new(ColorMode::Rgba), output).unwrap_err();
245/// assert_eq!(error, DecodeError::BufferTooShort { plane: Plane::Rows, len: 15, needed: 16 });
246/// # Ok::<(), Box<dyn std::error::Error>>(())
247/// ```
248#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
249pub enum Plane {
250    /// The packed rows of [`Output::Rows`].
251    Rows,
252    /// The luma plane of [`YuvaPlanes`].
253    Y,
254    /// The U chroma plane of [`YuvaPlanes`].
255    U,
256    /// The V chroma plane of [`YuvaPlanes`].
257    V,
258    /// The alpha plane of [`YuvaPlanes`].
259    A,
260}
261
262/// Why a decoding or one of its inputs failed.
263///
264/// The variants up to [`DecodeError::NotEnoughData`] are libwebp's
265/// `VP8StatusCode` values 1 to 7; [`DecodeError::code`] returns the C code.
266/// [`DecodeError::FrameFailed`] is a failed animation frame, for which libwebp
267/// reports no status. The others are the API's own validation, which runs
268/// before the translation is called.
269///
270/// # Examples
271///
272/// ```
273/// use webp::api::decode::{ColorMode, Config, DecodeError};
274///
275/// let error = Config::new(ColorMode::Rgb).crop(1, 0, 8, 8).validate().unwrap_err();
276/// assert_eq!(error, DecodeError::InvalidCrop { left: 1, top: 0, width: 8, height: 8 });
277/// assert_eq!(error.code(), None);
278/// assert_eq!(DecodeError::BitstreamError.to_string(), "invalid bitstream");
279/// ```
280#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
281#[non_exhaustive]
282pub enum DecodeError {
283    /// Memory could not be allocated (C: `VP8_STATUS_OUT_OF_MEMORY`).
284    OutOfMemory,
285    /// libwebp refused a parameter (C: `VP8_STATUS_INVALID_PARAM`): for the
286    /// incremental decoder, a caller output that does not fit the image, or
287    /// a crop outside it, which it learns from the header; mixed calls of
288    /// [`IncrementalDecoder::append`] and [`IncrementalDecoder::update`], or a
289    /// shorter buffer passed to `update`.
290    InvalidParam,
291    /// The bitstream is invalid or truncated (C: `VP8_STATUS_BITSTREAM_ERROR`).
292    BitstreamError,
293    /// The bitstream uses a feature that this decoder does not support, such
294    /// as an animation given to [`decode`] (C: `VP8_STATUS_UNSUPPORTED_FEATURE`).
295    UnsupportedFeature,
296    /// The incremental decoding has not completed: the error of
297    /// [`IncrementalDecoder::into_image`] before that (C:
298    /// `VP8_STATUS_SUSPENDED`, which the decoding steps report as
299    /// [`Status::NeedsMoreData`]).
300    Suspended,
301    /// The decoding was aborted by an I/O hook (C: `VP8_STATUS_USER_ABORT`);
302    /// the API sets no hooks, so it does not return this code.
303    UserAbort,
304    /// The data ends before the information asked for (C:
305    /// `VP8_STATUS_NOT_ENOUGH_DATA`): read more and try again.
306    NotEnoughData,
307    /// The animation decoder failed on a frame; libwebp's
308    /// `WebPAnimDecoderGetNext` reports no status.
309    FrameFailed,
310    /// The crop has a zero size, an odd `left` or `top`, a value above
311    /// `i32::MAX`, or does not lie inside the image.
312    InvalidCrop {
313        /// The left edge given.
314        left: u32,
315        /// The top edge given.
316        top: u32,
317        /// The width given.
318        width: u32,
319        /// The height given.
320        height: u32,
321    },
322    /// A scaled width or height is 0 or above 16383.
323    InvalidScale {
324        /// The width given.
325        width: u32,
326        /// The height given.
327        height: u32,
328    },
329    /// A stride is 0, shorter than a row of the output, longer than
330    /// `i32::MAX`, or so long that the plane's extent does not fit in `usize`.
331    InvalidStride {
332        /// The output with the stride.
333        plane: Plane,
334        /// The stride given, in bytes.
335        stride: usize,
336    },
337    /// A buffer is shorter than its rows: `(rows - 1) * stride + row length`
338    /// bytes, or empty.
339    BufferTooShort {
340        /// The output that is too short.
341        plane: Plane,
342        /// Its length, in bytes.
343        len: usize,
344        /// The bytes that its rows and stride address.
345        needed: usize,
346    },
347    /// The output does not match the color mode: [`Output::Rows`] for a YUV
348    /// mode, [`Output::Planes`] for an RGB mode, an alpha plane missing for
349    /// [`ColorMode::Yuva`] or given for [`ColorMode::Yuv`], or caller memory
350    /// asked to become an [`Image`].
351    OutputMismatch {
352        /// The color mode of the configuration.
353        mode: ColorMode,
354    },
355    /// A parameter is outside the range the API accepts: `dithering` or
356    /// `alpha_dithering` above 100.
357    InvalidParameter {
358        /// The parameter's name.
359        name: &'static str,
360    },
361}
362
363impl DecodeError {
364    /// The `VP8StatusCode` of this error, or `None` for [`DecodeError::FrameFailed`]
365    /// and the API's own validation errors.
366    ///
367    /// # Examples
368    ///
369    /// ```
370    /// use webp::api::decode::DecodeError;
371    /// use webp::webp::decode::VP8StatusCode;
372    ///
373    /// assert_eq!(DecodeError::NotEnoughData.code(), Some(VP8StatusCode::VP8_STATUS_NOT_ENOUGH_DATA));
374    /// assert_eq!(DecodeError::FrameFailed.code(), None);
375    /// ```
376    #[must_use]
377    pub const fn code(&self) -> Option<VP8StatusCode> {
378        Some(match self {
379            Self::OutOfMemory => VP8StatusCode::VP8_STATUS_OUT_OF_MEMORY,
380            Self::InvalidParam => VP8StatusCode::VP8_STATUS_INVALID_PARAM,
381            Self::BitstreamError => VP8StatusCode::VP8_STATUS_BITSTREAM_ERROR,
382            Self::UnsupportedFeature => VP8StatusCode::VP8_STATUS_UNSUPPORTED_FEATURE,
383            Self::Suspended => VP8StatusCode::VP8_STATUS_SUSPENDED,
384            Self::UserAbort => VP8StatusCode::VP8_STATUS_USER_ABORT,
385            Self::NotEnoughData => VP8StatusCode::VP8_STATUS_NOT_ENOUGH_DATA,
386            Self::FrameFailed
387            | Self::InvalidCrop { .. }
388            | Self::InvalidScale { .. }
389            | Self::InvalidStride { .. }
390            | Self::BufferTooShort { .. }
391            | Self::OutputMismatch { .. }
392            | Self::InvalidParameter { .. } => return None,
393        })
394    }
395
396    /// The error for a status that a failed call of the translation returned.
397    /// The translation returns `Err` only with codes 1 to 7; a code outside
398    /// them would be a bitstream error.
399    const fn from_status(status: VP8StatusCode) -> Self {
400        match status {
401            VP8StatusCode::VP8_STATUS_OUT_OF_MEMORY => Self::OutOfMemory,
402            VP8StatusCode::VP8_STATUS_INVALID_PARAM => Self::InvalidParam,
403            VP8StatusCode::VP8_STATUS_UNSUPPORTED_FEATURE => Self::UnsupportedFeature,
404            VP8StatusCode::VP8_STATUS_SUSPENDED => Self::Suspended,
405            VP8StatusCode::VP8_STATUS_USER_ABORT => Self::UserAbort,
406            VP8StatusCode::VP8_STATUS_NOT_ENOUGH_DATA => Self::NotEnoughData,
407            _ => Self::BitstreamError,
408        }
409    }
410}
411
412impl fmt::Display for DecodeError {
413    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
414        match self {
415            Self::OutOfMemory => f.write_str("out of memory"),
416            Self::InvalidParam => f.write_str("invalid parameter"),
417            Self::BitstreamError => f.write_str("invalid bitstream"),
418            Self::UnsupportedFeature => f.write_str("unsupported feature"),
419            Self::Suspended => f.write_str("the decoding has not completed"),
420            Self::UserAbort => f.write_str("aborted"),
421            Self::NotEnoughData => f.write_str("not enough data"),
422            Self::FrameFailed => f.write_str("the animation frame could not be decoded"),
423            Self::InvalidCrop {
424                left,
425                top,
426                width,
427                height,
428            } => write!(f, "invalid crop of {width} by {height} at {left},{top}"),
429            Self::InvalidScale { width, height } => write!(
430                f,
431                "invalid scale to {width} by {height}: each must be 1 to {MAX_SCALED_DIMENSION}"
432            ),
433            Self::InvalidStride { plane, stride } => {
434                write!(f, "invalid stride {stride} for the {plane:?} output")
435            }
436            Self::BufferTooShort { plane, len, needed } => write!(
437                f,
438                "the {plane:?} output holds {len} bytes, its rows need {needed}"
439            ),
440            Self::OutputMismatch { mode } => {
441                write!(f, "the output does not match the color mode {mode:?}")
442            }
443            Self::InvalidParameter { name } => write!(f, "invalid parameter: {name}"),
444        }
445    }
446}
447
448impl std::error::Error for DecodeError {}
449
450/// The `Result` of a call of the translation as the API's result.
451fn status(result: Result<(), VP8StatusCode>) -> Result<(), DecodeError> {
452    result.map_err(DecodeError::from_status)
453}
454
455//------------------------------------------------------------------------------
456// Features
457
458/// The compression of a still image or of an animation's first frame
459/// (C: `WebPBitstreamFeatures::format` 1 and 2).
460///
461/// # Examples
462///
463/// ```
464/// use webp::api::decode::{Features, Format};
465/// # use webp::api::encode::{encode_lossy, PixelLayout, PixelRows};
466/// # let rgb = [9_u8, 99, 199].repeat(4);
467/// # let file = encode_lossy(PixelRows { layout: PixelLayout::Rgb, data: &rgb, width: 2, height: 2, stride: 6 }, 75.0)?;
468///
469/// assert_eq!(Features::parse(&file)?.format, Some(Format::Lossy));
470/// # Ok::<(), Box<dyn std::error::Error>>(())
471/// ```
472#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
473pub enum Format {
474    /// A `VP8 ` bitstream.
475    Lossy,
476    /// A `VP8L` bitstream.
477    Lossless,
478}
479
480/// What a WebP file says about itself before decoding (C:
481/// `WebPBitstreamFeatures`).
482///
483/// # Examples
484///
485/// ```
486/// use webp::api::decode::{DecodeError, Features};
487/// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
488/// # let rgba = [1_u8, 2, 3, 128].repeat(15);
489/// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 5, height: 3, stride: 20 })?;
490///
491/// let features = Features::parse(&file)?;
492/// assert_eq!((features.width, features.height), (5, 3));
493/// assert!(features.has_alpha && !features.has_animation);
494///
495/// // A prefix that ends before the dimensions asks for more data.
496/// assert_eq!(Features::parse(&file[..10]), Err(DecodeError::NotEnoughData));
497/// # Ok::<(), Box<dyn std::error::Error>>(())
498/// ```
499#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
500pub struct Features {
501    /// The width in pixels: the canvas of an extended (`VP8X`) file.
502    pub width: u32,
503    /// The height in pixels: the canvas of an extended (`VP8X`) file.
504    pub height: u32,
505    /// Whether the file declares alpha (the `VP8X` flag, an `ALPH` chunk or a
506    /// lossless bitstream's alpha bit).
507    pub has_alpha: bool,
508    /// Whether the file is an animation; decode it with [`AnimationDecoder`].
509    pub has_animation: bool,
510    /// The compression of the image, or `None` when the parse did not reach
511    /// a bitstream header (libwebp reports 0, "undefined"): for an animation,
512    /// whose frames each carry their own format, and for an extended still
513    /// image probed with a prefix that ends before its image chunk. Use
514    /// [`has_animation`](Self::has_animation) to tell the two apart.
515    pub format: Option<Format>,
516}
517
518impl Features {
519    /// Reads the features from the start of a WebP file (C:
520    /// `WebPGetFeatures`); a prefix is enough once it reaches the bitstream's
521    /// header, or the `VP8X` chunk of an extended file.
522    ///
523    /// After the `VP8X` chunk of an extended still image the result can carry
524    /// `format: None`, with the canvas as the size, until the prefix reaches
525    /// the image chunk's header; a caller who needs the format reads more
526    /// until it is `Some`.
527    ///
528    /// # Errors
529    ///
530    /// [`DecodeError::NotEnoughData`] when the prefix ends too early, and
531    /// [`DecodeError::BitstreamError`] for a file that is not a WebP file
532    /// libwebp decodes.
533    ///
534    /// # Examples
535    ///
536    /// ```
537    /// use webp::api::decode::{DecodeError, Features};
538    ///
539    /// assert_eq!(Features::parse(b"RIFF"), Err(DecodeError::NotEnoughData));
540    /// assert_eq!(Features::parse(b"GIF89a, not a WebP file"), Err(DecodeError::BitstreamError));
541    /// ```
542    ///
543    /// A prefix of an extended still image that ends after the `VP8X` chunk
544    /// gives the canvas but no format yet:
545    ///
546    /// ```
547    /// use webp::api::decode::{Features, Format};
548    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
549    /// # fn chunk(tag: &[u8], payload: &[u8]) -> Vec<u8> {
550    /// #     let mut bytes = tag.to_vec();
551    /// #     bytes.extend_from_slice(&(payload.len() as u32).to_le_bytes());
552    /// #     bytes.extend_from_slice(payload);
553    /// #     if payload.len() % 2 == 1 { bytes.push(0); }
554    /// #     bytes
555    /// # }
556    /// # let rgba = [0_u8, 0, 0, 255].repeat(4);
557    /// # let image = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 2, height: 2, stride: 8 })?;
558    /// # let vp8x = chunk(b"VP8X", &[0x20 | 0x08, 0, 0, 0, 1, 0, 0, 1, 0, 0]);
559    /// # let body = [vp8x, chunk(b"ICCP", b"profile"), image[12..].to_vec(), chunk(b"EXIF", b"Exif\0\0MM")].concat();
560    /// # let mut file = b"RIFF".to_vec();
561    /// # file.extend_from_slice(&(body.len() as u32 + 4).to_le_bytes());
562    /// # file.extend_from_slice(b"WEBP");
563    /// # file.extend_from_slice(&body);
564    ///
565    /// // `file` is an extended 2 by 2 still image: a 12-byte RIFF header, an
566    /// // 18-byte `VP8X` chunk, then `ICCP`, `VP8L` and `EXIF` chunks.
567    /// let prefix = Features::parse(&file[..30])?;
568    /// assert_eq!((prefix.width, prefix.height), (2, 2));
569    /// assert_eq!((prefix.format, prefix.has_animation), (None, false));
570    ///
571    /// assert_eq!(Features::parse(&file)?.format, Some(Format::Lossless));
572    /// # Ok::<(), Box<dyn std::error::Error>>(())
573    /// ```
574    pub fn parse(data: &[u8]) -> Result<Self, DecodeError> {
575        let mut raw = WebPBitstreamFeatures::default();
576        status(webp_get_features(data, &mut raw))?;
577        Ok(Self {
578            width: raw.width.cast_unsigned(),
579            height: raw.height.cast_unsigned(),
580            has_alpha: raw.has_alpha != 0,
581            has_animation: raw.has_animation != 0,
582            format: match raw.format {
583                1 => Some(Format::Lossy),
584                2 => Some(Format::Lossless),
585                _ => None,
586            },
587        })
588    }
589}
590
591//------------------------------------------------------------------------------
592// Color modes
593
594/// The layout of the decoded samples (C: `WEBP_CSP_MODE`, in its order).
595///
596/// Names give the byte order of a pixel; the `Premultiplied` modes multiply
597/// red, green and blue by alpha.
598///
599/// # Examples
600///
601/// ```
602/// use webp::api::decode::ColorMode;
603///
604/// assert_eq!(ColorMode::Bgra.bytes_per_pixel(), Some(4));
605/// assert_eq!(ColorMode::Rgb565.bytes_per_pixel(), Some(2));
606/// assert_eq!(ColorMode::Yuva.bytes_per_pixel(), None);
607/// assert!(ColorMode::PremultipliedArgb.is_premultiplied());
608/// ```
609#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
610pub enum ColorMode {
611    /// Red, green, blue (C: `MODE_RGB`).
612    Rgb,
613    /// Red, green, blue, straight alpha (C: `MODE_RGBA`).
614    Rgba,
615    /// Blue, green, red (C: `MODE_BGR`).
616    Bgr,
617    /// Blue, green, red, straight alpha (C: `MODE_BGRA`).
618    Bgra,
619    /// Straight alpha, red, green, blue (C: `MODE_ARGB`).
620    Argb,
621    /// Red and green, then blue and straight alpha, 4 bits each, in two bytes
622    /// (C: `MODE_RGBA_4444`).
623    Rgba4444,
624    /// Red (5 bits) and green (6 bits), then blue (5 bits), in two bytes
625    /// (C: `MODE_RGB_565`).
626    Rgb565,
627    /// [`ColorMode::Rgba`] with premultiplied alpha (C: `MODE_rgbA`).
628    PremultipliedRgba,
629    /// [`ColorMode::Bgra`] with premultiplied alpha (C: `MODE_bgrA`).
630    PremultipliedBgra,
631    /// [`ColorMode::Argb`] with premultiplied alpha (C: `MODE_Argb`).
632    PremultipliedArgb,
633    /// [`ColorMode::Rgba4444`] with premultiplied alpha (C: `MODE_rgbA_4444`).
634    PremultipliedRgba4444,
635    /// Y, U and V planes, 4:2:0, limited range (C: `MODE_YUV`).
636    Yuv,
637    /// Y, U, V and straight alpha planes (C: `MODE_YUVA`).
638    Yuva,
639}
640
641impl ColorMode {
642    /// The C colorspace.
643    const fn raw(self) -> WEBP_CSP_MODE {
644        match self {
645            Self::Rgb => WEBP_CSP_MODE::MODE_RGB,
646            Self::Rgba => WEBP_CSP_MODE::MODE_RGBA,
647            Self::Bgr => WEBP_CSP_MODE::MODE_BGR,
648            Self::Bgra => WEBP_CSP_MODE::MODE_BGRA,
649            Self::Argb => WEBP_CSP_MODE::MODE_ARGB,
650            Self::Rgba4444 => WEBP_CSP_MODE::MODE_RGBA_4444,
651            Self::Rgb565 => WEBP_CSP_MODE::MODE_RGB_565,
652            Self::PremultipliedRgba => WEBP_CSP_MODE::MODE_rgbA,
653            Self::PremultipliedBgra => WEBP_CSP_MODE::MODE_bgrA,
654            Self::PremultipliedArgb => WEBP_CSP_MODE::MODE_Argb,
655            Self::PremultipliedRgba4444 => WEBP_CSP_MODE::MODE_rgbA_4444,
656            Self::Yuv => WEBP_CSP_MODE::MODE_YUV,
657            Self::Yuva => WEBP_CSP_MODE::MODE_YUVA,
658        }
659    }
660
661    /// The bytes of a pixel in the RGB modes (libwebp's `kModeBpp`), or
662    /// `None` for the planar YUV modes.
663    ///
664    /// # Examples
665    ///
666    /// ```
667    /// use webp::api::decode::ColorMode;
668    ///
669    /// assert_eq!(ColorMode::Rgb.bytes_per_pixel(), Some(3));
670    /// assert_eq!(ColorMode::Yuv.bytes_per_pixel(), None);
671    /// ```
672    #[must_use]
673    pub const fn bytes_per_pixel(self) -> Option<usize> {
674        match self {
675            Self::Rgb | Self::Bgr => Some(3),
676            Self::Rgba
677            | Self::Bgra
678            | Self::Argb
679            | Self::PremultipliedRgba
680            | Self::PremultipliedBgra
681            | Self::PremultipliedArgb => Some(4),
682            Self::Rgba4444 | Self::Rgb565 | Self::PremultipliedRgba4444 => Some(2),
683            Self::Yuv | Self::Yuva => None,
684        }
685    }
686
687    /// Whether the output holds alpha (C: `WebPIsAlphaMode`).
688    ///
689    /// # Examples
690    ///
691    /// ```
692    /// use webp::api::decode::ColorMode;
693    ///
694    /// assert!(ColorMode::Yuva.has_alpha());
695    /// assert!(!ColorMode::Rgb565.has_alpha());
696    /// ```
697    #[must_use]
698    pub const fn has_alpha(self) -> bool {
699        !matches!(self, Self::Rgb | Self::Bgr | Self::Rgb565 | Self::Yuv)
700    }
701
702    /// Whether red, green and blue are multiplied by alpha (C:
703    /// `WebPIsPremultipliedMode`).
704    ///
705    /// # Examples
706    ///
707    /// ```
708    /// use webp::api::decode::ColorMode;
709    ///
710    /// assert!(ColorMode::PremultipliedRgba4444.is_premultiplied());
711    /// assert!(!ColorMode::Rgba.is_premultiplied());
712    /// ```
713    #[must_use]
714    pub const fn is_premultiplied(self) -> bool {
715        matches!(
716            self,
717            Self::PremultipliedRgba
718                | Self::PremultipliedBgra
719                | Self::PremultipliedArgb
720                | Self::PremultipliedRgba4444
721        )
722    }
723
724    /// Whether the output is planar `Y'CbCr` ([`ColorMode::Yuv`],
725    /// [`ColorMode::Yuva`]) rather than packed RGB rows.
726    ///
727    /// # Examples
728    ///
729    /// ```
730    /// use webp::api::decode::ColorMode;
731    ///
732    /// assert!(ColorMode::Yuv.is_yuv());
733    /// assert!(!ColorMode::Argb.is_yuv());
734    /// ```
735    #[must_use]
736    pub const fn is_yuv(self) -> bool {
737        matches!(self, Self::Yuv | Self::Yuva)
738    }
739}
740
741//------------------------------------------------------------------------------
742// Configuration
743
744/// `value` as C's `int`, saturated; the API refuses values above `i32::MAX`
745/// before the translation sees them.
746fn to_int(value: u32) -> i32 {
747    i32::try_from(value).unwrap_or(i32::MAX)
748}
749
750/// Decoding options and the color mode: a `WebPDecoderOptions` with typed
751/// setters, and the output colorspace.
752///
753/// The setters store their value and never fail; [`Config::validate`], which
754/// every decoding calls first, reports a value that the API refuses, and
755/// [`Config::output_size`] checks the crop against an image.
756///
757/// # Examples
758///
759/// ```
760/// use webp::api::decode::{ColorMode, Config};
761///
762/// let config = Config::new(ColorMode::PremultipliedBgra)
763///     .crop(64, 32, 640, 480)
764///     .scale(320, 240)
765///     .multithreaded(true)
766///     .dithering(50);
767/// config.validate()?;
768/// assert_eq!(config.as_raw().use_cropping, 1);
769/// # Ok::<(), webp::api::decode::DecodeError>(())
770/// ```
771#[derive(Clone, Copy, Debug, PartialEq, Eq)]
772pub struct Config {
773    mode: ColorMode,
774    options: WebPDecoderOptions,
775    crop: Option<[u32; 4]>,
776    scale: Option<[u32; 2]>,
777}
778
779impl Default for Config {
780    /// [`ColorMode::Rgb`] without options, as `WebPInitDecoderConfig` leaves
781    /// a configuration.
782    fn default() -> Self {
783        Self::new(ColorMode::Rgb)
784    }
785}
786
787impl Config {
788    /// A configuration for `mode` with libwebp's default options: no crop,
789    /// scale, flip or dithering, the in-loop filter and fancy upsampling on,
790    /// one thread (C: `WebPInitDecoderConfig`).
791    ///
792    /// # Examples
793    ///
794    /// ```
795    /// use webp::api::decode::{ColorMode, Config};
796    ///
797    /// let config = Config::new(ColorMode::Yuva);
798    /// assert_eq!(config.mode(), ColorMode::Yuva);
799    /// assert_eq!(config.as_raw().no_fancy_upsampling, 0);
800    /// ```
801    #[must_use]
802    pub fn new(mode: ColorMode) -> Self {
803        let mut raw = WebPDecoderConfig::default();
804        let initialized = webp_init_decoder_config(&mut raw);
805        debug_assert!(initialized, "the crate's own ABI version matches");
806        Self {
807            mode,
808            options: raw.options,
809            crop: None,
810            scale: None,
811        }
812    }
813
814    /// Decodes only the rectangle of `width` by `height` pixels at `left`,
815    /// `top` (C: `use_cropping`, `crop_left`, `crop_top`, `crop_width`,
816    /// `crop_height`). `left` and `top` must be even: libwebp moves an odd
817    /// lossy crop to the even position, so the API refuses odd offsets for
818    /// every image. To read a rectangle at an odd position, crop one column or
819    /// row earlier and skip it. The crop applies before the scale.
820    ///
821    /// # Examples
822    ///
823    /// ```
824    /// use webp::api::decode::{ColorMode, Config, DecodeError};
825    ///
826    /// assert!(Config::new(ColorMode::Rgb).crop(2, 4, 3, 5).validate().is_ok());
827    /// assert!(Config::new(ColorMode::Rgb).crop(3, 4, 3, 5).validate().is_err());
828    /// ```
829    #[must_use]
830    pub fn crop(mut self, left: u32, top: u32, width: u32, height: u32) -> Self {
831        self.crop = Some([left, top, width, height]);
832        self.options.use_cropping = 1;
833        self.options.crop_left = to_int(left);
834        self.options.crop_top = to_int(top);
835        self.options.crop_width = to_int(width);
836        self.options.crop_height = to_int(height);
837        self
838    }
839
840    /// Scales the (cropped) image to `width` by `height` pixels, each 1 to
841    /// 16383 (C: `use_scaling`, `scaled_width`, `scaled_height`). libwebp's
842    /// rescaler disables fancy upsampling, and a scale below 3/4 in both
843    /// directions skips the in-loop filter. libwebp derives a side given as 0;
844    /// the API needs both, so that it can bound the output before decoding.
845    ///
846    /// # Examples
847    ///
848    /// ```
849    /// use webp::api::decode::{ColorMode, Config, DecodeError};
850    ///
851    /// assert!(Config::new(ColorMode::Rgb).scale(100, 50).validate().is_ok());
852    /// assert_eq!(
853    ///     Config::new(ColorMode::Rgb).scale(100, 0).validate(),
854    ///     Err(DecodeError::InvalidScale { width: 100, height: 0 })
855    /// );
856    /// ```
857    #[must_use]
858    pub fn scale(mut self, width: u32, height: u32) -> Self {
859        self.scale = Some([width, height]);
860        self.options.use_scaling = 1;
861        self.options.scaled_width = to_int(width);
862        self.options.scaled_height = to_int(height);
863        self
864    }
865
866    /// Flips the output vertically (C: `flip`).
867    ///
868    /// # Examples
869    ///
870    /// ```
871    /// use webp::api::decode::{ColorMode, Config};
872    ///
873    /// assert_eq!(Config::new(ColorMode::Rgb).flip(true).as_raw().flip, 1);
874    /// ```
875    #[must_use]
876    pub fn flip(mut self, on: bool) -> Self {
877        self.options.flip = i32::from(on);
878        self
879    }
880
881    /// Skips the in-loop filter of lossy images, which is faster and changes
882    /// the samples (C: `bypass_filtering`).
883    ///
884    /// # Examples
885    ///
886    /// ```
887    /// use webp::api::decode::{ColorMode, Config};
888    ///
889    /// assert_eq!(Config::new(ColorMode::Rgb).bypass_filtering(true).as_raw().bypass_filtering, 1);
890    /// ```
891    #[must_use]
892    pub fn bypass_filtering(mut self, on: bool) -> Self {
893        self.options.bypass_filtering = i32::from(on);
894        self
895    }
896
897    /// Fancy upsampling of the chroma of lossy images in the RGB modes, on
898    /// by default; off uses the faster point upsampler (C: the negation of
899    /// `no_fancy_upsampling`).
900    ///
901    /// # Examples
902    ///
903    /// ```
904    /// use webp::api::decode::{ColorMode, Config};
905    ///
906    /// let config = Config::new(ColorMode::Rgb).fancy_upsampling(false);
907    /// assert_eq!(config.as_raw().no_fancy_upsampling, 1);
908    /// ```
909    #[must_use]
910    pub fn fancy_upsampling(mut self, on: bool) -> Self {
911        self.options.no_fancy_upsampling = i32::from(!on);
912        self
913    }
914
915    /// Decodes lossy images with a second thread for filtering and output
916    /// (C: `use_threads`); the samples do not change.
917    ///
918    /// # Examples
919    ///
920    /// ```
921    /// use webp::api::decode::{ColorMode, Config};
922    ///
923    /// assert_eq!(Config::new(ColorMode::Rgb).multithreaded(true).as_raw().use_threads, 1);
924    /// ```
925    #[must_use]
926    pub fn multithreaded(mut self, on: bool) -> Self {
927        self.options.use_threads = i32::from(on);
928        self
929    }
930
931    /// The strength of the dither that libwebp adds to lossy output, 0 (off,
932    /// the default) to 100 (C: `dithering_strength`).
933    ///
934    /// # Examples
935    ///
936    /// ```
937    /// use webp::api::decode::{ColorMode, Config, DecodeError};
938    ///
939    /// assert!(Config::new(ColorMode::Rgb).dithering(100).validate().is_ok());
940    /// assert_eq!(
941    ///     Config::new(ColorMode::Rgb).dithering(101).validate(),
942    ///     Err(DecodeError::InvalidParameter { name: "dithering" })
943    /// );
944    /// ```
945    #[must_use]
946    pub fn dithering(mut self, strength: u8) -> Self {
947        self.options.dithering_strength = i32::from(strength);
948        self
949    }
950
951    /// The strength of the smoothing of quantized alpha, 0 (off, the default)
952    /// to 100 (C: `alpha_dithering_strength`).
953    ///
954    /// # Examples
955    ///
956    /// ```
957    /// use webp::api::decode::{ColorMode, Config};
958    ///
959    /// let config = Config::new(ColorMode::Rgba).alpha_dithering(100);
960    /// assert_eq!(config.as_raw().alpha_dithering_strength, 100);
961    /// ```
962    #[must_use]
963    pub fn alpha_dithering(mut self, strength: u8) -> Self {
964        self.options.alpha_dithering_strength = i32::from(strength);
965        self
966    }
967
968    /// The color mode of the output.
969    ///
970    /// # Examples
971    ///
972    /// ```
973    /// use webp::api::decode::{ColorMode, Config};
974    ///
975    /// assert_eq!(Config::default().mode(), ColorMode::Rgb);
976    /// ```
977    #[must_use]
978    pub const fn mode(&self) -> ColorMode {
979        self.mode
980    }
981
982    /// Checks what does not depend on the image: a crop of at least 1 by 1
983    /// pixel at even `left` and `top`, every value at most `i32::MAX`; a scale
984    /// of 1 to 16383 on each side; dithering strengths of at most 100; then
985    /// libwebp's `WebPValidateDecoderConfig`.
986    ///
987    /// # Errors
988    ///
989    /// [`DecodeError::InvalidCrop`], [`DecodeError::InvalidScale`] or
990    /// [`DecodeError::InvalidParameter`] for the API's rules, and
991    /// [`DecodeError::InvalidParam`] if libwebp refused the configuration
992    /// after them.
993    ///
994    /// # Examples
995    ///
996    /// ```
997    /// use webp::api::decode::{ColorMode, Config, DecodeError};
998    ///
999    /// assert_eq!(
1000    ///     Config::new(ColorMode::Rgb).crop(0, 0, 0, 8).validate(),
1001    ///     Err(DecodeError::InvalidCrop { left: 0, top: 0, width: 0, height: 8 })
1002    /// );
1003    /// ```
1004    pub fn validate(&self) -> Result<(), DecodeError> {
1005        if let Some([left, top, width, height]) = self.crop {
1006            let too_large = [left, top, width, height]
1007                .iter()
1008                .any(|&value| i32::try_from(value).is_err());
1009            if width == 0 || height == 0 || left % 2 != 0 || top % 2 != 0 || too_large {
1010                return Err(DecodeError::InvalidCrop {
1011                    left,
1012                    top,
1013                    width,
1014                    height,
1015                });
1016            }
1017        }
1018        if let Some([width, height]) = self.scale {
1019            let range = 1..=MAX_SCALED_DIMENSION;
1020            if !range.contains(&width) || !range.contains(&height) {
1021                return Err(DecodeError::InvalidScale { width, height });
1022            }
1023        }
1024        if self.options.dithering_strength > 100 {
1025            return Err(DecodeError::InvalidParameter { name: "dithering" });
1026        }
1027        if self.options.alpha_dithering_strength > 100 {
1028            return Err(DecodeError::InvalidParameter {
1029                name: "alpha_dithering",
1030            });
1031        }
1032        // A backstop: the checks above already refuse every configuration
1033        // that `WebPValidateDecoderConfig` refuses without features.
1034        if webp_validate_decoder_config(&self.raw_config()) {
1035            Ok(())
1036        } else {
1037            Err(DecodeError::InvalidParam)
1038        }
1039    }
1040
1041    /// The width and height of the output for an image with `features`: the
1042    /// crop's size, then the scale's, after [`Config::validate`] and a check
1043    /// that the crop lies inside the image (C: `WebPCheckCropDimensions`).
1044    ///
1045    /// # Errors
1046    ///
1047    /// The errors of [`Config::validate`], and [`DecodeError::InvalidCrop`]
1048    /// for a crop that does not lie inside the image.
1049    ///
1050    /// # Examples
1051    ///
1052    /// ```
1053    /// use webp::api::decode::{ColorMode, Config, Features};
1054    ///
1055    /// let features = Features { width: 640, height: 480, has_alpha: false, has_animation: false, format: None };
1056    /// let config = Config::new(ColorMode::Rgb).crop(320, 0, 320, 480).scale(160, 240);
1057    /// assert_eq!(config.output_size(&features)?, (160, 240));
1058    /// assert!(Config::new(ColorMode::Rgb).crop(322, 0, 320, 480).output_size(&features).is_err());
1059    /// # Ok::<(), webp::api::decode::DecodeError>(())
1060    /// ```
1061    pub fn output_size(&self, features: &Features) -> Result<(u32, u32), DecodeError> {
1062        self.validate()?;
1063        let (mut width, mut height) = (features.width, features.height);
1064        if let Some([left, top, crop_width, crop_height]) = self.crop {
1065            if !webp_check_crop_dimensions(
1066                to_int(features.width),
1067                to_int(features.height),
1068                to_int(left),
1069                to_int(top),
1070                to_int(crop_width),
1071                to_int(crop_height),
1072            ) {
1073                return Err(DecodeError::InvalidCrop {
1074                    left,
1075                    top,
1076                    width: crop_width,
1077                    height: crop_height,
1078                });
1079            }
1080            (width, height) = (crop_width, crop_height);
1081        }
1082        if let Some([scaled_width, scaled_height]) = self.scale {
1083            (width, height) = (scaled_width, scaled_height);
1084        }
1085        Ok((width, height))
1086    }
1087
1088    /// The options as libwebp reads them (C: `WebPDecoderOptions`).
1089    ///
1090    /// # Examples
1091    ///
1092    /// ```
1093    /// use webp::api::decode::{ColorMode, Config};
1094    ///
1095    /// let config = Config::new(ColorMode::Rgb).crop(0, 2, 10, 20);
1096    /// let raw = config.as_raw();
1097    /// assert_eq!((raw.crop_top, raw.crop_width, raw.crop_height), (2, 10, 20));
1098    /// ```
1099    #[must_use]
1100    pub const fn as_raw(&self) -> &WebPDecoderOptions {
1101        &self.options
1102    }
1103
1104    /// A `WebPDecoderConfig` with this colorspace and these options, and an
1105    /// output buffer without memory.
1106    fn raw_config<'a>(&self) -> WebPDecoderConfig<'a> {
1107        let mut raw = WebPDecoderConfig::default();
1108        let initialized = webp_init_decoder_config(&mut raw);
1109        debug_assert!(initialized, "the crate's own ABI version matches");
1110        raw.output.colorspace = self.mode.raw();
1111        raw.options = self.options;
1112        raw
1113    }
1114}
1115
1116//------------------------------------------------------------------------------
1117// Caller memory
1118
1119/// The caller's Y, U, V and optional alpha planes, an [`Output`] for
1120/// [`ColorMode::Yuv`] and [`ColorMode::Yuva`].
1121///
1122/// Every stride counts bytes. The Y and A planes have `height` rows of
1123/// `width` samples, the U and V planes `(height + 1) / 2` rows of
1124/// `(width + 1) / 2` samples; each stride is at least its row length and at
1125/// most `i32::MAX`, and each plane holds at least
1126/// `(rows - 1) * stride + row length` bytes. `a` is given exactly for
1127/// [`ColorMode::Yuva`]; `a_stride` is ignored without it.
1128///
1129/// # Examples
1130///
1131/// ```
1132/// use webp::api::decode::{decode_into, ColorMode, Config, Output, YuvaPlanes};
1133/// # use webp::api::encode::{encode_lossy, PixelLayout, PixelRows};
1134/// # let rgb = [90_u8, 60, 30].repeat(15);
1135/// # let file = encode_lossy(PixelRows { layout: PixelLayout::Rgb, data: &rgb, width: 5, height: 3, stride: 15 }, 90.0)?;
1136///
1137/// // A 5 by 3 image: chroma planes of 3 by 2, rows padded to 8 bytes.
1138/// let (mut y, mut u, mut v) = (vec![0_u8; 8 * 3], vec![0_u8; 8 * 2], vec![0_u8; 8 * 2]);
1139/// let planes = YuvaPlanes {
1140///     y: &mut y, y_stride: 8,
1141///     u: &mut u, v: &mut v, uv_stride: 8,
1142///     a: None, a_stride: 0,
1143/// };
1144/// decode_into(&file, &Config::new(ColorMode::Yuv), Output::Planes(planes))?;
1145/// assert!(y[..5].iter().all(|&luma| (16..=235).contains(&luma)));
1146/// # Ok::<(), Box<dyn std::error::Error>>(())
1147/// ```
1148pub struct YuvaPlanes<'a> {
1149    /// The luma plane.
1150    pub y: &'a mut [u8],
1151    /// The distance between luma rows, in bytes.
1152    pub y_stride: usize,
1153    /// The U (Cb) chroma plane.
1154    pub u: &'a mut [u8],
1155    /// The V (Cr) chroma plane.
1156    pub v: &'a mut [u8],
1157    /// The distance between rows of both chroma planes, in bytes.
1158    pub uv_stride: usize,
1159    /// The alpha plane, straight alpha, for [`ColorMode::Yuva`].
1160    pub a: Option<&'a mut [u8]>,
1161    /// The distance between alpha rows, in bytes.
1162    pub a_stride: usize,
1163}
1164
1165impl fmt::Debug for YuvaPlanes<'_> {
1166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1167        f.debug_struct("YuvaPlanes")
1168            .field("y_len", &self.y.len())
1169            .field("y_stride", &self.y_stride)
1170            .field("u_len", &self.u.len())
1171            .field("v_len", &self.v.len())
1172            .field("uv_stride", &self.uv_stride)
1173            .field("a_len", &self.a.as_ref().map(|a| a.len()))
1174            .field("a_stride", &self.a_stride)
1175            .finish()
1176    }
1177}
1178
1179/// Caller memory that a decoding writes into.
1180///
1181/// # Examples
1182///
1183/// ```
1184/// use webp::api::decode::{decode_into, ColorMode, Config, Output};
1185/// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
1186/// # let rgba = [7_u8, 8, 9, 255].repeat(12);
1187/// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 4, height: 3, stride: 16 })?;
1188///
1189/// // 4 by 3 BGR pixels in rows of 16 bytes (12 used).
1190/// let mut rows = vec![0_u8; 16 * 2 + 12];
1191/// let size = decode_into(&file, &Config::new(ColorMode::Bgr), Output::Rows { data: &mut rows, stride: 16 })?;
1192/// assert_eq!(size, (4, 3));
1193/// assert_eq!(&rows[..3], &[9, 8, 7]);
1194/// # Ok::<(), Box<dyn std::error::Error>>(())
1195/// ```
1196pub enum Output<'a> {
1197    /// Packed rows for the RGB modes: at least
1198    /// `(height - 1) * stride + width * bytes_per_pixel` bytes.
1199    Rows {
1200        /// The rows, top to bottom.
1201        data: &'a mut [u8],
1202        /// The distance from the start of a row to the next, in bytes: at
1203        /// least `width * bytes_per_pixel` and at most `i32::MAX`.
1204        stride: usize,
1205    },
1206    /// Planes for [`ColorMode::Yuv`] and [`ColorMode::Yuva`].
1207    Planes(YuvaPlanes<'a>),
1208}
1209
1210impl fmt::Debug for Output<'_> {
1211    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1212        match self {
1213            Self::Rows { data, stride } => f
1214                .debug_struct("Rows")
1215                .field("data_len", &data.len())
1216                .field("stride", stride)
1217                .finish(),
1218            Self::Planes(planes) => f.debug_tuple("Planes").field(planes).finish(),
1219        }
1220    }
1221}
1222
1223/// The API's check of one output plane: `rows` rows of `row` bytes at
1224/// `stride`, inside `len` bytes.
1225fn check_plane(
1226    plane: Plane,
1227    len: usize,
1228    stride: usize,
1229    row: usize,
1230    rows: usize,
1231) -> Result<(), DecodeError> {
1232    if stride < row || i32::try_from(stride).is_err() {
1233        return Err(DecodeError::InvalidStride { plane, stride });
1234    }
1235    let needed = rows
1236        .saturating_sub(1)
1237        .checked_mul(stride)
1238        .and_then(|extent| extent.checked_add(row))
1239        .ok_or(DecodeError::InvalidStride { plane, stride })?;
1240    if len < needed {
1241        return Err(DecodeError::BufferTooShort { plane, len, needed });
1242    }
1243    Ok(())
1244}
1245
1246/// Whether `output` has the shape that `mode` needs: rows for the RGB modes,
1247/// planes for the YUV modes, with an alpha plane exactly for `Yuva`.
1248fn check_shape(mode: ColorMode, output: &Output<'_>) -> Result<(), DecodeError> {
1249    let matches = match output {
1250        Output::Rows { .. } => !mode.is_yuv(),
1251        Output::Planes(planes) => mode.is_yuv() && planes.a.is_some() == (mode == ColorMode::Yuva),
1252    };
1253    if matches {
1254        Ok(())
1255    } else {
1256        Err(DecodeError::OutputMismatch { mode })
1257    }
1258}
1259
1260/// The checks of `output` against an output of `width` by `height` in
1261/// `mode` (C: `CheckDecBuffer`, with the API's own errors).
1262fn check_output(
1263    mode: ColorMode,
1264    width: u32,
1265    height: u32,
1266    output: &Output<'_>,
1267) -> Result<(), DecodeError> {
1268    check_shape(mode, output)?;
1269    let width = usize::try_from(width).unwrap_or(usize::MAX);
1270    let height = usize::try_from(height).unwrap_or(usize::MAX);
1271    match output {
1272        Output::Rows { data, stride } => {
1273            let bpp = mode.bytes_per_pixel().unwrap_or(1);
1274            let row = width.checked_mul(bpp).ok_or(DecodeError::InvalidStride {
1275                plane: Plane::Rows,
1276                stride: *stride,
1277            })?;
1278            check_plane(Plane::Rows, data.len(), *stride, row, height)
1279        }
1280        Output::Planes(planes) => {
1281            let (uv_width, uv_height) = (width.div_ceil(2), height.div_ceil(2));
1282            check_plane(Plane::Y, planes.y.len(), planes.y_stride, width, height)?;
1283            check_plane(
1284                Plane::U,
1285                planes.u.len(),
1286                planes.uv_stride,
1287                uv_width,
1288                uv_height,
1289            )?;
1290            check_plane(
1291                Plane::V,
1292                planes.v.len(),
1293                planes.uv_stride,
1294                uv_width,
1295                uv_height,
1296            )?;
1297            if let Some(a) = &planes.a {
1298                check_plane(Plane::A, a.len(), planes.a_stride, width, height)?;
1299            }
1300            Ok(())
1301        }
1302    }
1303}
1304
1305/// The checks of `output` that do not depend on the image: the shape, and
1306/// strides of 1 to `i32::MAX` bytes over non-empty slices.
1307fn check_output_shape(mode: ColorMode, output: &Output<'_>) -> Result<(), DecodeError> {
1308    check_shape(mode, output)?;
1309    let check = |plane, len: usize, stride: usize| {
1310        if stride == 0 || i32::try_from(stride).is_err() {
1311            Err(DecodeError::InvalidStride { plane, stride })
1312        } else if len == 0 {
1313            Err(DecodeError::BufferTooShort {
1314                plane,
1315                len,
1316                needed: 1,
1317            })
1318        } else {
1319            Ok(())
1320        }
1321    };
1322    match output {
1323        Output::Rows { data, stride } => check(Plane::Rows, data.len(), *stride),
1324        Output::Planes(planes) => {
1325            check(Plane::Y, planes.y.len(), planes.y_stride)?;
1326            check(Plane::U, planes.u.len(), planes.uv_stride)?;
1327            check(Plane::V, planes.v.len(), planes.uv_stride)?;
1328            if let Some(a) = &planes.a {
1329                check(Plane::A, a.len(), planes.a_stride)?;
1330            }
1331            Ok(())
1332        }
1333    }
1334}
1335
1336/// A stride that the checks above accepted, as C's `int`.
1337fn stride_int(stride: usize) -> i32 {
1338    i32::try_from(stride).unwrap_or(i32::MAX)
1339}
1340
1341/// Lends the caller's memory to `buffer` as `PlaneStorage::External`, with
1342/// each `size` equal to its slice's length (C: `is_external_memory` 1 and
1343/// the plane pointers, strides and sizes).
1344fn attach<'a>(buffer: &mut WebPDecBuffer<'a>, output: Output<'a>) {
1345    let plane = |region| PlaneOffset { region, offset: 0 };
1346    match output {
1347        Output::Rows { data, stride } => {
1348            buffer.u = WebPDecBufferPlanes::RGBA(WebPRGBABuffer {
1349                rgba: plane(0),
1350                stride: stride_int(stride),
1351                size: data.len(),
1352            });
1353            buffer.storage = PlaneStorage::External(vec![data]);
1354        }
1355        Output::Planes(planes) => {
1356            let YuvaPlanes {
1357                y,
1358                y_stride,
1359                u,
1360                v,
1361                uv_stride,
1362                a,
1363                a_stride,
1364            } = planes;
1365            buffer.u = WebPDecBufferPlanes::YUVA(WebPYUVABuffer {
1366                y: plane(0),
1367                u: plane(1),
1368                v: plane(2),
1369                a: a.is_some().then(|| plane(3)),
1370                y_stride: stride_int(y_stride),
1371                u_stride: stride_int(uv_stride),
1372                v_stride: stride_int(uv_stride),
1373                a_stride: a.as_ref().map_or(0, |_| stride_int(a_stride)),
1374                y_size: y.len(),
1375                u_size: u.len(),
1376                v_size: v.len(),
1377                a_size: a.as_ref().map_or(0, |a| a.len()),
1378            });
1379            let mut slices = vec![y, u, v];
1380            slices.extend(a);
1381            buffer.storage = PlaneStorage::External(slices);
1382        }
1383    }
1384    buffer.slow_memory = false;
1385}
1386
1387//------------------------------------------------------------------------------
1388// Decoded rows
1389
1390/// Rows of one plane: a region of memory, the position of the first row, a
1391/// signed stride in bytes and the number of rows.
1392///
1393/// # Examples
1394///
1395/// ```
1396/// use webp::api::decode::{decode, ColorMode, Config};
1397/// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
1398/// # let mut rgba = [0_u8, 0, 0, 255].repeat(6);
1399/// # rgba[..4].copy_from_slice(&[255, 0, 0, 255]);
1400/// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 3, height: 2, stride: 12 })?;
1401///
1402/// let image = decode(&file, &Config::new(ColorMode::Rgb))?;
1403/// let rows = image.rows().expect("an RGB mode");
1404/// assert_eq!((rows.len(), rows.row_len(), rows.stride()), (2, 9, 9));
1405/// assert_eq!(&rows.row(0).unwrap()[..3], &[255, 0, 0]);
1406/// assert_eq!(rows.iter().count(), 2);
1407/// # Ok::<(), Box<dyn std::error::Error>>(())
1408/// ```
1409#[derive(Clone, Copy)]
1410pub struct Rows<'s> {
1411    data: &'s [u8],
1412    first: usize,
1413    stride: isize,
1414    row_len: usize,
1415    count: u32,
1416}
1417
1418impl fmt::Debug for Rows<'_> {
1419    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1420        f.debug_struct("Rows")
1421            .field("region_len", &self.data.len())
1422            .field("first", &self.first)
1423            .field("stride", &self.stride)
1424            .field("row_len", &self.row_len)
1425            .field("count", &self.count)
1426            .finish()
1427    }
1428}
1429
1430impl<'s> Rows<'s> {
1431    /// The rows from `first` at `stride` (C's `int`) in `data`.
1432    fn new(data: &'s [u8], first: usize, stride: i32, row_len: usize, count: i32) -> Self {
1433        Self {
1434            data,
1435            first,
1436            stride: isize::try_from(stride).unwrap_or(0),
1437            row_len,
1438            count: u32::try_from(count).unwrap_or(0),
1439        }
1440    }
1441
1442    /// The number of rows.
1443    ///
1444    /// # Examples
1445    ///
1446    /// ```
1447    /// use webp::api::decode::{decode, ColorMode, Config};
1448    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
1449    /// # let rgba = [0_u8; 4 * 4 * 5];
1450    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 4, height: 5, stride: 16 })?;
1451    ///
1452    /// assert_eq!(decode(&file, &Config::new(ColorMode::Rgba))?.rows().unwrap().len(), 5);
1453    /// # Ok::<(), Box<dyn std::error::Error>>(())
1454    /// ```
1455    #[must_use]
1456    pub const fn len(&self) -> u32 {
1457        self.count
1458    }
1459
1460    /// Whether there are no rows, as before an incremental decoding has
1461    /// decoded any.
1462    ///
1463    /// # Examples
1464    ///
1465    /// ```
1466    /// use webp::api::decode::{decode, ColorMode, Config};
1467    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
1468    /// # let rgba = [0_u8; 4];
1469    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 1, height: 1, stride: 4 })?;
1470    ///
1471    /// assert!(!decode(&file, &Config::new(ColorMode::Rgba))?.rows().unwrap().is_empty());
1472    /// # Ok::<(), Box<dyn std::error::Error>>(())
1473    /// ```
1474    #[must_use]
1475    pub const fn is_empty(&self) -> bool {
1476        self.count == 0
1477    }
1478
1479    /// Row `index`, `row_len` bytes from the first row plus `index` strides,
1480    /// or `None` for an index at or past [`Rows::len`].
1481    ///
1482    /// # Examples
1483    ///
1484    /// ```
1485    /// use webp::api::decode::{decode, ColorMode, Config};
1486    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
1487    /// # let rgba = [5_u8, 6, 7, 255, 1, 2, 3, 255];
1488    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 1, height: 2, stride: 4 })?;
1489    ///
1490    /// let image = decode(&file, &Config::new(ColorMode::Rgb))?;
1491    /// let rows = image.rows().unwrap();
1492    /// assert_eq!(rows.row(1), Some(&[1_u8, 2, 3][..]));
1493    /// assert_eq!(rows.row(2), None);
1494    /// # Ok::<(), Box<dyn std::error::Error>>(())
1495    /// ```
1496    #[must_use]
1497    pub fn row(&self, index: u32) -> Option<&'s [u8]> {
1498        if index >= self.count {
1499            return None;
1500        }
1501        let offset = isize::try_from(index).ok()?.checked_mul(self.stride)?;
1502        let start = self.first.checked_add_signed(offset)?;
1503        self.data.get(start..start.checked_add(self.row_len)?)
1504    }
1505
1506    /// The rows in order: row 0, then row 1, and so on.
1507    ///
1508    /// # Examples
1509    ///
1510    /// ```
1511    /// use webp::api::decode::{decode, ColorMode, Config};
1512    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
1513    /// # let rgba = [9_u8; 4 * 6];
1514    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 2, height: 3, stride: 8 })?;
1515    ///
1516    /// let image = decode(&file, &Config::new(ColorMode::Rgba))?;
1517    /// assert!(image.rows().unwrap().iter().all(|row| row == [9_u8; 8]));
1518    /// # Ok::<(), Box<dyn std::error::Error>>(())
1519    /// ```
1520    pub fn iter(&self) -> impl Iterator<Item = &'s [u8]> + 's {
1521        let rows = *self;
1522        (0..rows.count).filter_map(move |index| rows.row(index))
1523    }
1524
1525    /// The bytes of a row: the width times the bytes per pixel, or the width
1526    /// of a plane.
1527    ///
1528    /// # Examples
1529    ///
1530    /// ```
1531    /// use webp::api::decode::{decode, ColorMode, Config};
1532    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
1533    /// # let rgba = [0_u8; 4 * 5];
1534    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 5, height: 1, stride: 20 })?;
1535    ///
1536    /// assert_eq!(decode(&file, &Config::new(ColorMode::Rgb565))?.rows().unwrap().row_len(), 10);
1537    /// # Ok::<(), Box<dyn std::error::Error>>(())
1538    /// ```
1539    #[must_use]
1540    pub const fn row_len(&self) -> usize {
1541        self.row_len
1542    }
1543
1544    /// The distance from a row to the next, in bytes; negative while a
1545    /// flipped incremental decoding runs, whose row 0 is then the bottom row
1546    /// of the output.
1547    ///
1548    /// # Examples
1549    ///
1550    /// ```
1551    /// use webp::api::decode::{decode, ColorMode, Config};
1552    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
1553    /// # let rgba = [0_u8; 4 * 3 * 2];
1554    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 3, height: 2, stride: 12 })?;
1555    ///
1556    /// assert_eq!(decode(&file, &Config::new(ColorMode::Argb))?.rows().unwrap().stride(), 12);
1557    /// # Ok::<(), Box<dyn std::error::Error>>(())
1558    /// ```
1559    #[must_use]
1560    pub const fn stride(&self) -> isize {
1561        self.stride
1562    }
1563}
1564
1565/// The rows of the Y, U, V and, for [`ColorMode::Yuva`], alpha planes.
1566///
1567/// # Examples
1568///
1569/// ```
1570/// use webp::api::decode::{decode, ColorMode, Config};
1571/// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
1572/// # let rgba = [40_u8, 80, 120, 200].repeat(15);
1573/// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 5, height: 3, stride: 20 })?;
1574///
1575/// let image = decode(&file, &Config::new(ColorMode::Yuva))?;
1576/// let planes = image.planes().expect("a YUV mode");
1577/// assert_eq!((planes.y.len(), planes.y.row_len()), (3, 5));
1578/// assert_eq!((planes.u.len(), planes.u.row_len()), (2, 3));
1579/// assert_eq!(planes.a.unwrap().row(0), Some(&[200_u8; 5][..]));
1580/// # Ok::<(), Box<dyn std::error::Error>>(())
1581/// ```
1582#[derive(Clone, Copy, Debug)]
1583pub struct YuvaRows<'s> {
1584    /// The luma rows.
1585    pub y: Rows<'s>,
1586    /// The U (Cb) rows.
1587    pub u: Rows<'s>,
1588    /// The V (Cr) rows.
1589    pub v: Rows<'s>,
1590    /// The alpha rows, for [`ColorMode::Yuva`].
1591    pub a: Option<Rows<'s>>,
1592}
1593
1594/// Where a plane of an [`Image`] lies in its memory.
1595#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1596struct PlaneLayout {
1597    offset: usize,
1598    stride: i32,
1599}
1600
1601/// The planes of an [`Image`].
1602#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1603enum Layout {
1604    Packed(PlaneLayout),
1605    Planar {
1606        y: PlaneLayout,
1607        u: PlaneLayout,
1608        v: PlaneLayout,
1609        a: Option<PlaneLayout>,
1610    },
1611}
1612
1613/// A decoded image in memory that libwebp allocated, which the image owns.
1614///
1615/// # Examples
1616///
1617/// ```
1618/// use webp::api::decode::{decode, ColorMode, Config};
1619/// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
1620/// # let rgba = [11_u8, 22, 33, 44].repeat(8);
1621/// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 4, height: 2, stride: 16 })?;
1622///
1623/// let image = decode(&file, &Config::new(ColorMode::Bgra))?;
1624/// assert_eq!((image.mode(), image.width(), image.height()), (ColorMode::Bgra, 4, 2));
1625/// assert_eq!(&image.samples()[..4], &[33, 22, 11, 44]);
1626/// let samples: Vec<u8> = image.into_samples();
1627/// assert_eq!(samples.len(), 4 * 4 * 2);
1628/// # Ok::<(), Box<dyn std::error::Error>>(())
1629/// ```
1630#[derive(Clone, PartialEq, Eq)]
1631pub struct Image {
1632    mode: ColorMode,
1633    width: u32,
1634    height: u32,
1635    samples: Vec<u8>,
1636    layout: Layout,
1637}
1638
1639impl fmt::Debug for Image {
1640    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1641        f.debug_struct("Image")
1642            .field("mode", &self.mode)
1643            .field("width", &self.width)
1644            .field("height", &self.height)
1645            .field("samples_len", &self.samples.len())
1646            .field("layout", &self.layout)
1647            .finish()
1648    }
1649}
1650
1651impl Image {
1652    /// The image in a buffer whose memory libwebp allocated: its memory and
1653    /// plane layout. A buffer that holds caller memory or no memory is not an
1654    /// image; the API never passes one.
1655    fn from_buffer(mode: ColorMode, buffer: WebPDecBuffer<'_>) -> Result<Self, DecodeError> {
1656        let width = u32::try_from(buffer.width).map_err(|_| DecodeError::InvalidParam)?;
1657        let height = u32::try_from(buffer.height).map_err(|_| DecodeError::InvalidParam)?;
1658        let PlaneStorage::Internal(samples) = buffer.storage else {
1659            return Err(DecodeError::OutputMismatch { mode });
1660        };
1661        if samples.is_empty() {
1662            // A backstop: both callers pass a buffer only after a complete
1663            // decoding, which allocated the memory.
1664            return Err(DecodeError::Suspended);
1665        }
1666        let plane = |offset: PlaneOffset, stride: i32| PlaneLayout {
1667            offset: offset.offset,
1668            stride,
1669        };
1670        let layout = match buffer.u {
1671            WebPDecBufferPlanes::RGBA(rgba) => Layout::Packed(plane(rgba.rgba, rgba.stride)),
1672            WebPDecBufferPlanes::YUVA(yuva) => Layout::Planar {
1673                y: plane(yuva.y, yuva.y_stride),
1674                u: plane(yuva.u, yuva.u_stride),
1675                v: plane(yuva.v, yuva.v_stride),
1676                a: yuva.a.map(|a| plane(a, yuva.a_stride)),
1677            },
1678        };
1679        Ok(Self {
1680            mode,
1681            width,
1682            height,
1683            samples,
1684            layout,
1685        })
1686    }
1687
1688    /// The color mode of the samples.
1689    ///
1690    /// # Examples
1691    ///
1692    /// ```
1693    /// use webp::api::decode::{decode, ColorMode, Config};
1694    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
1695    /// # let rgba = [0_u8; 4];
1696    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 1, height: 1, stride: 4 })?;
1697    ///
1698    /// assert_eq!(decode(&file, &Config::new(ColorMode::Yuv))?.mode(), ColorMode::Yuv);
1699    /// # Ok::<(), Box<dyn std::error::Error>>(())
1700    /// ```
1701    #[must_use]
1702    pub const fn mode(&self) -> ColorMode {
1703        self.mode
1704    }
1705
1706    /// The width in pixels, after crop and scale.
1707    ///
1708    /// # Examples
1709    ///
1710    /// ```
1711    /// use webp::api::decode::{decode, ColorMode, Config};
1712    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
1713    /// # let rgba = [0_u8; 4 * 8 * 8];
1714    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 8, height: 8, stride: 32 })?;
1715    ///
1716    /// let image = decode(&file, &Config::new(ColorMode::Rgb).scale(3, 2))?;
1717    /// assert_eq!((image.width(), image.height()), (3, 2));
1718    /// # Ok::<(), Box<dyn std::error::Error>>(())
1719    /// ```
1720    #[must_use]
1721    pub const fn width(&self) -> u32 {
1722        self.width
1723    }
1724
1725    /// The height in pixels, after crop and scale.
1726    ///
1727    /// # Examples
1728    ///
1729    /// ```
1730    /// use webp::api::decode::{decode, ColorMode, Config};
1731    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
1732    /// # let rgba = [0_u8; 4 * 8 * 8];
1733    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 8, height: 8, stride: 32 })?;
1734    ///
1735    /// assert_eq!(decode(&file, &Config::new(ColorMode::Rgb).crop(0, 2, 8, 4))?.height(), 4);
1736    /// # Ok::<(), Box<dyn std::error::Error>>(())
1737    /// ```
1738    #[must_use]
1739    pub const fn height(&self) -> u32 {
1740        self.height
1741    }
1742
1743    /// The rows of an RGB mode, top to bottom, or `None` for a YUV mode.
1744    ///
1745    /// # Examples
1746    ///
1747    /// ```
1748    /// use webp::api::decode::{decode, ColorMode, Config};
1749    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
1750    /// # let rgba = [1_u8, 2, 3, 4, 5, 6, 7, 8];
1751    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 1, height: 2, stride: 4 })?;
1752    ///
1753    /// let flipped = decode(&file, &Config::new(ColorMode::Rgba).flip(true))?;
1754    /// assert_eq!(flipped.rows().unwrap().row(0), Some(&[5_u8, 6, 7, 8][..]));
1755    /// assert!(decode(&file, &Config::new(ColorMode::Yuva))?.rows().is_none());
1756    /// # Ok::<(), Box<dyn std::error::Error>>(())
1757    /// ```
1758    #[must_use]
1759    pub fn rows(&self) -> Option<Rows<'_>> {
1760        let Layout::Packed(plane) = self.layout else {
1761            return None;
1762        };
1763        let row_len = usize::try_from(self.width)
1764            .ok()?
1765            .checked_mul(self.mode.bytes_per_pixel()?)?;
1766        Some(Rows::new(
1767            &self.samples,
1768            plane.offset,
1769            plane.stride,
1770            row_len,
1771            i32::try_from(self.height).ok()?,
1772        ))
1773    }
1774
1775    /// The planes of a YUV mode, or `None` for an RGB mode.
1776    ///
1777    /// # Examples
1778    ///
1779    /// ```
1780    /// use webp::api::decode::{decode, ColorMode, Config};
1781    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
1782    /// # let rgba = [255_u8; 4 * 4];
1783    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 2, height: 2, stride: 8 })?;
1784    ///
1785    /// let image = decode(&file, &Config::new(ColorMode::Yuv))?;
1786    /// let planes = image.planes().unwrap();
1787    /// assert_eq!(planes.y.row(0), Some(&[235_u8, 235][..])); // white, limited range
1788    /// assert!(planes.a.is_none());
1789    /// # Ok::<(), Box<dyn std::error::Error>>(())
1790    /// ```
1791    #[must_use]
1792    pub fn planes(&self) -> Option<YuvaRows<'_>> {
1793        let Layout::Planar { y, u, v, a } = self.layout else {
1794            return None;
1795        };
1796        let width = usize::try_from(self.width).ok()?;
1797        let height = i32::try_from(self.height).ok()?;
1798        let (uv_width, uv_height) = (width.div_ceil(2), (height + 1) / 2);
1799        let rows = |plane: PlaneLayout, row_len, count| {
1800            Rows::new(&self.samples, plane.offset, plane.stride, row_len, count)
1801        };
1802        Some(YuvaRows {
1803            y: rows(y, width, height),
1804            u: rows(u, uv_width, uv_height),
1805            v: rows(v, uv_width, uv_height),
1806            a: a.map(|a| rows(a, width, height)),
1807        })
1808    }
1809
1810    /// All the memory of the image: the rows of an RGB mode, or the Y, U, V
1811    /// and alpha planes one after the other, as libwebp lays them out.
1812    ///
1813    /// # Examples
1814    ///
1815    /// ```
1816    /// use webp::api::decode::{decode, ColorMode, Config};
1817    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
1818    /// # let rgba = [0_u8; 4 * 3 * 3];
1819    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 3, height: 3, stride: 12 })?;
1820    ///
1821    /// // 3 by 3 luma, 2 by 2 U and V, 3 by 3 alpha.
1822    /// assert_eq!(decode(&file, &Config::new(ColorMode::Yuva))?.samples().len(), 9 + 4 + 4 + 9);
1823    /// # Ok::<(), Box<dyn std::error::Error>>(())
1824    /// ```
1825    #[must_use]
1826    pub fn samples(&self) -> &[u8] {
1827        &self.samples
1828    }
1829
1830    /// The memory of the image, without a copy; see [`Image::samples`].
1831    ///
1832    /// # Examples
1833    ///
1834    /// ```
1835    /// use webp::api::decode::{decode, ColorMode, Config};
1836    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
1837    /// # let rgba = [3_u8; 4 * 2];
1838    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 2, height: 1, stride: 8 })?;
1839    ///
1840    /// assert_eq!(decode(&file, &Config::new(ColorMode::Rgba))?.into_samples(), vec![3_u8; 8]);
1841    /// # Ok::<(), Box<dyn std::error::Error>>(())
1842    /// ```
1843    #[must_use]
1844    pub fn into_samples(self) -> Vec<u8> {
1845        self.samples
1846    }
1847}
1848
1849//------------------------------------------------------------------------------
1850// Decoding
1851
1852/// The steps before `WebPDecode` that the API adds: the configuration, the
1853/// features (with `WebPDecode`'s status on failure), the refusal of an
1854/// animation that libwebp would report, and the output size.
1855fn prepare(data: &[u8], config: &Config) -> Result<(u32, u32), DecodeError> {
1856    config.validate()?;
1857    let features = match Features::parse(data) {
1858        Ok(features) => features,
1859        // WebPDecode treats not enough data as a bitstream error.
1860        Err(DecodeError::NotEnoughData) => return Err(DecodeError::BitstreamError),
1861        Err(error) => return Err(error),
1862    };
1863    if features.has_animation {
1864        return Err(DecodeError::UnsupportedFeature);
1865    }
1866    config.output_size(&features)
1867}
1868
1869/// Decodes a still WebP image into memory that libwebp allocates (C:
1870/// `WebPDecode` with an output buffer without memory). `WebPDecodeRGBA` and
1871/// the other simple functions of libwebp are this function with
1872/// `Config::new(mode)`.
1873///
1874/// # Errors
1875///
1876/// The errors of [`Config::validate`] and [`Config::output_size`] first; then
1877/// libwebp's status: [`DecodeError::BitstreamError`] for an invalid file or
1878/// one that ends before the image's dimensions, [`DecodeError::NotEnoughData`]
1879/// or [`DecodeError::BitstreamError`] for one that ends later,
1880/// [`DecodeError::UnsupportedFeature`] for an animation (use
1881/// [`AnimationDecoder`]), [`DecodeError::OutOfMemory`].
1882///
1883/// # Examples
1884///
1885/// ```
1886/// use webp::api::decode::{decode, ColorMode, Config, DecodeError};
1887/// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
1888/// # let rgba = [10_u8, 20, 30, 255].repeat(16);
1889/// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 4, height: 4, stride: 16 })?;
1890///
1891/// let image = decode(&file, &Config::new(ColorMode::Rgb))?;
1892/// assert_eq!(image.rows().unwrap().row(3), Some(&[10_u8, 20, 30].repeat(4)[..]));
1893/// // A prefix without the image's dimensions.
1894/// assert_eq!(decode(&file[..10], &Config::new(ColorMode::Rgb)), Err(DecodeError::BitstreamError));
1895/// # Ok::<(), Box<dyn std::error::Error>>(())
1896/// ```
1897pub fn decode(data: &[u8], config: &Config) -> Result<Image, DecodeError> {
1898    prepare(data, config)?;
1899    let mut raw = config.raw_config();
1900    status(webp_decode(data, &mut raw))?;
1901    Image::from_buffer(config.mode, raw.output)
1902}
1903
1904/// Decodes a still WebP image into the caller's memory (C: `WebPDecode` with
1905/// `is_external_memory` 1), which is checked against the output size first.
1906/// Returns the output's width and height. On failure, the rows that were
1907/// decoded stay in the caller's memory.
1908///
1909/// # Errors
1910///
1911/// The errors of [`decode`], and [`DecodeError::OutputMismatch`],
1912/// [`DecodeError::InvalidStride`] or [`DecodeError::BufferTooShort`] for
1913/// memory that does not fit the output.
1914///
1915/// # Examples
1916///
1917/// ```
1918/// use webp::api::decode::{decode_into, ColorMode, Config, Features, Output};
1919/// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
1920/// # let rgba = [1_u8, 2, 3, 4].repeat(64);
1921/// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 16, height: 4, stride: 64 })?;
1922///
1923/// // Budget exactly the rows of the cropped output.
1924/// let config = Config::new(ColorMode::Rgba).crop(4, 2, 8, 2);
1925/// let (width, height) = config.output_size(&Features::parse(&file)?)?;
1926/// let stride = width as usize * 4;
1927/// let mut rows = vec![0_u8; stride * height as usize];
1928/// decode_into(&file, &config, Output::Rows { data: &mut rows, stride })?;
1929/// assert_eq!(rows, [1_u8, 2, 3, 4].repeat(16));
1930/// # Ok::<(), Box<dyn std::error::Error>>(())
1931/// ```
1932pub fn decode_into(
1933    data: &[u8],
1934    config: &Config,
1935    output: Output<'_>,
1936) -> Result<(u32, u32), DecodeError> {
1937    let (width, height) = prepare(data, config)?;
1938    check_output(config.mode, width, height, &output)?;
1939    let mut raw = config.raw_config();
1940    attach(&mut raw.output, output);
1941    status(webp_decode(data, &mut raw))?;
1942    Ok((width, height))
1943}
1944
1945//------------------------------------------------------------------------------
1946// Incremental decoding
1947
1948/// How far an incremental decoding has come.
1949///
1950/// # Examples
1951///
1952/// ```
1953/// use webp::api::decode::{ColorMode, Config, IncrementalDecoder, Status};
1954/// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
1955/// # let rgba = [0_u8; 4 * 8 * 8];
1956/// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 8, height: 8, stride: 32 })?;
1957///
1958/// let config = Config::new(ColorMode::Rgba);
1959/// let mut decoder = IncrementalDecoder::new(&config)?;
1960/// assert_eq!(decoder.append(&file[..20])?, Status::NeedsMoreData);
1961/// assert_eq!(decoder.append(&file[20..])?, Status::Complete);
1962/// # Ok::<(), Box<dyn std::error::Error>>(())
1963/// ```
1964#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1965pub enum Status {
1966    /// The image is incomplete: pass more data (C: `VP8_STATUS_SUSPENDED`).
1967    NeedsMoreData,
1968    /// The image is decoded (C: `VP8_STATUS_OK`).
1969    Complete,
1970}
1971
1972/// A decoder that takes a still WebP file in pieces and lends the rows
1973/// decoded so far (C: `WebPIDecoder`).
1974///
1975/// It borrows the [`Config`] and, with [`IncrementalDecoder::with_output`],
1976/// the caller's memory, for its lifetime. [`IncrementalDecoder::append`]
1977/// copies each piece; [`IncrementalDecoder::update`] takes the whole data so
1978/// far each time, for a caller who keeps it. The two cannot be mixed.
1979/// The decoder is neither `Send` nor `Sync`.
1980///
1981/// # Examples
1982///
1983/// ```
1984/// use webp::api::decode::{ColorMode, Config, IncrementalDecoder, Status};
1985/// # use webp::api::encode::{encode_lossy, PixelLayout, PixelRows};
1986/// # let rgb: Vec<u8> = (0..64 * 48 * 3).map(|i| (i % 251) as u8).collect();
1987/// # let file = encode_lossy(PixelRows { layout: PixelLayout::Rgb, data: &rgb, width: 64, height: 48, stride: 192 }, 80.0)?;
1988///
1989/// let config = Config::new(ColorMode::Rgb);
1990/// let mut decoder = IncrementalDecoder::new(&config)?;
1991/// let mut status = Status::NeedsMoreData;
1992/// for piece in file.chunks(100) {
1993///     status = decoder.append(piece)?;
1994///     // The rows decoded so far, lent until the next call.
1995///     if let Some(rows) = decoder.rows() {
1996///         assert_eq!(rows.len(), decoder.decoded_rows());
1997///     }
1998/// }
1999/// assert_eq!(status, Status::Complete);
2000/// let image = decoder.into_image()?;
2001/// assert_eq!((image.width(), image.height()), (64, 48));
2002/// # Ok::<(), Box<dyn std::error::Error>>(())
2003/// ```
2004pub struct IncrementalDecoder<'a> {
2005    idec: WebPIDecoder<'a, 'a>,
2006    mode: ColorMode,
2007    library_memory: bool,
2008    complete: bool,
2009    /// Whether an `update`, or an `append` that did not fail with
2010    /// `OutOfMemory`, reached the translation, so that an empty `append` may
2011    /// reach it too.
2012    started: bool,
2013}
2014
2015impl fmt::Debug for IncrementalDecoder<'_> {
2016    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2017        f.debug_struct("IncrementalDecoder")
2018            .field("mode", &self.mode)
2019            .field("library_memory", &self.library_memory)
2020            .field("complete", &self.complete)
2021            .field("decoded_rows", &self.decoded_rows())
2022            .finish()
2023    }
2024}
2025
2026impl<'a> IncrementalDecoder<'a> {
2027    /// An incremental decoding into memory that libwebp allocates when the
2028    /// header arrives (C: `WebPINewDecoder` with a buffer in the colorspace
2029    /// of `config`, and `config`'s options, as `WebPIDecode` sets them).
2030    ///
2031    /// # Errors
2032    ///
2033    /// The errors of [`Config::validate`].
2034    ///
2035    /// # Examples
2036    ///
2037    /// ```
2038    /// use webp::api::decode::{ColorMode, Config, IncrementalDecoder};
2039    ///
2040    /// let config = Config::new(ColorMode::Yuva).flip(true);
2041    /// let decoder = IncrementalDecoder::new(&config)?;
2042    /// assert_eq!(decoder.decoded_rows(), 0);
2043    /// # Ok::<(), webp::api::decode::DecodeError>(())
2044    /// ```
2045    pub fn new(config: &'a Config) -> Result<Self, DecodeError> {
2046        config.validate()?;
2047        let mut idec = webp_i_new_decoder(None).ok_or(DecodeError::OutOfMemory)?;
2048        idec.own_output_mut().colorspace = config.mode.raw();
2049        idec.set_options(&config.options);
2050        Ok(Self {
2051            idec,
2052            mode: config.mode,
2053            library_memory: true,
2054            complete: false,
2055            started: false,
2056        })
2057    }
2058
2059    /// An incremental decoding into the caller's memory (C: `WebPINewRGB` or
2060    /// `WebPINewYUVA`, and `config`'s options). The image's size is not known
2061    /// yet, so the API checks only the shape of `output` (rows for the RGB
2062    /// modes, planes for the YUV modes, an alpha plane exactly for
2063    /// [`ColorMode::Yuva`]), strides of 1 to `i32::MAX` bytes and non-empty
2064    /// slices; libwebp checks the rest when the header arrives and returns
2065    /// [`DecodeError::InvalidParam`] for memory that does not fit. Check
2066    /// before with [`Config::output_size`] and the rules of [`Output`].
2067    ///
2068    /// # Errors
2069    ///
2070    /// The errors of [`Config::validate`], [`DecodeError::OutputMismatch`],
2071    /// [`DecodeError::InvalidStride`] and [`DecodeError::BufferTooShort`].
2072    ///
2073    /// # Examples
2074    ///
2075    /// ```
2076    /// use webp::api::decode::{ColorMode, Config, IncrementalDecoder, Output, Status};
2077    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2078    /// # let rgba = [50_u8, 60, 70, 255].repeat(6);
2079    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 3, height: 2, stride: 12 })?;
2080    ///
2081    /// let config = Config::new(ColorMode::Rgb);
2082    /// let mut rows = vec![0_u8; 2 * 9];
2083    /// {
2084    ///     let output = Output::Rows { data: &mut rows, stride: 9 };
2085    ///     let mut decoder = IncrementalDecoder::with_output(&config, output)?;
2086    ///     assert_eq!(decoder.update(&file)?, Status::Complete);
2087    /// }
2088    /// assert_eq!(rows, [50_u8, 60, 70].repeat(6));
2089    /// # Ok::<(), Box<dyn std::error::Error>>(())
2090    /// ```
2091    pub fn with_output(config: &'a Config, output: Output<'a>) -> Result<Self, DecodeError> {
2092        config.validate()?;
2093        check_output_shape(config.mode, &output)?;
2094        let idec = match output {
2095            Output::Rows { data, stride } => {
2096                webp_i_new_rgb(config.mode.raw(), Some(data), stride_int(stride))
2097            }
2098            Output::Planes(planes) => {
2099                let a_stride = planes.a.as_ref().map_or(0, |_| stride_int(planes.a_stride));
2100                webp_i_new_yuva(
2101                    Some(planes.y),
2102                    stride_int(planes.y_stride),
2103                    Some(planes.u),
2104                    stride_int(planes.uv_stride),
2105                    Some(planes.v),
2106                    stride_int(planes.uv_stride),
2107                    planes.a,
2108                    a_stride,
2109                )
2110            }
2111        };
2112        let mut idec = idec.ok_or(DecodeError::InvalidParam)?;
2113        idec.set_options(&config.options);
2114        Ok(Self {
2115            idec,
2116            mode: config.mode,
2117            library_memory: false,
2118            complete: false,
2119            started: false,
2120        })
2121    }
2122
2123    /// The step's result as the API reports it.
2124    fn step(&mut self, result: Result<(), VP8StatusCode>) -> Result<Status, DecodeError> {
2125        match result {
2126            Ok(()) => {
2127                self.complete = true;
2128                Ok(Status::Complete)
2129            }
2130            Err(VP8StatusCode::VP8_STATUS_SUSPENDED) => Ok(Status::NeedsMoreData),
2131            Err(code) => Err(DecodeError::from_status(code)),
2132        }
2133    }
2134
2135    /// Copies the next piece of the file and decodes as far as it reaches
2136    /// (C: `WebPIAppend`). An empty piece before any data is
2137    /// [`Status::NeedsMoreData`]: libwebp asserts against that call, so the
2138    /// API answers it without calling the decoder.
2139    ///
2140    /// # Errors
2141    ///
2142    /// [`DecodeError::BitstreamError`] for an invalid file (and for every
2143    /// call after a failure), [`DecodeError::UnsupportedFeature`] for an
2144    /// animation, [`DecodeError::InvalidParam`] for caller memory or a crop
2145    /// that does not fit the image, or after [`IncrementalDecoder::update`],
2146    /// and [`DecodeError::OutOfMemory`].
2147    ///
2148    /// # Examples
2149    ///
2150    /// ```
2151    /// use webp::api::decode::{ColorMode, Config, DecodeError, IncrementalDecoder, Status};
2152    ///
2153    /// let config = Config::new(ColorMode::Rgb);
2154    /// let mut decoder = IncrementalDecoder::new(&config)?;
2155    /// assert_eq!(decoder.append(b"RIFF"), Ok(Status::NeedsMoreData));
2156    /// assert_eq!(decoder.append(b"\0\0\0\0JPEG"), Err(DecodeError::BitstreamError));
2157    /// # Ok::<(), DecodeError>(())
2158    /// ```
2159    pub fn append(&mut self, data: &[u8]) -> Result<Status, DecodeError> {
2160        if data.is_empty() && !self.started {
2161            // libwebp asserts that data was stored before (`WebPIAppend` of
2162            // zero bytes first); without the assertion it reports SUSPENDED.
2163            return Ok(Status::NeedsMoreData);
2164        }
2165        let result = webp_i_append(&mut self.idec, data);
2166        // An out-of-memory failure can leave the buffer empty: a piece above
2167        // `MAX_CHUNK_PAYLOAD` or a failed reservation stores nothing.
2168        if result != Err(VP8StatusCode::VP8_STATUS_OUT_OF_MEMORY) {
2169            self.started = true;
2170        }
2171        self.step(result)
2172    }
2173
2174    /// Decodes as far as `data`, the whole file so far, reaches, without
2175    /// copying it (C: `WebPIUpdate`). Each call passes the previous data and
2176    /// more; the data may move between calls.
2177    ///
2178    /// # Errors
2179    ///
2180    /// The errors of [`IncrementalDecoder::append`];
2181    /// [`DecodeError::InvalidParam`] also for data shorter than before, or
2182    /// after `append`.
2183    ///
2184    /// # Examples
2185    ///
2186    /// ```
2187    /// use webp::api::decode::{ColorMode, Config, IncrementalDecoder, Status};
2188    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2189    /// # let rgba = [0_u8; 4 * 16];
2190    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 4, height: 4, stride: 16 })?;
2191    ///
2192    /// let config = Config::new(ColorMode::Rgba);
2193    /// let mut decoder = IncrementalDecoder::new(&config)?;
2194    /// let mut received = Vec::new();
2195    /// for piece in file.chunks(7) {
2196    ///     received.extend_from_slice(piece);
2197    ///     let status = decoder.update(&received)?;
2198    ///     assert_eq!(status == Status::Complete, received.len() == file.len());
2199    /// }
2200    /// # Ok::<(), Box<dyn std::error::Error>>(())
2201    /// ```
2202    pub fn update(&mut self, data: &[u8]) -> Result<Status, DecodeError> {
2203        self.started = true;
2204        let result = webp_i_update(&mut self.idec, data);
2205        self.step(result)
2206    }
2207
2208    /// The width and height of the output, once libwebp has set the output up
2209    /// after the header (C: the width and height of the output buffer that
2210    /// `WebPIDecodedArea` returns, not its height out-parameter `last_y`,
2211    /// which [`decoded_rows`](Self::decoded_rows) reports);
2212    /// `None` before, including the moment after a lossless header when the
2213    /// decoded area exists with a width of 0.
2214    ///
2215    /// # Examples
2216    ///
2217    /// ```
2218    /// use webp::api::decode::{ColorMode, Config, IncrementalDecoder};
2219    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2220    /// # let rgba = [0_u8; 4 * 6 * 6];
2221    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 6, height: 6, stride: 24 })?;
2222    ///
2223    /// let config = Config::new(ColorMode::Rgb).scale(3, 2);
2224    /// let mut decoder = IncrementalDecoder::new(&config)?;
2225    /// assert_eq!(decoder.output_size(), None);
2226    /// decoder.append(&file)?;
2227    /// assert_eq!(decoder.output_size(), Some((3, 2)));
2228    /// # Ok::<(), Box<dyn std::error::Error>>(())
2229    /// ```
2230    #[must_use]
2231    pub fn output_size(&self) -> Option<(u32, u32)> {
2232        let buffer = webp_i_decoded_area(&self.idec, None, None, None, None)?;
2233        let width = u32::try_from(buffer.width)
2234            .ok()
2235            .filter(|&width| width > 0)?;
2236        let height = u32::try_from(buffer.height)
2237            .ok()
2238            .filter(|&height| height > 0)?;
2239        Some((width, height))
2240    }
2241
2242    /// The number of output rows decoded so far, from the top of the
2243    /// unflipped output (C: `last_y`).
2244    ///
2245    /// # Examples
2246    ///
2247    /// ```
2248    /// use webp::api::decode::{ColorMode, Config, IncrementalDecoder};
2249    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2250    /// # let rgba = [0_u8; 4 * 2 * 3];
2251    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 2, height: 3, stride: 8 })?;
2252    ///
2253    /// let config = Config::new(ColorMode::Rgba);
2254    /// let mut decoder = IncrementalDecoder::new(&config)?;
2255    /// decoder.append(&file)?;
2256    /// assert_eq!(decoder.decoded_rows(), 3);
2257    /// # Ok::<(), Box<dyn std::error::Error>>(())
2258    /// ```
2259    #[must_use]
2260    pub fn decoded_rows(&self) -> u32 {
2261        let mut rows = 0;
2262        let _ = webp_i_decoded_area(&self.idec, None, None, None, Some(&mut rows));
2263        u32::try_from(rows).unwrap_or(0)
2264    }
2265
2266    /// The rows of an RGB mode decoded so far, lent until the next call that
2267    /// takes `&mut self` (C: `WebPIDecGetRGB`); `None` for a YUV mode or before
2268    /// the output exists. Row 0 is the first decoded row: while a flipped
2269    /// decoding runs, that is the bottom row of the output and the stride is
2270    /// negative; once complete, the stride is positive and row 0 is the top.
2271    ///
2272    /// # Examples
2273    ///
2274    /// ```
2275    /// use webp::api::decode::{ColorMode, Config, IncrementalDecoder};
2276    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2277    /// # let rgba = [4_u8, 3, 2, 1].repeat(4);
2278    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 2, height: 2, stride: 8 })?;
2279    ///
2280    /// let config = Config::new(ColorMode::Rgba);
2281    /// let mut decoder = IncrementalDecoder::new(&config)?;
2282    /// assert!(decoder.rows().is_none());
2283    /// decoder.append(&file)?;
2284    /// assert_eq!(decoder.rows().unwrap().row(1), Some(&[4_u8, 3, 2, 1, 4, 3, 2, 1][..]));
2285    /// # Ok::<(), Box<dyn std::error::Error>>(())
2286    /// ```
2287    #[must_use]
2288    pub fn rows(&self) -> Option<Rows<'_>> {
2289        let (mut last_y, mut width, mut stride) = (0, 0, 0);
2290        let (region, first) = webp_i_dec_get_rgb(
2291            &self.idec,
2292            Some(&mut last_y),
2293            Some(&mut width),
2294            None,
2295            Some(&mut stride),
2296        )?;
2297        let row_len = usize::try_from(width)
2298            .ok()?
2299            .checked_mul(self.mode.bytes_per_pixel()?)?;
2300        Some(Rows::new(region, first, stride, row_len, last_y))
2301    }
2302
2303    /// The planes of a YUV mode decoded so far, lent like
2304    /// [`IncrementalDecoder::rows`] (C: `WebPIDecGetYUVA`); `None` for an RGB
2305    /// mode or before the output exists. Luma and alpha have
2306    /// [`IncrementalDecoder::decoded_rows`] rows, U and V half as many,
2307    /// rounded up; with a scale, libwebp writes chroma and alpha rows later
2308    /// than luma rows, so those are final only once the decoding completes.
2309    ///
2310    /// # Examples
2311    ///
2312    /// ```
2313    /// use webp::api::decode::{ColorMode, Config, IncrementalDecoder};
2314    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2315    /// # let rgba = [0_u8, 0, 0, 255].repeat(9);
2316    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 3, height: 3, stride: 12 })?;
2317    ///
2318    /// let config = Config::new(ColorMode::Yuv);
2319    /// let mut decoder = IncrementalDecoder::new(&config)?;
2320    /// decoder.append(&file)?;
2321    /// let planes = decoder.planes().unwrap();
2322    /// assert_eq!((planes.y.len(), planes.u.len()), (3, 2));
2323    /// assert_eq!(planes.y.row(0), Some(&[16_u8, 16, 16][..])); // black, limited range
2324    /// # Ok::<(), Box<dyn std::error::Error>>(())
2325    /// ```
2326    #[must_use]
2327    pub fn planes(&self) -> Option<YuvaRows<'_>> {
2328        let (mut last_y, mut width, mut stride, mut uv_stride, mut a_stride) = (0, 0, 0, 0, 0);
2329        let (mut u, mut v, mut a) = (None, None, None);
2330        let (y_region, y_first) = webp_i_dec_get_yuva(
2331            &self.idec,
2332            Some(&mut last_y),
2333            Some(&mut u),
2334            Some(&mut v),
2335            Some(&mut a),
2336            Some(&mut width),
2337            None,
2338            Some(&mut stride),
2339            Some(&mut uv_stride),
2340            Some(&mut a_stride),
2341        )?;
2342        let width = usize::try_from(width).ok()?;
2343        let (uv_width, uv_rows) = (width.div_ceil(2), (last_y + 1) / 2);
2344        let ((u_region, u_first), (v_region, v_first)) = (u?, v?);
2345        Some(YuvaRows {
2346            y: Rows::new(y_region, y_first, stride, width, last_y),
2347            u: Rows::new(u_region, u_first, uv_stride, uv_width, uv_rows),
2348            v: Rows::new(v_region, v_first, uv_stride, uv_width, uv_rows),
2349            a: a.map(|(region, first)| Rows::new(region, first, a_stride, width, last_y)),
2350        })
2351    }
2352
2353    /// The decoded image, in the memory that libwebp allocated for a decoder
2354    /// of [`IncrementalDecoder::new`], once the decoding has completed.
2355    ///
2356    /// # Errors
2357    ///
2358    /// [`DecodeError::Suspended`] before the decoding has completed, and
2359    /// [`DecodeError::OutputMismatch`] for a decoder of
2360    /// [`IncrementalDecoder::with_output`], whose samples are in the caller's
2361    /// memory.
2362    ///
2363    /// # Examples
2364    ///
2365    /// ```
2366    /// use webp::api::decode::{ColorMode, Config, DecodeError, IncrementalDecoder};
2367    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2368    /// # let rgba = [0_u8; 4 * 4];
2369    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 2, height: 2, stride: 8 })?;
2370    ///
2371    /// let config = Config::new(ColorMode::Rgba);
2372    /// let mut decoder = IncrementalDecoder::new(&config)?;
2373    /// decoder.append(&file[..file.len() / 2])?;
2374    /// assert_eq!(decoder.into_image().unwrap_err(), DecodeError::Suspended);
2375    /// # Ok::<(), Box<dyn std::error::Error>>(())
2376    /// ```
2377    pub fn into_image(mut self) -> Result<Image, DecodeError> {
2378        if !self.library_memory {
2379            return Err(DecodeError::OutputMismatch { mode: self.mode });
2380        }
2381        if !self.complete {
2382            return Err(DecodeError::Suspended);
2383        }
2384        let buffer = std::mem::take(self.idec.own_output_mut());
2385        Image::from_buffer(self.mode, buffer)
2386    }
2387}
2388
2389//------------------------------------------------------------------------------
2390// Container
2391
2392/// The payload of a chunk iterator: the demuxer always borrows it from the
2393/// input, which is what the API lends, so `None` is a backstop the API does
2394/// not reach.
2395fn payload<'s>(bytes: &Cow<'s, [u8]>) -> Option<&'s [u8]> {
2396    match bytes {
2397        Cow::Borrowed(bytes) => Some(bytes),
2398        Cow::Owned(_) => None,
2399    }
2400}
2401
2402/// The error of a demuxer that did not parse `data`: the error of
2403/// [`Features::parse`] when it fails (libwebp's demuxer reports a file that
2404/// is not WebP as a header in progress), then [`DecodeError::NotEnoughData`]
2405/// when a partial parse succeeds or asks for more data, and
2406/// [`DecodeError::BitstreamError`] otherwise.
2407fn demux_error(data: &[u8]) -> DecodeError {
2408    if let Err(error) = Features::parse(data) {
2409        return error;
2410    }
2411    match demux_bytes(data, true, WEBP_DEMUX_ABI_VERSION) {
2412        (Some(_), _) | (None, WebPDemuxState::WEBP_DEMUX_PARSING_HEADER) => {
2413            DecodeError::NotEnoughData
2414        }
2415        (None, _) => DecodeError::BitstreamError,
2416    }
2417}
2418
2419/// The container of a WebP file: its metadata chunks and the canvas and
2420/// animation parameters, through libwebp's demuxer (C: `WebPDemuxer`).
2421///
2422/// It borrows the file's bytes; the chunk payloads borrow the container.
2423///
2424/// # Examples
2425///
2426/// ```
2427/// use webp::api::decode::Container;
2428/// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2429/// # fn chunk(tag: &[u8], payload: &[u8]) -> Vec<u8> {
2430/// #     let mut bytes = tag.to_vec();
2431/// #     bytes.extend_from_slice(&(payload.len() as u32).to_le_bytes());
2432/// #     bytes.extend_from_slice(payload);
2433/// #     if payload.len() % 2 == 1 { bytes.push(0); }
2434/// #     bytes
2435/// # }
2436/// # let rgba = [0_u8, 0, 0, 255].repeat(4);
2437/// # let image = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 2, height: 2, stride: 8 })?;
2438/// # let vp8x = chunk(b"VP8X", &[0x20 | 0x08, 0, 0, 0, 1, 0, 0, 1, 0, 0]);
2439/// # let body = [vp8x, chunk(b"ICCP", b"profile"), image[12..].to_vec(), chunk(b"EXIF", b"Exif\0\0MM")].concat();
2440/// # let mut file = b"RIFF".to_vec();
2441/// # file.extend_from_slice(&(body.len() as u32 + 4).to_le_bytes());
2442/// # file.extend_from_slice(b"WEBP");
2443/// # file.extend_from_slice(&body);
2444///
2445/// // `file` is an extended 2 by 2 WebP file with an ICC profile and EXIF data.
2446/// let container = Container::new(&file)?;
2447/// assert_eq!((container.canvas_width(), container.canvas_height()), (2, 2));
2448/// assert_eq!(container.icc_profile(), Some(&b"profile"[..]));
2449/// assert_eq!(container.exif(), Some(&b"Exif\0\0MM"[..]));
2450/// assert_eq!(container.xmp(), None);
2451/// # Ok::<(), Box<dyn std::error::Error>>(())
2452/// ```
2453pub struct Container<'d> {
2454    demux: WebPDemuxer<'d>,
2455    state: WebPDemuxState,
2456}
2457
2458impl fmt::Debug for Container<'_> {
2459    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2460        f.debug_struct("Container")
2461            .field("complete", &self.is_complete())
2462            .field("canvas_width", &self.canvas_width())
2463            .field("canvas_height", &self.canvas_height())
2464            .field("frame_count", &self.frame_count())
2465            .finish_non_exhaustive()
2466    }
2467}
2468
2469impl<'d> Container<'d> {
2470    /// Parses a complete WebP file (C: `WebPDemux`).
2471    ///
2472    /// # Errors
2473    ///
2474    /// The error of [`Features::parse`] for data that is not a WebP file or
2475    /// ends inside its header; then [`DecodeError::NotEnoughData`] for a file
2476    /// that ends early and [`DecodeError::BitstreamError`] for one that does
2477    /// not parse.
2478    ///
2479    /// # Examples
2480    ///
2481    /// ```
2482    /// use webp::api::decode::{Container, DecodeError};
2483    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2484    /// # let rgba = [0_u8; 4 * 9];
2485    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 3, height: 3, stride: 12 })?;
2486    ///
2487    /// assert!(Container::new(&file)?.is_complete());
2488    /// assert_eq!(Container::new(&file[..file.len() - 2]).unwrap_err(), DecodeError::NotEnoughData);
2489    /// assert_eq!(Container::new(b"not a WebP file").unwrap_err(), DecodeError::BitstreamError);
2490    /// # Ok::<(), Box<dyn std::error::Error>>(())
2491    /// ```
2492    pub fn new(data: &'d [u8]) -> Result<Self, DecodeError> {
2493        match demux_bytes(data, false, WEBP_DEMUX_ABI_VERSION) {
2494            (Some(demux), state) => Ok(Self { demux, state }),
2495            (None, _) => Err(demux_error(data)),
2496        }
2497    }
2498
2499    /// Parses the start of a WebP file (C: `WebPDemuxPartial`); the chunks
2500    /// and frames that the data reaches are available, which is enough for an
2501    /// `ICCP` chunk, which precedes the image data.
2502    ///
2503    /// # Errors
2504    ///
2505    /// [`DecodeError::NotEnoughData`] when the data ends inside the file
2506    /// header, [`DecodeError::BitstreamError`] when it does not parse; as for
2507    /// [`Container::new`], the error of [`Features::parse`] comes first.
2508    ///
2509    /// # Examples
2510    ///
2511    /// ```
2512    /// use webp::api::decode::Container;
2513    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2514    /// # let rgba = [0_u8; 4 * 9];
2515    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 3, height: 3, stride: 12 })?;
2516    ///
2517    /// let container = Container::partial(&file[..file.len() - 2])?;
2518    /// assert!(!container.is_complete());
2519    /// # Ok::<(), Box<dyn std::error::Error>>(())
2520    /// ```
2521    pub fn partial(data: &'d [u8]) -> Result<Self, DecodeError> {
2522        match demux_bytes(data, true, WEBP_DEMUX_ABI_VERSION) {
2523            (Some(demux), state) => Ok(Self { demux, state }),
2524            (None, _) => Err(demux_error(data)),
2525        }
2526    }
2527
2528    /// Whether the whole file was parsed (C: `WEBP_DEMUX_DONE`).
2529    ///
2530    /// # Examples
2531    ///
2532    /// ```
2533    /// use webp::api::decode::Container;
2534    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2535    /// # let rgba = [0_u8; 4];
2536    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 1, height: 1, stride: 4 })?;
2537    ///
2538    /// assert!(Container::partial(&file)?.is_complete());
2539    /// # Ok::<(), Box<dyn std::error::Error>>(())
2540    /// ```
2541    #[must_use]
2542    pub fn is_complete(&self) -> bool {
2543        self.state == WebPDemuxState::WEBP_DEMUX_DONE
2544    }
2545
2546    /// One of the demuxer's values (C: `WebPDemuxGetI`).
2547    fn get(&self, feature: WebPFormatFeature) -> u32 {
2548        webp_demux_get_i(&self.demux, feature)
2549    }
2550
2551    /// The canvas width in pixels: the image's for a simple file.
2552    ///
2553    /// # Examples
2554    ///
2555    /// ```
2556    /// use webp::api::decode::Container;
2557    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2558    /// # let rgba = [0_u8; 4 * 6];
2559    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 3, height: 2, stride: 12 })?;
2560    ///
2561    /// assert_eq!(Container::new(&file)?.canvas_width(), 3);
2562    /// # Ok::<(), Box<dyn std::error::Error>>(())
2563    /// ```
2564    #[must_use]
2565    pub fn canvas_width(&self) -> u32 {
2566        self.get(WebPFormatFeature::WEBP_FF_CANVAS_WIDTH)
2567    }
2568
2569    /// The canvas height in pixels: the image's for a simple file.
2570    ///
2571    /// # Examples
2572    ///
2573    /// ```
2574    /// use webp::api::decode::Container;
2575    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2576    /// # let rgba = [0_u8; 4 * 6];
2577    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 3, height: 2, stride: 12 })?;
2578    ///
2579    /// assert_eq!(Container::new(&file)?.canvas_height(), 2);
2580    /// # Ok::<(), Box<dyn std::error::Error>>(())
2581    /// ```
2582    #[must_use]
2583    pub fn canvas_height(&self) -> u32 {
2584        self.get(WebPFormatFeature::WEBP_FF_CANVAS_HEIGHT)
2585    }
2586
2587    /// Whether the file declares alpha (C: `ALPHA_FLAG` of
2588    /// `WEBP_FF_FORMAT_FLAGS`, which the demuxer also sets for a simple
2589    /// file whose image has alpha).
2590    ///
2591    /// # Examples
2592    ///
2593    /// ```
2594    /// use webp::api::decode::Container;
2595    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2596    /// # let rgba = [0_u8, 0, 0, 100];
2597    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 1, height: 1, stride: 4 })?;
2598    ///
2599    /// assert!(Container::new(&file)?.has_alpha());
2600    /// # Ok::<(), Box<dyn std::error::Error>>(())
2601    /// ```
2602    #[must_use]
2603    pub fn has_alpha(&self) -> bool {
2604        self.get(WebPFormatFeature::WEBP_FF_FORMAT_FLAGS) & WebPFeatureFlags::ALPHA_FLAG.0 != 0
2605    }
2606
2607    /// Whether the file is an animation (C: `ANIMATION_FLAG` of
2608    /// `WEBP_FF_FORMAT_FLAGS`).
2609    ///
2610    /// # Examples
2611    ///
2612    /// ```
2613    /// use webp::api::decode::Container;
2614    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2615    /// # let rgba = [0_u8; 4];
2616    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 1, height: 1, stride: 4 })?;
2617    ///
2618    /// assert!(!Container::new(&file)?.has_animation());
2619    /// # Ok::<(), Box<dyn std::error::Error>>(())
2620    /// ```
2621    #[must_use]
2622    pub fn has_animation(&self) -> bool {
2623        self.get(WebPFormatFeature::WEBP_FF_FORMAT_FLAGS) & WebPFeatureFlags::ANIMATION_FLAG.0 != 0
2624    }
2625
2626    /// The number of times an animation loops, 0 for forever (C:
2627    /// `WEBP_FF_LOOP_COUNT`); a still image reports 1, the demuxer's default.
2628    ///
2629    /// # Examples
2630    ///
2631    /// ```
2632    /// use webp::api::decode::Container;
2633    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2634    /// # let rgba = [0_u8; 4];
2635    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 1, height: 1, stride: 4 })?;
2636    ///
2637    /// assert_eq!(Container::new(&file)?.loop_count(), 1);
2638    /// # Ok::<(), Box<dyn std::error::Error>>(())
2639    /// ```
2640    #[must_use]
2641    pub fn loop_count(&self) -> u32 {
2642        self.get(WebPFormatFeature::WEBP_FF_LOOP_COUNT)
2643    }
2644
2645    /// The background color of an animation as `0xAARRGGBB`: the `ANIM`
2646    /// chunk's bytes (blue, green, red, alpha) read as a little-endian `u32`
2647    /// (C: `WEBP_FF_BACKGROUND_COLOR`). It is reported, not applied: the
2648    /// canvas of [`AnimationDecoder`] starts transparent black. A still image
2649    /// reports `0xFFFFFFFF`.
2650    ///
2651    /// # Examples
2652    ///
2653    /// ```
2654    /// use webp::api::decode::Container;
2655    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2656    /// # let rgba = [0_u8; 4];
2657    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 1, height: 1, stride: 4 })?;
2658    ///
2659    /// assert_eq!(Container::new(&file)?.background_color(), 0xFFFF_FFFF);
2660    /// # Ok::<(), Box<dyn std::error::Error>>(())
2661    /// ```
2662    #[must_use]
2663    pub fn background_color(&self) -> u32 {
2664        self.get(WebPFormatFeature::WEBP_FF_BACKGROUND_COLOR)
2665    }
2666
2667    /// The number of frames: 1 for a still image (C: `WEBP_FF_FRAME_COUNT`);
2668    /// the frames parsed so far for a partial container.
2669    ///
2670    /// # Examples
2671    ///
2672    /// ```
2673    /// use webp::api::decode::Container;
2674    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2675    /// # let rgba = [0_u8; 4];
2676    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 1, height: 1, stride: 4 })?;
2677    ///
2678    /// assert_eq!(Container::new(&file)?.frame_count(), 1);
2679    /// # Ok::<(), Box<dyn std::error::Error>>(())
2680    /// ```
2681    #[must_use]
2682    pub fn frame_count(&self) -> u32 {
2683        self.get(WebPFormatFeature::WEBP_FF_FRAME_COUNT)
2684    }
2685
2686    /// The payload of the first chunk with `fourcc` (C: `WebPDemuxGetChunk`
2687    /// with chunk number 1).
2688    fn first_chunk(&self, fourcc: [u8; 4]) -> Option<&[u8]> {
2689        let iter = webp_demux_get_chunk(&self.demux, fourcc, 1)?;
2690        payload(&iter.chunk.bytes)
2691    }
2692
2693    /// The raw ICC profile: the payload of the first `ICCP` chunk, which the
2694    /// demuxer keeps when the `VP8X` flags announce it.
2695    ///
2696    /// # Examples
2697    ///
2698    /// ```
2699    /// use webp::api::decode::Container;
2700    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2701    /// # let rgba = [0_u8; 4];
2702    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 1, height: 1, stride: 4 })?;
2703    ///
2704    /// // A simple file has no metadata; readers then assume sRGB.
2705    /// assert_eq!(Container::new(&file)?.icc_profile(), None);
2706    /// # Ok::<(), Box<dyn std::error::Error>>(())
2707    /// ```
2708    #[must_use]
2709    pub fn icc_profile(&self) -> Option<&[u8]> {
2710        self.first_chunk(*b"ICCP")
2711    }
2712
2713    /// The raw EXIF data: the payload of the first `EXIF` chunk, unparsed
2714    /// (the orientation, if any, is in it).
2715    ///
2716    /// # Examples
2717    ///
2718    /// ```
2719    /// use webp::api::decode::Container;
2720    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2721    /// # let rgba = [0_u8; 4];
2722    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 1, height: 1, stride: 4 })?;
2723    ///
2724    /// assert_eq!(Container::new(&file)?.exif(), None);
2725    /// # Ok::<(), Box<dyn std::error::Error>>(())
2726    /// ```
2727    #[must_use]
2728    pub fn exif(&self) -> Option<&[u8]> {
2729        self.first_chunk(*b"EXIF")
2730    }
2731
2732    /// The raw XMP packet: the payload of the first `XMP ` chunk.
2733    ///
2734    /// # Examples
2735    ///
2736    /// ```
2737    /// use webp::api::decode::Container;
2738    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2739    /// # let rgba = [0_u8; 4];
2740    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 1, height: 1, stride: 4 })?;
2741    ///
2742    /// assert_eq!(Container::new(&file)?.xmp(), None);
2743    /// # Ok::<(), Box<dyn std::error::Error>>(())
2744    /// ```
2745    #[must_use]
2746    pub fn xmp(&self) -> Option<&[u8]> {
2747        self.first_chunk(*b"XMP ")
2748    }
2749
2750    /// The payloads of every chunk with `fourcc` that the demuxer keeps
2751    /// (`ICCP`, `EXIF`, `XMP ` and unknown chunks), in file order (C:
2752    /// `WebPDemuxGetChunk` and `WebPDemuxNextChunk`).
2753    ///
2754    /// # Examples
2755    ///
2756    /// ```
2757    /// use webp::api::decode::Container;
2758    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2759    /// # let rgba = [0_u8; 4];
2760    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 1, height: 1, stride: 4 })?;
2761    ///
2762    /// assert_eq!(Container::new(&file)?.chunks(*b"EXIF").count(), 0);
2763    /// # Ok::<(), Box<dyn std::error::Error>>(())
2764    /// ```
2765    #[must_use]
2766    pub fn chunks(&self, fourcc: [u8; 4]) -> Chunks<'_> {
2767        Chunks {
2768            iter: webp_demux_get_chunk(&self.demux, fourcc, 1),
2769            started: false,
2770        }
2771    }
2772}
2773
2774/// The payloads of the chunks with one tag; see [`Container::chunks`].
2775///
2776/// # Examples
2777///
2778/// ```
2779/// use webp::api::decode::{Chunks, Container};
2780/// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2781/// # let rgba = [0_u8; 4];
2782/// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 1, height: 1, stride: 4 })?;
2783///
2784/// let container = Container::new(&file)?;
2785/// let mut chunks: Chunks<'_> = container.chunks(*b"XMP ");
2786/// assert_eq!(chunks.next(), None);
2787/// # Ok::<(), Box<dyn std::error::Error>>(())
2788/// ```
2789pub struct Chunks<'s> {
2790    iter: Option<WebPChunkIterator<'s>>,
2791    started: bool,
2792}
2793
2794impl fmt::Debug for Chunks<'_> {
2795    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2796        f.debug_struct("Chunks")
2797            .field("chunk_num", &self.iter.as_ref().map(|iter| iter.chunk_num))
2798            .field(
2799                "num_chunks",
2800                &self.iter.as_ref().map(|iter| iter.num_chunks),
2801            )
2802            .finish()
2803    }
2804}
2805
2806impl<'s> Iterator for Chunks<'s> {
2807    type Item = &'s [u8];
2808
2809    fn next(&mut self) -> Option<&'s [u8]> {
2810        let iter = self.iter.as_mut()?;
2811        if self.started && !webp_demux_next_chunk(iter) {
2812            self.iter = None;
2813            return None;
2814        }
2815        self.started = true;
2816        payload(&iter.chunk.bytes)
2817    }
2818}
2819
2820//------------------------------------------------------------------------------
2821// Animation
2822
2823/// The color mode of an animation's canvas: the four modes that libwebp's
2824/// animation decoder supports.
2825///
2826/// # Examples
2827///
2828/// ```
2829/// use webp::api::decode::{AnimationMode, AnimationOptions};
2830///
2831/// assert_eq!(AnimationOptions::default().mode, AnimationMode::Rgba);
2832/// ```
2833#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
2834pub enum AnimationMode {
2835    /// Red, green, blue, straight alpha (C: `MODE_RGBA`).
2836    #[default]
2837    Rgba,
2838    /// Blue, green, red, straight alpha (C: `MODE_BGRA`).
2839    Bgra,
2840    /// Red, green, blue, premultiplied alpha (C: `MODE_rgbA`); the frames are
2841    /// blended premultiplied.
2842    PremultipliedRgba,
2843    /// Blue, green, red, premultiplied alpha (C: `MODE_bgrA`).
2844    PremultipliedBgra,
2845}
2846
2847impl AnimationMode {
2848    /// The C colorspace.
2849    const fn raw(self) -> WEBP_CSP_MODE {
2850        match self {
2851            Self::Rgba => WEBP_CSP_MODE::MODE_RGBA,
2852            Self::Bgra => WEBP_CSP_MODE::MODE_BGRA,
2853            Self::PremultipliedRgba => WEBP_CSP_MODE::MODE_rgbA,
2854            Self::PremultipliedBgra => WEBP_CSP_MODE::MODE_bgrA,
2855        }
2856    }
2857}
2858
2859/// The options of an [`AnimationDecoder`] (C: `WebPAnimDecoderOptions`).
2860///
2861/// # Examples
2862///
2863/// ```
2864/// use webp::api::decode::{AnimationMode, AnimationOptions};
2865///
2866/// let options = AnimationOptions { mode: AnimationMode::PremultipliedBgra, multithreaded: true };
2867/// assert!(options.multithreaded);
2868/// ```
2869#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
2870pub struct AnimationOptions {
2871    /// The color mode of the canvas, [`AnimationMode::Rgba`] by default.
2872    pub mode: AnimationMode,
2873    /// Decodes lossy frames with a second thread (C: `use_threads`); the
2874    /// canvases do not change.
2875    pub multithreaded: bool,
2876}
2877
2878/// The parameters of an animation (C: `WebPAnimInfo`).
2879///
2880/// # Examples
2881///
2882/// ```
2883/// use webp::api::decode::{AnimationDecoder, AnimationOptions};
2884/// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2885/// # let rgba = [0_u8; 4 * 6];
2886/// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 3, height: 2, stride: 12 })?;
2887///
2888/// // A still image is an animation of one frame.
2889/// let info = AnimationDecoder::new(&file, AnimationOptions::default())?.info();
2890/// assert_eq!((info.canvas_width, info.canvas_height, info.frame_count), (3, 2, 1));
2891/// # Ok::<(), Box<dyn std::error::Error>>(())
2892/// ```
2893#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2894pub struct AnimationInfo {
2895    /// The canvas width in pixels.
2896    pub canvas_width: u32,
2897    /// The canvas height in pixels.
2898    pub canvas_height: u32,
2899    /// The number of times the animation loops, 0 for forever (1 for a still
2900    /// image).
2901    pub loop_count: u32,
2902    /// The background color as `0xAARRGGBB` (the `ANIM` chunk's bytes read as
2903    /// a little-endian `u32`), reported and not applied; see
2904    /// [`Container::background_color`].
2905    pub background_color: u32,
2906    /// The number of frames.
2907    pub frame_count: u32,
2908}
2909
2910/// A decoded frame: the whole canvas after the frame was blended and the
2911/// previous one disposed, and the frame's end time.
2912///
2913/// # Examples
2914///
2915/// ```
2916/// use webp::api::decode::{AnimationDecoder, AnimationOptions, Frame};
2917/// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2918/// # let rgba = [1_u8, 2, 3, 4].repeat(2);
2919/// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 2, height: 1, stride: 8 })?;
2920///
2921/// let mut decoder = AnimationDecoder::new(&file, AnimationOptions::default())?;
2922/// let frame: Frame<'_> = decoder.next_frame()?.expect("one frame");
2923/// assert_eq!((frame.canvas, frame.stride, frame.timestamp_ms), (&[1_u8, 2, 3, 4, 1, 2, 3, 4][..], 8, 0));
2924/// # Ok::<(), Box<dyn std::error::Error>>(())
2925/// ```
2926#[derive(Clone, Copy)]
2927pub struct Frame<'s> {
2928    /// The canvas: `canvas_height` rows of `canvas_width` pixels of 4 bytes.
2929    pub canvas: &'s [u8],
2930    /// The distance between canvas rows, in bytes: `4 * canvas_width`.
2931    pub stride: usize,
2932    /// The time at which the frame ends, in milliseconds: the sum of the
2933    /// durations so far (0 for a still image).
2934    pub timestamp_ms: i32,
2935}
2936
2937impl fmt::Debug for Frame<'_> {
2938    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2939        f.debug_struct("Frame")
2940            .field("canvas_len", &self.canvas.len())
2941            .field("stride", &self.stride)
2942            .field("timestamp_ms", &self.timestamp_ms)
2943            .finish()
2944    }
2945}
2946
2947/// A decoder of a WebP animation into full canvases (C: `WebPAnimDecoder`).
2948///
2949/// It borrows the file's bytes. A still image is an animation of one frame.
2950/// Each [`AnimationDecoder::next_frame`] lends the canvas until the next call.
2951/// The canvas starts transparent black; the background color is reported in
2952/// [`AnimationInfo`], not applied.
2953///
2954/// # Examples
2955///
2956/// ```
2957/// use webp::api::decode::{AnimationDecoder, AnimationOptions};
2958/// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
2959/// # fn chunk(tag: &[u8], payload: &[u8]) -> Vec<u8> {
2960/// #     let mut bytes = tag.to_vec();
2961/// #     bytes.extend_from_slice(&(payload.len() as u32).to_le_bytes());
2962/// #     bytes.extend_from_slice(payload);
2963/// #     if payload.len() % 2 == 1 { bytes.push(0); }
2964/// #     bytes
2965/// # }
2966/// # fn frame(red: u8, duration: u8) -> Vec<u8> {
2967/// #     let rgba = [red, 0, 0, 255].repeat(4);
2968/// #     let image = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 2, height: 2, stride: 8 }).unwrap();
2969/// #     let mut payload = vec![0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, duration, 0, 0, 0];
2970/// #     payload.extend_from_slice(&image[12..]);
2971/// #     chunk(b"ANMF", &payload)
2972/// # }
2973/// # let vp8x = chunk(b"VP8X", &[0x02, 0, 0, 0, 1, 0, 0, 1, 0, 0]);
2974/// # let anim = chunk(b"ANIM", &[0x10, 0x20, 0x30, 0xff, 3, 0]);
2975/// # let body = [vp8x, anim, frame(100, 40), frame(200, 60)].concat();
2976/// # let mut file = b"RIFF".to_vec();
2977/// # file.extend_from_slice(&(body.len() as u32 + 4).to_le_bytes());
2978/// # file.extend_from_slice(b"WEBP");
2979/// # file.extend_from_slice(&body);
2980///
2981/// // `file` is a 2 by 2 animation of a red frame for 40 ms and a brighter one
2982/// // for 60 ms, looping 3 times.
2983/// let mut decoder = AnimationDecoder::new(&file, AnimationOptions::default())?;
2984/// let info = decoder.info();
2985/// assert_eq!((info.frame_count, info.loop_count, info.background_color), (2, 3, 0xff30_2010));
2986/// let mut frames = Vec::new();
2987/// while let Some(frame) = decoder.next_frame()? {
2988///     frames.push((frame.canvas[0], frame.timestamp_ms));
2989/// }
2990/// assert_eq!(frames, [(100, 40), (200, 100)]);
2991/// # Ok::<(), Box<dyn std::error::Error>>(())
2992/// ```
2993pub struct AnimationDecoder<'d> {
2994    dec: WebPAnimDecoder<'d>,
2995}
2996
2997impl fmt::Debug for AnimationDecoder<'_> {
2998    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2999        f.debug_struct("AnimationDecoder")
3000            .field("info", &self.info())
3001            .field("has_more_frames", &self.has_more_frames())
3002            .finish_non_exhaustive()
3003    }
3004}
3005
3006impl<'d> AnimationDecoder<'d> {
3007    /// Parses the file and prepares its decoding (C: `WebPAnimDecoderNew`).
3008    ///
3009    /// This allocates two canvases of `4 * canvas_width * canvas_height` bytes
3010    /// and zeroes them; a small file can declare a canvas of up to 2^32
3011    /// pixels. To budget that memory before it is allocated, read the canvas
3012    /// size first with [`Features::parse`] or [`Container::canvas_width`] and
3013    /// [`Container::canvas_height`].
3014    ///
3015    /// # Errors
3016    ///
3017    /// The errors of [`Features::parse`]; [`DecodeError::NotEnoughData`] for
3018    /// a file that ends early and [`DecodeError::BitstreamError`] for one that
3019    /// does not parse; [`DecodeError::OutOfMemory`] when the canvases cannot
3020    /// be allocated.
3021    ///
3022    /// # Examples
3023    ///
3024    /// ```
3025    /// use webp::api::decode::{AnimationDecoder, AnimationMode, AnimationOptions, Features};
3026    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
3027    /// # let rgba = [0_u8; 4 * 6];
3028    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 3, height: 2, stride: 12 })?;
3029    ///
3030    /// let features = Features::parse(&file)?;
3031    /// let canvases = 2 * 4 * u64::from(features.width) * u64::from(features.height);
3032    /// assert!(canvases <= 1 << 20, "within the budget");
3033    /// let options = AnimationOptions { mode: AnimationMode::Bgra, multithreaded: false };
3034    /// let decoder = AnimationDecoder::new(&file, options)?;
3035    /// # let _ = decoder;
3036    /// # Ok::<(), Box<dyn std::error::Error>>(())
3037    /// ```
3038    pub fn new(data: &'d [u8], options: AnimationOptions) -> Result<Self, DecodeError> {
3039        let mut raw = WebPAnimDecoderOptions::default();
3040        let initialized = webp_anim_decoder_options_init(&mut raw);
3041        debug_assert!(initialized, "the crate's own ABI version matches");
3042        raw.color_mode = options.mode.raw();
3043        raw.use_threads = i32::from(options.multithreaded);
3044        if let Some(dec) = anim_decoder_new_bytes(data, Some(&raw), WEBP_DEMUX_ABI_VERSION) {
3045            return Ok(Self { dec });
3046        }
3047        // libwebp reports no status: the features, then the demuxer, then the
3048        // canvases can fail, the options being valid.
3049        Features::parse(data)?;
3050        if demux_bytes(data, false, WEBP_DEMUX_ABI_VERSION).0.is_none() {
3051            return Err(demux_error(data));
3052        }
3053        Err(DecodeError::OutOfMemory)
3054    }
3055
3056    /// The animation's parameters (C: `WebPAnimDecoderGetInfo`).
3057    ///
3058    /// # Examples
3059    ///
3060    /// ```
3061    /// use webp::api::decode::{AnimationDecoder, AnimationOptions};
3062    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
3063    /// # let rgba = [0_u8; 4];
3064    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 1, height: 1, stride: 4 })?;
3065    ///
3066    /// assert_eq!(AnimationDecoder::new(&file, AnimationOptions::default())?.info().loop_count, 1);
3067    /// # Ok::<(), Box<dyn std::error::Error>>(())
3068    /// ```
3069    #[must_use]
3070    pub fn info(&self) -> AnimationInfo {
3071        let info = webp_anim_decoder_get_info(&self.dec);
3072        AnimationInfo {
3073            canvas_width: info.canvas_width,
3074            canvas_height: info.canvas_height,
3075            loop_count: info.loop_count,
3076            background_color: info.bgcolor,
3077            frame_count: info.frame_count,
3078        }
3079    }
3080
3081    /// Whether frames remain to be decoded (C:
3082    /// `WebPAnimDecoderHasMoreFrames`).
3083    ///
3084    /// # Examples
3085    ///
3086    /// ```
3087    /// use webp::api::decode::{AnimationDecoder, AnimationOptions};
3088    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
3089    /// # let rgba = [0_u8; 4];
3090    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 1, height: 1, stride: 4 })?;
3091    ///
3092    /// let mut decoder = AnimationDecoder::new(&file, AnimationOptions::default())?;
3093    /// assert!(decoder.has_more_frames());
3094    /// decoder.next_frame()?;
3095    /// assert!(!decoder.has_more_frames());
3096    /// # Ok::<(), Box<dyn std::error::Error>>(())
3097    /// ```
3098    #[must_use]
3099    pub fn has_more_frames(&self) -> bool {
3100        webp_anim_decoder_has_more_frames(&self.dec)
3101    }
3102
3103    /// Decodes the next frame and lends the canvas until the next call (C:
3104    /// `WebPAnimDecoderGetNext`); `Ok(None)` after the last frame.
3105    ///
3106    /// # Errors
3107    ///
3108    /// [`DecodeError::FrameFailed`] when the frame cannot be decoded; the
3109    /// decoder stays at that frame.
3110    ///
3111    /// # Examples
3112    ///
3113    /// ```
3114    /// use webp::api::decode::{AnimationDecoder, AnimationOptions};
3115    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
3116    /// # let rgba = [8_u8; 4];
3117    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 1, height: 1, stride: 4 })?;
3118    ///
3119    /// let mut decoder = AnimationDecoder::new(&file, AnimationOptions::default())?;
3120    /// assert_eq!(decoder.next_frame()?.map(|frame| frame.canvas.to_vec()), Some(vec![8_u8; 4]));
3121    /// assert!(decoder.next_frame()?.is_none());
3122    /// # Ok::<(), Box<dyn std::error::Error>>(())
3123    /// ```
3124    pub fn next_frame(&mut self) -> Result<Option<Frame<'_>>, DecodeError> {
3125        if !self.has_more_frames() {
3126            return Ok(None);
3127        }
3128        let stride = usize::try_from(self.info().canvas_width)
3129            .unwrap_or(usize::MAX)
3130            .saturating_mul(4);
3131        match webp_anim_decoder_get_next(&mut self.dec) {
3132            Some((canvas, timestamp_ms)) => Ok(Some(Frame {
3133                canvas,
3134                stride,
3135                timestamp_ms,
3136            })),
3137            None => Err(DecodeError::FrameFailed),
3138        }
3139    }
3140
3141    /// Restarts from the first frame (C: `WebPAnimDecoderReset`).
3142    ///
3143    /// # Examples
3144    ///
3145    /// ```
3146    /// use webp::api::decode::{AnimationDecoder, AnimationOptions};
3147    /// # use webp::api::encode::{encode_lossless, PixelLayout, PixelRows};
3148    /// # let rgba = [0_u8; 4];
3149    /// # let file = encode_lossless(PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 1, height: 1, stride: 4 })?;
3150    ///
3151    /// let mut decoder = AnimationDecoder::new(&file, AnimationOptions::default())?;
3152    /// decoder.next_frame()?;
3153    /// decoder.reset();
3154    /// assert!(decoder.has_more_frames());
3155    /// # Ok::<(), Box<dyn std::error::Error>>(())
3156    /// ```
3157    pub fn reset(&mut self) {
3158        webp_anim_decoder_reset(&mut self.dec);
3159    }
3160}