Skip to main content

webp/mux/
anim_encode.rs

1// libwebp v1.6.0, src/mux/anim_encode.c:
2//
3// Copyright 2014 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//  AnimEncoder implementation.
13//
14
15//! Translation of `src/mux/anim_encode.c` from libwebp v1.6.0.
16//!
17//! Work package: WP15 (mux and animation encode).
18//!
19//! # Representation
20//!
21//! - The encoder owns its mux, the three canvases, the ring of encoded frames,
22//!   both configurations, the options and the error string. C's `curr_canvas`,
23//!   a pointer to the caller's frame during `WebPAnimEncoderAdd`, is the frame
24//!   argument of the functions that read it; nothing keeps it.
25//! - C makes `WebPPictureView`s of the current canvas for the sub-frame
26//!   rectangles (`GetSubRect`) and encodes them later (`EncodeCandidate`),
27//!   after `IncreaseTransparency` or `FlattenSimilarBlocks` may have changed the
28//!   canvas through which the view sees, and the lossless encoding writes into
29//!   the canvas through the view (`WebPReplaceTransparentPixels` unless `exact`),
30//!   which a later candidate reads. The translation checks the rectangle where C
31//!   makes the view and makes the view where it is used: a shared one
32//!   (`webp_picture_view`) for reading, and one that borrows the canvas's ARGB
33//!   samples exclusively for an encoding ([`sub_frame_view`]), so that the
34//!   encoder writes where C writes (see "Views of the canvas" below).
35//! - C copies the frame's progress hook into the canvas copy and from there
36//!   into the views. The views here call the frame's hook through a borrow, so
37//!   the candidate encodings report progress as in C; the canvas copy holds no
38//!   hook, so the re-encoding of `WebPAnimEncoderAssemble` reports none, where C
39//!   calls the hook of the last frame (see `# Deviations from upstream`,
40//!   item 2).
41//! - **Views of the canvas.** C makes `WebPPictureView`s of the current canvas
42//!   in `GetSubRect` and encodes them later in `EncodeCandidate`. Between the
43//!   two, `IncreaseTransparency`, `FlattenSimilarBlocks` and
44//!   `CopyCurrentCanvas` change the canvas, which the view sees, and the
45//!   lossless encoding writes into the canvas through the view
46//!   (`WebPReplaceTransparentPixels` unless `exact`), which the lossy candidate
47//!   of the same frame then encodes. The shared view of
48//!   `src/enc/picture_rescale_enc.rs` would copy its planes before that write
49//!   (as `webp_encode` in `src/enc/webp_enc.rs` does for a view) and lose it.
50//!   The translation therefore checks the rectangle where C makes the view and
51//!   makes the view where it is used: a shared `webp_picture_view` for
52//!   `WebPGetColorPalette`, and for an encoding a picture that borrows the
53//!   canvas's ARGB samples exclusively as `PlaneStorage::External`
54//!   (`sub_frame_view`), as the C ABI lends caller memory. No interface of
55//!   `src/enc/` changes. Evidence: with a shared view, the "patchy" cases of
56//!   `option_and_config_matrix_matches_the_c_encoder` (noisy opaque content, so
57//!   that the lossy candidate wins, next to transparent pixels that keep a
58//!   color) give other bytes than C.
59//!
60//! # Deviations from upstream
61//!
62//! Changes of representation that the ADRs allow, or behavior that the Rust
63//! side cannot reproduce exactly. Each records the reason.
64//!
65//! 1. **`EncodeFrame`** removes the memory writer from the picture after the
66//!    call, where C leaves `writer` and `custom_ptr` set (C never encodes the
67//!    picture again without setting them); the writer holds the memory writer
68//!    through an `Rc<RefCell<...>>`, because the canvas copy is a
69//!    `WebPPicture<'static>`.
70//! 2. **Progress hook.** C copies the frame's `progress_hook` and `user_data`
71//!    into the canvas copy (`CopyCurrentCanvas`) and from there into each view.
72//!    The views here call the frame's hook through a borrow, so every candidate
73//!    encoding reports as in C. The canvas copy holds no hook, so the
74//!    re-encoding of the canvas in `WebPAnimEncoderAssemble`
75//!    (`FrameToFullCanvas`, for a single frame smaller than the canvas) reports
76//!    nothing, where C calls the last frame's hook with that frame's
77//!    `user_data`, which the header does not promise to keep valid. The tests
78//!    accept C's count there and require 0.
79//! 3. **Verbose output** (`SanitizeEncoderOptions`, `FlushFrames`, the YUV
80//!    warning) goes to `std::io::stderr`, unbuffered like C's `stderr`; write
81//!    errors are ignored, as `fprintf` ignores them.
82//!
83//! # Excluded undefined behavior
84//!
85//! Inputs that are undefined behavior (or assertion failures) in C and are
86//! therefore excluded from the oracle comparison (PORTING rule 8):
87//!
88//! 1. **`WebPAnimEncoderAdd` after `WebPAnimEncoderAssemble`:** the flushed
89//!    encoder has no frame left, and `IncreasePreviousDuration` reads
90//!    `GetFrame(enc, count - 1)`, which fails C's assertion and indexes before
91//!    the ring in release. The translation wraps the `size_t` arithmetic as C
92//!    does and panics where the index leaves the vector. Not generated.
93//! 2. **`FrameToFullCanvas` when its second encoding fails:** C frees the first
94//!    encoding's bytes and `OptimizeSingleFrame` frees them again (a double
95//!    free). In C the stale progress hook can make the second encoding fail;
96//!    the translation calls no hook there (`# Deviations from upstream`,
97//!    item 2), and only a memory error remains, which is not injected.
98//! 3. **`WebPAnimEncoderRefineRect` with a rectangle that clips to nothing**
99//!    fails the assertion of `MinimizeChangeRectangle`'s pixel comparison, and
100//!    with a quality outside `[0, 100]` converts a NaN to `int`. The test skips
101//!    both.
102//!
103//! # Checks not applicable
104//!
105//! These checks do not apply, or cannot be made, with the reason:
106//!
107//! 1. **Big-endian targets** are not run. `DecodeFrameOntoCanvas` reads the
108//!    decoded BGRA bytes as native-order words, as C's `uint32_t*` view does.
109//! 2. **32-bit targets** are not run; `ENCODED_FRAME_SIZE` follows the pointer
110//!    width and the encoder never allocates more than 31 frames.
111//! 3. **Threads**: `thread_level` 0 and 1 are matrix dimensions; the encoder
112//!    adds no thread of its own.
113
114use std::borrow::Cow;
115use std::cell::RefCell;
116use std::io::Write as _;
117use std::rc::Rc;
118
119use crate::dec::webp_dec::webp_decode;
120use crate::enc::config_enc::webp_validate_config;
121use crate::enc::picture_csp_enc::webp_picture_yuva_to_argb;
122use crate::enc::picture_enc::{
123    argb_samples, argb_samples_mut, webp_memory_write, webp_memory_writer_clear,
124    webp_memory_writer_init, webp_picture_alloc,
125};
126use crate::enc::picture_rescale_enc::{webp_picture_copy, webp_picture_view};
127use crate::enc::webp_enc::webp_encode;
128use crate::mux::muxedit::{
129    webp_mux_assemble, webp_mux_delete, webp_mux_delete_chunk, webp_mux_push_frame,
130    webp_mux_set_animation_params, webp_mux_set_canvas_size, webp_mux_set_chunk,
131    webp_mux_set_image,
132};
133use crate::mux::muxi::WebPMux;
134use crate::mux::muxread::{webp_mux_get_canvas_size, webp_mux_get_chunk, webp_mux_get_frame};
135use crate::utils::utils::{webp_copy_pixels, webp_get_color_palette, webp_safe_calloc};
136use crate::webp::decode::{
137    WEBP_CSP_MODE, WebPDecBufferPlanes, WebPRGBABuffer, webp_get_features, webp_init_decoder_config,
138};
139use crate::webp::encode::{
140    WebPConfig, WebPEncodingError, WebPMemoryWriter, WebPPicture, webp_config_init,
141    webp_picture_init,
142};
143use crate::webp::format_constants::{MAX_DURATION, MAX_IMAGE_AREA};
144use crate::webp::mux::{
145    WEBP_MUX_ABI_VERSION, WebPAnimEncoderOptions, WebPChunkId, WebPMuxError, WebPMuxFrameInfo,
146    webp_mux_create, webp_mux_new,
147};
148use crate::webp::mux_types::{
149    WebPData, WebPMuxAnimBlend, WebPMuxAnimDispose, webp_data_clear, webp_data_copy,
150};
151use crate::webp::types::{PlaneOffset, PlaneStorage, webp_abi_is_incompatible};
152
153// upstream: src/mux/anim_encode.c ERROR_STR_MAX_LENGTH
154const ERROR_STR_MAX_LENGTH: usize = 100;
155
156//------------------------------------------------------------------------------
157// Internal structs.
158
159// upstream: src/mux/anim_encode.c FrameRectangle
160/// Stores frame rectangle dimensions.
161#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
162struct FrameRectangle {
163    x_offset: i32,
164    y_offset: i32,
165    width: i32,
166    height: i32,
167}
168
169// upstream: src/mux/anim_encode.c EncodedFrame
170/// Used to store two candidates of encoded data for an animation frame. One of
171/// the two will be chosen later.
172#[expect(clippy::struct_field_names, reason = "the C field names")]
173#[derive(Clone, Debug, Default)]
174struct EncodedFrame {
175    /// Encoded frame rectangle.
176    sub_frame: WebPMuxFrameInfo<'static>,
177    /// Encoded frame if it is a key-frame.
178    key_frame: WebPMuxFrameInfo<'static>,
179    /// True if `key_frame` has been chosen.
180    is_key_frame: bool,
181}
182
183/// C's `sizeof(EncodedFrame)`, for the allocation test of the frame array: two
184/// `WebPMuxFrameInfo` (a pointer and a `size_t`, then seven 32-bit fields,
185/// padded to the pointer alignment) and an `int`, padded the same way.
186const ENCODED_FRAME_SIZE: usize = {
187    let word = core::mem::size_of::<usize>();
188    let info = (2 * word + 7 * 4).next_multiple_of(word);
189    (2 * info + 4).next_multiple_of(word)
190};
191
192// upstream: src/mux/anim_encode.c WebPAnimEncoder
193/// The animation encoder (C: `struct WebPAnimEncoder`, opaque in `mux.h`).
194/// Chunks set without copying (`WebPAnimEncoderSetChunk`) borrow their bytes
195/// for `'a`; the frames are always copied into the mux.
196#[expect(clippy::struct_excessive_bools, reason = "the C struct's flags")]
197pub struct WebPAnimEncoder<'a> {
198    /// Canvas width.
199    canvas_width: i32,
200    /// Canvas height.
201    canvas_height: i32,
202    /// Global encoding options.
203    options: WebPAnimEncoderOptions,
204
205    /// Previous WebP frame rectangle.
206    prev_rect: FrameRectangle,
207    /// Cached in case a re-encode is needed.
208    last_config: WebPConfig,
209    /// If `last_config` uses lossless, then this config uses lossy and vice
210    /// versa; only valid if `options.allow_mixed` is true.
211    last_config_reversed: WebPConfig,
212
213    // C: WebPPicture* curr_canvas, the caller's frame during WebPAnimEncoderAdd;
214    // passed as an argument here.
215
216    // Canvas buffers.
217    /// Possibly modified current canvas.
218    curr_canvas_copy: WebPPicture<'static>,
219    /// True if pixels in `curr_canvas_copy` differ from those in `curr_canvas`.
220    curr_canvas_copy_modified: bool,
221
222    /// Previous canvas.
223    prev_canvas: WebPPicture<'static>,
224    /// Previous canvas disposed to background.
225    prev_canvas_disposed: WebPPicture<'static>,
226
227    // Encoded data.
228    /// Array of encoded frames.
229    encoded_frames: Vec<EncodedFrame>,
230    /// Number of allocated frames.
231    size: usize,
232    /// Frame start index.
233    start: usize,
234    /// Number of valid frames.
235    count: usize,
236    /// If >0, `flush_count` frames starting from `start` are ready to be added
237    /// to mux.
238    flush_count: usize,
239
240    // key-frame related.
241    /// min(canvas size - frame size) over the frames. Can be negative in certain
242    /// cases due to transparent pixels in a frame.
243    best_delta: i64,
244    /// Index of selected key-frame relative to `start`.
245    keyframe: i32,
246    /// Frames seen since the last key-frame.
247    count_since_key_frame: i32,
248
249    /// Timestamp of the first frame.
250    first_timestamp: i32,
251    /// Timestamp of the last added frame.
252    prev_timestamp: i32,
253    /// True if it's not yet decided if previous frame would be a sub-frame or a
254    /// key-frame.
255    prev_candidate_undecided: bool,
256
257    // Misc.
258    /// True if first frame is yet to be added/being added.
259    is_first_frame: bool,
260    /// True if `WebPAnimEncoderAdd()` has already been called with a NULL frame.
261    got_null_frame: bool,
262
263    /// Number of input frames processed so far.
264    in_frame_count: usize,
265    /// Number of frames added to mux so far. This may be different from
266    /// `in_frame_count` due to merging.
267    out_frame_count: usize,
268
269    /// Muxer to assemble the WebP bitstream.
270    mux: WebPMux<'a>,
271    /// Error string. Empty if no error.
272    error_str: String,
273}
274
275// -----------------------------------------------------------------------------
276// Life of WebPAnimEncoder object.
277
278// upstream: src/mux/anim_encode.c DELTA_INFINITY
279const DELTA_INFINITY: i64 = 1 << 32;
280// upstream: src/mux/anim_encode.c KEYFRAME_NONE
281const KEYFRAME_NONE: i32 = -1;
282
283// upstream: src/mux/anim_encode.c ResetCounters
284/// Reset the counters in the `WebPAnimEncoder`.
285fn reset_counters(enc: &mut WebPAnimEncoder<'_>) {
286    enc.start = 0;
287    enc.count = 0;
288    enc.flush_count = 0;
289    enc.best_delta = DELTA_INFINITY;
290    enc.keyframe = KEYFRAME_NONE;
291}
292
293// upstream: src/mux/anim_encode.c DisableKeyframes
294fn disable_keyframes(enc_options: &mut WebPAnimEncoderOptions) {
295    enc_options.kmax = i32::MAX;
296    enc_options.kmin = enc_options.kmax - 1;
297}
298
299// upstream: src/mux/anim_encode.c MAX_CACHED_FRAMES
300const MAX_CACHED_FRAMES: i32 = 30;
301
302/// `fprintf(stderr, ...)`: write errors are ignored, as C ignores them.
303fn print_stderr(args: core::fmt::Arguments<'_>) {
304    let _ = std::io::stderr().write_fmt(args);
305}
306
307// upstream: src/mux/anim_encode.c SanitizeEncoderOptions
308fn sanitize_encoder_options(enc_options: &mut WebPAnimEncoderOptions) {
309    let mut print_warning = enc_options.verbose != 0;
310
311    if enc_options.minimize_size != 0 {
312        disable_keyframes(enc_options);
313    }
314
315    if enc_options.kmax == 1 {
316        // All frames will be key-frames.
317        enc_options.kmin = 0;
318        enc_options.kmax = 0;
319        return;
320    } else if enc_options.kmax <= 0 {
321        disable_keyframes(enc_options);
322        print_warning = false;
323    }
324
325    if enc_options.kmin >= enc_options.kmax {
326        enc_options.kmin = enc_options.kmax - 1;
327        if print_warning {
328            print_stderr(format_args!(
329                "WARNING: Setting kmin = {}, so that kmin < kmax.\n",
330                enc_options.kmin
331            ));
332        }
333    } else {
334        let kmin_limit = enc_options.kmax / 2 + 1;
335        if enc_options.kmin < kmin_limit && kmin_limit < enc_options.kmax {
336            // This ensures that enc.keyframe + kmin >= kmax is always true. So, we
337            // can flush all the frames in the 'count_since_key_frame == kmax' case.
338            enc_options.kmin = kmin_limit;
339            if print_warning {
340                print_stderr(format_args!(
341                    "WARNING: Setting kmin = {}, so that kmin >= kmax / 2 + 1.\n",
342                    enc_options.kmin
343                ));
344            }
345        }
346    }
347    // Limit the max number of frames that are allocated.
348    if enc_options.kmax - enc_options.kmin > MAX_CACHED_FRAMES {
349        enc_options.kmin = enc_options.kmax - MAX_CACHED_FRAMES;
350        if print_warning {
351            print_stderr(format_args!(
352                "WARNING: Setting kmin = {}, so that kmax - kmin <= {}.\n",
353                enc_options.kmin, MAX_CACHED_FRAMES
354            ));
355        }
356    }
357    debug_assert!(enc_options.kmin < enc_options.kmax);
358}
359
360// upstream: src/mux/anim_encode.c DefaultEncoderOptions
361fn default_encoder_options(enc_options: &mut WebPAnimEncoderOptions) {
362    enc_options.anim_params.loop_count = 0;
363    enc_options.anim_params.bgcolor = 0xffff_ffff; // White.
364    enc_options.minimize_size = 0;
365    disable_keyframes(enc_options);
366    enc_options.allow_mixed = 0;
367    enc_options.verbose = 0;
368}
369
370// upstream: src/mux/anim_encode.c WebPAnimEncoderOptionsInitInternal
371/// Internal, version-checked, entry point of `WebPAnimEncoderOptionsInit`.
372/// Returns false in case of version mismatch (C: also for `NULL` options).
373#[must_use]
374pub fn webp_anim_encoder_options_init_internal(
375    enc_options: &mut WebPAnimEncoderOptions,
376    abi_version: i32,
377) -> bool {
378    if webp_abi_is_incompatible(abi_version, WEBP_MUX_ABI_VERSION) {
379        return false;
380    }
381    default_encoder_options(enc_options);
382    true
383}
384
385// upstream: src/mux/anim_encode.c TRANSPARENT_COLOR
386/// This value is used to match a later call to `WebPReplaceTransparentPixels()`,
387/// making it a no-op for lossless (see `WebPEncode()`).
388const TRANSPARENT_COLOR: u32 = 0x0000_0000;
389
390/// C's conversion of an `int` to `uint64_t`, which sign-extends.
391fn c_u64(value: i32) -> u64 {
392    i64::from(value).cast_unsigned()
393}
394
395/// The position of the sample at `x`, `y` of an ARGB plane with a stride of
396/// `stride` pixels (C: `y * argb_stride + x`, computed in `int`).
397fn pixel(x: i32, y: i32, stride: i32) -> usize {
398    usize::try_from(y * stride + x).expect("a pixel inside the canvas")
399}
400
401/// The ARGB samples of a picture, from its first sample (C: `picture->argb`).
402fn argb<'p>(picture: &'p WebPPicture<'_>) -> &'p [u32] {
403    argb_samples(
404        &picture.argb_storage,
405        picture.argb.expect("the canvas has an ARGB plane"),
406    )
407}
408
409/// The ARGB samples of a picture, mutably.
410fn argb_mut<'p>(picture: &'p mut WebPPicture<'_>) -> &'p mut [u32] {
411    let plane = picture.argb.expect("the canvas has an ARGB plane");
412    argb_samples_mut(&mut picture.argb_storage, plane)
413}
414
415// upstream: src/mux/anim_encode.c ClearRectangle
416fn clear_rectangle(picture: &mut WebPPicture<'_>, left: i32, top: i32, width: i32, height: i32) {
417    let stride = picture.argb_stride;
418    let samples = argb_mut(picture);
419    for j in top..top + height {
420        for i in left..left + width {
421            samples[pixel(i, j, stride)] = TRANSPARENT_COLOR;
422        }
423    }
424}
425
426// upstream: src/mux/anim_encode.c WebPUtilClearPic
427fn webp_util_clear_pic(picture: &mut WebPPicture<'_>, rect: Option<&FrameRectangle>) {
428    if let Some(rect) = rect {
429        clear_rectangle(
430            picture,
431            rect.x_offset,
432            rect.y_offset,
433            rect.width,
434            rect.height,
435        );
436    } else {
437        let (width, height) = (picture.width, picture.height);
438        clear_rectangle(picture, 0, 0, width, height);
439    }
440}
441
442// upstream: src/mux/anim_encode.c MarkNoError
443fn mark_no_error(enc: &mut WebPAnimEncoder<'_>) {
444    enc.error_str.clear(); // Empty string.
445}
446
447/// `snprintf(enc->error_str, ERROR_STR_MAX_LENGTH, ...)`: the message, cut to
448/// the `ERROR_STR_MAX_LENGTH - 1` bytes that fit before the terminating `NUL`.
449fn set_error_str(enc: &mut WebPAnimEncoder<'_>, message: String) {
450    let mut message = message;
451    let mut end = message.len().min(ERROR_STR_MAX_LENGTH - 1);
452    while !message.is_char_boundary(end) {
453        end -= 1;
454    }
455    message.truncate(end);
456    enc.error_str = message;
457}
458
459// upstream: src/mux/anim_encode.c MarkError
460/// Records `"<str>."` as the error string. Crate-visible for the C ABI, which
461/// reports frames that it cannot lend this way.
462pub(crate) fn mark_error(enc: &mut WebPAnimEncoder<'_>, str: &str) {
463    set_error_str(enc, format!("{str}."));
464}
465
466// upstream: src/mux/anim_encode.c MarkError2
467fn mark_error2(enc: &mut WebPAnimEncoder<'_>, str: &str, error_code: i32) {
468    set_error_str(enc, format!("{str}: {error_code}."));
469}
470
471// upstream: src/mux/anim_encode.c WebPAnimEncoderNewInternal
472/// Internal, version-checked, entry point of `WebPAnimEncoderNew`. Returns
473/// `None` on a version mismatch, invalid dimensions or a memory error.
474///
475/// # Panics
476///
477/// Never: the sanitized options keep `kmax - kmin + 1` positive.
478#[must_use]
479pub fn webp_anim_encoder_new_internal<'a>(
480    width: i32,
481    height: i32,
482    enc_options: Option<&WebPAnimEncoderOptions>,
483    abi_version: i32,
484) -> Option<WebPAnimEncoder<'a>> {
485    if webp_abi_is_incompatible(abi_version, WEBP_MUX_ABI_VERSION) {
486        return None;
487    }
488    if width <= 0 || height <= 0 || c_u64(width) * c_u64(height) >= MAX_IMAGE_AREA {
489        return None;
490    }
491
492    // C: enc = WebPSafeCalloc(1, sizeof(*enc)), a value here.
493    let mut enc = WebPAnimEncoder {
494        canvas_width: 0,
495        canvas_height: 0,
496        options: WebPAnimEncoderOptions::default(),
497        prev_rect: FrameRectangle::default(),
498        last_config: WebPConfig::default(),
499        last_config_reversed: WebPConfig::default(),
500        curr_canvas_copy: WebPPicture::default(),
501        curr_canvas_copy_modified: false,
502        prev_canvas: WebPPicture::default(),
503        prev_canvas_disposed: WebPPicture::default(),
504        encoded_frames: Vec::new(),
505        size: 0,
506        start: 0,
507        count: 0,
508        flush_count: 0,
509        best_delta: 0,
510        keyframe: 0,
511        count_since_key_frame: 0,
512        first_timestamp: 0,
513        prev_timestamp: 0,
514        prev_candidate_undecided: false,
515        is_first_frame: false,
516        got_null_frame: false,
517        in_frame_count: 0,
518        out_frame_count: 0,
519        mux: WebPMux::default(),
520        error_str: String::new(),
521    };
522    mark_no_error(&mut enc);
523
524    // Dimensions and options.
525    enc.canvas_width = width;
526    enc.canvas_height = height;
527    if let Some(enc_options) = enc_options {
528        enc.options = *enc_options;
529        sanitize_encoder_options(&mut enc.options);
530    } else {
531        default_encoder_options(&mut enc.options);
532    }
533
534    // Canvas buffers.
535    if !webp_picture_init(&mut enc.curr_canvas_copy)
536        || !webp_picture_init(&mut enc.prev_canvas)
537        || !webp_picture_init(&mut enc.prev_canvas_disposed)
538    {
539        return None;
540    }
541    enc.curr_canvas_copy.width = width;
542    enc.curr_canvas_copy.height = height;
543    enc.curr_canvas_copy.use_argb = 1;
544    if webp_picture_alloc(&mut enc.curr_canvas_copy).is_err()
545        || webp_picture_copy(&enc.curr_canvas_copy, &mut enc.prev_canvas).is_err()
546        || webp_picture_copy(&enc.curr_canvas_copy, &mut enc.prev_canvas_disposed).is_err()
547    {
548        return None;
549    }
550    webp_util_clear_pic(&mut enc.prev_canvas, None);
551    enc.curr_canvas_copy_modified = true;
552
553    // Encoded frames.
554    reset_counters(&mut enc);
555    // Note: one extra storage is for the previous frame.
556    enc.size = usize::try_from(enc.options.kmax - enc.options.kmin + 1)
557        .expect("SanitizeEncoderOptions keeps kmin below kmax, or both at 0");
558    // We need space for at least 2 frames. But when kmin, kmax are both zero,
559    // enc->size will be 1. So we handle that special case below.
560    if enc.size < 2 {
561        enc.size = 2;
562    }
563    enc.encoded_frames = webp_safe_calloc::<EncodedFrame>(enc.size as u64, ENCODED_FRAME_SIZE)?;
564
565    enc.mux = webp_mux_new()?;
566
567    enc.count_since_key_frame = 0;
568    enc.first_timestamp = 0;
569    enc.prev_timestamp = 0;
570    enc.prev_candidate_undecided = false;
571    enc.is_first_frame = true;
572    enc.got_null_frame = false;
573
574    Some(enc) // All OK.
575}
576
577// upstream: src/mux/anim_encode.c FrameRelease
578/// Release the data contained by `encoded_frame`.
579fn frame_release(encoded_frame: &mut EncodedFrame) {
580    webp_data_clear(&mut encoded_frame.sub_frame.bitstream);
581    webp_data_clear(&mut encoded_frame.key_frame.bitstream);
582    *encoded_frame = EncodedFrame::default();
583}
584
585// upstream: src/mux/anim_encode.c WebPAnimEncoderDelete
586/// Deletes the `WebPAnimEncoder` object (the drop of the value; C frees the
587/// pictures, the frames and the mux).
588pub fn webp_anim_encoder_delete(enc: WebPAnimEncoder<'_>) {
589    let mut enc = enc;
590    for encoded_frame in &mut enc.encoded_frames {
591        frame_release(encoded_frame);
592    }
593    webp_mux_delete(enc.mux);
594}
595
596// -----------------------------------------------------------------------------
597// Frame addition.
598
599// upstream: src/mux/anim_encode.c GetFrame
600/// Returns the position of the cached frame at the given `position` relative to
601/// `start`. C adds the `size_t` values with wrap-around.
602fn get_frame(enc: &WebPAnimEncoder<'_>, position: usize) -> usize {
603    let index = enc.start.wrapping_add(position);
604    debug_assert!(index < enc.size);
605    index
606}
607
608// upstream: src/mux/anim_encode.c ComparePixelsFunc
609/// Compares `length` pixels of `src` and `dst` from the given positions, with
610/// the given steps between pixels.
611type ComparePixelsFunc = fn(&[u32], usize, usize, &[u32], usize, usize, i32, i32) -> bool;
612
613// upstream: src/mux/anim_encode.c ComparePixelsLossless
614/// Returns true if `length` number of pixels in `src` and `dst` are equal,
615/// assuming the given step sizes between pixels. `max_allowed_diff` is unused
616/// and only there to allow function pointer use.
617#[expect(
618    clippy::too_many_arguments,
619    reason = "the C signature with the positions of its pointers"
620)]
621fn compare_pixels_lossless(
622    src: &[u32],
623    src_pos: usize,
624    src_step: usize,
625    dst: &[u32],
626    dst_pos: usize,
627    dst_step: usize,
628    length: i32,
629    _max_allowed_diff: i32,
630) -> bool {
631    debug_assert!(length > 0);
632    let (mut src_pos, mut dst_pos, mut length) = (src_pos, dst_pos, length);
633    while length > 0 {
634        length -= 1;
635        if src[src_pos] != dst[dst_pos] {
636            return false;
637        }
638        src_pos += src_step;
639        dst_pos += dst_step;
640    }
641    true
642}
643
644// upstream: src/mux/anim_encode.c PixelsAreSimilar
645/// Helper to check if each channel in `src` and `dst` is at most off by
646/// `max_allowed_diff`.
647fn pixels_are_similar(src: u32, dst: u32, max_allowed_diff: i32) -> bool {
648    let src_a = ((src >> 24) & 0xff).cast_signed();
649    let src_r = ((src >> 16) & 0xff).cast_signed();
650    let src_g = ((src >> 8) & 0xff).cast_signed();
651    let src_b = (src & 0xff).cast_signed();
652    let dst_a = ((dst >> 24) & 0xff).cast_signed();
653    let dst_r = ((dst >> 16) & 0xff).cast_signed();
654    let dst_g = ((dst >> 8) & 0xff).cast_signed();
655    let dst_b = (dst & 0xff).cast_signed();
656
657    (src_a == dst_a)
658        && ((src_r - dst_r).abs() * dst_a <= (max_allowed_diff * 255))
659        && ((src_g - dst_g).abs() * dst_a <= (max_allowed_diff * 255))
660        && ((src_b - dst_b).abs() * dst_a <= (max_allowed_diff * 255))
661}
662
663// upstream: src/mux/anim_encode.c ComparePixelsLossy
664/// Returns true if `length` number of pixels in `src` and `dst` are within an
665/// error bound, assuming the given step sizes between pixels.
666#[expect(
667    clippy::too_many_arguments,
668    reason = "the C signature with the positions of its pointers"
669)]
670fn compare_pixels_lossy(
671    src: &[u32],
672    src_pos: usize,
673    src_step: usize,
674    dst: &[u32],
675    dst_pos: usize,
676    dst_step: usize,
677    length: i32,
678    max_allowed_diff: i32,
679) -> bool {
680    debug_assert!(length > 0);
681    let (mut src_pos, mut dst_pos, mut length) = (src_pos, dst_pos, length);
682    while length > 0 {
683        length -= 1;
684        if !pixels_are_similar(src[src_pos], dst[dst_pos], max_allowed_diff) {
685            return false;
686        }
687        src_pos += src_step;
688        dst_pos += dst_step;
689    }
690    true
691}
692
693// upstream: src/mux/anim_encode.c IsEmptyRect
694fn is_empty_rect(rect: &FrameRectangle) -> bool {
695    (rect.width == 0) || (rect.height == 0)
696}
697
698// upstream: src/mux/anim_encode.c QualityToMaxDiff
699#[expect(
700    clippy::cast_possible_truncation,
701    reason = "C's (int) conversion of a value in [1, 31] for qualities in [0, 100]"
702)]
703fn quality_to_max_diff(quality: f32) -> i32 {
704    let val = (f64::from(quality) / 100.0).powf(0.5);
705    let max_diff = 31.0 * (1.0 - val) + 1.0 * val;
706    (max_diff + 0.5) as i32
707}
708
709/// A stride in pixels as a step between samples (the canvases have positive
710/// strides).
711fn step(stride: i32) -> usize {
712    usize::try_from(stride).expect("a positive stride")
713}
714
715// upstream: src/mux/anim_encode.c MinimizeChangeRectangle
716/// Assumes that an initial valid guess of change rectangle `rect` is passed.
717#[expect(
718    clippy::too_many_lines,
719    reason = "the four boundary loops of the C function"
720)]
721fn minimize_change_rectangle(
722    src: &WebPPicture<'_>,
723    dst: &WebPPicture<'_>,
724    rect: &mut FrameRectangle,
725    is_lossless: bool,
726    quality: f32,
727) {
728    let compare_pixels: ComparePixelsFunc = if is_lossless {
729        compare_pixels_lossless
730    } else {
731        compare_pixels_lossy
732    };
733    let max_allowed_diff_lossy = quality_to_max_diff(quality);
734    let max_allowed_diff = if is_lossless {
735        0
736    } else {
737        max_allowed_diff_lossy
738    };
739    let (src_argb, src_stride) = (argb(src), src.argb_stride);
740    let (dst_argb, dst_stride) = (argb(dst), dst.argb_stride);
741
742    // Assumption/correctness checks.
743    debug_assert!(src.width == dst.width && src.height == dst.height);
744    debug_assert!(rect.x_offset + rect.width <= dst.width);
745    debug_assert!(rect.y_offset + rect.height <= dst.height);
746
747    let no_change = 'search: {
748        // Left boundary.
749        let mut i = rect.x_offset;
750        while i < rect.x_offset + rect.width {
751            let src_pos = pixel(i, rect.y_offset, src_stride);
752            let dst_pos = pixel(i, rect.y_offset, dst_stride);
753            if compare_pixels(
754                src_argb,
755                src_pos,
756                step(src_stride),
757                dst_argb,
758                dst_pos,
759                step(dst_stride),
760                rect.height,
761                max_allowed_diff,
762            ) {
763                rect.width -= 1; // Redundant column.
764                rect.x_offset += 1;
765            } else {
766                break;
767            }
768            i += 1;
769        }
770        if rect.width == 0 {
771            break 'search true;
772        }
773
774        // Right boundary.
775        let mut i = rect.x_offset + rect.width - 1;
776        while i >= rect.x_offset {
777            let src_pos = pixel(i, rect.y_offset, src_stride);
778            let dst_pos = pixel(i, rect.y_offset, dst_stride);
779            if compare_pixels(
780                src_argb,
781                src_pos,
782                step(src_stride),
783                dst_argb,
784                dst_pos,
785                step(dst_stride),
786                rect.height,
787                max_allowed_diff,
788            ) {
789                rect.width -= 1; // Redundant column.
790            } else {
791                break;
792            }
793            i -= 1;
794        }
795        if rect.width == 0 {
796            break 'search true;
797        }
798
799        // Top boundary.
800        let mut j = rect.y_offset;
801        while j < rect.y_offset + rect.height {
802            let src_pos = pixel(rect.x_offset, j, src_stride);
803            let dst_pos = pixel(rect.x_offset, j, dst_stride);
804            if compare_pixels(
805                src_argb,
806                src_pos,
807                1,
808                dst_argb,
809                dst_pos,
810                1,
811                rect.width,
812                max_allowed_diff,
813            ) {
814                rect.height -= 1; // Redundant row.
815                rect.y_offset += 1;
816            } else {
817                break;
818            }
819            j += 1;
820        }
821        if rect.height == 0 {
822            break 'search true;
823        }
824
825        // Bottom boundary.
826        let mut j = rect.y_offset + rect.height - 1;
827        while j >= rect.y_offset {
828            let src_pos = pixel(rect.x_offset, j, src_stride);
829            let dst_pos = pixel(rect.x_offset, j, dst_stride);
830            if compare_pixels(
831                src_argb,
832                src_pos,
833                1,
834                dst_argb,
835                dst_pos,
836                1,
837                rect.width,
838                max_allowed_diff,
839            ) {
840                rect.height -= 1; // Redundant row.
841            } else {
842                break;
843            }
844            j -= 1;
845        }
846        if rect.height == 0 {
847            break 'search true;
848        }
849
850        is_empty_rect(rect)
851    };
852    if no_change {
853        // NoChange:
854        rect.x_offset = 0;
855        rect.y_offset = 0;
856        rect.width = 0;
857        rect.height = 0;
858    }
859}
860
861// upstream: src/mux/anim_encode.c SnapToEvenOffsets
862/// Snap rectangle to even offsets (and adjust dimensions if needed).
863fn snap_to_even_offsets(rect: &mut FrameRectangle) {
864    rect.width += rect.x_offset & 1;
865    rect.height += rect.y_offset & 1;
866    rect.x_offset &= !1;
867    rect.y_offset &= !1;
868}
869
870// upstream: src/mux/anim_encode.c SubFrameParams
871/// The rectangles of one dispose method. C also keeps the views of the current
872/// canvas for the two rectangles (`sub_frame_ll`, `sub_frame_lossy`); the
873/// translation makes them where they are used (see the module documentation).
874#[derive(Clone, Copy, Debug, Default)]
875struct SubFrameParams {
876    /// Should try this set of parameters.
877    should_try: bool,
878    /// Frame with empty rectangle can be skipped.
879    empty_rect_allowed: bool,
880    /// Frame rectangle for lossless compression.
881    rect_ll: FrameRectangle,
882    /// Frame rectangle for lossy compression. Could be smaller than `rect_ll` as
883    /// pixels with small diffs can be ignored.
884    rect_lossy: FrameRectangle,
885}
886
887// upstream: src/mux/anim_encode.c SubFrameParamsInit
888/// C also initializes the two views (`WebPPictureInit`, which cannot fail for
889/// the current version). `SubFrameParamsFree` frees them; the views here are
890/// dropped where they are used, so it has no counterpart.
891fn sub_frame_params_init(should_try: bool, empty_rect_allowed: bool) -> SubFrameParams {
892    SubFrameParams {
893        should_try,
894        empty_rect_allowed,
895        ..SubFrameParams::default()
896    }
897}
898
899// upstream: src/mux/anim_encode.c GetSubRect
900/// Given previous and current canvas, picks the optimal rectangle for the
901/// current frame based on `is_lossless` and other parameters. Assumes that the
902/// initial guess `rect` is valid. C then makes the view of the rectangle; this
903/// checks the rectangle as `WebPPictureView` does and returns the result.
904#[expect(
905    clippy::too_many_arguments,
906    clippy::fn_params_excessive_bools,
907    reason = "the C signature without the view"
908)]
909fn get_sub_rect(
910    prev_canvas: &WebPPicture<'_>,
911    curr_canvas: &WebPPicture<'_>,
912    is_key_frame: bool,
913    is_first_frame: bool,
914    empty_rect_allowed: bool,
915    is_lossless: bool,
916    quality: f32,
917    rect: &mut FrameRectangle,
918) -> bool {
919    if !is_key_frame || is_first_frame {
920        // Optimize frame rectangle.
921        // Note: This behaves as expected for first frame, as 'prev_canvas' is
922        // initialized to a fully transparent canvas in the beginning.
923        minimize_change_rectangle(prev_canvas, curr_canvas, rect, is_lossless, quality);
924    }
925
926    if is_empty_rect(rect) {
927        if empty_rect_allowed {
928            // No need to get 'sub_frame'.
929            return true;
930        }
931        // Force a 1x1 rectangle.
932        rect.width = 1;
933        rect.height = 1;
934        debug_assert_eq!(rect.x_offset, 0);
935        debug_assert_eq!(rect.y_offset, 0);
936    }
937
938    snap_to_even_offsets(rect);
939    webp_picture_view(
940        curr_canvas,
941        rect.x_offset,
942        rect.y_offset,
943        rect.width,
944        rect.height,
945    )
946    .is_some()
947}
948
949// upstream: src/mux/anim_encode.c GetSubRects
950/// Picks optimal frame rectangle for both lossless and lossy compression. The
951/// initial guess for frame rectangles will be the full canvas.
952fn get_sub_rects(
953    prev_canvas: &WebPPicture<'_>,
954    curr_canvas: &WebPPicture<'_>,
955    is_key_frame: bool,
956    is_first_frame: bool,
957    quality: f32,
958    params: &mut SubFrameParams,
959) -> bool {
960    // Lossless frame rectangle.
961    params.rect_ll.x_offset = 0;
962    params.rect_ll.y_offset = 0;
963    params.rect_ll.width = curr_canvas.width;
964    params.rect_ll.height = curr_canvas.height;
965    if !get_sub_rect(
966        prev_canvas,
967        curr_canvas,
968        is_key_frame,
969        is_first_frame,
970        params.empty_rect_allowed,
971        true,
972        quality,
973        &mut params.rect_ll,
974    ) {
975        return false;
976    }
977    // Lossy frame rectangle.
978    params.rect_lossy = params.rect_ll; // seed with lossless rect.
979    get_sub_rect(
980        prev_canvas,
981        curr_canvas,
982        is_key_frame,
983        is_first_frame,
984        params.empty_rect_allowed,
985        false,
986        quality,
987        &mut params.rect_lossy,
988    )
989}
990
991// upstream: src/mux/anim_encode.c clip
992fn clip(v: i32, min_v: i32, max_v: i32) -> i32 {
993    if v < min_v {
994        min_v
995    } else if v > max_v {
996        max_v
997    } else {
998        v
999    }
1000}
1001
1002// upstream: src/mux/anim_encode.c WebPAnimEncoderRefineRect
1003/// Picks the optimal rectangle between two pictures, starting with initial
1004/// values of offsets and dimensions that are passed in. The initial values will
1005/// be clipped, if necessary, to make sure the rectangle is within the canvas.
1006/// `use_argb` must be true for both pictures (declared in `animi.h`). Returns
1007/// true on success; C also returns 0 for `NULL` pictures.
1008#[expect(
1009    clippy::too_many_arguments,
1010    reason = "the C signature with its four in/out parameters"
1011)]
1012#[must_use]
1013pub fn webp_anim_encoder_refine_rect(
1014    prev_canvas: &WebPPicture<'_>,
1015    curr_canvas: &WebPPicture<'_>,
1016    is_lossless: i32,
1017    quality: f32,
1018    x_offset: &mut i32,
1019    y_offset: &mut i32,
1020    width: &mut i32,
1021    height: &mut i32,
1022) -> bool {
1023    if prev_canvas.width != curr_canvas.width
1024        || prev_canvas.height != curr_canvas.height
1025        || prev_canvas.use_argb == 0
1026        || curr_canvas.use_argb == 0
1027    {
1028        return false;
1029    }
1030    let right = clip(*x_offset + *width, 0, curr_canvas.width);
1031    let left = clip(*x_offset, 0, curr_canvas.width - 1);
1032    let bottom = clip(*y_offset + *height, 0, curr_canvas.height);
1033    let top = clip(*y_offset, 0, curr_canvas.height - 1);
1034    let mut rect = FrameRectangle {
1035        x_offset: left,
1036        y_offset: top,
1037        ..FrameRectangle::default()
1038    };
1039    rect.width = clip(right - left, 0, curr_canvas.width - rect.x_offset);
1040    rect.height = clip(bottom - top, 0, curr_canvas.height - rect.y_offset);
1041    minimize_change_rectangle(
1042        prev_canvas,
1043        curr_canvas,
1044        &mut rect,
1045        is_lossless != 0,
1046        quality,
1047    );
1048    snap_to_even_offsets(&mut rect);
1049    *x_offset = rect.x_offset;
1050    *y_offset = rect.y_offset;
1051    *width = rect.width;
1052    *height = rect.height;
1053    true
1054}
1055
1056// upstream: src/mux/anim_encode.c DisposeFrameRectangle
1057fn dispose_frame_rectangle(
1058    dispose_method: WebPMuxAnimDispose,
1059    rect: &FrameRectangle,
1060    curr_canvas: &mut WebPPicture<'_>,
1061) {
1062    if dispose_method == WebPMuxAnimDispose::WEBP_MUX_DISPOSE_BACKGROUND {
1063        webp_util_clear_pic(curr_canvas, Some(rect));
1064    }
1065}
1066
1067// upstream: src/mux/anim_encode.c RectArea
1068fn rect_area(rect: &FrameRectangle) -> u32 {
1069    rect.width
1070        .cast_unsigned()
1071        .wrapping_mul(rect.height.cast_unsigned())
1072}
1073
1074// upstream: src/mux/anim_encode.c IsLosslessBlendingPossible
1075fn is_lossless_blending_possible(
1076    src: &WebPPicture<'_>,
1077    dst: &WebPPicture<'_>,
1078    rect: &FrameRectangle,
1079) -> bool {
1080    let (src_argb, dst_argb) = (argb(src), argb(dst));
1081    debug_assert!(src.width == dst.width && src.height == dst.height);
1082    debug_assert!(rect.x_offset + rect.width <= dst.width);
1083    debug_assert!(rect.y_offset + rect.height <= dst.height);
1084    for j in rect.y_offset..rect.y_offset + rect.height {
1085        for i in rect.x_offset..rect.x_offset + rect.width {
1086            let src_pixel = src_argb[pixel(i, j, src.argb_stride)];
1087            let dst_pixel = dst_argb[pixel(i, j, dst.argb_stride)];
1088            let dst_alpha = dst_pixel >> 24;
1089            if dst_alpha != 0xff && src_pixel != dst_pixel {
1090                // In this case, if we use blending, we can't attain the desired
1091                // 'dst_pixel' value for this pixel. So, blending is not possible.
1092                return false;
1093            }
1094        }
1095    }
1096    true
1097}
1098
1099// upstream: src/mux/anim_encode.c IsLossyBlendingPossible
1100fn is_lossy_blending_possible(
1101    src: &WebPPicture<'_>,
1102    dst: &WebPPicture<'_>,
1103    rect: &FrameRectangle,
1104    quality: f32,
1105) -> bool {
1106    let max_allowed_diff_lossy = quality_to_max_diff(quality);
1107    let (src_argb, dst_argb) = (argb(src), argb(dst));
1108    debug_assert!(src.width == dst.width && src.height == dst.height);
1109    debug_assert!(rect.x_offset + rect.width <= dst.width);
1110    debug_assert!(rect.y_offset + rect.height <= dst.height);
1111    for j in rect.y_offset..rect.y_offset + rect.height {
1112        for i in rect.x_offset..rect.x_offset + rect.width {
1113            let src_pixel = src_argb[pixel(i, j, src.argb_stride)];
1114            let dst_pixel = dst_argb[pixel(i, j, dst.argb_stride)];
1115            let dst_alpha = dst_pixel >> 24;
1116            if dst_alpha != 0xff
1117                && !pixels_are_similar(src_pixel, dst_pixel, max_allowed_diff_lossy)
1118            {
1119                // In this case, if we use blending, we can't attain the desired
1120                // 'dst_pixel' value for this pixel. So, blending is not possible.
1121                return false;
1122            }
1123        }
1124    }
1125    true
1126}
1127
1128// upstream: src/mux/anim_encode.c IncreaseTransparency
1129/// For pixels in `rect`, replace those pixels in `dst` that are same as `src`
1130/// by transparent pixels. Returns true if at least one pixel gets modified.
1131fn increase_transparency(
1132    src: &WebPPicture<'_>,
1133    rect: &FrameRectangle,
1134    dst: &mut WebPPicture<'_>,
1135) -> bool {
1136    let mut modified = false;
1137    debug_assert!(src.width == dst.width && src.height == dst.height);
1138    let (src_stride, dst_stride) = (src.argb_stride, dst.argb_stride);
1139    let psrc = argb(src);
1140    let pdst = argb_mut(dst);
1141    for j in rect.y_offset..rect.y_offset + rect.height {
1142        for i in rect.x_offset..rect.x_offset + rect.width {
1143            let (s, d) = (pixel(i, j, src_stride), pixel(i, j, dst_stride));
1144            if psrc[s] == pdst[d] && pdst[d] != TRANSPARENT_COLOR {
1145                pdst[d] = TRANSPARENT_COLOR;
1146                modified = true;
1147            }
1148        }
1149    }
1150    modified
1151}
1152
1153// upstream: src/mux/anim_encode.c FlattenSimilarBlocks
1154/// Replace similar blocks of pixels by a 'see-through' transparent block with
1155/// uniform average color. Assumes lossy compression is being used. Returns true
1156/// if at least one pixel gets modified.
1157fn flatten_similar_blocks(
1158    src: &WebPPicture<'_>,
1159    rect: &FrameRectangle,
1160    dst: &mut WebPPicture<'_>,
1161    quality: f32,
1162) -> bool {
1163    let max_allowed_diff_lossy = quality_to_max_diff(quality);
1164    let mut modified = false;
1165    let block_size = 8;
1166    let y_start = (rect.y_offset + block_size) & !(block_size - 1);
1167    let y_end = (rect.y_offset + rect.height) & !(block_size - 1);
1168    let x_start = (rect.x_offset + block_size) & !(block_size - 1);
1169    let x_end = (rect.x_offset + rect.width) & !(block_size - 1);
1170    debug_assert!(src.width == dst.width && src.height == dst.height);
1171    debug_assert_eq!(block_size & (block_size - 1), 0); // must be a power of 2
1172    let (src_stride, dst_stride) = (src.argb_stride, dst.argb_stride);
1173    let psrc = argb(src);
1174    let pdst = argb_mut(dst);
1175    // Iterate over each block and count similar pixels.
1176    let mut j = y_start;
1177    while j < y_end {
1178        let mut i = x_start;
1179        while i < x_end {
1180            let mut cnt = 0;
1181            let (mut avg_r, mut avg_g, mut avg_b) = (0, 0, 0);
1182            let src_block = pixel(i, j, src_stride);
1183            let dst_block = pixel(i, j, dst_stride);
1184            for y in 0..block_size {
1185                for x in 0..block_size {
1186                    let src_pixel = psrc[src_block + pixel(x, y, src_stride)];
1187                    let alpha = (src_pixel >> 24).cast_signed();
1188                    if alpha == 0xff
1189                        && pixels_are_similar(
1190                            src_pixel,
1191                            pdst[dst_block + pixel(x, y, dst_stride)],
1192                            max_allowed_diff_lossy,
1193                        )
1194                    {
1195                        cnt += 1;
1196                        avg_r += ((src_pixel >> 16) & 0xff).cast_signed();
1197                        avg_g += ((src_pixel >> 8) & 0xff).cast_signed();
1198                        avg_b += (src_pixel & 0xff).cast_signed();
1199                    }
1200                }
1201            }
1202            // If we have a fully similar block, we replace it with an
1203            // average transparent block. This compresses better in lossy mode.
1204            if cnt == block_size * block_size {
1205                // C: (0x00 << 24) | ..., the alpha byte is zero.
1206                let color =
1207                    (((avg_r / cnt) << 16) | ((avg_g / cnt) << 8) | (avg_b / cnt)).cast_unsigned();
1208                for y in 0..block_size {
1209                    for x in 0..block_size {
1210                        pdst[dst_block + pixel(x, y, dst_stride)] = color;
1211                    }
1212                }
1213                modified = true;
1214            }
1215            i += block_size;
1216        }
1217        j += block_size;
1218    }
1219    modified
1220}
1221
1222// upstream: src/mux/anim_encode.c EncodeFrame
1223/// Encodes `pic` with `config` into `memory`. C sets `pic->writer` to
1224/// `WebPMemoryWrite` with `custom_ptr = memory` and leaves them set; the
1225/// writer here is removed after the call, as it borrows the memory writer.
1226fn encode_frame(
1227    config: &WebPConfig,
1228    pic: &mut WebPPicture<'_>,
1229    memory: &mut WebPMemoryWriter,
1230) -> bool {
1231    pic.use_argb = 1;
1232    let shared = Rc::new(RefCell::new(core::mem::take(memory)));
1233    let writer = Rc::clone(&shared);
1234    pic.writer = Some(Box::new(move |data: &[u8]| {
1235        webp_memory_write(&mut writer.borrow_mut(), data)
1236    }));
1237    let ok = webp_encode(config, pic);
1238    pic.writer = None;
1239    *memory = match Rc::try_unwrap(shared) {
1240        Ok(cell) => cell.into_inner(),
1241        Err(_) => unreachable!("the writer that held the other reference is dropped"),
1242    };
1243    ok
1244}
1245
1246// upstream: src/mux/anim_encode.c Candidate
1247/// Struct representing a candidate encoded frame including its metadata.
1248#[derive(Clone, Debug, Default)]
1249struct Candidate {
1250    mem: WebPMemoryWriter,
1251    info: WebPMuxFrameInfo<'static>,
1252    rect: FrameRectangle,
1253    /// True if this candidate should be evaluated.
1254    evaluate: bool,
1255}
1256
1257// upstream: src/mux/anim_encode.c EncodeCandidate
1258/// Generates a candidate encoded frame given a picture and metadata.
1259fn encode_candidate(
1260    sub_frame: &mut WebPPicture<'_>,
1261    rect: &FrameRectangle,
1262    encoder_config: &WebPConfig,
1263    use_blending: bool,
1264    candidate: &mut Candidate,
1265) -> Result<(), WebPEncodingError> {
1266    let mut config = *encoder_config;
1267    *candidate = Candidate::default();
1268
1269    // Set frame rect and info.
1270    candidate.rect = *rect;
1271    candidate.info.id = WebPChunkId::WEBP_CHUNK_ANMF;
1272    candidate.info.x_offset = rect.x_offset;
1273    candidate.info.y_offset = rect.y_offset;
1274    candidate.info.dispose_method = WebPMuxAnimDispose::WEBP_MUX_DISPOSE_NONE; // Set later.
1275    candidate.info.blend_method = if use_blending {
1276        WebPMuxAnimBlend::WEBP_MUX_BLEND
1277    } else {
1278        WebPMuxAnimBlend::WEBP_MUX_NO_BLEND
1279    };
1280    candidate.info.duration = 0; // Set in next call to WebPAnimEncoderAdd().
1281
1282    // Encode picture.
1283    webp_memory_writer_init(&mut candidate.mem);
1284
1285    if config.lossless == 0 && use_blending {
1286        // Disable filtering to avoid blockiness in reconstructed frames at the
1287        // time of decoding.
1288        config.autofilter = 0;
1289        config.filter_strength = 0;
1290    }
1291    if !encode_frame(&config, sub_frame, &mut candidate.mem) {
1292        let error_code = sub_frame.error_code;
1293        webp_memory_writer_clear(&mut candidate.mem);
1294        return Err(error_code);
1295    }
1296
1297    candidate.evaluate = true;
1298    Ok(())
1299}
1300
1301// upstream: src/mux/anim_encode.c CopyCurrentCanvas
1302/// Copies the frame into the canvas copy when the copy was modified. C also
1303/// copies the frame's `progress_hook` and `user_data` into the copy; the views
1304/// borrow the frame's hook where they are encoded instead.
1305fn copy_current_canvas(enc: &mut WebPAnimEncoder<'_>, curr_canvas: &WebPPicture<'_>) {
1306    if enc.curr_canvas_copy_modified {
1307        webp_copy_pixels(curr_canvas, &mut enc.curr_canvas_copy);
1308        enc.curr_canvas_copy_modified = false;
1309    }
1310}
1311
1312// upstream: src/mux/anim_encode.c LL_DISP_NONE
1313const LL_DISP_NONE: usize = 0;
1314// upstream: src/mux/anim_encode.c LL_DISP_BG
1315const LL_DISP_BG: usize = 1;
1316// upstream: src/mux/anim_encode.c LOSSY_DISP_NONE
1317const LOSSY_DISP_NONE: usize = 2;
1318// upstream: src/mux/anim_encode.c LOSSY_DISP_BG
1319const LOSSY_DISP_BG: usize = 3;
1320// upstream: src/mux/anim_encode.c CANDIDATE_COUNT
1321const CANDIDATE_COUNT: usize = 4;
1322
1323// upstream: src/mux/anim_encode.c MIN_COLORS_LOSSY
1324const MIN_COLORS_LOSSY: i32 = 31; // Don't try lossy below this threshold.
1325// upstream: src/mux/anim_encode.c MAX_COLORS_LOSSLESS
1326const MAX_COLORS_LOSSLESS: i32 = 194; // Don't try lossless above this threshold.
1327
1328/// C's view of the `rect` rectangle of `canvas` (`WebPPictureView` in
1329/// `GetSubRect`), for an encoding: the picture borrows the canvas's ARGB
1330/// samples exclusively, so that `WebPEncode` writes into the canvas where C
1331/// writes through the view, and it reports progress through `progress_hook`,
1332/// the frame's hook that C copies into the view. Like a view, it has the
1333/// canvas's specifications, no writer and no statistics. No C counterpart.
1334fn sub_frame_view<'v>(
1335    canvas: &'v mut WebPPicture<'static>,
1336    rect: &FrameRectangle,
1337    progress_hook: Option<&'v mut crate::webp::encode::WebPProgressHook<'_>>,
1338) -> WebPPicture<'v> {
1339    // The canvas copy is an ARGB picture: C's view of a YUV picture, after an
1340    // encoding of WebPAnimEncoderAssemble left the copy in YUV, would need
1341    // another WebPAnimEncoderAdd after WebPAnimEncoderAssemble, which the
1342    // module documentation excludes (`# Excluded undefined behavior`, item 1).
1343    debug_assert!(canvas.use_argb != 0);
1344    let plane = canvas.argb.expect("the canvas has an ARGB plane");
1345    let offset = plane.offset + pixel(rect.x_offset, rect.y_offset, canvas.argb_stride);
1346    let mut view = WebPPicture {
1347        use_argb: canvas.use_argb,
1348        colorspace: canvas.colorspace,
1349        width: rect.width,
1350        height: rect.height,
1351        pad1: canvas.pad1,
1352        argb: Some(PlaneOffset {
1353            region: 0,
1354            offset: 0,
1355        }),
1356        argb_stride: canvas.argb_stride,
1357        pad2: canvas.pad2,
1358        extra_info_type: canvas.extra_info_type,
1359        error_code: canvas.error_code,
1360        pad3: canvas.pad3,
1361        pad6: canvas.pad6,
1362        ..WebPPicture::default()
1363    };
1364    let region = canvas
1365        .argb_storage
1366        .region_mut(plane.region)
1367        .expect("the canvas's ARGB region exists");
1368    view.argb_storage = PlaneStorage::External(vec![&mut region[offset..]]);
1369    if let Some(hook) = progress_hook {
1370        view.progress_hook = Some(Box::new(move |percent: i32| hook(percent)));
1371    }
1372    view
1373}
1374
1375// upstream: src/mux/anim_encode.c GenerateCandidates
1376/// Generates candidates for a given dispose method given pre-filled sub-frame
1377/// `params`.
1378#[expect(
1379    clippy::too_many_arguments,
1380    reason = "the C signature with the caller's frame"
1381)]
1382fn generate_candidates(
1383    enc: &mut WebPAnimEncoder<'_>,
1384    curr_frame: &mut WebPPicture<'_>,
1385    candidates: &mut [Candidate; CANDIDATE_COUNT],
1386    dispose_method: WebPMuxAnimDispose,
1387    is_lossless: bool,
1388    is_key_frame: bool,
1389    params: &SubFrameParams,
1390    config_ll: &WebPConfig,
1391    config_lossy: &WebPConfig,
1392) -> Result<(), WebPEncodingError> {
1393    let is_dispose_none = dispose_method == WebPMuxAnimDispose::WEBP_MUX_DISPOSE_NONE;
1394    let candidate_ll = if is_dispose_none {
1395        LL_DISP_NONE
1396    } else {
1397        LL_DISP_BG
1398    };
1399    let candidate_lossy = if is_dispose_none {
1400        LOSSY_DISP_NONE
1401    } else {
1402        LOSSY_DISP_BG
1403    };
1404
1405    copy_current_canvas(enc, curr_frame);
1406    // C: curr_canvas = &enc->curr_canvas_copy, prev_canvas = the previous canvas
1407    // of the dispose method; borrowed field by field below.
1408    let prev_canvas = if is_dispose_none {
1409        &enc.prev_canvas
1410    } else {
1411        &enc.prev_canvas_disposed
1412    };
1413    let use_blending_ll = !is_key_frame
1414        && is_lossless_blending_possible(prev_canvas, &enc.curr_canvas_copy, &params.rect_ll);
1415    let use_blending_lossy = !is_key_frame
1416        && is_lossy_blending_possible(
1417            prev_canvas,
1418            &enc.curr_canvas_copy,
1419            &params.rect_lossy,
1420            config_lossy.quality,
1421        );
1422
1423    // Pick candidates to be tried.
1424    let (evaluate_ll, evaluate_lossy) = if enc.options.allow_mixed == 0 {
1425        (is_lossless, !is_lossless)
1426    } else if enc.options.minimize_size != 0 {
1427        (true, true)
1428    } else {
1429        // Use a heuristic for trying lossless and/or lossy compression.
1430        let rect = &params.rect_ll;
1431        let sub_frame_ll = webp_picture_view(
1432            &enc.curr_canvas_copy,
1433            rect.x_offset,
1434            rect.y_offset,
1435            rect.width,
1436            rect.height,
1437        )
1438        .expect("GetSubRect checked the rectangle of the view");
1439        let num_colors = webp_get_color_palette(&sub_frame_ll, None);
1440        (
1441            num_colors < MAX_COLORS_LOSSLESS,
1442            num_colors >= MIN_COLORS_LOSSY,
1443        )
1444    };
1445
1446    // Generate candidates.
1447    if evaluate_ll {
1448        copy_current_canvas(enc, curr_frame);
1449        if use_blending_ll {
1450            let prev_canvas = if is_dispose_none {
1451                &enc.prev_canvas
1452            } else {
1453                &enc.prev_canvas_disposed
1454            };
1455            enc.curr_canvas_copy_modified =
1456                increase_transparency(prev_canvas, &params.rect_ll, &mut enc.curr_canvas_copy);
1457        }
1458        let mut sub_frame_ll = sub_frame_view(
1459            &mut enc.curr_canvas_copy,
1460            &params.rect_ll,
1461            curr_frame.progress_hook.as_mut(),
1462        );
1463        encode_candidate(
1464            &mut sub_frame_ll,
1465            &params.rect_ll,
1466            config_ll,
1467            use_blending_ll,
1468            &mut candidates[candidate_ll],
1469        )?;
1470    }
1471    if evaluate_lossy {
1472        copy_current_canvas(enc, curr_frame);
1473        if use_blending_lossy {
1474            let prev_canvas = if is_dispose_none {
1475                &enc.prev_canvas
1476            } else {
1477                &enc.prev_canvas_disposed
1478            };
1479            enc.curr_canvas_copy_modified = flatten_similar_blocks(
1480                prev_canvas,
1481                &params.rect_lossy,
1482                &mut enc.curr_canvas_copy,
1483                config_lossy.quality,
1484            );
1485        }
1486        let mut sub_frame_lossy = sub_frame_view(
1487            &mut enc.curr_canvas_copy,
1488            &params.rect_lossy,
1489            curr_frame.progress_hook.as_mut(),
1490        );
1491        encode_candidate(
1492            &mut sub_frame_lossy,
1493            &params.rect_lossy,
1494            config_lossy,
1495            use_blending_lossy,
1496            &mut candidates[candidate_lossy],
1497        )?;
1498        enc.curr_canvas_copy_modified = true;
1499    }
1500    Ok(())
1501}
1502
1503// upstream: src/mux/anim_encode.c GetEncodedData
1504/// Moves the written bytes of `memory` into `encoded_data` (C points
1505/// `encoded_data` at the writer's buffer, which it then owns).
1506fn get_encoded_data(memory: &mut WebPMemoryWriter, encoded_data: &mut WebPData<'static>) {
1507    let mut bytes = core::mem::take(&mut memory.mem);
1508    bytes.truncate(memory.size);
1509    encoded_data.bytes = Cow::Owned(bytes);
1510}
1511
1512// upstream: src/mux/anim_encode.c SetPreviousDisposeMethod
1513/// Sets dispose method of the previous frame to be `dispose_method`.
1514fn set_previous_dispose_method(enc: &mut WebPAnimEncoder<'_>, dispose_method: WebPMuxAnimDispose) {
1515    let position = enc.count.wrapping_sub(2);
1516    let prev = get_frame(enc, position);
1517    debug_assert!(enc.count >= 2); // As current and previous frames are in enc.
1518
1519    let undecided = enc.prev_candidate_undecided;
1520    let prev_enc_frame = &mut enc.encoded_frames[prev];
1521    if undecided {
1522        debug_assert_eq!(dispose_method, WebPMuxAnimDispose::WEBP_MUX_DISPOSE_NONE);
1523        prev_enc_frame.sub_frame.dispose_method = dispose_method;
1524        prev_enc_frame.key_frame.dispose_method = dispose_method;
1525    } else {
1526        let prev_info = if prev_enc_frame.is_key_frame {
1527            &mut prev_enc_frame.key_frame
1528        } else {
1529            &mut prev_enc_frame.sub_frame
1530        };
1531        prev_info.dispose_method = dispose_method;
1532    }
1533}
1534
1535// upstream: src/mux/anim_encode.c IncreasePreviousDuration
1536fn increase_previous_duration(enc: &mut WebPAnimEncoder<'_>, duration: i32) -> bool {
1537    const LOSSLESS_1X1_BYTES: [u8; 28] = [
1538        0x52, 0x49, 0x46, 0x46, 0x14, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50, 0x56, 0x50, 0x38,
1539        0x4c, 0x08, 0x00, 0x00, 0x00, 0x2f, 0x00, 0x00, 0x00, 0x10, 0x88, 0x88, 0x08,
1540    ];
1541    const LOSSY_1X1_BYTES: [u8; 72] = [
1542        0x52, 0x49, 0x46, 0x46, 0x40, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50, 0x56, 0x50, 0x38,
1543        0x58, 0x0a, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1544        0x41, 0x4c, 0x50, 0x48, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x56, 0x50, 0x38, 0x20, 0x18,
1545        0x00, 0x00, 0x00, 0x30, 0x01, 0x00, 0x9d, 0x01, 0x2a, 0x01, 0x00, 0x01, 0x00, 0x02, 0x00,
1546        0x34, 0x25, 0xa4, 0x00, 0x03, 0x70, 0x00, 0xfe, 0xfb, 0xfd, 0x50, 0x00,
1547    ];
1548    let position = enc.count.wrapping_sub(1);
1549    let prev = get_frame(enc, position);
1550
1551    debug_assert!(enc.count >= 1);
1552    debug_assert!(
1553        !enc.encoded_frames[prev].is_key_frame
1554            || enc.encoded_frames[prev].sub_frame.duration
1555                == enc.encoded_frames[prev].key_frame.duration
1556    );
1557    debug_assert_eq!(
1558        enc.encoded_frames[prev].sub_frame.duration,
1559        enc.encoded_frames[prev].sub_frame.duration & (MAX_DURATION - 1)
1560    );
1561    debug_assert_eq!(duration, duration & (MAX_DURATION - 1));
1562
1563    let new_duration = enc.encoded_frames[prev].sub_frame.duration + duration;
1564    if new_duration >= MAX_DURATION {
1565        // Special case.
1566        // Separate out previous frame from earlier merged frames to avoid
1567        // overflow. We add a 1x1 transparent frame for the previous frame, with
1568        // blending on.
1569        let rect = FrameRectangle {
1570            x_offset: 0,
1571            y_offset: 0,
1572            width: 1,
1573            height: 1,
1574        };
1575        let lossless_1x1 = WebPData {
1576            bytes: Cow::Borrowed(&LOSSLESS_1X1_BYTES),
1577        };
1578        let lossy_1x1 = WebPData {
1579            bytes: Cow::Borrowed(&LOSSY_1X1_BYTES),
1580        };
1581        let can_use_lossless = enc.last_config.lossless != 0 || enc.options.allow_mixed != 0;
1582        let curr = get_frame(enc, enc.count);
1583        let curr_enc_frame = &mut enc.encoded_frames[curr];
1584        curr_enc_frame.is_key_frame = false;
1585        curr_enc_frame.sub_frame.id = WebPChunkId::WEBP_CHUNK_ANMF;
1586        curr_enc_frame.sub_frame.x_offset = 0;
1587        curr_enc_frame.sub_frame.y_offset = 0;
1588        curr_enc_frame.sub_frame.dispose_method = WebPMuxAnimDispose::WEBP_MUX_DISPOSE_NONE;
1589        curr_enc_frame.sub_frame.blend_method = WebPMuxAnimBlend::WEBP_MUX_BLEND;
1590        curr_enc_frame.sub_frame.duration = duration;
1591        let source = if can_use_lossless {
1592            &lossless_1x1
1593        } else {
1594            &lossy_1x1
1595        };
1596        let Some(copy) = webp_data_copy(source) else {
1597            curr_enc_frame.sub_frame.bitstream = WebPData::default();
1598            return false;
1599        };
1600        curr_enc_frame.sub_frame.bitstream = copy;
1601        enc.count += 1;
1602        enc.count_since_key_frame += 1;
1603        enc.flush_count = enc.count - 1;
1604        enc.prev_candidate_undecided = false;
1605        enc.prev_rect = rect;
1606    } else {
1607        // Regular case.
1608        // Increase duration of the previous frame by 'duration'.
1609        enc.encoded_frames[prev].sub_frame.duration = new_duration;
1610        enc.encoded_frames[prev].key_frame.duration = new_duration;
1611    }
1612    true
1613}
1614
1615// upstream: src/mux/anim_encode.c PickBestCandidate
1616/// Pick the candidate encoded frame with smallest size and release other
1617/// candidates.
1618fn pick_best_candidate(
1619    enc: &mut WebPAnimEncoder<'_>,
1620    candidates: &mut [Candidate; CANDIDATE_COUNT],
1621    is_key_frame: bool,
1622    encoded_frame: usize,
1623) {
1624    let mut best_idx: Option<usize> = None;
1625    let mut best_size = usize::MAX;
1626    for (i, candidate) in candidates.iter().enumerate() {
1627        if candidate.evaluate {
1628            let candidate_size = candidate.mem.size;
1629            if candidate_size < best_size {
1630                best_idx = Some(i);
1631                best_size = candidate_size;
1632            }
1633        }
1634    }
1635    debug_assert!(best_idx.is_some());
1636    for (i, candidate) in candidates.iter_mut().enumerate() {
1637        if candidate.evaluate {
1638            if Some(i) == best_idx {
1639                let frame = &mut enc.encoded_frames[encoded_frame];
1640                let dst = if is_key_frame {
1641                    &mut frame.key_frame
1642                } else {
1643                    &mut frame.sub_frame
1644                };
1645                *dst = candidate.info.clone();
1646                get_encoded_data(&mut candidate.mem, &mut dst.bitstream);
1647                if !is_key_frame {
1648                    // Note: Previous dispose method only matters for non-keyframes.
1649                    // Also, we don't want to modify previous dispose method that was
1650                    // selected when a non key-frame was assumed.
1651                    let prev_dispose_method = if i == LL_DISP_NONE || i == LOSSY_DISP_NONE {
1652                        WebPMuxAnimDispose::WEBP_MUX_DISPOSE_NONE
1653                    } else {
1654                        WebPMuxAnimDispose::WEBP_MUX_DISPOSE_BACKGROUND
1655                    };
1656                    set_previous_dispose_method(enc, prev_dispose_method);
1657                }
1658                enc.prev_rect = candidate.rect; // save for next frame.
1659            } else {
1660                webp_memory_writer_clear(&mut candidate.mem);
1661                candidate.evaluate = false;
1662            }
1663        }
1664    }
1665}
1666
1667// upstream: src/mux/anim_encode.c SetFrame
1668/// Depending on the configuration, tries different compressions
1669/// (lossy/lossless), dispose methods, blending methods etc to encode the
1670/// current frame and outputs the best one in `encoded_frame`. `frame_skipped`
1671/// will be set to true if this frame should actually be skipped.
1672#[expect(clippy::too_many_lines, reason = "follows the C function")]
1673fn set_frame(
1674    enc: &mut WebPAnimEncoder<'_>,
1675    curr_frame: &mut WebPPicture<'_>,
1676    config: &WebPConfig,
1677    is_key_frame: bool,
1678    encoded_frame: usize,
1679    frame_skipped: &mut bool,
1680) -> Result<(), WebPEncodingError> {
1681    let mut candidates: [Candidate; CANDIDATE_COUNT] = Default::default();
1682    let is_lossless = config.lossless != 0;
1683    let consider_lossless = is_lossless || enc.options.allow_mixed != 0;
1684    let consider_lossy = !is_lossless || enc.options.allow_mixed != 0;
1685    let is_first_frame = enc.is_first_frame;
1686
1687    // First frame cannot be skipped as there is no 'previous frame' to merge it
1688    // to. So, empty rectangle is not allowed for the first frame.
1689    let empty_rect_allowed_none = !is_first_frame;
1690
1691    // Even if there is exact pixel match between 'disposed previous canvas' and
1692    // 'current canvas', we can't skip current frame, as there may not be exact
1693    // pixel match between 'previous canvas' and 'current canvas'. So, we don't
1694    // allow empty rectangle in this case.
1695    let empty_rect_allowed_bg = false;
1696
1697    // If current frame is a key-frame, dispose method of previous frame doesn't
1698    // matter, so we don't try dispose to background.
1699    // Also, if key-frame insertion is on, and previous frame could be picked as
1700    // either a sub-frame or a key-frame, then we can't be sure about what frame
1701    // rectangle would be disposed. In that case too, we don't try dispose to
1702    // background.
1703    let dispose_bg_possible = !is_key_frame && !enc.prev_candidate_undecided;
1704
1705    let mut config_ll = *config;
1706    let mut config_lossy = *config;
1707    config_ll.lossless = 1;
1708    config_lossy.lossless = 0;
1709    enc.last_config = *config;
1710    enc.last_config_reversed = if config.lossless != 0 {
1711        config_lossy
1712    } else {
1713        config_ll
1714    };
1715    *frame_skipped = false;
1716
1717    let mut dispose_none_params = sub_frame_params_init(true, empty_rect_allowed_none);
1718    let mut dispose_bg_params = sub_frame_params_init(false, empty_rect_allowed_bg);
1719
1720    let result = (|| {
1721        // Change-rectangle assuming previous frame was DISPOSE_NONE.
1722        if !get_sub_rects(
1723            &enc.prev_canvas,
1724            &enc.curr_canvas_copy,
1725            is_key_frame,
1726            is_first_frame,
1727            config_lossy.quality,
1728            &mut dispose_none_params,
1729        ) {
1730            return Err(WebPEncodingError::VP8_ENC_ERROR_INVALID_CONFIGURATION);
1731        }
1732
1733        if (consider_lossless && is_empty_rect(&dispose_none_params.rect_ll))
1734            || (consider_lossy && is_empty_rect(&dispose_none_params.rect_lossy))
1735        {
1736            // Don't encode the frame at all. Instead, the duration of the previous
1737            // frame will be increased later.
1738            debug_assert!(empty_rect_allowed_none);
1739            *frame_skipped = true;
1740            return Ok(());
1741        }
1742
1743        if dispose_bg_possible {
1744            // Change-rectangle assuming previous frame was DISPOSE_BACKGROUND.
1745            webp_copy_pixels(&enc.prev_canvas, &mut enc.prev_canvas_disposed);
1746            dispose_frame_rectangle(
1747                WebPMuxAnimDispose::WEBP_MUX_DISPOSE_BACKGROUND,
1748                &enc.prev_rect,
1749                &mut enc.prev_canvas_disposed,
1750            );
1751
1752            if !get_sub_rects(
1753                &enc.prev_canvas_disposed,
1754                &enc.curr_canvas_copy,
1755                is_key_frame,
1756                is_first_frame,
1757                config_lossy.quality,
1758                &mut dispose_bg_params,
1759            ) {
1760                return Err(WebPEncodingError::VP8_ENC_ERROR_INVALID_CONFIGURATION);
1761            }
1762            debug_assert!(!is_empty_rect(&dispose_bg_params.rect_ll));
1763            debug_assert!(!is_empty_rect(&dispose_bg_params.rect_lossy));
1764
1765            if enc.options.minimize_size != 0 {
1766                // Try both dispose methods.
1767                dispose_bg_params.should_try = true;
1768                dispose_none_params.should_try = true;
1769            } else if (is_lossless
1770                && rect_area(&dispose_bg_params.rect_ll) < rect_area(&dispose_none_params.rect_ll))
1771                || (!is_lossless
1772                    && rect_area(&dispose_bg_params.rect_lossy)
1773                        < rect_area(&dispose_none_params.rect_lossy))
1774            {
1775                dispose_bg_params.should_try = true; // Pick DISPOSE_BACKGROUND.
1776                dispose_none_params.should_try = false;
1777            }
1778        }
1779
1780        if dispose_none_params.should_try {
1781            generate_candidates(
1782                enc,
1783                curr_frame,
1784                &mut candidates,
1785                WebPMuxAnimDispose::WEBP_MUX_DISPOSE_NONE,
1786                is_lossless,
1787                is_key_frame,
1788                &dispose_none_params,
1789                &config_ll,
1790                &config_lossy,
1791            )?;
1792        }
1793
1794        if dispose_bg_params.should_try {
1795            debug_assert!(!enc.is_first_frame);
1796            debug_assert!(dispose_bg_possible);
1797            generate_candidates(
1798                enc,
1799                curr_frame,
1800                &mut candidates,
1801                WebPMuxAnimDispose::WEBP_MUX_DISPOSE_BACKGROUND,
1802                is_lossless,
1803                is_key_frame,
1804                &dispose_bg_params,
1805                &config_ll,
1806                &config_lossy,
1807            )?;
1808        }
1809
1810        pick_best_candidate(enc, &mut candidates, is_key_frame, encoded_frame);
1811        Ok(())
1812    })();
1813
1814    if result.is_err() {
1815        // Err:
1816        for candidate in &mut candidates {
1817            if candidate.evaluate {
1818                webp_memory_writer_clear(&mut candidate.mem);
1819            }
1820        }
1821    }
1822    // End: C calls SubFrameParamsFree on both parameter sets.
1823    result
1824}
1825
1826// upstream: src/mux/anim_encode.c KeyFramePenalty
1827/// Calculate the penalty incurred if we encode given frame as a key frame
1828/// instead of a sub-frame.
1829fn key_frame_penalty(encoded_frame: &EncodedFrame) -> i64 {
1830    let size = |data: &WebPData<'_>| i64::try_from(data.bytes.len()).expect("a size below 2^63");
1831    size(&encoded_frame.key_frame.bitstream) - size(&encoded_frame.sub_frame.bitstream)
1832}
1833
1834// upstream: src/mux/anim_encode.c CacheFrame
1835#[expect(clippy::too_many_lines, reason = "follows the C function")]
1836fn cache_frame(
1837    enc: &mut WebPAnimEncoder<'_>,
1838    curr_frame: &mut WebPPicture<'_>,
1839    config: &WebPConfig,
1840) -> bool {
1841    let mut ok = false;
1842    let mut frame_skipped = false;
1843    let mut error_code = WebPEncodingError::VP8_ENC_OK;
1844    let position = enc.count;
1845    let encoded_frame = get_frame(enc, position);
1846
1847    enc.count += 1;
1848
1849    'end: {
1850        if enc.is_first_frame {
1851            // Add this as a key-frame.
1852            if let Err(err) = set_frame(
1853                enc,
1854                curr_frame,
1855                config,
1856                true,
1857                encoded_frame,
1858                &mut frame_skipped,
1859            ) {
1860                error_code = err;
1861                break 'end;
1862            }
1863            debug_assert!(!frame_skipped); // First frame can't be skipped, even if empty.
1864            debug_assert!(position == 0 && enc.count == 1);
1865            enc.encoded_frames[encoded_frame].is_key_frame = true;
1866            enc.flush_count = 0;
1867            enc.count_since_key_frame = 0;
1868            enc.prev_candidate_undecided = false;
1869        } else {
1870            enc.count_since_key_frame += 1;
1871            if enc.count_since_key_frame <= enc.options.kmin {
1872                // Add this as a frame rectangle.
1873                if let Err(err) = set_frame(
1874                    enc,
1875                    curr_frame,
1876                    config,
1877                    false,
1878                    encoded_frame,
1879                    &mut frame_skipped,
1880                ) {
1881                    error_code = err;
1882                    break 'end;
1883                }
1884                if !frame_skipped {
1885                    enc.encoded_frames[encoded_frame].is_key_frame = false;
1886                    enc.flush_count = enc.count - 1;
1887                    enc.prev_candidate_undecided = false;
1888                }
1889            } else {
1890                // Add this as a frame rectangle to enc.
1891                if let Err(err) = set_frame(
1892                    enc,
1893                    curr_frame,
1894                    config,
1895                    false,
1896                    encoded_frame,
1897                    &mut frame_skipped,
1898                ) {
1899                    error_code = err;
1900                    break 'end;
1901                }
1902                if !frame_skipped {
1903                    let prev_rect_sub = enc.prev_rect;
1904
1905                    // Add this as a key-frame to enc, too.
1906                    if let Err(err) = set_frame(
1907                        enc,
1908                        curr_frame,
1909                        config,
1910                        true,
1911                        encoded_frame,
1912                        &mut frame_skipped,
1913                    ) {
1914                        error_code = err;
1915                        break 'end;
1916                    }
1917                    debug_assert!(!frame_skipped); // Key-frame cannot be an empty rectangle.
1918                    let prev_rect_key = enc.prev_rect;
1919
1920                    // Analyze size difference of the two variants.
1921                    let curr_delta = key_frame_penalty(&enc.encoded_frames[encoded_frame]);
1922                    if curr_delta <= enc.best_delta {
1923                        // Pick this as the key-frame.
1924                        if enc.keyframe != KEYFRAME_NONE {
1925                            let old_keyframe = get_frame(
1926                                enc,
1927                                usize::try_from(enc.keyframe).expect("a frame position"),
1928                            );
1929                            debug_assert!(enc.encoded_frames[old_keyframe].is_key_frame);
1930                            enc.encoded_frames[old_keyframe].is_key_frame = false;
1931                        }
1932                        enc.encoded_frames[encoded_frame].is_key_frame = true;
1933                        enc.prev_candidate_undecided = true;
1934                        enc.keyframe = i32::try_from(position).expect("at most size frames");
1935                        enc.best_delta = curr_delta;
1936                        enc.flush_count = enc.count - 1; // We can flush previous frames.
1937                    } else {
1938                        enc.encoded_frames[encoded_frame].is_key_frame = false;
1939                        enc.prev_candidate_undecided = false;
1940                    }
1941                    // Note: We need '>=' below because when kmin and kmax are both
1942                    // zero, count_since_key_frame will always be > kmax.
1943                    if enc.count_since_key_frame >= enc.options.kmax {
1944                        enc.flush_count = enc.count - 1;
1945                        enc.count_since_key_frame = 0;
1946                        enc.keyframe = KEYFRAME_NONE;
1947                        enc.best_delta = DELTA_INFINITY;
1948                    }
1949                    if !enc.prev_candidate_undecided {
1950                        enc.prev_rect = if enc.encoded_frames[encoded_frame].is_key_frame {
1951                            prev_rect_key
1952                        } else {
1953                            prev_rect_sub
1954                        };
1955                    }
1956                }
1957            }
1958        }
1959
1960        if !frame_skipped {
1961            // Update previous to previous and previous canvases for next call.
1962            webp_copy_pixels(curr_frame, &mut enc.prev_canvas);
1963            enc.is_first_frame = false;
1964        }
1965
1966        // Skip:
1967        ok = true;
1968        enc.in_frame_count += 1;
1969    }
1970
1971    // End:
1972    if !ok || frame_skipped {
1973        frame_release(&mut enc.encoded_frames[encoded_frame]);
1974        // We reset some counters, as the frame addition failed/was skipped.
1975        enc.count -= 1;
1976        if !enc.is_first_frame {
1977            enc.count_since_key_frame -= 1;
1978        }
1979        if !ok {
1980            mark_error2(
1981                enc,
1982                "ERROR adding frame. WebPEncodingError",
1983                error_code.0.cast_signed(),
1984            );
1985        }
1986    }
1987    curr_frame.error_code = error_code; // report error_code
1988    debug_assert!(ok || error_code != WebPEncodingError::VP8_ENC_OK);
1989    ok
1990}
1991
1992// upstream: src/mux/anim_encode.c FlushFrames
1993fn flush_frames(enc: &mut WebPAnimEncoder<'_>) -> bool {
1994    while enc.flush_count > 0 {
1995        let curr = get_frame(enc, 0);
1996        let frame = &enc.encoded_frames[curr];
1997        let info = if frame.is_key_frame {
1998            &frame.key_frame
1999        } else {
2000            &frame.sub_frame
2001        };
2002        if let Err(err) = webp_mux_push_frame(&mut enc.mux, info, 1) {
2003            mark_error2(enc, "ERROR adding frame. WebPMuxError", err.0);
2004            return false;
2005        }
2006        if enc.options.verbose != 0 {
2007            print_stderr(format_args!(
2008                "INFO: Added frame. offset:{},{} dispose:{} blend:{}\n",
2009                info.x_offset, info.y_offset, info.dispose_method.0, info.blend_method.0
2010            ));
2011        }
2012        enc.out_frame_count += 1;
2013        frame_release(&mut enc.encoded_frames[curr]);
2014        enc.start += 1;
2015        enc.flush_count -= 1;
2016        enc.count -= 1;
2017        if enc.keyframe != KEYFRAME_NONE {
2018            enc.keyframe -= 1;
2019        }
2020    }
2021
2022    if enc.count == 1 && enc.start != 0 {
2023        // Move enc->start to index 0.
2024        let enc_start_tmp = enc.start;
2025        enc.encoded_frames.swap(0, enc_start_tmp);
2026        frame_release(&mut enc.encoded_frames[enc_start_tmp]);
2027        enc.start = 0;
2028    }
2029    true
2030}
2031
2032// upstream: src/mux/anim_encode.c WebPAnimEncoderAdd
2033/// Optimizes the given frame for WebP, encodes it and adds it to the encoder.
2034/// The last call should be with `frame = None`, which indicates that no more
2035/// frames are to be added and determines the duration of the last frame.
2036/// Timestamps must not decrease. A YUV(A) frame is converted to ARGB in place,
2037/// which incurs a small loss. `None` configuration picks lossless defaults.
2038/// Returns false on error, with `frame.error_code` set (C also returns 0 for a
2039/// `NULL` encoder).
2040#[must_use]
2041pub fn webp_anim_encoder_add(
2042    enc: &mut WebPAnimEncoder<'_>,
2043    frame: Option<&mut WebPPicture<'_>>,
2044    timestamp: i32,
2045    encoder_config: Option<&WebPConfig>,
2046) -> bool {
2047    let mut frame = frame;
2048    mark_no_error(enc);
2049
2050    if enc.is_first_frame {
2051        enc.first_timestamp = timestamp;
2052    } else {
2053        // Make sure timestamps are non-decreasing (integer wrap-around is OK).
2054        let prev_frame_duration = timestamp
2055            .cast_unsigned()
2056            .wrapping_sub(enc.prev_timestamp.cast_unsigned());
2057        if prev_frame_duration >= MAX_DURATION.cast_unsigned() {
2058            if let Some(frame) = frame.as_deref_mut() {
2059                frame.error_code = WebPEncodingError::VP8_ENC_ERROR_INVALID_CONFIGURATION;
2060            }
2061            mark_error(enc, "ERROR adding frame: timestamps must be non-decreasing");
2062            return false;
2063        }
2064        if !increase_previous_duration(enc, prev_frame_duration.cast_signed()) {
2065            return false;
2066        }
2067        // IncreasePreviousDuration() may add a frame to avoid exceeding
2068        // MAX_DURATION which could cause CacheFrame() to over read
2069        // 'encoded_frames' before the next flush.
2070        if enc.count == enc.size && !flush_frames(enc) {
2071            return false;
2072        }
2073    }
2074
2075    let Some(frame) = frame else {
2076        // Special: last call.
2077        enc.got_null_frame = true;
2078        enc.prev_timestamp = timestamp;
2079        return true;
2080    };
2081
2082    if frame.width != enc.canvas_width || frame.height != enc.canvas_height {
2083        frame.error_code = WebPEncodingError::VP8_ENC_ERROR_INVALID_CONFIGURATION;
2084        mark_error(enc, "ERROR adding frame: Invalid frame dimensions");
2085        return false;
2086    }
2087
2088    if frame.use_argb == 0 {
2089        // Convert frame from YUV(A) to ARGB.
2090        if enc.options.verbose != 0 {
2091            print_stderr(format_args!(
2092                "WARNING: Converting frame from YUV(A) to ARGB format; this incurs a small loss.\n"
2093            ));
2094        }
2095        if webp_picture_yuva_to_argb(frame).is_err() {
2096            mark_error(enc, "ERROR converting frame from YUV(A) to ARGB");
2097            return false;
2098        }
2099    }
2100
2101    let mut config = WebPConfig::default();
2102    if let Some(encoder_config) = encoder_config {
2103        if !webp_validate_config(encoder_config) {
2104            mark_error(enc, "ERROR adding frame: Invalid WebPConfig");
2105            return false;
2106        }
2107        config = *encoder_config;
2108    } else {
2109        if !webp_config_init(&mut config) {
2110            mark_error(enc, "Cannot Init config");
2111            return false;
2112        }
2113        config.lossless = 1;
2114    }
2115    // C: enc->curr_canvas = frame, the argument of the calls below.
2116    debug_assert!(enc.curr_canvas_copy_modified);
2117    copy_current_canvas(enc, frame);
2118
2119    let ok = cache_frame(enc, frame, &config) && flush_frames(enc);
2120
2121    enc.curr_canvas_copy_modified = true;
2122    if ok {
2123        enc.prev_timestamp = timestamp;
2124    }
2125    ok
2126}
2127
2128// -----------------------------------------------------------------------------
2129// Bitstream assembly.
2130
2131// upstream: src/mux/anim_encode.c DecodeFrameOntoCanvas
2132/// Clears `canvas` and decodes the frame onto it at the frame's offsets. C
2133/// decodes into a view of the canvas (`MODE_BGRA`, whose bytes are the ARGB
2134/// words in native byte order); the translation decodes into a buffer with the
2135/// view's stride and size and copies its rows into the canvas, also after a
2136/// failed decoding, which leaves the canvas as C leaves it.
2137fn decode_frame_onto_canvas(frame: &WebPMuxFrameInfo<'_>, canvas: &mut WebPPicture<'_>) -> bool {
2138    let image = &frame.bitstream;
2139    let mut config = crate::webp::decode::WebPDecoderConfig::default();
2140    if !webp_init_decoder_config(&mut config) {
2141        return false;
2142    }
2143    webp_util_clear_pic(canvas, None);
2144    if webp_get_features(&image.bytes, &mut config.input).is_err() {
2145        return false;
2146    }
2147    let (view_offset, view_stride, view_width, view_height) = {
2148        let Some(sub_image) = webp_picture_view(
2149            canvas,
2150            frame.x_offset,
2151            frame.y_offset,
2152            config.input.width,
2153            config.input.height,
2154        ) else {
2155            return false;
2156        };
2157        let plane = sub_image.argb.expect("a view of an ARGB picture");
2158        (
2159            plane.offset,
2160            sub_image.argb_stride,
2161            sub_image.width,
2162            sub_image.height,
2163        )
2164    };
2165    let stride = view_stride * 4;
2166    let size = usize::try_from(stride * view_height).expect("a view inside the canvas");
2167    let mut rows = vec![0_u8; size];
2168    config.output.colorspace = WEBP_CSP_MODE::MODE_BGRA;
2169    config.output.u = WebPDecBufferPlanes::RGBA(WebPRGBABuffer {
2170        rgba: PlaneOffset::default(),
2171        stride,
2172        size,
2173    });
2174    config.output.storage = PlaneStorage::External(vec![&mut rows]);
2175
2176    let ok = webp_decode(&image.bytes, &mut config).is_ok();
2177    drop(config);
2178    let canvas_offset = canvas.argb.expect("the canvas has an ARGB plane").offset;
2179    let samples = argb_mut(canvas);
2180    for y in 0..view_height {
2181        let row = pixel(0, y, stride);
2182        let dst = view_offset - canvas_offset + pixel(0, y, view_stride);
2183        for x in 0..usize::try_from(view_width).expect("a positive width") {
2184            let at = row + 4 * x;
2185            samples[dst + x] =
2186                u32::from_ne_bytes([rows[at], rows[at + 1], rows[at + 2], rows[at + 3]]);
2187        }
2188    }
2189    ok
2190}
2191
2192// upstream: src/mux/anim_encode.c FrameToFullCanvas
2193/// Decodes `frame` onto the canvas copy and re-encodes the whole canvas with the
2194/// last configuration (and its reverse, if mixed compression is allowed, keeping
2195/// the smaller). Returns the encoded image, or `None` where C returns 0.
2196fn frame_to_full_canvas(
2197    enc: &mut WebPAnimEncoder<'_>,
2198    frame: &WebPMuxFrameInfo<'_>,
2199) -> Option<WebPData<'static>> {
2200    let mut mem1 = WebPMemoryWriter::default();
2201    let mut mem2 = WebPMemoryWriter::default();
2202    webp_memory_writer_init(&mut mem1);
2203    webp_memory_writer_init(&mut mem2);
2204    let mut full_image = WebPData::default();
2205
2206    let ok = (|| {
2207        let canvas_buf = &mut enc.curr_canvas_copy;
2208        if !decode_frame_onto_canvas(frame, canvas_buf) {
2209            return false;
2210        }
2211        if !encode_frame(&enc.last_config, canvas_buf, &mut mem1) {
2212            return false;
2213        }
2214        get_encoded_data(&mut mem1, &mut full_image);
2215
2216        if enc.options.allow_mixed != 0 {
2217            if !encode_frame(
2218                &enc.last_config_reversed,
2219                &mut enc.curr_canvas_copy,
2220                &mut mem2,
2221            ) {
2222                return false;
2223            }
2224            if mem2.size < full_image.bytes.len() {
2225                get_encoded_data(&mut mem2, &mut full_image);
2226                webp_memory_writer_clear(&mut mem1);
2227            } else {
2228                webp_memory_writer_clear(&mut mem2);
2229            }
2230        }
2231        true
2232    })();
2233    if !ok {
2234        // Err: C also frees the bytes of 'full_image' here, which its caller
2235        // frees again when the second encoding fails (the module documentation,
2236        // `# Excluded undefined behavior`, item 2).
2237        webp_memory_writer_clear(&mut mem1);
2238        webp_memory_writer_clear(&mut mem2);
2239        return None;
2240    }
2241    Some(full_image)
2242}
2243
2244// upstream: src/mux/anim_encode.c OptimizeSingleFrame
2245/// Convert a single-frame animation to a non-animated image if appropriate.
2246/// C creates the temporary mux over `webp_data` and replaces `webp_data` before
2247/// it deletes the mux; the mux borrows `webp_data` here, so it is dropped first.
2248fn optimize_single_frame(
2249    enc: &mut WebPAnimEncoder<'_>,
2250    webp_data: &mut WebPData<'static>,
2251) -> Result<(), WebPMuxError> {
2252    let mut replacement: Option<WebPData<'static>> = None;
2253    let result = {
2254        let input = WebPData {
2255            bytes: Cow::Borrowed(&webp_data.bytes[..]),
2256        };
2257        let Some(mut mux) = webp_mux_create(&input, 0) else {
2258            return Err(WebPMuxError::WEBP_MUX_BAD_DATA);
2259        };
2260        debug_assert_eq!(enc.out_frame_count, 1);
2261
2262        let result = (|| {
2263            let frame = webp_mux_get_frame(&mux, 1)?;
2264            if frame.id != WebPChunkId::WEBP_CHUNK_ANMF {
2265                return Ok(()); // Non-animation: nothing to do.
2266            }
2267            let (_canvas_width, _canvas_height) = webp_mux_get_canvas_size(&mux)?;
2268            let Some(full_image) = frame_to_full_canvas(enc, &frame) else {
2269                return Err(WebPMuxError::WEBP_MUX_BAD_DATA);
2270            };
2271            webp_mux_set_image(&mut mux, &full_image, 1)?;
2272            let webp_data2 = webp_mux_assemble(&mut mux)?;
2273
2274            if webp_data2.bytes.len() < input.bytes.len() {
2275                // Pick 'webp_data2' if smaller.
2276                replacement = Some(webp_data2);
2277            }
2278            Ok(())
2279        })();
2280        webp_mux_delete(mux);
2281        result
2282    };
2283    if let Some(webp_data2) = replacement {
2284        webp_data_clear(webp_data);
2285        *webp_data = webp_data2;
2286    }
2287    result
2288}
2289
2290/// C's `(int)(delta_time / (enc->in_frame_count - 1))`: the frame count is
2291/// converted to `double` and the quotient truncated to `int`.
2292#[expect(
2293    clippy::cast_precision_loss,
2294    clippy::cast_possible_truncation,
2295    reason = "C's conversions of size_t to double and of double to int"
2296)]
2297fn average(delta_time: f64, frames: usize) -> i32 {
2298    (delta_time / frames as f64) as i32
2299}
2300
2301// upstream: src/mux/anim_encode.c WebPAnimEncoderAssemble
2302/// Assembles all frames added so far into a WebP bitstream in `webp_data`. This
2303/// call should be preceded by a call to `WebPAnimEncoderAdd` with `frame =
2304/// None`; if not, the duration of the last frame will be internally estimated.
2305/// Returns true on success. `webp_data` is written as C writes it: emptied when
2306/// the mux assembly starts, and holding the assembled data when only the
2307/// single-frame optimization fails. C also returns 0 for `NULL` arguments; a
2308/// `NULL` `webp_data` records an error string, which the C ABI does.
2309#[must_use]
2310pub fn webp_anim_encoder_assemble(
2311    enc: &mut WebPAnimEncoder<'_>,
2312    webp_data: &mut WebPData<'static>,
2313) -> bool {
2314    mark_no_error(enc);
2315
2316    if enc.in_frame_count == 0 {
2317        mark_error(enc, "ERROR: No frames to assemble");
2318        return false;
2319    }
2320
2321    if !enc.got_null_frame && enc.in_frame_count > 1 && enc.count > 0 {
2322        // set duration of the last frame to be avg of durations of previous frames.
2323        let delta_time = f64::from(
2324            enc.prev_timestamp
2325                .cast_unsigned()
2326                .wrapping_sub(enc.first_timestamp.cast_unsigned()),
2327        );
2328        let average_duration = average(delta_time, enc.in_frame_count - 1);
2329        if !increase_previous_duration(enc, average_duration) {
2330            return false;
2331        }
2332    }
2333
2334    // Flush any remaining frames.
2335    enc.flush_count = enc.count;
2336    if !flush_frames(enc) {
2337        return false;
2338    }
2339
2340    let result: Result<(), WebPMuxError> = (|| {
2341        // Set definitive canvas size.
2342        webp_mux_set_canvas_size(&mut enc.mux, enc.canvas_width, enc.canvas_height)?;
2343
2344        webp_mux_set_animation_params(&mut enc.mux, &enc.options.anim_params)?;
2345
2346        // Assemble into a WebP bitstream.
2347        *webp_data = WebPData::default(); // C: memset in WebPMuxAssemble.
2348        *webp_data = webp_mux_assemble(&mut enc.mux)?;
2349
2350        if enc.out_frame_count == 1 {
2351            optimize_single_frame(enc, webp_data)?;
2352        }
2353        Ok(())
2354    })();
2355    if let Err(err) = result {
2356        mark_error2(enc, "ERROR assembling WebP", err.0);
2357        return false;
2358    }
2359    true
2360}
2361
2362// upstream: src/mux/anim_encode.c WebPAnimEncoderGetError
2363/// Get error string corresponding to the most recent call using `enc`: the
2364/// error of the last call, or an empty string if it succeeded. C returns `NULL`
2365/// for a `NULL` encoder; its string lives in the encoder until the next call.
2366#[must_use]
2367pub fn webp_anim_encoder_get_error<'e>(enc: &'e WebPAnimEncoder<'_>) -> &'e str {
2368    &enc.error_str
2369}
2370
2371// upstream: src/mux/anim_encode.c WebPAnimEncoderSetChunk
2372/// Adds a chunk with id `fourcc` and data `chunk_data` to the encoder's mux; any
2373/// existing chunk(s) with the same id are removed. Without copying, the data
2374/// must exist until `WebPAnimEncoderAssemble`. C first returns
2375/// `WEBP_MUX_INVALID_ARGUMENT` for a `NULL` encoder.
2376///
2377/// # Errors
2378///
2379/// As `WebPMuxSetChunk`.
2380pub fn webp_anim_encoder_set_chunk<'a>(
2381    enc: &mut WebPAnimEncoder<'a>,
2382    fourcc: &[u8; 4],
2383    chunk_data: &WebPData<'a>,
2384    copy_data: i32,
2385) -> Result<(), WebPMuxError> {
2386    webp_mux_set_chunk(&mut enc.mux, fourcc, chunk_data, copy_data)
2387}
2388
2389// upstream: src/mux/anim_encode.c WebPAnimEncoderGetChunk
2390/// Gets a reference to the data of the chunk with id `fourcc` in the encoder's
2391/// mux. C first returns `WEBP_MUX_INVALID_ARGUMENT` for a `NULL` encoder.
2392///
2393/// # Errors
2394///
2395/// As `WebPMuxGetChunk`.
2396pub fn webp_anim_encoder_get_chunk<'e, 'a>(
2397    enc: &'e WebPAnimEncoder<'a>,
2398    fourcc: &[u8; 4],
2399) -> Result<&'e WebPData<'a>, WebPMuxError> {
2400    webp_mux_get_chunk(&enc.mux, fourcc)
2401}
2402
2403// upstream: src/mux/anim_encode.c WebPAnimEncoderDeleteChunk
2404/// Deletes the chunk with the given `fourcc` from the encoder's mux. C first
2405/// returns `WEBP_MUX_INVALID_ARGUMENT` for a `NULL` encoder.
2406///
2407/// # Errors
2408///
2409/// As `WebPMuxDeleteChunk`.
2410pub fn webp_anim_encoder_delete_chunk(
2411    enc: &mut WebPAnimEncoder<'_>,
2412    fourcc: &[u8; 4],
2413) -> Result<(), WebPMuxError> {
2414    webp_mux_delete_chunk(&mut enc.mux, fourcc)
2415}