Skip to main content

webp/demux/
anim_decode.rs

1// libwebp v1.6.0, src/demux/anim_decode.c:
2//
3// Copyright 2015 Google Inc. All Rights Reserved.
4//
5// Use of this source code is governed by a BSD-style license
6// that can be found in the COPYING file in the root of the source
7// tree. An additional intellectual property rights grant can be found
8// in the file PATENTS. All contributing project authors may
9// be found in the AUTHORS file in the root of the source tree.
10// -----------------------------------------------------------------------------
11//
12//  AnimDecoder implementation.
13//
14
15//! Translation of `src/demux/anim_decode.c` from libwebp v1.6.0.
16//!
17//! Work package: WP14 (animation decode and demux ABI).
18//!
19//! # Representation
20//!
21//! - [`WebPAnimDecoder`] owns the demuxer that it creates from the caller's
22//!   `WebPData`, which therefore outlives the decoder, as `demux.h` requires.
23//! - C keeps the iterator of the previous frame (`prev_iter`), whose `private_`
24//!   points at the decoder's own demuxer. A Rust iterator that borrows a field of
25//!   the struct holding it would be self-referential, so the decoder keeps the
26//!   plain fields of that iterator ([`IteratorFields`]) and builds the current
27//!   frame's iterator in each `GetNext` call.
28//! - C keeps a `WebPDecoderConfig` whose output buffer points into the canvas.
29//!   The decoder keeps the options and the colorspace, and lends the canvas to a
30//!   configuration built for each `GetNext` call (ADR 0003, "Decoding context
31//!   per call").
32//! - `src/webp/mux.h` is a reviewed include (`tools/units.json`): only the
33//!   `WEBP_MUX_*` enums of `mux_types.h` are used.
34//! - **API shapes.**
35//!   `webp_anim_decoder_get_next(&mut dec) -> Option<(&[u8], i32)>` (canvas and
36//!   timestamp), `webp_anim_decoder_get_info(&dec) -> WebPAnimInfo`,
37//!   `has_more_frames`, `reset`, `get_demuxer(&dec) -> &WebPDemuxer`, and
38//!   `webp_anim_decoder_delete(dec)` as the drop. Only `MODE_RGBA`,
39//!   `MODE_BGRA`, `MODE_rgbA` and `MODE_bgrA` are accepted. C's widths are kept
40//!   in the canvas arithmetic (`(size_t)size != size`, the `uint64_t` products,
41//!   the `uint32_t` pixel indexes).
42//!
43//! # Deviations from upstream
44//!
45//! Changes of representation that the ADRs allow, or behavior that the Rust
46//! side cannot reproduce exactly. Each records the reason.
47//!
48//! 1. **Decoder configuration per call.** C points the output at
49//!    `curr_frame + out_offset` with the size `iter.height * stride`, which on
50//!    the bottom rows reaches `x_offset * 4` bytes past the canvas, where C
51//!    never writes. The translation lends the canvas from `out_offset` to its
52//!    end, with that length as the size. `CheckDecBuffer` asks for
53//!    `stride * (height - 1) + width * 4` bytes, which both sizes hold for
54//!    every frame inside the canvas, and the demuxer admits no other, so the
55//!    same frames pass and fail. The rest of the configuration is rebuilt per
56//!    call: `WebPDecode` overwrites `config.input` and the output's dimensions
57//!    before reading them.
58//! 2. **Canvas allocation.** `WebPSafeCalloc(canvas_width * 4, canvas_height)`
59//!    is `webp_safe_calloc(canvas_width * 4 * canvas_height, 1)`: the size
60//!    tests agree (`h > MAX / n` holds exactly when `n * h > MAX`), and the
61//!    product cannot wrap. The Rust helper writes the zeros when it reserves,
62//!    where C's `calloc` may leave the pages untouched until the first frame's
63//!    `ZeroFillCanvas` and `CopyCanvas` write both canvases; the memory is
64//!    touched earlier, which no result shows.
65//! 3. **Canvas after a failure.** C callers can read the canvas that a failed
66//!    `GetNext` leaves behind through the pointer of an earlier call (the
67//!    header promises it only until the next call). The Rust API ends the
68//!    borrow, so that canvas is compared only through the C ABI (`PARTIAL` in
69//!    `abi_animation_decoder_matches_the_c_library`), which hands out the same
70//!    memory.
71//!
72//! # Excluded undefined behavior
73//!
74//! Inputs that are undefined behavior (or assertion failures) in C and are
75//! therefore excluded from the oracle comparison (PORTING rule 8):
76//!
77//! 1. **Timestamp overflow.** `prev_frame_timestamp + iter.duration` is an
78//!    `int` sum; 129 frames of the largest duration (0xFFFFFF) overflow it,
79//!    which is undefined. The translation panics in the dev and `checked`
80//!    profiles and wraps in release. The inputs keep the sum below 2^31.
81//! 2. **`ZeroFillFrameRect` offsets.** `y_offset * buf_stride` is computed in
82//!    `int` and overflows for canvases of 2 GiB and more. Not reached.
83//!
84//! # Checks not applicable
85//!
86//! These checks do not apply, or cannot be made, with the reason:
87//!
88//! 1. **Big-endian targets** (`WORDS_BIGENDIAN`) are not run; `CHANNEL_SHIFT`
89//!    is translated for both byte orders. Its big-endian form shifts the
90//!    blended channel by `CHANNEL_SHIFT(3) = 0` in `BlendChannelNonPremult`, as
91//!    C does.
92//! 2. **32-bit targets** are not run; `(size_t)size != size` and
93//!    `CheckSizeOverflow` never fail on 64-bit hosts.
94//! 3. **Allocation limits.** The demuxer limits a canvas to fewer than 2^32
95//!    pixels (`MAX_IMAGE_AREA`), so `WebPSafeCalloc`'s 2^34-byte limit is never
96//!    reached by the canvases; a refused host reservation fails `New` as C's
97//!    `NULL` does, and no test reaches it.
98//! 4. **`WebPDemuxReleaseIterator(&dec->prev_iter)`** in `GetNext`, `Reset` and
99//!    `Delete` frees nothing in C; the translation keeps comments at those
100//!    points.
101//! 5. **Threads.** `use_threads` goes to the decoder options; 0 and 1 (and -3)
102//!    are matrix dimensions.
103
104use crate::dec::webp_dec::webp_decode;
105use crate::demux::demux::{WebPDemuxer, demux_bytes, webp_demux_get_frame, webp_demux_get_i};
106use crate::utils::utils::{check_size_overflow, webp_safe_calloc};
107use crate::webp::decode::{
108    WEBP_CSP_MODE, WebPBitstreamFeatures, WebPDecBuffer, WebPDecBufferPlanes, WebPDecoderConfig,
109    WebPDecoderOptions, WebPRGBABuffer, webp_get_features, webp_init_decoder_config,
110};
111use crate::webp::demux::{
112    WEBP_DEMUX_ABI_VERSION, WebPAnimDecoderOptions, WebPAnimInfo, WebPFormatFeature, WebPIterator,
113};
114use crate::webp::mux_types::{WebPData, WebPMuxAnimBlend, WebPMuxAnimDispose};
115use crate::webp::types::{PlaneOffset, PlaneStorage, webp_abi_is_incompatible};
116
117// upstream: src/demux/anim_decode.c NUM_CHANNELS
118const NUM_CHANNELS: u32 = 4;
119
120// upstream: src/demux/anim_decode.c CHANNEL_SHIFT
121/// Channel extraction from a `u32` representation of a `u8` RGBA/BGRA buffer
122/// (C: `WORDS_BIGENDIAN` selects the big-endian form).
123#[cfg(target_endian = "big")]
124const fn channel_shift(i: u32) -> u32 {
125    24 - i * 8
126}
127
128// upstream: src/demux/anim_decode.c CHANNEL_SHIFT
129/// Channel extraction from a `u32` representation of a `u8` RGBA/BGRA buffer.
130#[cfg(not(target_endian = "big"))]
131const fn channel_shift(i: u32) -> u32 {
132    i * 8
133}
134
135// upstream: src/demux/anim_decode.c BlendRowFunc
136/// Blends `num_pixels` pixels of `src` over `dst`, writing into `src`. C casts the
137/// canvas to `uint32_t*`; the slices start at the first pixel's byte, and each
138/// pixel is read and written in host byte order (ADR 0003, "Untyped sample
139/// buffers").
140type BlendRowFunc = fn(&mut [u8], &[u8], i32);
141
142/// The fields of a `WebPIterator` that `IsKeyFrame`, `FindBlendRangeAtRow` and
143/// the dispose step read (C keeps the whole iterator of the previous frame as
144/// `prev_iter`). Zeroed, it is the iterator after `WebPAnimDecoderReset`'s
145/// `memset`. No C counterpart.
146#[derive(Clone, Copy, Debug, Default)]
147struct IteratorFields {
148    frame_num: i32,
149    x_offset: i32,
150    y_offset: i32,
151    width: i32,
152    height: i32,
153    dispose_method: WebPMuxAnimDispose,
154    has_alpha: i32,
155    blend_method: WebPMuxAnimBlend,
156}
157
158impl From<&WebPIterator<'_>> for IteratorFields {
159    fn from(iter: &WebPIterator<'_>) -> Self {
160        Self {
161            frame_num: iter.frame_num,
162            x_offset: iter.x_offset,
163            y_offset: iter.y_offset,
164            width: iter.width,
165            height: iter.height,
166            dispose_method: iter.dispose_method,
167            has_alpha: iter.has_alpha,
168            blend_method: iter.blend_method,
169        }
170    }
171}
172
173// upstream: src/demux/anim_decode.c WebPAnimDecoder
174/// Decoder of a (possibly) animated WebP file into full canvases (C: `struct
175/// WebPAnimDecoder`, opaque in `webp/demux.h`). It borrows the caller's
176/// `WebPData` for its lifetime through the demuxer it owns.
177#[derive(Debug)]
178pub struct WebPAnimDecoder<'a> {
179    /// Demuxer created from the given WebP bitstream (C: `demux`).
180    demux: WebPDemuxer<'a>,
181    /// Decoder options (C: `config.options`).
182    options: WebPDecoderOptions,
183    /// Output colorspace (C: `config.output.colorspace`). The canvas is attached
184    /// as the output buffer for each frame.
185    colorspace: WEBP_CSP_MODE,
186    /// The chosen blend row function (C: `blend_func`).
187    blend_func: BlendRowFunc,
188    /// Global info about the animation (C: `info`).
189    info: WebPAnimInfo,
190    /// Current canvas, not disposed (C: `curr_frame`).
191    curr_frame: Vec<u8>,
192    /// Previous canvas, properly disposed (C: `prev_frame_disposed`).
193    prev_frame_disposed: Vec<u8>,
194    /// Previous frame timestamp in milliseconds (C: `prev_frame_timestamp`).
195    prev_frame_timestamp: i32,
196    /// The fields of the previous frame's iterator (C: `prev_iter`).
197    prev_iter: IteratorFields,
198    /// True if the previous frame was a keyframe (C: `prev_frame_was_keyframe`).
199    prev_frame_was_keyframe: bool,
200    /// Index of the next frame to be decoded, starting from 1 (C: `next_frame`).
201    next_frame: i32,
202}
203
204// upstream: src/demux/anim_decode.c DefaultDecoderOptions
205fn default_decoder_options(dec_options: &mut WebPAnimDecoderOptions) {
206    dec_options.color_mode = WEBP_CSP_MODE::MODE_RGBA;
207    dec_options.use_threads = 0;
208}
209
210// upstream: src/demux/anim_decode.c WebPAnimDecoderOptionsInitInternal
211/// Internal, version-checked, entry point of `WebPAnimDecoderOptionsInit`: sets
212/// the color mode to `MODE_RGBA` and turns threads off; the padding is left
213/// as it is. Returns false in case of version mismatch. C also returns 0 for a
214/// `NULL` structure, which exists only at the C ABI.
215#[must_use]
216pub fn webp_anim_decoder_options_init_internal(
217    dec_options: &mut WebPAnimDecoderOptions,
218    abi_version: i32,
219) -> bool {
220    if webp_abi_is_incompatible(abi_version, WEBP_DEMUX_ABI_VERSION) {
221        return false;
222    }
223    default_decoder_options(dec_options);
224    true
225}
226
227// upstream: src/demux/anim_decode.c ApplyDecoderOptions
228/// Checks the color mode and derives the decoder settings that C writes into
229/// `dec`: the blend row function, the decoder options and the colorspace of the
230/// output buffer (C: `config->output.is_external_memory = 1`; the canvas is
231/// attached as caller memory for each frame). Returns `None` where C returns 0.
232fn apply_decoder_options(
233    dec_options: &WebPAnimDecoderOptions,
234) -> Option<(BlendRowFunc, WebPDecoderOptions, WEBP_CSP_MODE)> {
235    let mode = dec_options.color_mode;
236    if mode != WEBP_CSP_MODE::MODE_RGBA
237        && mode != WEBP_CSP_MODE::MODE_BGRA
238        && mode != WEBP_CSP_MODE::MODE_rgbA
239        && mode != WEBP_CSP_MODE::MODE_bgrA
240    {
241        return None;
242    }
243    let blend_func: BlendRowFunc =
244        if mode == WEBP_CSP_MODE::MODE_RGBA || mode == WEBP_CSP_MODE::MODE_BGRA {
245            blend_pixel_row_non_premult
246        } else {
247            blend_pixel_row_premult
248        };
249    let mut config = WebPDecoderConfig::default();
250    if !webp_init_decoder_config(&mut config) {
251        return None;
252    }
253    config.options.use_threads = dec_options.use_threads;
254    // Note: config->output.u.RGBA is set at the time of decoding each frame.
255    Some((blend_func, config.options, mode))
256}
257
258// upstream: src/demux/anim_decode.c WebPAnimDecoderNewInternal
259/// Internal, version-checked, entry point of `WebPAnimDecoderNew`. Returns
260/// `None` in case of a version mismatch, a parsing error, an invalid option or
261/// a memory error. `dec_options` `None` selects the defaults (`MODE_RGBA`, no
262/// threads). `webp_data` must stay unchanged for the decoder's lifetime, which
263/// the borrow enforces.
264#[must_use]
265pub fn webp_anim_decoder_new_internal<'a>(
266    webp_data: &'a WebPData<'_>,
267    dec_options: Option<&WebPAnimDecoderOptions>,
268    abi_version: i32,
269) -> Option<WebPAnimDecoder<'a>> {
270    anim_decoder_new_bytes(&webp_data.bytes, dec_options, abi_version)
271}
272
273/// The body of [`webp_anim_decoder_new_internal`] over the bytes of
274/// `webp_data` (no C counterpart): the decoder and its demuxer borrow `bytes`
275/// rather than the `WebPData` value that holds them, so that the safe API
276/// (`src/api/decode.rs`, WP16) can build one from a caller's `&[u8]` that
277/// outlives the call. `webp_demux(webp_data)` is
278/// `demux_bytes(bytes, false, WEBP_DEMUX_ABI_VERSION)`.
279pub(crate) fn anim_decoder_new_bytes<'a>(
280    bytes: &'a [u8],
281    dec_options: Option<&WebPAnimDecoderOptions>,
282    abi_version: i32,
283) -> Option<WebPAnimDecoder<'a>> {
284    if webp_abi_is_incompatible(abi_version, WEBP_DEMUX_ABI_VERSION) {
285        return None;
286    }
287
288    // Validate the bitstream before doing expensive allocations. The demuxer may
289    // be more tolerant than the decoder.
290    let mut features = WebPBitstreamFeatures::default();
291    if webp_get_features(bytes, &mut features).is_err() {
292        return None;
293    }
294
295    // C: dec = WebPSafeCalloc(1ULL, sizeof(*dec)). The decoder is a struct value
296    // here, assembled from the parts below.
297    let mut options = WebPAnimDecoderOptions::default();
298    match dec_options {
299        Some(dec_options) => options = *dec_options,
300        None => default_decoder_options(&mut options),
301    }
302    let (blend_func, decoder_options, colorspace) = apply_decoder_options(&options)?;
303
304    let demux = demux_bytes(bytes, false, WEBP_DEMUX_ABI_VERSION).0?;
305
306    let info = WebPAnimInfo {
307        canvas_width: webp_demux_get_i(&demux, WebPFormatFeature::WEBP_FF_CANVAS_WIDTH),
308        canvas_height: webp_demux_get_i(&demux, WebPFormatFeature::WEBP_FF_CANVAS_HEIGHT),
309        loop_count: webp_demux_get_i(&demux, WebPFormatFeature::WEBP_FF_LOOP_COUNT),
310        bgcolor: webp_demux_get_i(&demux, WebPFormatFeature::WEBP_FF_BACKGROUND_COLOR),
311        frame_count: webp_demux_get_i(&demux, WebPFormatFeature::WEBP_FF_FRAME_COUNT),
312        pad: [0; 4],
313    };
314
315    // Note: calloc() because we fill frame with zeroes as well.
316    let curr_frame = canvas_calloc(info.canvas_width, info.canvas_height)?;
317    let prev_frame_disposed = canvas_calloc(info.canvas_width, info.canvas_height)?;
318
319    let mut dec = WebPAnimDecoder {
320        demux,
321        options: decoder_options,
322        colorspace,
323        blend_func,
324        info,
325        curr_frame,
326        prev_frame_disposed,
327        prev_frame_timestamp: 0,
328        prev_iter: IteratorFields::default(),
329        prev_frame_was_keyframe: false,
330        next_frame: 0,
331    };
332    webp_anim_decoder_reset(&mut dec);
333    Some(dec)
334}
335
336/// C's `WebPSafeCalloc(canvas_width * NUM_CHANNELS, canvas_height)`: a zeroed
337/// canvas of `canvas_width * 4 * canvas_height` bytes, or `None` where C returns
338/// `NULL`. The `uint32_t` product `canvas_width * NUM_CHANNELS` is the element
339/// count and the height the element size; the Rust helper takes the byte count
340/// with an element size of one. The two size tests agree: for `n > 0`,
341/// `h > MAX / n` holds exactly when `n * h > MAX`, which is `1 > MAX / (n * h)`,
342/// and the product cannot wrap, because the demuxer limits both dimensions to
343/// 2^24.
344fn canvas_calloc(canvas_width: u32, canvas_height: u32) -> Option<Vec<u8>> {
345    let nmemb = u64::from(canvas_width.wrapping_mul(NUM_CHANNELS));
346    webp_safe_calloc::<u8>(nmemb * u64::from(canvas_height), 1)
347}
348
349// upstream: src/demux/anim_decode.c WebPAnimDecoderGetInfo
350/// Returns the global information about the animation. C writes it to `*info`
351/// and returns 1, or 0 for `NULL` arguments, which exist only at the C ABI.
352#[must_use]
353pub fn webp_anim_decoder_get_info(dec: &WebPAnimDecoder<'_>) -> WebPAnimInfo {
354    dec.info
355}
356
357// upstream: src/demux/anim_decode.c IsFullFrame
358/// Returns true if the frame covers the full canvas.
359fn is_full_frame(width: i32, height: i32, canvas_width: i32, canvas_height: i32) -> bool {
360    width == canvas_width && height == canvas_height
361}
362
363// upstream: src/demux/anim_decode.c ZeroFillCanvas
364/// Clears the canvas to transparent. Returns false when the size does not fit
365/// in `usize`.
366fn zero_fill_canvas(buf: &mut [u8], canvas_width: u32, canvas_height: u32) -> bool {
367    // sizeof(*buf) is 1.
368    let size = u64::from(canvas_width)
369        .wrapping_mul(u64::from(canvas_height))
370        .wrapping_mul(u64::from(NUM_CHANNELS));
371    if !check_size_overflow(size) {
372        return false;
373    }
374    let Ok(size) = usize::try_from(size) else {
375        return false;
376    };
377    buf[..size].fill(0);
378    true
379}
380
381// upstream: src/demux/anim_decode.c ZeroFillFrameRect
382/// Clears the given frame rectangle to transparent. C computes the offsets in
383/// `int`, whose overflow is undefined (the module documentation, `# Excluded
384/// undefined behavior`, item 2); the frame lies inside the canvas, so the
385/// offset is never negative otherwise.
386fn zero_fill_frame_rect(
387    buf: &mut [u8],
388    buf_stride: i32,
389    x_offset: i32,
390    y_offset: i32,
391    width: i32,
392    height: i32,
393) {
394    debug_assert!(width * NUM_CHANNELS.cast_signed() <= buf_stride);
395    let mut start = y_offset * buf_stride + x_offset * NUM_CHANNELS.cast_signed();
396    let row = usize::try_from(width * NUM_CHANNELS.cast_signed()).unwrap_or(0);
397    for _ in 0..height {
398        let at = usize::try_from(start).expect("the frame rectangle lies inside the canvas");
399        buf[at..at + row].fill(0);
400        start += buf_stride;
401    }
402}
403
404// upstream: src/demux/anim_decode.c CopyCanvas
405/// Copies `width * height` pixels from `src` to `dst`. Returns false when the
406/// size does not fit in `usize`.
407fn copy_canvas(src: &[u8], dst: &mut [u8], width: u32, height: u32) -> bool {
408    let size = u64::from(width)
409        .wrapping_mul(u64::from(height))
410        .wrapping_mul(u64::from(NUM_CHANNELS));
411    if !check_size_overflow(size) {
412        return false;
413    }
414    let Ok(size) = usize::try_from(size) else {
415        return false;
416    };
417    dst[..size].copy_from_slice(&src[..size]);
418    true
419}
420
421// upstream: src/demux/anim_decode.c IsKeyFrame
422/// Returns true if the current frame is a key-frame.
423#[expect(
424    clippy::if_same_then_else,
425    reason = "C's IsKeyFrame returns 1 from two separate branches"
426)]
427fn is_key_frame(
428    curr: &IteratorFields,
429    prev: &IteratorFields,
430    prev_frame_was_key_frame: bool,
431    canvas_width: i32,
432    canvas_height: i32,
433) -> bool {
434    if curr.frame_num == 1 {
435        true
436    } else if (curr.has_alpha == 0 || curr.blend_method == WebPMuxAnimBlend::WEBP_MUX_NO_BLEND)
437        && is_full_frame(curr.width, curr.height, canvas_width, canvas_height)
438    {
439        true
440    } else {
441        prev.dispose_method == WebPMuxAnimDispose::WEBP_MUX_DISPOSE_BACKGROUND
442            && (is_full_frame(prev.width, prev.height, canvas_width, canvas_height)
443                || prev_frame_was_key_frame)
444    }
445}
446
447// upstream: src/demux/anim_decode.c BlendChannelNonPremult
448/// Blends a single channel of `src` over `dst`, given their alpha channel
449/// values. `src` and `dst` are assumed to be NOT pre-multiplied by alpha.
450fn blend_channel_non_premult(
451    src: u32,
452    src_a: u8,
453    dst: u32,
454    dst_a: u8,
455    scale: u32,
456    shift: u32,
457) -> u8 {
458    let src_channel = ((src >> shift) & 0xff) as u8;
459    let dst_channel = ((dst >> shift) & 0xff) as u8;
460    // C computes the sum in int; it stays below 2 * 255 * 255.
461    let blend_unscaled =
462        u32::from(src_channel) * u32::from(src_a) + u32::from(dst_channel) * u32::from(dst_a);
463    debug_assert!(u64::from(blend_unscaled) < (1u64 << 32) / u64::from(scale));
464    #[expect(
465        clippy::cast_possible_truncation,
466        reason = "C returns the shifted value as uint8_t"
467    )]
468    let blended = (blend_unscaled.wrapping_mul(scale) >> channel_shift(3)) as u8;
469    blended
470}
471
472// upstream: src/demux/anim_decode.c BlendPixelNonPremult
473/// Blends `src` over `dst` assuming they are NOT pre-multiplied by alpha.
474#[expect(
475    clippy::cast_possible_truncation,
476    clippy::cast_sign_loss,
477    reason = "C assigns the int results to uint8_t variables"
478)]
479fn blend_pixel_non_premult(src: u32, dst: u32) -> u32 {
480    let src_a = ((src >> channel_shift(3)) & 0xff) as u8;
481
482    if src_a == 0 {
483        dst
484    } else {
485        let dst_a = ((dst >> channel_shift(3)) & 0xff) as u8;
486        // This is the approximate integer arithmetic for the actual formula:
487        // dst_factor_a = (dst_a * (255 - src_a)) / 255.
488        let dst_factor_a = ((i32::from(dst_a) * (256 - i32::from(src_a))) >> 8) as u8;
489        let blend_a = (i32::from(src_a) + i32::from(dst_factor_a)) as u8;
490        let scale = (1u32 << 24) / u32::from(blend_a);
491
492        let blend_r =
493            blend_channel_non_premult(src, src_a, dst, dst_factor_a, scale, channel_shift(0));
494        let blend_g =
495            blend_channel_non_premult(src, src_a, dst, dst_factor_a, scale, channel_shift(1));
496        let blend_b =
497            blend_channel_non_premult(src, src_a, dst, dst_factor_a, scale, channel_shift(2));
498        debug_assert!(i32::from(src_a) + i32::from(dst_factor_a) < 256);
499
500        (u32::from(blend_r) << channel_shift(0))
501            | (u32::from(blend_g) << channel_shift(1))
502            | (u32::from(blend_b) << channel_shift(2))
503            | (u32::from(blend_a) << channel_shift(3))
504    }
505}
506
507/// The pixel at byte `at` of a canvas, as C reads it through `uint32_t*`.
508fn read_pixel(buf: &[u8], at: usize) -> u32 {
509    u32::from_ne_bytes([buf[at], buf[at + 1], buf[at + 2], buf[at + 3]])
510}
511
512// upstream: src/demux/anim_decode.c BlendPixelRowNonPremult
513/// Blends `num_pixels` in `src` over `dst` assuming they are NOT pre-multiplied
514/// by alpha.
515fn blend_pixel_row_non_premult(src: &mut [u8], dst: &[u8], num_pixels: i32) {
516    for i in 0..usize::try_from(num_pixels).unwrap_or(0) {
517        let at = 4 * i;
518        let src_pixel = read_pixel(src, at);
519        let src_alpha = ((src_pixel >> channel_shift(3)) & 0xff) as u8;
520        if src_alpha != 0xff {
521            let blended = blend_pixel_non_premult(src_pixel, read_pixel(dst, at));
522            src[at..at + 4].copy_from_slice(&blended.to_ne_bytes());
523        }
524    }
525}
526
527// upstream: src/demux/anim_decode.c ChannelwiseMultiply
528/// Individually multiplies each channel in `pix` by `scale`.
529fn channelwise_multiply(pix: u32, scale: u32) -> u32 {
530    let mask = 0x00FF_00FF_u32;
531    let rb = (pix & mask).wrapping_mul(scale) >> 8;
532    let ag = ((pix >> 8) & mask).wrapping_mul(scale);
533    (rb & mask) | (ag & !mask)
534}
535
536// upstream: src/demux/anim_decode.c BlendPixelPremult
537/// Blends `src` over `dst` assuming they are pre-multiplied by alpha.
538fn blend_pixel_premult(src: u32, dst: u32) -> u32 {
539    let src_a = ((src >> channel_shift(3)) & 0xff) as u8;
540    // C passes the int 256 - src_a as the uint32_t scale.
541    src.wrapping_add(channelwise_multiply(dst, 256 - u32::from(src_a)))
542}
543
544// upstream: src/demux/anim_decode.c BlendPixelRowPremult
545/// Blends `num_pixels` in `src` over `dst` assuming they are pre-multiplied by
546/// alpha.
547fn blend_pixel_row_premult(src: &mut [u8], dst: &[u8], num_pixels: i32) {
548    for i in 0..usize::try_from(num_pixels).unwrap_or(0) {
549        let at = 4 * i;
550        let src_pixel = read_pixel(src, at);
551        let src_alpha = ((src_pixel >> channel_shift(3)) & 0xff) as u8;
552        if src_alpha != 0xff {
553            let blended = blend_pixel_premult(src_pixel, read_pixel(dst, at));
554            src[at..at + 4].copy_from_slice(&blended.to_ne_bytes());
555        }
556    }
557}
558
559// upstream: src/demux/anim_decode.c FindBlendRangeAtRow
560/// Returns two ranges (`<left, width>` pairs) at row `canvas_y` that belong to
561/// `src` but not `dst`, as `(left1, width1, left2, width2)`. A range is empty if
562/// its width is 0 (C writes the four values through pointers). Changing `>` to
563/// `>=` in `src_max_x > dst_max_x` is an equivalent mutation: equal right edges
564/// give a range of width 0 either way.
565fn find_blend_range_at_row(
566    src: &IteratorFields,
567    dst: &IteratorFields,
568    canvas_y: i32,
569) -> (i32, i32, i32, i32) {
570    let src_max_x = src.x_offset + src.width;
571    let dst_max_x = dst.x_offset + dst.width;
572    let dst_max_y = dst.y_offset + dst.height;
573    debug_assert!(canvas_y >= src.y_offset && canvas_y < (src.y_offset + src.height));
574    let mut left1 = -1;
575    let mut width1 = 0;
576    let mut left2 = -1;
577    let mut width2 = 0;
578
579    if canvas_y < dst.y_offset
580        || canvas_y >= dst_max_y
581        || src.x_offset >= dst_max_x
582        || src_max_x <= dst.x_offset
583    {
584        left1 = src.x_offset;
585        width1 = src.width;
586        return (left1, width1, left2, width2);
587    }
588
589    if src.x_offset < dst.x_offset {
590        left1 = src.x_offset;
591        width1 = dst.x_offset - src.x_offset;
592    }
593
594    if src_max_x > dst_max_x {
595        left2 = dst_max_x;
596        width2 = src_max_x - dst_max_x;
597    }
598    (left1, width1, left2, width2)
599}
600
601/// C's `size_t` pixel index `canvas_y * width + left`: the `int` operands are
602/// converted to `uint32_t`, and the arithmetic wraps there.
603fn pixel_index(canvas_y: i32, width: u32, left: i32) -> usize {
604    canvas_y
605        .cast_unsigned()
606        .wrapping_mul(width)
607        .wrapping_add(left.cast_unsigned()) as usize
608}
609
610// upstream: src/demux/anim_decode.c WebPAnimDecoderGetNext
611/// Fetches the next frame: the fully reconstructed canvas of `canvas_width * 4 *
612/// canvas_height` bytes in the decoder's color mode, and its timestamp in
613/// milliseconds. Returns `None` if there is a parsing or decoding error, or if
614/// there are no more frames (C returns 0 and writes neither output). After a
615/// failure the canvas holds whatever the failed step left in it, as in C, and
616/// the decoder stays at the same frame.
617///
618/// # Panics
619///
620/// Never for a decoder of `webp_anim_decoder_new`: the demuxer keeps every frame
621/// inside the canvas, so the frame's offset lies inside the canvas.
622#[expect(
623    clippy::too_many_lines,
624    reason = "C's WebPAnimDecoderGetNext is one function, translated as it is"
625)]
626pub fn webp_anim_decoder_get_next<'d>(dec: &'d mut WebPAnimDecoder<'_>) -> Option<(&'d [u8], i32)> {
627    if !webp_anim_decoder_has_more_frames(dec) {
628        return None;
629    }
630
631    let width = dec.info.canvas_width;
632    let height = dec.info.canvas_height;
633    let blend_row = dec.blend_func;
634
635    // Get compressed frame.
636    let iter = webp_demux_get_frame(&dec.demux, dec.next_frame)?;
637    let timestamp = dec.prev_frame_timestamp + iter.duration;
638    let curr = IteratorFields::from(&iter);
639
640    // Initialize.
641    let is_key_frame = is_key_frame(
642        &curr,
643        &dec.prev_iter,
644        dec.prev_frame_was_keyframe,
645        width.cast_signed(),
646        height.cast_signed(),
647    );
648    if is_key_frame {
649        if !zero_fill_canvas(&mut dec.curr_frame, width, height) {
650            return None;
651        }
652    } else if !copy_canvas(&dec.prev_frame_disposed, &mut dec.curr_frame, width, height) {
653        return None;
654    }
655
656    // Decode.
657    {
658        let input: &[u8] = &iter.fragment.bytes;
659        let stride = width.wrapping_mul(NUM_CHANNELS); // at most 25 + 2 bits
660        let out_offset = i64::from(iter.y_offset)
661            .cast_unsigned()
662            .wrapping_mul(u64::from(stride))
663            .wrapping_add(
664                i64::from(iter.x_offset)
665                    .cast_unsigned()
666                    .wrapping_mul(u64::from(NUM_CHANNELS)),
667            ); // 53b
668        let size = i64::from(iter.height)
669            .cast_unsigned()
670            .wrapping_mul(u64::from(stride)); // at most 25 + 27b
671        if usize::try_from(size).is_err() {
672            return None;
673        }
674        // C points the output at curr_frame + out_offset with the size
675        // iter.height * stride, which on the bottom rows reaches x_offset * 4
676        // bytes past the canvas, where C never writes. The canvas from that
677        // offset to its end is lent with its own length as the size: the buffer
678        // check asks only for stride * (height - 1) + width * 4 bytes, so the same
679        // frames pass and fail (the module documentation, `# Deviations from
680        // upstream`, item 1). The demuxer keeps every frame inside the canvas, so
681        // the offset lies inside it.
682        let out_offset =
683            usize::try_from(out_offset).expect("the demuxer keeps the frame inside the canvas");
684        let canvas = &mut dec.curr_frame[out_offset..];
685        let mut config = WebPDecoderConfig {
686            input: WebPBitstreamFeatures::default(),
687            output: WebPDecBuffer {
688                colorspace: dec.colorspace,
689                u: WebPDecBufferPlanes::RGBA(WebPRGBABuffer {
690                    rgba: PlaneOffset::default(),
691                    stride: stride.cast_signed(),
692                    size: canvas.len(),
693                }),
694                storage: PlaneStorage::External(vec![canvas]),
695                ..WebPDecBuffer::default()
696            },
697            options: dec.options,
698        };
699
700        if webp_decode(input, &mut config).is_err() {
701            return None;
702        }
703    }
704
705    // During the decoding of current frame, we may have set some pixels to be
706    // transparent (i.e. alpha < 255). However, the value of each of these
707    // pixels should have been determined by blending it against the value of
708    // that pixel in the previous frame if blending method of is WEBP_MUX_BLEND.
709    if iter.frame_num > 1 && iter.blend_method == WebPMuxAnimBlend::WEBP_MUX_BLEND && !is_key_frame
710    {
711        if dec.prev_iter.dispose_method == WebPMuxAnimDispose::WEBP_MUX_DISPOSE_NONE {
712            // Blend transparent pixels with pixels in previous canvas.
713            for y in 0..iter.height {
714                let offset = 4 * pixel_index(iter.y_offset + y, width, iter.x_offset);
715                blend_row(
716                    &mut dec.curr_frame[offset..],
717                    &dec.prev_frame_disposed[offset..],
718                    iter.width,
719                );
720            }
721        } else {
722            debug_assert_eq!(
723                dec.prev_iter.dispose_method,
724                WebPMuxAnimDispose::WEBP_MUX_DISPOSE_BACKGROUND
725            );
726            // We need to blend a transparent pixel with its value just after
727            // initialization. That is, blend it with:
728            // * Fully transparent pixel if it belongs to prevRect <-- No-op.
729            // * The pixel in the previous canvas otherwise <-- Need alpha-blending.
730            for y in 0..iter.height {
731                let canvas_y = iter.y_offset + y;
732                let (left1, width1, left2, width2) =
733                    find_blend_range_at_row(&curr, &dec.prev_iter, canvas_y);
734                if width1 > 0 {
735                    let offset1 = 4 * pixel_index(canvas_y, width, left1);
736                    blend_row(
737                        &mut dec.curr_frame[offset1..],
738                        &dec.prev_frame_disposed[offset1..],
739                        width1,
740                    );
741                }
742                if width2 > 0 {
743                    let offset2 = 4 * pixel_index(canvas_y, width, left2);
744                    blend_row(
745                        &mut dec.curr_frame[offset2..],
746                        &dec.prev_frame_disposed[offset2..],
747                        width2,
748                    );
749                }
750            }
751        }
752    }
753
754    // Update info of the previous frame and dispose it for the next iteration.
755    dec.prev_frame_timestamp = timestamp;
756    // C: WebPDemuxReleaseIterator(&dec->prev_iter), which frees nothing.
757    dec.prev_iter = curr;
758    dec.prev_frame_was_keyframe = is_key_frame;
759    if !copy_canvas(&dec.curr_frame, &mut dec.prev_frame_disposed, width, height) {
760        return None;
761    }
762    if dec.prev_iter.dispose_method == WebPMuxAnimDispose::WEBP_MUX_DISPOSE_BACKGROUND {
763        zero_fill_frame_rect(
764            &mut dec.prev_frame_disposed,
765            width.wrapping_mul(NUM_CHANNELS).cast_signed(),
766            dec.prev_iter.x_offset,
767            dec.prev_iter.y_offset,
768            dec.prev_iter.width,
769            dec.prev_iter.height,
770        );
771    }
772    dec.next_frame += 1;
773
774    // All OK, fill in the values.
775    Some((&dec.curr_frame, timestamp))
776}
777
778// upstream: src/demux/anim_decode.c WebPAnimDecoderHasMoreFrames
779/// Returns true if some frames are yet to be decoded. C also returns 0 for a
780/// `NULL` decoder, which exists only at the C ABI.
781#[must_use]
782pub fn webp_anim_decoder_has_more_frames(dec: &WebPAnimDecoder<'_>) -> bool {
783    dec.next_frame <= dec.info.frame_count.cast_signed()
784}
785
786// upstream: src/demux/anim_decode.c WebPAnimDecoderReset
787/// Resets the decoder, so that the next `webp_anim_decoder_get_next` restarts
788/// decoding from the first frame. The canvases keep their contents, as in C.
789pub fn webp_anim_decoder_reset(dec: &mut WebPAnimDecoder<'_>) {
790    dec.prev_frame_timestamp = 0;
791    // C: WebPDemuxReleaseIterator(&dec->prev_iter), which frees nothing, then
792    // memset(&dec->prev_iter, 0, sizeof(dec->prev_iter)).
793    dec.prev_iter = IteratorFields::default();
794    dec.prev_frame_was_keyframe = false;
795    dec.next_frame = 1;
796}
797
798// upstream: src/demux/anim_decode.c WebPAnimDecoderGetDemuxer
799/// Returns the decoder's demuxer, for example to read EXIF, XMP or ICC chunks.
800/// It is owned by the decoder. C returns `NULL` for a `NULL` decoder, which
801/// exists only at the C ABI.
802#[must_use]
803pub fn webp_anim_decoder_get_demuxer<'d, 'a>(dec: &'d WebPAnimDecoder<'a>) -> &'d WebPDemuxer<'a> {
804    &dec.demux
805}
806
807// upstream: src/demux/anim_decode.c WebPAnimDecoderDelete
808/// Deletes the decoder: dropping it releases the demuxer and both canvases. C
809/// accepts `NULL`; in Rust the caller holds no `Option`. C also calls
810/// `WebPDemuxReleaseIterator(&dec->prev_iter)`, which frees nothing.
811pub fn webp_anim_decoder_delete(dec: WebPAnimDecoder<'_>) {
812    drop(dec);
813}
814
815impl WebPAnimDecoder<'_> {
816    /// The current canvas, mutably, for the C ABI, which hands C its pointer
817    /// after a successful `webp_anim_decoder_get_next` (C: `dec->curr_frame`).
818    pub(crate) fn canvas_mut(&mut self) -> &mut [u8] {
819        &mut self.curr_frame
820    }
821}