Skip to main content

webp/abi/
mux.rs

1// libwebp v1.6.0, src/webp/mux.h:
2//
3// Copyright 2011 Google Inc. All Rights Reserved.
4//
5// Use of this source code is governed by a BSD-style license
6// that can be found in the COPYING file in the root of the source
7// tree. An additional intellectual property rights grant can be found
8// in the file PATENTS. All contributing project authors may
9// be found in the AUTHORS file in the root of the source tree.
10// -----------------------------------------------------------------------------
11//
12//  RIFF container manipulation and encoding for WebP images.
13//
14// Authors: Urvang (urvang@google.com)
15//          Vikas (vikasa@google.com)
16
17//! C ABI export of `src/webp/mux.h` from libwebp v1.6.0.
18//!
19//! Mirrors the header's structs with `repr(C)` and converts them to the
20//! safe representations at the boundary; see
21//! `docs/adr/0004-c-abi-boundary.md`.
22//!
23//! Work package: WP15 (mux and animation encode).
24//!
25//! # Objects
26//!
27//! - A C `WebPMux*` is a heap box of the translation's mux, and a
28//!   `WebPAnimEncoder*` a heap box of the translation's encoder with a buffer
29//!   for its error string; the `Delete` functions drop them.
30//! - The translation's mux keeps the chunks that it is given without copying
31//!   (`copy_data == 0`) as borrowed bytes, so the caller's bytes are lent to it
32//!   as a `WebPData` that borrows them for `'static`, under the header's
33//!   contract that they exist as long as the mux reads them ("it must exist for
34//!   the lifetime of the mux object" for `WebPMuxCreate()`, "until a call to
35//!   `WebPMuxAssemble()`" for the setters). Unlike the demux ABI no box over the
36//!   caller's `WebPData` is needed: the mux borrows the bytes, not the struct.
37//!   Bytes given with copying are lent only for the call, which copies them.
38//! - `WebPMuxFrameInfo` is mirrored with C's field order and reuses the public
39//!   `WebPData` mirror of `src/abi/demux.rs`; `WebPMuxAnimParams` and
40//!   `WebPAnimEncoderOptions` have no pointers and are shared with
41//!   `src/webp/mux.rs`; `WebPMuxError` and `WebPChunkId` are the newtypes of
42//!   `src/webp/mux.rs` over C's enum types. `tests/wp15_abi_layout.rs` checks
43//!   the layouts.
44//! - Data that C allocates for the caller (`WebPMuxAssemble()`,
45//!   `WebPMuxGetFrame()`, `WebPAnimEncoderAssemble()`) is a block of the
46//!   platform `malloc` (`malloc_copy`), which `WebPDataClear()` releases with
47//!   `WebPFree()`. Data that C returns from inside the mux
48//!   (`WebPMuxGetChunk()`, `WebPAnimEncoderGetChunk()`) points into the mux; C's
49//!   `NULL` bytes of an empty copied chunk are a null pointer.
50//! - `WebPAnimEncoderAdd()` converts the caller's frame for the call as
51//!   `src/abi/encode.rs` converts pictures (`with_picture`), lending the ARGB
52//!   plane, or the YUVA planes that the conversion to ARGB reads, and writes
53//!   the results back: the error code and, after a conversion, the new ARGB
54//!   plane. The frame's progress hook is called with the frame's pointer, where
55//!   C passes its view of the encoder's canvas (`# Deviations from upstream`,
56//!   item 1).
57//! - The error string that `WebPAnimEncoderGetError()` returns lives in the
58//!   encoder's box, NUL-terminated in `ERROR_STR_MAX_LENGTH` bytes, and is
59//!   updated by every call that changes it, as C's string is.
60//!
61//! # Restrictions
62//!
63//! Bytes lent to a mux are an immutable Rust slice while the mux may read
64//! them, so they must not change then; C would read the changed bytes. A
65//! frame's progress hook must not touch the frame (see the module
66//! documentation of `src/abi/encode.rs`).
67//!
68//! # Deviations from upstream
69//!
70//! Changes of representation that the ADRs allow, or behavior that the Rust
71//! side cannot reproduce exactly. Each records the reason.
72//!
73//! 1. **C ABI frames.** `WebPAnimEncoderAdd` converts the frame with
74//!    `with_picture` of `src/abi/encode.rs`; a frame that it cannot lend (the
75//!    rejected layouts of `src/abi/encode.rs`: a negative stride over several
76//!    rows, overlapping planes, a misaligned ARGB plane) records
77//!    `VP8_ENC_ERROR_INVALID_CONFIGURATION` and the error string "ERROR adding
78//!    frame: the C ABI cannot lend the frame's planes.", where C would encode
79//!    it. The frame's C hook is called with the frame's pointer
80//!    (`progress_closure(hook, frame)`), where C copies `progress_hook` and
81//!    `user_data` from the frame into the canvas copy (`anim_encode.c` lines
82//!    834 and 835) and calls the hook with its sub-frame view's pointer:
83//!    `user_data` matches, the pointer identity does not. A hook must not touch
84//!    the frame (see the module documentation of `src/abi/encode.rs`).
85//!
86//! # Checks not applicable
87//!
88//! These checks do not apply, or cannot be made, with the reason:
89//!
90//! 1. **`NULL` arguments and `NULL` bytes** exist only at the C ABI (PORTING
91//!    rule 8); every `NULL` case of `mux.h` is compared there. The Rust API
92//!    takes references, and an empty `WebPData` it is given is an empty,
93//!    non-null slice (C rejects only `NULL` bytes).
94//! 2. **`WebPAnimEncoderRefineRect`** is declared in an internal header, so the
95//!    C ABI does not export it; the probe and the test call it on each side
96//!    directly.
97
98use core::ffi::{c_char, c_int};
99use core::ptr;
100use core::slice;
101use std::borrow::Cow;
102
103use crate::abi::demux::WebPData;
104use crate::abi::encode::{Mode, WebPPicture, progress_closure, with_picture};
105use crate::abi::types::malloc_copy;
106use crate::mux::anim_encode::{self as anim, WebPAnimEncoder as RsAnimEncoder};
107use crate::mux::muxedit as edit;
108use crate::mux::muxi::{CHUNK_INDEX, WebPMux as RsMux};
109use crate::mux::muxinternal::{self as internal, chunk_get_index_from_four_cc};
110use crate::mux::muxread as read;
111use crate::webp::encode::WebPConfig;
112use crate::webp::format_constants::MAX_CHUNK_PAYLOAD;
113use crate::webp::mux::{
114    WEBP_MUX_ABI_VERSION, WebPAnimEncoderOptions, WebPChunkId, WebPMuxAnimParams, WebPMuxError,
115    WebPMuxFrameInfo as RsFrameInfo,
116};
117use crate::webp::mux_types::{WebPData as RsData, WebPMuxAnimBlend, WebPMuxAnimDispose};
118use crate::webp::types::webp_abi_is_incompatible;
119
120// upstream: src/webp/format_constants.h MAX_IMAGE_AREA
121const MAX_IMAGE_AREA: u64 = crate::webp::format_constants::MAX_IMAGE_AREA;
122// upstream: src/mux/anim_encode.c ERROR_STR_MAX_LENGTH
123const ERROR_STR_MAX_LENGTH: usize = 100;
124
125//------------------------------------------------------------------------------
126// Mirrors and objects
127
128// upstream: src/webp/mux.h WebPMuxFrameInfo
129/// Encapsulates data about a single frame (C layout).
130#[repr(C)]
131#[derive(Clone, Copy, Debug)]
132pub struct WebPMuxFrameInfo {
133    /// Image data: can be a raw VP8/VP8L bitstream or a single-image WebP file.
134    pub bitstream: WebPData,
135    /// x-offset of the frame.
136    pub x_offset: c_int,
137    /// y-offset of the frame.
138    pub y_offset: c_int,
139    /// Duration of the frame (in milliseconds).
140    pub duration: c_int,
141    /// Frame type: should be one of `WEBP_CHUNK_ANMF` or `WEBP_CHUNK_IMAGE`.
142    pub id: WebPChunkId,
143    /// Disposal method for the frame.
144    pub dispose_method: WebPMuxAnimDispose,
145    /// Blend operation for the frame.
146    pub blend_method: WebPMuxAnimBlend,
147    /// Padding for later use.
148    pub pad: [u32; 1],
149}
150
151/// The object behind a C `WebPMux*` (C: `struct WebPMux`, opaque in the
152/// header): the translation's mux over lent bytes.
153pub type WebPMux = RsMux<'static>;
154
155/// The object behind a C `WebPAnimEncoder*` (C: `struct WebPAnimEncoder`).
156pub struct WebPAnimEncoder {
157    /// The translation's encoder.
158    enc: RsAnimEncoder<'static>,
159    /// The error string as C keeps it: NUL-terminated (C: `error_str`).
160    error: [c_char; ERROR_STR_MAX_LENGTH],
161}
162
163impl WebPAnimEncoder {
164    /// Copies the encoder's error string into `error`, where C keeps it.
165    fn sync_error(&mut self) {
166        let message = anim::webp_anim_encoder_get_error(&self.enc).as_bytes();
167        copy_error_bytes(&mut self.error, message);
168    }
169}
170
171//------------------------------------------------------------------------------
172// Helpers
173
174fn copy_error_bytes(error: &mut [c_char; ERROR_STR_MAX_LENGTH], message: &[u8]) {
175    let length = message.len().min(ERROR_STR_MAX_LENGTH - 1);
176    for (target, &byte) in error.iter_mut().zip(&message[..length]) {
177        *target = c_char::from_ne_bytes([byte]);
178    }
179    error[length] = 0;
180}
181
182/// Writes an output parameter that the caller checked for null.
183///
184/// # Safety
185///
186/// `ptr` points to a writable `T`.
187unsafe fn put<T>(ptr: *mut T, value: T) {
188    // SAFETY: a valid, writable `T` (caller's contract).
189    unsafe { ptr.write(value) };
190}
191
192/// The bytes of a C `WebPData` as a `WebPData` that borrows them.
193///
194/// # Safety
195///
196/// `data.bytes` is not null and points to `data.size` readable bytes, which
197/// stay valid and unchanged while the translation may read them: for the call
198/// when it copies them, for as long as the mux keeps them otherwise (the
199/// header's contract).
200unsafe fn lend(data: &WebPData) -> RsData<'static> {
201    // SAFETY: readable for `size` bytes and valid while borrowed (caller's
202    // contract).
203    let bytes: &'static [u8] = unsafe { slice::from_raw_parts(data.bytes, data.size) };
204    RsData {
205        bytes: Cow::Borrowed(bytes),
206    }
207}
208
209/// The C view of bytes inside a mux: a null pointer for C's `NULL` bytes (an
210/// empty copy), the bytes' address otherwise.
211fn data_to_c(data: &RsData<'_>) -> WebPData {
212    WebPData {
213        bytes: if crate::mux::muxi::data_is_null(data) {
214            ptr::null()
215        } else {
216            data.bytes.as_ptr()
217        },
218        size: data.bytes.len(),
219    }
220}
221
222/// Bytes that C allocates for the caller: a block of the platform `malloc`,
223/// which `WebPFree()` releases; `None` when the allocation fails.
224fn data_to_caller(data: &RsData<'_>) -> Option<WebPData> {
225    let block = malloc_copy(&data.bytes);
226    (!block.is_null()).then_some(WebPData {
227        bytes: block,
228        size: data.bytes.len(),
229    })
230}
231
232/// The four characters at `fourcc`.
233///
234/// # Safety
235///
236/// `fourcc` is not null and points to four readable characters.
237unsafe fn read_fourcc(fourcc: *const c_char) -> [u8; 4] {
238    // SAFETY: four readable characters (caller's contract).
239    unsafe { fourcc.cast::<[u8; 4]>().read_unaligned() }
240}
241
242/// The mux behind a C `WebPMux*`, or `None` for null.
243///
244/// # Safety
245///
246/// `mux` is null or a live mux of this library that no other reference uses.
247unsafe fn mux_mut<'m>(mux: *mut WebPMux) -> Option<&'m mut RsMux<'static>> {
248    // SAFETY: null or a live mux (caller's contract).
249    unsafe { mux.as_mut() }
250}
251
252/// The mux behind a C `const WebPMux*`, or `None` for null.
253///
254/// # Safety
255///
256/// `mux` is null or a live mux of this library.
257unsafe fn mux_ref<'m>(mux: *const WebPMux) -> Option<&'m RsMux<'static>> {
258    // SAFETY: null or a live mux (caller's contract).
259    unsafe { mux.as_ref() }
260}
261
262/// The encoder behind a C `WebPAnimEncoder*`, or `None` for null.
263///
264/// # Safety
265///
266/// `enc` is null or a live encoder of this library that no other reference
267/// uses.
268unsafe fn encoder<'e>(enc: *mut WebPAnimEncoder) -> Option<&'e mut WebPAnimEncoder> {
269    // SAFETY: null or a live encoder (caller's contract).
270    unsafe { enc.as_mut() }
271}
272
273/// The C code of a result.
274fn code<T>(result: &Result<T, WebPMuxError>) -> WebPMuxError {
275    WebPMuxError::of(result)
276}
277
278//------------------------------------------------------------------------------
279// Life of a Mux object
280
281// upstream: src/mux/muxinternal.c WebPGetMuxVersion
282/// Returns the version number of the mux library, packed in hexadecimal using
283/// 8 bits for each of major/minor/revision. E.g: v2.5.7 is 0x020507.
284#[unsafe(export_name = "WebPGetMuxVersion")]
285#[must_use]
286pub extern "C" fn webp_get_mux_version() -> c_int {
287    internal::webp_get_mux_version()
288}
289
290// upstream: src/mux/muxedit.c WebPNewInternal
291/// Internal, version-checked, entry point of `WebPMuxNew()`: an empty mux, or
292/// null for a version mismatch.
293#[unsafe(export_name = "WebPNewInternal")]
294#[must_use]
295pub extern "C" fn webp_new_internal(version: c_int) -> *mut WebPMux {
296    match edit::webp_new_internal(version) {
297        Some(mux) => Box::into_raw(Box::new(mux)),
298        None => ptr::null_mut(),
299    }
300}
301
302// upstream: src/mux/muxedit.c WebPMuxDelete
303/// Deletes the mux object.
304///
305/// # Safety
306///
307/// `mux` is null or a mux of this library that is not used again.
308#[unsafe(export_name = "WebPMuxDelete")]
309pub unsafe extern "C" fn webp_mux_delete(mux: *mut WebPMux) {
310    if mux.is_null() {
311        return;
312    }
313    // SAFETY: a mux of this library, which the caller gives up.
314    let mux = unsafe { Box::from_raw(mux) };
315    edit::webp_mux_delete(*mux);
316}
317
318//------------------------------------------------------------------------------
319// Mux creation.
320
321// upstream: src/mux/muxread.c WebPMuxCreateInternal
322/// Internal, version-checked, entry point of `WebPMuxCreate()`: a mux from WebP
323/// RIFF data, or null for invalid data or a memory error. With `copy_data ==
324/// 0` the mux keeps pointers into the bitstream, which must exist for the
325/// lifetime of the mux.
326///
327/// # Safety
328///
329/// `bitstream` is null or a valid `WebPData` whose bytes are readable; without
330/// copying they stay valid and unchanged until `WebPMuxDelete()`.
331#[unsafe(export_name = "WebPMuxCreateInternal")]
332#[must_use]
333pub unsafe extern "C" fn webp_mux_create_internal(
334    bitstream: *const WebPData,
335    copy_data: c_int,
336    version: c_int,
337) -> *mut WebPMux {
338    if webp_abi_is_incompatible(version, WEBP_MUX_ABI_VERSION) {
339        return ptr::null_mut(); // version mismatch
340    }
341    // SAFETY: null or a valid `WebPData` (caller's contract).
342    let Some(bitstream) = (unsafe { bitstream.as_ref() }) else {
343        return ptr::null_mut();
344    };
345    if bitstream.bytes.is_null() {
346        return ptr::null_mut();
347    }
348    // SAFETY: readable bytes, valid while the mux keeps them (caller's
349    // contract).
350    let data = unsafe { lend(bitstream) };
351    match read::webp_mux_create_internal(&data, copy_data, version) {
352        Some(mux) => Box::into_raw(Box::new(mux)),
353        None => ptr::null_mut(),
354    }
355}
356
357//------------------------------------------------------------------------------
358// Non-image chunks.
359
360// upstream: src/mux/muxedit.c WebPMuxSetChunk
361/// Adds a chunk with id `fourcc` and data `chunk_data` in the mux object; any
362/// existing chunk(s) with the same id are removed. Without copying the data
363/// must exist until a call to `WebPMuxAssemble()`.
364///
365/// # Safety
366///
367/// `mux` is null or a live mux of this library; `fourcc` is null or four
368/// readable characters; `chunk_data` is null or a valid `WebPData` whose
369/// non-null bytes are readable for `size` when it is at most
370/// `MAX_CHUNK_PAYLOAD`, and without copying stay valid and unchanged while the
371/// mux keeps them.
372#[unsafe(export_name = "WebPMuxSetChunk")]
373#[must_use]
374pub unsafe extern "C" fn webp_mux_set_chunk(
375    mux: *mut WebPMux,
376    fourcc: *const c_char,
377    chunk_data: *const WebPData,
378    copy_data: c_int,
379) -> WebPMuxError {
380    // SAFETY: null or a live mux (caller's contract).
381    let mux = unsafe { mux_mut(mux) };
382    // SAFETY: null or a valid `WebPData` (caller's contract).
383    let chunk_data = unsafe { chunk_data.as_ref() };
384    let (Some(mux), Some(chunk_data)) = (mux, chunk_data) else {
385        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
386    };
387    if fourcc.is_null()
388        || chunk_data.bytes.is_null()
389        || chunk_data.size as u64 > u64::from(MAX_CHUNK_PAYLOAD)
390    {
391        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
392    }
393    // SAFETY: four readable characters (checked non-null; caller's contract).
394    let tag = unsafe { read_fourcc(fourcc) };
395    // SAFETY: readable bytes of a checked size, valid while the mux keeps them
396    // (caller's contract).
397    let data = unsafe { lend(chunk_data) };
398    code(&edit::webp_mux_set_chunk(mux, &tag, &data, copy_data))
399}
400
401// upstream: src/mux/muxread.c WebPMuxGetChunk
402/// Gets a reference to the data of the chunk with id `fourcc` in the mux
403/// object; the caller must not free it. On `WEBP_MUX_NOT_FOUND` for a known
404/// chunk type `*chunk_data` is reset, as C's `MuxGet` does.
405///
406/// # Safety
407///
408/// `mux` is null or a live mux of this library; `fourcc` is null or four
409/// readable characters; `chunk_data` is null or writable.
410#[unsafe(export_name = "WebPMuxGetChunk")]
411#[must_use]
412pub unsafe extern "C" fn webp_mux_get_chunk(
413    mux: *const WebPMux,
414    fourcc: *const c_char,
415    chunk_data: *mut WebPData,
416) -> WebPMuxError {
417    // SAFETY: null or a live mux (caller's contract).
418    let Some(mux) = (unsafe { mux_ref(mux) }) else {
419        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
420    };
421    if fourcc.is_null() || chunk_data.is_null() {
422        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
423    }
424    // SAFETY: four readable characters (checked non-null; caller's contract).
425    let tag = unsafe { read_fourcc(fourcc) };
426    // SAFETY: a writable `WebPData` (checked non-null; caller's contract).
427    unsafe { get_chunk(read::webp_mux_get_chunk(mux, &tag), &tag, chunk_data) }
428}
429
430/// Writes the result of a chunk getter as C's `WebPMuxGetChunk()` does.
431///
432/// # Safety
433///
434/// `chunk_data` points to a writable `WebPData`.
435unsafe fn get_chunk(
436    result: Result<&RsData<'_>, WebPMuxError>,
437    tag: &[u8; 4],
438    chunk_data: *mut WebPData,
439) -> WebPMuxError {
440    match result {
441        Ok(data) => {
442            // SAFETY: writable (caller's contract).
443            unsafe { put(chunk_data, data_to_c(data)) };
444            WebPMuxError::WEBP_MUX_OK
445        }
446        Err(err) => {
447            if err == WebPMuxError::WEBP_MUX_NOT_FOUND
448                && chunk_get_index_from_four_cc(tag) != CHUNK_INDEX::IDX_UNKNOWN
449            {
450                // C: WebPDataInit(data) in MuxGet.
451                let empty = WebPData {
452                    bytes: ptr::null(),
453                    size: 0,
454                };
455                // SAFETY: writable (caller's contract).
456                unsafe { put(chunk_data, empty) };
457            }
458            err
459        }
460    }
461}
462
463// upstream: src/mux/muxedit.c WebPMuxDeleteChunk
464/// Deletes the chunk with the given `fourcc` from the mux object.
465///
466/// # Safety
467///
468/// `mux` is null or a live mux of this library; `fourcc` is null or four
469/// readable characters.
470#[unsafe(export_name = "WebPMuxDeleteChunk")]
471#[must_use]
472pub unsafe extern "C" fn webp_mux_delete_chunk(
473    mux: *mut WebPMux,
474    fourcc: *const c_char,
475) -> WebPMuxError {
476    // SAFETY: null or a live mux (caller's contract).
477    let Some(mux) = (unsafe { mux_mut(mux) }) else {
478        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
479    };
480    if fourcc.is_null() {
481        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
482    }
483    // SAFETY: four readable characters (checked non-null; caller's contract).
484    let tag = unsafe { read_fourcc(fourcc) };
485    code(&edit::webp_mux_delete_chunk(mux, &tag))
486}
487
488//------------------------------------------------------------------------------
489// Images.
490
491// upstream: src/mux/muxedit.c WebPMuxSetImage
492/// Sets the (non-animated) image in the mux object; any existing images
493/// (including frames) are removed. Without copying the data must exist until a
494/// call to `WebPMuxAssemble()`.
495///
496/// # Safety
497///
498/// `mux` is null or a live mux of this library; `bitstream` is null or a valid
499/// `WebPData` whose non-null bytes are readable for `size` when it is at most
500/// `MAX_CHUNK_PAYLOAD`, and without copying stay valid and unchanged while the
501/// mux keeps them.
502#[unsafe(export_name = "WebPMuxSetImage")]
503#[must_use]
504pub unsafe extern "C" fn webp_mux_set_image(
505    mux: *mut WebPMux,
506    bitstream: *const WebPData,
507    copy_data: c_int,
508) -> WebPMuxError {
509    // SAFETY: null or a live mux (caller's contract).
510    let mux = unsafe { mux_mut(mux) };
511    // SAFETY: null or a valid `WebPData` (caller's contract).
512    let bitstream = unsafe { bitstream.as_ref() };
513    let (Some(mux), Some(bitstream)) = (mux, bitstream) else {
514        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
515    };
516    if bitstream.bytes.is_null() || bitstream.size as u64 > u64::from(MAX_CHUNK_PAYLOAD) {
517        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
518    }
519    // SAFETY: readable bytes of a checked size, valid while the mux keeps them
520    // (caller's contract).
521    let data = unsafe { lend(bitstream) };
522    code(&edit::webp_mux_set_image(mux, &data, copy_data))
523}
524
525// upstream: src/mux/muxedit.c WebPMuxPushFrame
526/// Adds a frame at the end of the mux object; `frame->id` must be
527/// `WEBP_CHUNK_ANMF`. Without copying the data must exist until a call to
528/// `WebPMuxAssemble()`.
529///
530/// # Safety
531///
532/// `mux` is null or a live mux of this library; `frame` is null or a valid
533/// frame whose non-null bitstream bytes are readable for their size when it is
534/// at most `MAX_CHUNK_PAYLOAD`, and without copying stay valid and unchanged
535/// while the mux keeps them.
536#[unsafe(export_name = "WebPMuxPushFrame")]
537#[must_use]
538pub unsafe extern "C" fn webp_mux_push_frame(
539    mux: *mut WebPMux,
540    frame: *const WebPMuxFrameInfo,
541    copy_data: c_int,
542) -> WebPMuxError {
543    // SAFETY: null or a live mux (caller's contract).
544    let mux = unsafe { mux_mut(mux) };
545    // SAFETY: null or a valid frame (caller's contract).
546    let frame = unsafe { frame.as_ref() };
547    let (Some(mux), Some(frame)) = (mux, frame) else {
548        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
549    };
550    if frame.id != WebPChunkId::WEBP_CHUNK_ANMF {
551        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
552    }
553    if frame.bitstream.bytes.is_null() || frame.bitstream.size as u64 > u64::from(MAX_CHUNK_PAYLOAD)
554    {
555        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
556    }
557    let info = RsFrameInfo {
558        // SAFETY: readable bytes of a checked size, valid while the mux keeps
559        // them (caller's contract).
560        bitstream: unsafe { lend(&frame.bitstream) },
561        x_offset: frame.x_offset,
562        y_offset: frame.y_offset,
563        duration: frame.duration,
564        id: frame.id,
565        dispose_method: frame.dispose_method,
566        blend_method: frame.blend_method,
567        pad: frame.pad,
568    };
569    code(&edit::webp_mux_push_frame(mux, &info, copy_data))
570}
571
572// upstream: src/mux/muxread.c WebPMuxGetFrame
573/// Gets the nth frame from the mux object (`nth = 0` is the last position).
574/// The bitstream is a single-image WebP file allocated for the caller, who
575/// releases it with `WebPDataClear()`. On failure `*frame` is unchanged;
576/// `pad` is never written.
577///
578/// # Safety
579///
580/// `mux` is null or a live mux of this library; `frame` is null or writable.
581#[unsafe(export_name = "WebPMuxGetFrame")]
582#[must_use]
583pub unsafe extern "C" fn webp_mux_get_frame(
584    mux: *const WebPMux,
585    nth: u32,
586    frame: *mut WebPMuxFrameInfo,
587) -> WebPMuxError {
588    // SAFETY: null or a live mux (caller's contract).
589    let Some(mux) = (unsafe { mux_ref(mux) }) else {
590        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
591    };
592    if frame.is_null() {
593        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
594    }
595    let info = match read::webp_mux_get_frame(mux, nth) {
596        Ok(info) => info,
597        Err(err) => return err,
598    };
599    // C writes the fields and then allocates the bitstream; a failed
600    // allocation leaves them written. The fields are written one by one, so
601    // `pad` keeps the caller's value and the frame may be uninitialized.
602    let bitstream = data_to_caller(&info.bitstream);
603    // SAFETY: a writable frame (checked non-null; caller's contract); only
604    // the field's address is computed.
605    let field = unsafe { &raw mut (*frame).x_offset };
606    // SAFETY: the writable field.
607    unsafe { put(field, info.x_offset) };
608    // SAFETY: as above.
609    let field = unsafe { &raw mut (*frame).y_offset };
610    // SAFETY: as above.
611    unsafe { put(field, info.y_offset) };
612    // SAFETY: as above.
613    let field = unsafe { &raw mut (*frame).duration };
614    // SAFETY: as above.
615    unsafe { put(field, info.duration) };
616    // SAFETY: as above.
617    let field = unsafe { &raw mut (*frame).id };
618    // SAFETY: as above.
619    unsafe { put(field, info.id) };
620    // SAFETY: as above.
621    let field = unsafe { &raw mut (*frame).dispose_method };
622    // SAFETY: as above.
623    unsafe { put(field, info.dispose_method) };
624    // SAFETY: as above.
625    let field = unsafe { &raw mut (*frame).blend_method };
626    // SAFETY: as above.
627    unsafe { put(field, info.blend_method) };
628    let Some(bitstream) = bitstream else {
629        return WebPMuxError::WEBP_MUX_MEMORY_ERROR;
630    };
631    // SAFETY: as above.
632    let field = unsafe { &raw mut (*frame).bitstream };
633    // SAFETY: as above.
634    unsafe { put(field, bitstream) };
635    WebPMuxError::WEBP_MUX_OK
636}
637
638// upstream: src/mux/muxedit.c WebPMuxDeleteFrame
639/// Deletes a frame from the mux object (`nth = 0` is the last position).
640///
641/// # Safety
642///
643/// `mux` is null or a live mux of this library.
644#[unsafe(export_name = "WebPMuxDeleteFrame")]
645#[must_use]
646pub unsafe extern "C" fn webp_mux_delete_frame(mux: *mut WebPMux, nth: u32) -> WebPMuxError {
647    // SAFETY: null or a live mux (caller's contract).
648    let Some(mux) = (unsafe { mux_mut(mux) }) else {
649        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
650    };
651    code(&edit::webp_mux_delete_frame(mux, nth))
652}
653
654//------------------------------------------------------------------------------
655// Animation.
656
657// upstream: src/mux/muxedit.c WebPMuxSetAnimationParams
658/// Sets the animation parameters in the mux object; any existing ANIM chunks
659/// are removed.
660///
661/// # Safety
662///
663/// `mux` is null or a live mux of this library; `params` is null or valid.
664#[unsafe(export_name = "WebPMuxSetAnimationParams")]
665#[must_use]
666pub unsafe extern "C" fn webp_mux_set_animation_params(
667    mux: *mut WebPMux,
668    params: *const WebPMuxAnimParams,
669) -> WebPMuxError {
670    // SAFETY: null or a live mux (caller's contract).
671    let mux = unsafe { mux_mut(mux) };
672    // SAFETY: null or valid (caller's contract).
673    let params = unsafe { params.as_ref() };
674    let (Some(mux), Some(params)) = (mux, params) else {
675        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
676    };
677    code(&edit::webp_mux_set_animation_params(mux, params))
678}
679
680// upstream: src/mux/muxread.c WebPMuxGetAnimationParams
681/// Gets the animation parameters from the mux object.
682///
683/// # Safety
684///
685/// `mux` is null or a live mux of this library; `params` is null or writable.
686#[unsafe(export_name = "WebPMuxGetAnimationParams")]
687#[must_use]
688pub unsafe extern "C" fn webp_mux_get_animation_params(
689    mux: *const WebPMux,
690    params: *mut WebPMuxAnimParams,
691) -> WebPMuxError {
692    // SAFETY: null or a live mux (caller's contract).
693    let Some(mux) = (unsafe { mux_ref(mux) }) else {
694        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
695    };
696    if params.is_null() {
697        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
698    }
699    match read::webp_mux_get_animation_params(mux) {
700        Ok(value) => {
701            // SAFETY: writable (checked non-null; caller's contract).
702            unsafe { put(params, value) };
703            WebPMuxError::WEBP_MUX_OK
704        }
705        Err(err) => err,
706    }
707}
708
709//------------------------------------------------------------------------------
710// Misc Utilities.
711
712// upstream: src/mux/muxedit.c WebPMuxSetCanvasSize
713/// Sets the canvas size for the mux object; `(0, 0)` takes the bounding box of
714/// the frames at `WebPMuxAssemble()`.
715///
716/// # Safety
717///
718/// `mux` is null or a live mux of this library.
719#[unsafe(export_name = "WebPMuxSetCanvasSize")]
720#[must_use]
721pub unsafe extern "C" fn webp_mux_set_canvas_size(
722    mux: *mut WebPMux,
723    width: c_int,
724    height: c_int,
725) -> WebPMuxError {
726    // SAFETY: null or a live mux (caller's contract).
727    let Some(mux) = (unsafe { mux_mut(mux) }) else {
728        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
729    };
730    code(&edit::webp_mux_set_canvas_size(mux, width, height))
731}
732
733// upstream: src/mux/muxread.c WebPMuxGetCanvasSize
734/// Gets the canvas size from the mux object.
735///
736/// # Safety
737///
738/// `mux` is null or a live mux of this library; `width` and `height` are null
739/// or writable.
740#[unsafe(export_name = "WebPMuxGetCanvasSize")]
741#[must_use]
742pub unsafe extern "C" fn webp_mux_get_canvas_size(
743    mux: *const WebPMux,
744    width: *mut c_int,
745    height: *mut c_int,
746) -> WebPMuxError {
747    // SAFETY: null or a live mux (caller's contract).
748    let Some(mux) = (unsafe { mux_ref(mux) }) else {
749        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
750    };
751    if width.is_null() || height.is_null() {
752        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
753    }
754    match read::webp_mux_get_canvas_size(mux) {
755        Ok((w, h)) => {
756            // SAFETY: writable (checked non-null; caller's contract).
757            unsafe { put(width, w) };
758            // SAFETY: writable (checked non-null; caller's contract).
759            unsafe { put(height, h) };
760            WebPMuxError::WEBP_MUX_OK
761        }
762        Err(err) => err,
763    }
764}
765
766// upstream: src/mux/muxread.c WebPMuxGetFeatures
767/// Gets the feature flags from the mux object.
768///
769/// # Safety
770///
771/// `mux` is null or a live mux of this library; `flags` is null or writable.
772#[unsafe(export_name = "WebPMuxGetFeatures")]
773#[must_use]
774pub unsafe extern "C" fn webp_mux_get_features(
775    mux: *const WebPMux,
776    flags: *mut u32,
777) -> WebPMuxError {
778    // SAFETY: null or a live mux (caller's contract).
779    let Some(mux) = (unsafe { mux_ref(mux) }) else {
780        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
781    };
782    if flags.is_null() {
783        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
784    }
785    match read::webp_mux_get_features(mux) {
786        Ok(value) => {
787            // SAFETY: writable (checked non-null; caller's contract).
788            unsafe { put(flags, value) };
789            WebPMuxError::WEBP_MUX_OK
790        }
791        Err(err) => err,
792    }
793}
794
795// upstream: src/mux/muxread.c WebPMuxNumChunks
796/// Gets number of chunks with the given `id` in the mux object.
797///
798/// # Safety
799///
800/// `mux` is null or a live mux of this library; `num_elements` is null or
801/// writable.
802#[unsafe(export_name = "WebPMuxNumChunks")]
803#[must_use]
804pub unsafe extern "C" fn webp_mux_num_chunks(
805    mux: *const WebPMux,
806    id: WebPChunkId,
807    num_elements: *mut c_int,
808) -> WebPMuxError {
809    // SAFETY: null or a live mux (caller's contract).
810    let Some(mux) = (unsafe { mux_ref(mux) }) else {
811        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
812    };
813    if num_elements.is_null() {
814        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
815    }
816    match read::webp_mux_num_chunks(mux, id) {
817        Ok(value) => {
818            // SAFETY: writable (checked non-null; caller's contract).
819            unsafe { put(num_elements, value) };
820            WebPMuxError::WEBP_MUX_OK
821        }
822        Err(err) => err,
823    }
824}
825
826// upstream: src/mux/muxedit.c WebPMuxAssemble
827/// Assembles all chunks in WebP RIFF format into `assembled_data`, which is
828/// allocated for the caller and released with `WebPDataClear()`; it is zeroed
829/// first, so that it is empty on failure.
830///
831/// # Safety
832///
833/// `mux` is null or a live mux of this library whose lent bytes are valid;
834/// `assembled_data` is null or writable.
835#[unsafe(export_name = "WebPMuxAssemble")]
836#[must_use]
837pub unsafe extern "C" fn webp_mux_assemble(
838    mux: *mut WebPMux,
839    assembled_data: *mut WebPData,
840) -> WebPMuxError {
841    if assembled_data.is_null() {
842        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
843    }
844    let empty = WebPData {
845        bytes: ptr::null(),
846        size: 0,
847    };
848    // Clean up returned data, in case something goes wrong.
849    // SAFETY: writable (checked non-null; caller's contract).
850    unsafe { put(assembled_data, empty) };
851    // SAFETY: null or a live mux (caller's contract).
852    let Some(mux) = (unsafe { mux_mut(mux) }) else {
853        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
854    };
855    let data = match edit::webp_mux_assemble(mux) {
856        Ok(data) => data,
857        Err(err) => return err,
858    };
859    let Some(data) = data_to_caller(&data) else {
860        return WebPMuxError::WEBP_MUX_MEMORY_ERROR;
861    };
862    // SAFETY: writable (checked non-null; caller's contract).
863    unsafe { put(assembled_data, data) };
864    WebPMuxError::WEBP_MUX_OK
865}
866
867//------------------------------------------------------------------------------
868// WebPAnimEncoder API
869
870// upstream: src/mux/anim_encode.c WebPAnimEncoderOptionsInitInternal
871/// Internal, version-checked, entry point of `WebPAnimEncoderOptionsInit()`.
872/// Returns false for null options or a version mismatch. It writes only the
873/// fields that C's `DefaultEncoderOptions` writes, not the padding.
874///
875/// # Safety
876///
877/// `enc_options` is null or writable.
878#[unsafe(export_name = "WebPAnimEncoderOptionsInitInternal")]
879#[must_use]
880pub unsafe extern "C" fn webp_anim_encoder_options_init_internal(
881    enc_options: *mut WebPAnimEncoderOptions,
882    abi_version: c_int,
883) -> c_int {
884    if enc_options.is_null() {
885        return 0;
886    }
887    let mut defaults = WebPAnimEncoderOptions::default();
888    if !anim::webp_anim_encoder_options_init_internal(&mut defaults, abi_version) {
889        return 0;
890    }
891    // C writes one field at a time; the options may be uninitialized.
892    // SAFETY: writable options (checked non-null; caller's contract); only the
893    // field's address is computed.
894    let field = unsafe { &raw mut (*enc_options).anim_params };
895    // SAFETY: the writable field.
896    unsafe { put(field, defaults.anim_params) };
897    // SAFETY: as above.
898    let field = unsafe { &raw mut (*enc_options).minimize_size };
899    // SAFETY: as above.
900    unsafe { put(field, defaults.minimize_size) };
901    // SAFETY: as above.
902    let field = unsafe { &raw mut (*enc_options).kmin };
903    // SAFETY: as above.
904    unsafe { put(field, defaults.kmin) };
905    // SAFETY: as above.
906    let field = unsafe { &raw mut (*enc_options).kmax };
907    // SAFETY: as above.
908    unsafe { put(field, defaults.kmax) };
909    // SAFETY: as above.
910    let field = unsafe { &raw mut (*enc_options).allow_mixed };
911    // SAFETY: as above.
912    unsafe { put(field, defaults.allow_mixed) };
913    // SAFETY: as above.
914    let field = unsafe { &raw mut (*enc_options).verbose };
915    // SAFETY: as above.
916    unsafe { put(field, defaults.verbose) };
917    1
918}
919
920/// The fields of the caller's options that the encoder reads; C copies the
921/// whole struct, whose padding the encoder never reads.
922///
923/// # Safety
924///
925/// `options` points to valid options.
926unsafe fn read_options(options: *const WebPAnimEncoderOptions) -> WebPAnimEncoderOptions {
927    /// Reads one field.
928    ///
929    /// # Safety
930    ///
931    /// `field` points to an initialized `T`.
932    unsafe fn get<T>(field: *const T) -> T {
933        // SAFETY: an initialized field (caller's contract).
934        unsafe { field.read() }
935    }
936    // SAFETY: valid options (caller's contract); only the field's address is
937    // computed.
938    let anim_params = unsafe { &raw const (*options).anim_params };
939    // SAFETY: as above.
940    let minimize_size = unsafe { &raw const (*options).minimize_size };
941    // SAFETY: as above.
942    let kmin = unsafe { &raw const (*options).kmin };
943    // SAFETY: as above.
944    let kmax = unsafe { &raw const (*options).kmax };
945    // SAFETY: as above.
946    let allow_mixed = unsafe { &raw const (*options).allow_mixed };
947    // SAFETY: as above.
948    let verbose = unsafe { &raw const (*options).verbose };
949    WebPAnimEncoderOptions {
950        // SAFETY: an initialized field of valid options.
951        anim_params: unsafe { get(anim_params) },
952        // SAFETY: as above.
953        minimize_size: unsafe { get(minimize_size) },
954        // SAFETY: as above.
955        kmin: unsafe { get(kmin) },
956        // SAFETY: as above.
957        kmax: unsafe { get(kmax) },
958        // SAFETY: as above.
959        allow_mixed: unsafe { get(allow_mixed) },
960        // SAFETY: as above.
961        verbose: unsafe { get(verbose) },
962        padding: [0; 4],
963    }
964}
965
966// upstream: src/mux/anim_encode.c WebPAnimEncoderNewInternal
967/// Internal, version-checked, entry point of `WebPAnimEncoderNew()`: an encoder
968/// for a `width` by `height` canvas, with default options for null options;
969/// null for a version mismatch, invalid dimensions or a memory error.
970///
971/// # Safety
972///
973/// `enc_options` is null or valid options.
974#[unsafe(export_name = "WebPAnimEncoderNewInternal")]
975#[must_use]
976pub unsafe extern "C" fn webp_anim_encoder_new_internal(
977    width: c_int,
978    height: c_int,
979    enc_options: *const WebPAnimEncoderOptions,
980    abi_version: c_int,
981) -> *mut WebPAnimEncoder {
982    // C reads the options only once these checks have passed.
983    if webp_abi_is_incompatible(abi_version, WEBP_MUX_ABI_VERSION)
984        || width <= 0
985        || height <= 0
986        || u64::from(width.unsigned_abs()) * u64::from(height.unsigned_abs()) >= MAX_IMAGE_AREA
987    {
988        return ptr::null_mut();
989    }
990    let options = if enc_options.is_null() {
991        None
992    } else {
993        // SAFETY: valid options (checked non-null; caller's contract).
994        Some(unsafe { read_options(enc_options) })
995    };
996    let Some(enc) =
997        anim::webp_anim_encoder_new_internal(width, height, options.as_ref(), abi_version)
998    else {
999        return ptr::null_mut();
1000    };
1001    let mut handle = Box::new(WebPAnimEncoder {
1002        enc,
1003        error: [0; ERROR_STR_MAX_LENGTH],
1004    });
1005    handle.sync_error();
1006    Box::into_raw(handle)
1007}
1008
1009// upstream: src/mux/anim_encode.c WebPAnimEncoderAdd
1010/// Optimizes the given frame for WebP, encodes it and adds it to the encoder;
1011/// a null frame ends the sequence. Returns false on error, with
1012/// `frame->error_code` set. A frame whose planes this module cannot lend (see
1013/// `src/abi/encode.rs`) records `VP8_ENC_ERROR_INVALID_CONFIGURATION` and an
1014/// error string, where C would encode it.
1015///
1016/// # Safety
1017///
1018/// `enc` is null or a live encoder of this library; `frame` is null or a valid
1019/// picture whose ARGB plane (or YUVA planes, without `use_argb`) is readable for
1020/// its dimensions and whose memory fields are null or blocks of the platform
1021/// `malloc`; `config` is null or a valid configuration.
1022#[unsafe(export_name = "WebPAnimEncoderAdd")]
1023#[must_use]
1024pub unsafe extern "C" fn webp_anim_encoder_add(
1025    enc: *mut WebPAnimEncoder,
1026    frame: *mut WebPPicture,
1027    timestamp: c_int,
1028    encoder_config: *const WebPConfig,
1029) -> c_int {
1030    // SAFETY: null or a live encoder (caller's contract).
1031    let Some(handle) = (unsafe { encoder(enc) }) else {
1032        return 0;
1033    };
1034    // SAFETY: null or a valid configuration (caller's contract).
1035    let config: Option<WebPConfig> = unsafe { encoder_config.as_ref() }.copied();
1036    // SAFETY: null or a valid picture (caller's contract); the borrow ends
1037    // before the conversion.
1038    let ok = match unsafe { frame.as_ref() } {
1039        None => anim::webp_anim_encoder_add(&mut handle.enc, None, timestamp, config.as_ref()),
1040        Some(c) => {
1041            let hook = c.progress_hook;
1042            // WebPCopyPixels reads the ARGB plane; WebPPictureYUVAToARGB reads
1043            // the YUVA planes and makes the ARGB plane.
1044            let modes = if c.use_argb != 0 {
1045                (Mode::Discard, Mode::Read)
1046            } else {
1047                (Mode::Read, Mode::Discard)
1048            };
1049            let enc = &mut handle.enc;
1050            // SAFETY: the planes of the modes are readable (caller's contract).
1051            let result = unsafe {
1052                with_picture(frame, modes, true, |rs| {
1053                    rs.progress_hook = hook.map(|hook| progress_closure(hook, frame));
1054                    let ok = anim::webp_anim_encoder_add(enc, Some(rs), timestamp, config.as_ref());
1055                    rs.progress_hook = None;
1056                    ok
1057                })
1058            };
1059            if let Some((ok, written)) = result {
1060                ok && written
1061            } else {
1062                anim::mark_error(
1063                    &mut handle.enc,
1064                    "ERROR adding frame: the C ABI cannot lend the frame's planes",
1065                );
1066                false
1067            }
1068        }
1069    };
1070    handle.sync_error();
1071    c_int::from(ok)
1072}
1073
1074/// A slice that no caller passes: marks a `WebPData` that
1075/// `webp_anim_encoder_assemble` did not write.
1076static UNWRITTEN: [u8; 1] = [0];
1077
1078// upstream: src/mux/anim_encode.c WebPAnimEncoderAssemble
1079/// Assembles all frames added so far into a WebP bitstream in `webp_data`,
1080/// which is allocated for the caller and released with `WebPDataClear()`.
1081/// Returns true on success. `webp_data` is written where C writes it.
1082///
1083/// # Safety
1084///
1085/// `enc` is null or a live encoder of this library whose lent chunk bytes are
1086/// valid; `webp_data` is null or writable.
1087#[unsafe(export_name = "WebPAnimEncoderAssemble")]
1088#[must_use]
1089pub unsafe extern "C" fn webp_anim_encoder_assemble(
1090    enc: *mut WebPAnimEncoder,
1091    webp_data: *mut WebPData,
1092) -> c_int {
1093    // SAFETY: null or a live encoder (caller's contract).
1094    let Some(handle) = (unsafe { encoder(enc) }) else {
1095        return 0;
1096    };
1097    if webp_data.is_null() {
1098        anim::mark_error(&mut handle.enc, "ERROR assembling: NULL input");
1099        handle.sync_error();
1100        return 0;
1101    }
1102    let mut data = RsData {
1103        bytes: Cow::Borrowed(&UNWRITTEN),
1104    };
1105    let mut ok = anim::webp_anim_encoder_assemble(&mut handle.enc, &mut data);
1106    if !ptr::eq(data.bytes.as_ptr(), UNWRITTEN.as_ptr()) {
1107        let value = if data.bytes.is_empty() {
1108            WebPData {
1109                bytes: ptr::null(),
1110                size: 0,
1111            }
1112        } else if let Some(value) = data_to_caller(&data) {
1113            value
1114        } else {
1115            ok = false;
1116            WebPData {
1117                bytes: ptr::null(),
1118                size: 0,
1119            }
1120        };
1121        // SAFETY: writable (checked non-null; caller's contract).
1122        unsafe { put(webp_data, value) };
1123    }
1124    handle.sync_error();
1125    c_int::from(ok)
1126}
1127
1128// upstream: src/mux/anim_encode.c WebPAnimEncoderGetError
1129/// Get error string corresponding to the most recent call using `enc`: null for
1130/// a null encoder, the error of the last call, or an empty string. The string
1131/// is owned by `enc` and changes with the next call to `WebPAnimEncoderAdd()`
1132/// or `WebPAnimEncoderAssemble()`.
1133///
1134/// # Safety
1135///
1136/// `enc` is null or a live encoder of this library.
1137#[unsafe(export_name = "WebPAnimEncoderGetError")]
1138#[must_use]
1139pub unsafe extern "C" fn webp_anim_encoder_get_error(enc: *mut WebPAnimEncoder) -> *const c_char {
1140    // SAFETY: null or a live encoder (caller's contract).
1141    let Some(handle) = (unsafe { encoder(enc) }) else {
1142        return ptr::null();
1143    };
1144    handle.sync_error();
1145    handle.error.as_ptr()
1146}
1147
1148// upstream: src/mux/anim_encode.c WebPAnimEncoderDelete
1149/// Deletes the `WebPAnimEncoder` object.
1150///
1151/// # Safety
1152///
1153/// `enc` is null or an encoder of this library that is not used again.
1154#[unsafe(export_name = "WebPAnimEncoderDelete")]
1155pub unsafe extern "C" fn webp_anim_encoder_delete(enc: *mut WebPAnimEncoder) {
1156    if enc.is_null() {
1157        return;
1158    }
1159    // SAFETY: an encoder of this library, which the caller gives up.
1160    let handle = unsafe { Box::from_raw(enc) };
1161    anim::webp_anim_encoder_delete(handle.enc);
1162}
1163
1164// upstream: src/mux/anim_encode.c WebPAnimEncoderSetChunk
1165/// Adds a chunk with id `fourcc` and data `chunk_data` to the encoder's mux;
1166/// any existing chunk(s) with the same id are removed. Without copying the data
1167/// must exist until a call to `WebPAnimEncoderAssemble()`.
1168///
1169/// # Safety
1170///
1171/// As `WebPMuxSetChunk()`, with `enc` null or a live encoder of this library.
1172#[unsafe(export_name = "WebPAnimEncoderSetChunk")]
1173#[must_use]
1174pub unsafe extern "C" fn webp_anim_encoder_set_chunk(
1175    enc: *mut WebPAnimEncoder,
1176    fourcc: *const c_char,
1177    chunk_data: *const WebPData,
1178    copy_data: c_int,
1179) -> WebPMuxError {
1180    // SAFETY: null or a live encoder (caller's contract).
1181    let Some(handle) = (unsafe { encoder(enc) }) else {
1182        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
1183    };
1184    // SAFETY: null or a valid `WebPData` (caller's contract).
1185    let Some(chunk_data) = (unsafe { chunk_data.as_ref() }) else {
1186        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
1187    };
1188    if fourcc.is_null()
1189        || chunk_data.bytes.is_null()
1190        || chunk_data.size as u64 > u64::from(MAX_CHUNK_PAYLOAD)
1191    {
1192        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
1193    }
1194    // SAFETY: four readable characters (checked non-null; caller's contract).
1195    let tag = unsafe { read_fourcc(fourcc) };
1196    // SAFETY: readable bytes of a checked size, valid while the encoder keeps
1197    // them (caller's contract).
1198    let data = unsafe { lend(chunk_data) };
1199    code(&anim::webp_anim_encoder_set_chunk(
1200        &mut handle.enc,
1201        &tag,
1202        &data,
1203        copy_data,
1204    ))
1205}
1206
1207// upstream: src/mux/anim_encode.c WebPAnimEncoderGetChunk
1208/// Gets a reference to the data of the chunk with id `fourcc` in the encoder's
1209/// mux; the caller must not free it.
1210///
1211/// # Safety
1212///
1213/// As `WebPMuxGetChunk()`, with `enc` null or a live encoder of this library.
1214#[unsafe(export_name = "WebPAnimEncoderGetChunk")]
1215#[must_use]
1216pub unsafe extern "C" fn webp_anim_encoder_get_chunk(
1217    enc: *const WebPAnimEncoder,
1218    fourcc: *const c_char,
1219    chunk_data: *mut WebPData,
1220) -> WebPMuxError {
1221    // SAFETY: null or a live encoder (caller's contract).
1222    let Some(handle) = (unsafe { enc.as_ref() }) else {
1223        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
1224    };
1225    if fourcc.is_null() || chunk_data.is_null() {
1226        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
1227    }
1228    // SAFETY: four readable characters (checked non-null; caller's contract).
1229    let tag = unsafe { read_fourcc(fourcc) };
1230    // SAFETY: a writable `WebPData` (checked non-null; caller's contract).
1231    unsafe {
1232        get_chunk(
1233            anim::webp_anim_encoder_get_chunk(&handle.enc, &tag),
1234            &tag,
1235            chunk_data,
1236        )
1237    }
1238}
1239
1240// upstream: src/mux/anim_encode.c WebPAnimEncoderDeleteChunk
1241/// Deletes the chunk with the given `fourcc` from the encoder's mux.
1242///
1243/// # Safety
1244///
1245/// `enc` is null or a live encoder of this library; `fourcc` is null or four
1246/// readable characters.
1247#[unsafe(export_name = "WebPAnimEncoderDeleteChunk")]
1248#[must_use]
1249pub unsafe extern "C" fn webp_anim_encoder_delete_chunk(
1250    enc: *mut WebPAnimEncoder,
1251    fourcc: *const c_char,
1252) -> WebPMuxError {
1253    // SAFETY: null or a live encoder (caller's contract).
1254    let Some(handle) = (unsafe { encoder(enc) }) else {
1255        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
1256    };
1257    if fourcc.is_null() {
1258        return WebPMuxError::WEBP_MUX_INVALID_ARGUMENT;
1259    }
1260    // SAFETY: four readable characters (checked non-null; caller's contract).
1261    let tag = unsafe { read_fourcc(fourcc) };
1262    code(&anim::webp_anim_encoder_delete_chunk(&mut handle.enc, &tag))
1263}
1264
1265#[cfg(test)]
1266mod tests {
1267    use super::{ERROR_STR_MAX_LENGTH, c_char, copy_error_bytes};
1268
1269    #[test]
1270    fn error_bytes_preserve_high_bits_and_terminate_when_truncated() {
1271        let message = [0x80, 0xff, b'A'];
1272        let mut error = [0 as c_char; ERROR_STR_MAX_LENGTH];
1273        copy_error_bytes(&mut error, &message);
1274        assert_eq!(
1275            error[..3]
1276                .iter()
1277                .map(|byte| byte.to_ne_bytes()[0])
1278                .collect::<Vec<_>>(),
1279            message
1280        );
1281        assert_eq!(error[3], 0);
1282
1283        let long_message = [0xff; ERROR_STR_MAX_LENGTH + 1];
1284        copy_error_bytes(&mut error, &long_message);
1285        assert!(
1286            error[..ERROR_STR_MAX_LENGTH - 1]
1287                .iter()
1288                .all(|byte| byte.to_ne_bytes() == [0xff])
1289        );
1290        assert_eq!(error[ERROR_STR_MAX_LENGTH - 1], 0);
1291    }
1292}