Skip to main content

webp/abi/
encode.rs

1// libwebp v1.6.0, src/webp/encode.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//   WebP encoder: main interface
13//
14// Author: Skal (pascal.massimino@gmail.com)
15
16//! C ABI export of `src/webp/encode.h` from libwebp v1.6.0.
17//!
18//! Mirrors the header's structs with `repr(C)` and converts them to the
19//! safe representations at the boundary; see
20//! `docs/adr/0004-c-abi-boundary.md`.
21//!
22//! Work package: WP13 (encoder integration).
23//!
24//! `WebPConfig` and `WebPAuxStats` have no pointers, so the C ABI uses the
25//! `repr(C)` structs of `src/webp/encode.rs`; `WebPPicture` and
26//! `WebPMemoryWriter` have `repr(C)` mirrors here. `tests/wp13_abi_layout.rs`
27//! compares every mirror and shared struct with the C compiler's layout.
28//!
29//! # Pictures
30//!
31//! A C `WebPPicture` is converted for each call (as WP12 converts a
32//! `WebPDecBuffer`), and the call's results are written back into it: the
33//! dimensions, `use_argb`, `colorspace`, the strides, the plane pointers,
34//! `error_code`, `memory_` and `memory_argb_`. Its callback, `custom_ptr`,
35//! `user_data`, `stats`, `extra_info` and padding fields stay as the caller set
36//! them, except where C copies a whole picture (`WebPPictureCopy`,
37//! `WebPPictureView`), which this module does with the C struct itself.
38//!
39//! - Memory that the library allocates for a picture (`memory_` for the Y, U, V
40//!   and A planes, `memory_argb_` for the ARGB plane) is a block of the platform
41//!   `malloc` of C's size (`WebPPictureAllocYUVA`, `WebPPictureAllocARGB`, with
42//!   the ARGB plane at the `WEBP_ALIGN`ed address), which `WebPPictureFree`
43//!   releases. This module records the address and size of each block, and
44//!   assumes, as `encode.h` requires, that C releases it only through
45//!   `WebPPictureFree` (or the functions that replace the planes): a block that C
46//!   frees itself stays recorded, and caller memory that later lands at the same
47//!   address in `memory_` would be read at the recorded size. During a call the
48//!   translation works on a copy of the block (`PlaneStorage::Internal`), which
49//!   goes back into the block after the call; new samples go into a new block.
50//! - Caller memory (planes outside the picture's own block, as after
51//!   `WebPPictureView` or when the caller sets the plane pointers) is lent to the
52//!   translation for the duration of the call, only for the planes that C's path
53//!   reads or writes: shared slices for a call that only reads them, exclusive
54//!   slices for one that writes them. A plane's slice covers the samples that its
55//!   dimensions and stride address, `(height - 1) * stride + width`. Calls that
56//!   do not touch the planes (`WebPPictureAlloc`, `WebPPictureFree`, the
57//!   importers, a conversion's output, the storage that `use_argb` does not
58//!   select) lend nothing, and `WebPPictureView`, which only computes addresses,
59//!   lends no sample.
60//! - `WebPEncode` lends the planes of C's path, and none when the configuration
61//!   or the picture fails C's validation. It gives the translation zeroed copies
62//!   of the statistics and of the `extra_info` map and closures around the C
63//!   writer and progress hook that pass the caller's picture pointer, as C passes
64//!   it. The statistics go back to `*stats` once the validation has passed (C
65//!   resets them there), also when this module then refuses the picture. The
66//!   map goes back to `extra_info` when the lossy encoder ran, also after a
67//!   failure, since C fills it one macroblock at a time (its entries are C's,
68//!   and those C did not reach are zero where C leaves them untouched), and when
69//!   a lossless encoding succeeds (C zeroes it then); the caller's bytes are
70//!   never read.
71//!
72//! # Callbacks
73//!
74//! While `WebPEncode` runs, the caller's planes are lent exclusively to the
75//! translation. A writer or progress hook must therefore neither call a library
76//! function on the picture being encoded (C allows, for example,
77//! `WebPPictureHasTransparency(picture)` there) nor read or write those planes
78//! through `picture` itself: both alias the lent slices. No upstream callback
79//! does either. A picture in library memory is not affected, since the
80//! translation works on a copy of its block.
81//!
82//! # Cases that this module rejects
83//!
84//! Rust cannot lend these planes, so the calls that read or write them fail: a
85//! plane with a negative stride over more than one row (it lies before its
86//! pointer), planes that a writing call would write and that overlap, and an
87//! ARGB plane not aligned for `uint32_t`. Functions that report errors on the
88//! picture record `VP8_ENC_ERROR_INVALID_CONFIGURATION` and return 0, the other
89//! functions return 0 or do nothing. Packed input rows with a negative stride
90//! (the importers and the simple API) are copied into rows with a positive
91//! stride first, which hold the same bytes; rows with a positive stride are lent
92//! as they are. See `# Deviations from upstream`, item 2.
93//!
94//! # Deviations from upstream
95//!
96//! Changes of representation that the ADRs allow, or behavior that the Rust
97//! side cannot reproduce exactly. Each records the reason.
98//!
99//! 1. **C ABI pictures per call.** The library's blocks (`memory_`,
100//!    `memory_argb_`) are copied into the translation's storage for each call
101//!    and back afterwards (one copy of the picture per call; the copy reserves
102//!    fallibly, and a refused reservation fails the call with
103//!    `VP8_ENC_ERROR_OUT_OF_MEMORY` where the function records errors). Caller
104//!    planes are lent only where C's path reads or writes them, with the extent
105//!    that their dimensions and strides address,
106//!    `(height - 1) * stride + width` samples: as `PlaneStorage::External` to a
107//!    call that writes them and as `PlaneStorage::Shared` to one that only
108//!    reads them (`WebPPictureCopy`'s source, `Distortion`, the input of a
109//!    conversion), so that a source and a reference may share memory.
110//!    `WebPPictureHasTransparency` lends only the alpha plane of a YUV picture
111//!    or the ARGB plane of an ARGB picture; when that plane lies in the
112//!    picture's own block, the whole block is copied, which reads samples that
113//!    C does not touch (the Y, U and V planes, which this module initialized)
114//!    and can fail when the host refuses the copy (the call then returns 0).
115//!    `WebPPictureView` only computes addresses: it lends each plane as an
116//!    empty region with the plane at a large offset, so that the translation's
117//!    offsets give C's pointer arithmetic for any stride. Calls that do not
118//!    touch a storage (`WebPPictureAlloc`, `Free`, the importers, a
119//!    conversion's output, the storage that `use_argb` does not select) lend
120//!    nothing there. `WebPEncode` lends the planes of C's path: the YUVA planes
121//!    for a lossy encoding of a YUV picture (written by the cleanup and
122//!    `show_compressed`), the ARGB plane for a lossy encoding that converts it,
123//!    the ARGB plane for a lossless encoding (written when transparent pixels
124//!    are replaced) or the YUVA planes when it is `NULL` and C converts them,
125//!    and nothing when the configuration or the picture fails C's validation.
126//!    It never reads the caller's `*stats` or `extra_info`, which may be
127//!    uninitialized (`cwebp` passes an uninitialized `WebPAuxStats` and a
128//!    `WebPMalloc`ed map): the translation gets zeroed copies. The statistics
129//!    go back to `*stats` once `WebPValidateConfig`, `WebPValidatePicture` and
130//!    the dimension limit have passed, where C resets and fills them; when this
131//!    module then refuses the picture (a rejected layout, a refused copy of its
132//!    block), the zeroed statistics go back, as C has reset them at that point.
133//!    The map goes back to `extra_info` whenever the lossy path ran: after a
134//!    user abort or a write failure inside the encoder loop, the filled prefix
135//!    is C's (C fills the map one macroblock at a time, `StoreSideInfo` in
136//!    `VP8EncLoop` and `VP8EncTokenLoop`) and the unfilled entries are zero
137//!    where C leaves the caller's bytes untouched; after a lossy failure before
138//!    the encoder loop (a failed conversion, a failed `InitVP8Encoder`) the
139//!    whole map is zero where C leaves it untouched. A lossless encoding writes
140//!    the map back only on success, where C zeroes it (`VP8LEncodeImage`); a
141//!    failed validation writes nothing, as in C. The encode probe zeroes the
142//!    map before the call, so the ABI test compares every case byte for byte,
143//!    the failed lossy encodings with a partly filled map included. A C
144//!    callback that reads `picture->stats`, `extra_info` or another picture
145//!    field during the encoding sees the values from before the call; no
146//!    upstream callback reads them (ADR 0003, "Concrete callback forms"). The
147//!    callbacks receive the caller's picture pointer.
148//! 2. **C ABI rejects** a plane that a call reads or writes when it has a
149//!    negative stride over more than one row (Rust cannot lend memory before
150//!    the pointer), planes that a writing call would write and that overlap,
151//!    and such an ARGB plane when it is not aligned for `uint32_t`: Rust cannot
152//!    lend those slices (as `src/abi/decode.rs` does,
153//!    `# Deviations from upstream`, item 2). Planes that the call does not
154//!    touch are never checked (the unselected storage, any plane for
155//!    `WebPPictureView`, the luma and chroma planes for
156//!    `WebPPictureHasTransparency`, the planes outside C's path in
157//!    `WebPEncode`; `abi_accepts_the_layouts_that_c_never_reads` covers
158//!    misaligned pointers with negative strides there, and upside-down planes
159//!    for views). Functions that record errors return 0 with
160//!    `VP8_ENC_ERROR_INVALID_CONFIGURATION`; `WebPPictureCopy`, `Distortion`
161//!    and `HasTransparency` return 0; `WebPCleanupTransparentArea` and
162//!    `WebPBlendAlpha` do nothing. Packed input rows with a negative stride
163//!    (the importers, the simple API) are copied into rows with a positive
164//!    stride, which hold the same bytes, so C's results stay; the copy reserves
165//!    fallibly, and a refused reservation fails the import with
166//!    `VP8_ENC_ERROR_OUT_OF_MEMORY` (the simple API returns 0). Rows with a
167//!    positive stride are lent as they are. Rows of a picture without width are
168//!    passed with the stride 0, since `Import` reads none of them.
169//! 3. **`WebPPictureIsView`** passes C's `memory_` and `memory_argb_` to the
170//!    translation as the ownership of the storage, which is what the
171//!    translation reads. A picture whose `memory_` is set while its planes
172//!    point elsewhere converts as caller memory in the other functions (they
173//!    never read `memory_` apart from releasing it, which the ABI does as C
174//!    does).
175//! 4. **`WebPMemoryWrite` in the C ABI** gives the translation a copy of the
176//!    written bytes and copies the new ones back, or the whole buffer into a
177//!    new block of the translation's capacity when it grows (one copy of the
178//!    written bytes per call). The copy reserves fallibly; a refused
179//!    reservation returns 0, as C does when its buffer cannot grow, but it can
180//!    also happen when C would not have needed to grow the buffer.
181//! 5. **`WebPPictureDistortion` in the C ABI** writes `result` only on success;
182//!    C writes the channels it measured before an allocation failure.
183//!
184//! # Upstream behavior preserved
185//!
186//! Behavior of the C code that a reader might take for a defect, which the
187//! translation keeps:
188//!
189//! 1. **`WebPPictureAlloc(NULL)` and `WebPPictureInitInternal(NULL, version)`
190//!    return 1**; `WebPPictureCopy(pic, pic)` returns 1 without copying.
191//! 2. **`WebPMemoryWriterInit` does not release the previous buffer.**
192//! 3. **`WebPConfigPreset` with an invalid quality writes the configuration and
193//!    returns 0**, so the simple API returns 0 without writing `*output`; every
194//!    other failure writes `NULL`.
195//!
196//! # Use by the mux ABI
197//!
198//! `Mode`, `with_picture` and `progress_closure` are crate-visible for
199//! `src/abi/mux.rs`:
200//!
201//! 1. `WebPAnimEncoderAdd` converts the caller's frame for one call exactly as
202//!    `WebPEncode` does: the ARGB plane (or, without `use_argb`, the YUVA
203//!    planes that `WebPPictureYUVAToARGB` reads) is lent, the results are
204//!    written back (the error code and, after a conversion, the new ARGB
205//!    block), and the frame's C progress hook is wrapped as a closure.
206//! 2. `with_picture` is the function around `picture_to_rust` and
207//!    `picture_to_c` that every encode ABI entry point uses, so
208//!    `src/abi/mux.rs` needs nothing else; `picture_to_rust`, `picture_to_c`,
209//!    `Converted`, `Refused` and `set_error` stay private.
210
211use core::ffi::{c_int, c_void};
212use core::mem::{MaybeUninit, offset_of, size_of};
213use core::ptr;
214use core::slice;
215use std::borrow::Cow;
216use std::collections::BTreeMap;
217use std::sync::{Mutex, MutexGuard, PoisonError};
218
219use crate::abi::types::{malloc_copy, platform_free, platform_malloc};
220use crate::enc::config_enc as config_rs;
221use crate::enc::picture_csp_enc as csp;
222use crate::enc::picture_enc as picture_rs;
223use crate::enc::picture_psnr_enc as psnr;
224use crate::enc::picture_rescale_enc as rescale;
225use crate::enc::picture_tools_enc as tools;
226use crate::enc::webp_enc as enc;
227use crate::utils::utils::WEBP_ALIGN_CST;
228use crate::webp::encode::{
229    WEBP_ENCODER_ABI_VERSION, WEBP_MAX_DIMENSION, WebPAuxStats, WebPConfig, WebPEncCSP,
230    WebPEncodingError, WebPMemoryWriter as RsMemoryWriter, WebPPicture as RsPicture, WebPPreset,
231    WebPProgressHook as RsProgressHook, WebPWriterFunction as RsWriterFunction, webp_config_preset,
232};
233use crate::webp::types::{PlaneOffset, PlaneStorage, webp_abi_is_incompatible};
234
235//------------------------------------------------------------------------------
236// Mirrors of the structs with pointers
237
238// upstream: src/webp/encode.h WebPWriterFunction
239/// Signature of the output function (C layout): writes `data_size` bytes of
240/// `data` and returns 0 on failure.
241pub type WebPWriterFunction =
242    unsafe extern "C" fn(data: *const u8, data_size: usize, picture: *const WebPPicture) -> c_int;
243
244// upstream: src/webp/encode.h WebPProgressHook
245/// Progress hook (C layout): returns 0 to request an abort.
246pub type WebPProgressHook =
247    unsafe extern "C" fn(percent: c_int, picture: *const WebPPicture) -> c_int;
248
249// upstream: src/webp/encode.h WebPMemoryWriter
250/// The memory writer of `WebPMemoryWrite` (C layout). `mem` is a block of the
251/// platform `malloc` that `WebPMemoryWriterClear()` or `WebPFree()` releases.
252#[repr(C)]
253#[derive(Clone, Copy, Debug)]
254pub struct WebPMemoryWriter {
255    /// Final buffer (of size `max_size`, larger than `size`).
256    pub mem: *mut u8,
257    /// Final size.
258    pub size: usize,
259    /// Total capacity.
260    pub max_size: usize,
261    /// Padding for later use.
262    pub pad: [u32; 1],
263}
264
265// upstream: src/webp/encode.h WebPPicture
266/// Main exchange structure (C layout).
267#[repr(C)]
268#[derive(Clone, Copy, Debug)]
269pub struct WebPPicture {
270    /// Main flag for encoder selecting between ARGB or YUV input.
271    pub use_argb: c_int,
272    /// Colorspace: should be `YUV420` for now (`Y'CbCr`).
273    pub colorspace: WebPEncCSP,
274    /// Width (less or equal to `WEBP_MAX_DIMENSION`).
275    pub width: c_int,
276    /// Height (less or equal to `WEBP_MAX_DIMENSION`).
277    pub height: c_int,
278    /// Luma plane.
279    pub y: *mut u8,
280    /// Chroma U plane.
281    pub u: *mut u8,
282    /// Chroma V plane.
283    pub v: *mut u8,
284    /// Luma stride.
285    pub y_stride: c_int,
286    /// Chroma stride.
287    pub uv_stride: c_int,
288    /// Alpha plane.
289    pub a: *mut u8,
290    /// Stride of the alpha plane.
291    pub a_stride: c_int,
292    /// Padding for later use.
293    pub pad1: [u32; 2],
294    /// ARGB (32 bit) plane.
295    pub argb: *mut u32,
296    /// Stride in pixels, not bytes.
297    pub argb_stride: c_int,
298    /// Padding for later use.
299    pub pad2: [u32; 3],
300    /// Byte-emission hook; can be `NULL`.
301    pub writer: Option<WebPWriterFunction>,
302    /// Can be used by the writer.
303    pub custom_ptr: *mut c_void,
304    /// 1: intra type, 2: segment, 3: quant, ...
305    pub extra_info_type: c_int,
306    /// If not `NULL`, an array of one byte per macroblock.
307    pub extra_info: *mut u8,
308    /// Pointer to side statistics (updated only if not `NULL`).
309    pub stats: *mut WebPAuxStats,
310    /// Error code for the latest error encountered during encoding.
311    pub error_code: WebPEncodingError,
312    /// If not `NULL`, report progress during encoding.
313    pub progress_hook: Option<WebPProgressHook>,
314    /// Free to be set to any value and used during callbacks.
315    pub user_data: *mut c_void,
316    /// Padding for later use.
317    pub pad3: [u32; 3],
318    /// Unused for now.
319    pub pad4: *mut u8,
320    /// Unused for now.
321    pub pad5: *mut u8,
322    /// Padding for later use.
323    pub pad6: [u32; 8],
324    /// Row chunk of memory for the YUVA planes.
325    pub memory_: *mut c_void,
326    /// And for the ARGB plane.
327    pub memory_argb_: *mut c_void,
328    /// Padding for later use.
329    pub pad7: [*mut c_void; 2],
330}
331
332//------------------------------------------------------------------------------
333// Picture memory blocks
334
335/// The blocks that this module gave to C pictures as `memory_` or
336/// `memory_argb_`, with their sizes in bytes.
337static BLOCKS: Mutex<BTreeMap<usize, usize>> = Mutex::new(BTreeMap::new());
338
339fn blocks() -> MutexGuard<'static, BTreeMap<usize, usize>> {
340    BLOCKS.lock().unwrap_or_else(PoisonError::into_inner)
341}
342
343/// The size of a picture block, or `None` for memory this module did not
344/// allocate.
345fn block_size(block: *mut c_void) -> Option<usize> {
346    blocks().get(&(block as usize)).copied()
347}
348
349/// A new zeroed block of `size` bytes of the platform `malloc`, recorded as a
350/// picture block; null when `malloc` fails.
351fn new_block(size: usize) -> *mut u8 {
352    let block = platform_malloc(size.max(1));
353    if !block.is_null() {
354        // SAFETY: `block` is a new allocation of at least `size` bytes.
355        unsafe { ptr::write_bytes(block, 0, size) };
356        blocks().insert(block as usize, size);
357    }
358    block
359}
360
361/// Releases the memory that a C picture gives up (C: `WebPSafeFree`), which is
362/// `free()` for a block of this module and for any other pointer.
363///
364/// # Safety
365///
366/// `block` is null or a live block of the platform `malloc` that is not used
367/// again.
368unsafe fn release_block(block: *mut c_void) {
369    if block.is_null() {
370        return;
371    }
372    blocks().remove(&(block as usize));
373    // SAFETY: the caller gives up a block of the platform `malloc`.
374    unsafe { platform_free(block.cast()) };
375}
376
377//------------------------------------------------------------------------------
378// Picture conversion
379
380/// How a call uses one storage of a picture (the YUVA planes or the ARGB plane).
381#[derive(Clone, Copy, Debug, PartialEq, Eq)]
382pub(crate) enum Mode {
383    /// The call does not touch the planes: nothing is lent.
384    Discard,
385    /// The call only computes plane addresses (`WebPPictureView`): each plane is
386    /// an empty region at [`ADDRESS_OFFSET`], so that the translation's offsets
387    /// give C's pointer arithmetic for any stride, and no sample is lent.
388    Address,
389    /// The call reads the planes: caller memory is lent shared.
390    Read,
391    /// The call reads and writes the planes: caller memory is lent exclusively.
392    Write,
393}
394
395/// The offset of a plane in its empty region in `Mode::Address`: far enough from
396/// 0 and from the limits of the translation's offset arithmetic (`offset_by`,
397/// which converts a position to `i64`) that a view's offsets, which C computes
398/// as pointer differences, stay in range for either sign: 2^62 with 64-bit
399/// pointers, and 2^31 with 32-bit pointers, where a difference lies in
400/// (-2^31, 2^31).
401const ADDRESS_OFFSET: usize = if usize::BITS > 32 {
402    usize::MAX / 4 + 1
403} else {
404    usize::MAX / 2 + 1
405};
406
407/// Why a C picture cannot be converted.
408#[derive(Clone, Copy, Debug, PartialEq, Eq)]
409enum Refused {
410    /// A plane layout that Rust cannot lend (see the module documentation).
411    Layout,
412    /// The host refused the memory for a copy of the picture's block.
413    Memory,
414}
415
416/// Where the translation's storage of a picture came from.
417#[derive(Debug)]
418enum Origin {
419    /// Nothing was lent; the storage is an `External` storage without regions,
420    /// which no translated function creates, so it marks an untouched storage.
421    Nothing,
422    /// The picture's own block (`memory_` or `memory_argb_`), copied for the call.
423    Block { base: *mut u8, size: usize },
424    /// Caller memory lent per plane: the start of each region.
425    Lent(Vec<*mut u8>),
426}
427
428/// A C picture as the translation sees it during one call.
429struct Converted<'a> {
430    picture: RsPicture<'a>,
431    yuva: Origin,
432    argb: Origin,
433}
434
435/// The rows of a plane, in samples from its first sample: `(height - 1) *
436/// stride + width`, or 0 for an empty plane. `None` for a negative stride over
437/// more than one row, or a size that no memory can have.
438fn plane_extent(width: i32, height: i32, stride: i32) -> Option<usize> {
439    if width <= 0 || height <= 0 {
440        return Some(0);
441    }
442    if height > 1 && stride < 0 {
443        return None;
444    }
445    let rows = if height > 1 {
446        i64::from(height - 1) * i64::from(stride)
447    } else {
448        0
449    };
450    usize::try_from(rows + i64::from(width)).ok()
451}
452
453/// C's `HALVE` on a dimension, `(x + 1) >> 1`, in 64 bits as `WebPPictureAllocYUVA`
454/// computes it.
455fn halve(x: i32) -> i32 {
456    i32::try_from((i64::from(x) + 1) >> 1).unwrap_or(i32::MAX)
457}
458
459/// Whether two byte ranges overlap; an empty range overlaps nothing.
460fn ranges_overlap(a: *const u8, a_len: usize, b: *const u8, b_len: usize) -> bool {
461    let (a, b) = (a as usize, b as usize);
462    a_len > 0 && b_len > 0 && a < b.saturating_add(b_len) && b < a.saturating_add(a_len)
463}
464
465/// A converted storage: the storage, the planes in it, the origin and the lent
466/// byte ranges.
467type StorageParts<'a, T> = (
468    PlaneStorage<'a, T>,
469    Vec<Option<PlaneOffset>>,
470    Origin,
471    Vec<(*const u8, usize)>,
472);
473
474/// The storage of `Mode::Address`: an empty region per non-null plane, with the
475/// plane at [`ADDRESS_OFFSET`], and the bases that give C's plane addresses back.
476fn address_storage<'a, T>(planes: &[(*mut u8, Option<usize>)]) -> StorageParts<'a, T> {
477    let elem = size_of::<T>();
478    let mut regions: Vec<&'a [T]> = Vec::new();
479    let mut bases = Vec::new();
480    let mut offsets = Vec::with_capacity(planes.len());
481    for &(plane, _) in planes {
482        if plane.is_null() {
483            offsets.push(None);
484            continue;
485        }
486        offsets.push(Some(PlaneOffset {
487            region: regions.len(),
488            offset: ADDRESS_OFFSET,
489        }));
490        regions.push(&[]);
491        bases.push(plane.wrapping_sub(ADDRESS_OFFSET.wrapping_mul(elem)));
492    }
493    if regions.is_empty() {
494        return (
495            PlaneStorage::External(Vec::new()),
496            offsets,
497            Origin::Nothing,
498            Vec::new(),
499        );
500    }
501    (
502        PlaneStorage::Shared(regions),
503        offsets,
504        Origin::Lent(bases),
505        Vec::new(),
506    )
507}
508
509/// The storage of a picture whose planes lie inside its own block (`memory_`
510/// or `memory_argb_`): a copy of the block. `None` when `memory` is not a block
511/// of this module or a plane lies outside it. The size comes from the `BLOCKS`
512/// registry, which relies on C releasing the block only through this module
513/// (see `# Pictures` in the module documentation).
514///
515/// # Safety
516///
517/// `memory` is null or the picture's memory field.
518unsafe fn block_storage<'a, T: Copy>(
519    memory: *mut c_void,
520    planes: &[(*mut u8, Option<usize>)],
521) -> Option<Result<StorageParts<'a, T>, Refused>> {
522    let elem = size_of::<T>();
523    let base = memory.cast::<u8>();
524    let size = block_size(memory)?;
525    let inside = planes.iter().all(|&(plane, extent)| {
526        plane.is_null()
527            || extent.is_some_and(|extent| {
528                let offset = (plane as usize).wrapping_sub(base as usize);
529                plane as usize >= base as usize
530                    && offset.is_multiple_of(elem)
531                    && extent
532                        .checked_mul(elem)
533                        .and_then(|bytes| bytes.checked_add(offset))
534                        .is_some_and(|end| end <= size)
535            })
536    });
537    if !inside || size % elem != 0 {
538        return None;
539    }
540    // SAFETY: the block is a live, initialized block of `size` bytes from the
541    // platform `malloc` (this module zeroes it when it allocates it), aligned for
542    // `T`; the copy ends before the translation runs.
543    let block = unsafe { slice::from_raw_parts(base.cast::<T>(), size / elem) };
544    let mut samples = Vec::new();
545    if samples.try_reserve_exact(block.len()).is_err() {
546        return Some(Err(Refused::Memory));
547    }
548    samples.extend_from_slice(block);
549    let offsets = planes
550        .iter()
551        .map(|&(plane, _)| {
552            (!plane.is_null()).then(|| PlaneOffset {
553                region: 0,
554                offset: (plane as usize - base as usize) / elem,
555            })
556        })
557        .collect();
558    Some(Ok((
559        PlaneStorage::Internal(samples),
560        offsets,
561        Origin::Block { base, size },
562        Vec::new(),
563    )))
564}
565
566/// Converts one storage of a C picture. `planes` are the plane pointers with
567/// their extents in samples (`None` when the plane cannot be lent). Fails for a
568/// layout that this module rejects (see the module documentation) and when the
569/// host refuses the memory for a copy of the picture's block.
570///
571/// # Safety
572///
573/// For `Read` and `Write`, every non-null plane points to its extent of
574/// initialized samples, which only the translation accesses during the call
575/// (exclusively for `Write`); `memory` is null or the picture's memory field.
576unsafe fn storage_to_rust<'a, T: Copy>(
577    mode: Mode,
578    memory: *mut c_void,
579    planes: &[(*mut u8, Option<usize>)],
580) -> Result<StorageParts<'a, T>, Refused> {
581    let elem = size_of::<T>();
582    let nothing = || {
583        Ok((
584            PlaneStorage::External(Vec::new()),
585            vec![None; planes.len()],
586            Origin::Nothing,
587            Vec::new(),
588        ))
589    };
590    if mode == Mode::Discard {
591        return nothing();
592    }
593    if mode == Mode::Address {
594        return Ok(address_storage(planes));
595    }
596    // SAFETY: the caller's contract, passed on.
597    if let Some(parts) = unsafe { block_storage(memory, planes) } {
598        return parts;
599    }
600    if planes.iter().all(|&(plane, _)| plane.is_null()) {
601        return nothing();
602    }
603    let mut offsets = Vec::with_capacity(planes.len());
604    let mut bases = Vec::new();
605    let mut ranges: Vec<(*const u8, usize)> = Vec::new();
606    for &(plane, extent) in planes {
607        if plane.is_null() {
608            offsets.push(None);
609            continue;
610        }
611        let extent = extent.ok_or(Refused::Layout)?;
612        let bytes = extent.checked_mul(elem).ok_or(Refused::Layout)?;
613        if bytes > isize::MAX as usize || !(plane as usize).is_multiple_of(align_of::<T>()) {
614            return Err(Refused::Layout);
615        }
616        if mode == Mode::Write
617            && ranges
618                .iter()
619                .any(|&(start, len)| ranges_overlap(start, len, plane, bytes))
620        {
621            return Err(Refused::Layout);
622        }
623        offsets.push(Some(PlaneOffset {
624            region: bases.len(),
625            offset: 0,
626        }));
627        bases.push(plane);
628        ranges.push((plane, bytes));
629    }
630    let lengths: Vec<usize> = ranges.iter().map(|&(_, bytes)| bytes / elem).collect();
631    let storage = if mode == Mode::Read {
632        PlaneStorage::Shared(
633            bases
634                .iter()
635                .zip(&lengths)
636                .map(|(&start, &len)| {
637                    // SAFETY: the caller lends `len` initialized samples at
638                    // `start` for the call; shared slices may overlap.
639                    unsafe { slice::from_raw_parts(start.cast::<T>().cast_const(), len) }
640                })
641                .collect(),
642        )
643    } else {
644        PlaneStorage::External(
645            bases
646                .iter()
647                .zip(&lengths)
648                .map(|(&start, &len)| {
649                    // SAFETY: the caller lends `len` writable samples at `start`
650                    // exclusively for the call, and the regions are disjoint.
651                    unsafe { slice::from_raw_parts_mut(start.cast::<T>(), len) }
652                })
653                .collect(),
654        )
655    };
656    Ok((storage, offsets, Origin::Lent(bases), ranges))
657}
658
659/// Converts a C picture for one call, with the given use of its two storages.
660/// The translation's picture holds no callbacks, `stats` or `extra_info`.
661/// Fails as [`storage_to_rust`] does.
662///
663/// # Safety
664///
665/// The planes that `yuva` and `argb` lend meet the contract of
666/// [`storage_to_rust`].
667unsafe fn picture_to_rust<'a>(
668    c: &WebPPicture,
669    yuva: Mode,
670    argb: Mode,
671) -> Result<Converted<'a>, Refused> {
672    let (width, height) = (c.width, c.height);
673    let (uv_width, uv_height) = (halve(width), halve(height));
674    // SAFETY: the caller's contract, passed on.
675    let (yuva_storage, yuva_planes, yuva_origin, yuva_ranges) = unsafe {
676        storage_to_rust::<u8>(
677            yuva,
678            c.memory_,
679            &[
680                (c.y, plane_extent(width, height, c.y_stride)),
681                (c.u, plane_extent(uv_width, uv_height, c.uv_stride)),
682                (c.v, plane_extent(uv_width, uv_height, c.uv_stride)),
683                (c.a, plane_extent(width, height, c.a_stride)),
684            ],
685        )
686    }?;
687    // SAFETY: as above.
688    let (argb_storage, argb_planes, argb_origin, argb_ranges) = unsafe {
689        storage_to_rust::<u32>(
690            argb,
691            c.memory_argb_,
692            &[(c.argb.cast(), plane_extent(width, height, c.argb_stride))],
693        )
694    }?;
695    if (yuva == Mode::Write || argb == Mode::Write)
696        && yuva_ranges.iter().any(|&(a, a_len)| {
697            argb_ranges
698                .iter()
699                .any(|&(b, b_len)| ranges_overlap(a, a_len, b, b_len))
700        })
701    {
702        return Err(Refused::Layout);
703    }
704    let picture = RsPicture {
705        use_argb: c.use_argb,
706        colorspace: c.colorspace,
707        width,
708        height,
709        y: yuva_planes[0],
710        u: yuva_planes[1],
711        v: yuva_planes[2],
712        y_stride: c.y_stride,
713        uv_stride: c.uv_stride,
714        a: yuva_planes[3],
715        a_stride: c.a_stride,
716        pad1: c.pad1,
717        argb: argb_planes[0],
718        argb_stride: c.argb_stride,
719        pad2: c.pad2,
720        writer: None,
721        extra_info_type: c.extra_info_type,
722        extra_info: None,
723        stats: None,
724        error_code: c.error_code,
725        progress_hook: None,
726        pad3: c.pad3,
727        pad6: c.pad6,
728        yuva: yuva_storage,
729        argb_storage,
730    };
731    Ok(Converted {
732        picture,
733        yuva: yuva_origin,
734        argb: argb_origin,
735    })
736}
737
738/// The C pointers of planes in regions that start at `bases`; null for a
739/// missing plane. The arithmetic wraps, as the bases of `Mode::Address` lie
740/// outside the planes.
741fn plane_pointers<T>(bases: &[*mut u8], planes: &[Option<PlaneOffset>]) -> Vec<*mut u8> {
742    planes
743        .iter()
744        .map(|plane| {
745            plane
746                .and_then(|plane| {
747                    bases
748                        .get(plane.region)
749                        .map(|&base| base.wrapping_add(plane.offset.wrapping_mul(size_of::<T>())))
750                })
751                .unwrap_or(ptr::null_mut())
752        })
753        .collect()
754}
755
756/// The memory of one storage after a call: `Ok(None)` when the C planes and
757/// memory field stay as they are, `Ok(Some(pointers))` with the new plane
758/// pointers otherwise, and `Err(())` when the block for new samples could not be
759/// allocated (the old memory is then released and the planes are null). Updates
760/// `memory` (C's `memory_` or `memory_argb_`).
761///
762/// # Safety
763///
764/// `origin` and `memory` belong to the storage's conversion, and `memory` is
765/// null or a live block of the platform `malloc`.
766unsafe fn storage_to_c<T: Copy>(
767    storage: &PlaneStorage<'_, T>,
768    planes: &[Option<PlaneOffset>],
769    origin: &Origin,
770    memory: &mut *mut c_void,
771) -> Result<Option<Vec<*mut u8>>, ()> {
772    let elem = size_of::<T>();
773    match storage {
774        // Untouched: nothing was lent.
775        PlaneStorage::External(regions) if regions.is_empty() => Ok(None),
776        // Untouched caller memory.
777        PlaneStorage::External(_) | PlaneStorage::Shared(_) => match origin {
778            Origin::Lent(bases) => Ok(Some(plane_pointers::<T>(bases, planes))),
779            _ => Ok(None),
780        },
781        // The translation released the planes (C: WebPSafeFree of the memory).
782        PlaneStorage::Internal(samples) if samples.is_empty() => {
783            // SAFETY: the picture gives up its memory, as C frees it.
784            unsafe { release_block(*memory) };
785            *memory = ptr::null_mut();
786            Ok(Some(vec![ptr::null_mut(); planes.len()]))
787        }
788        PlaneStorage::Internal(samples) => {
789            let bytes = samples.len() * elem;
790            let data = match origin {
791                Origin::Block { base, size } if *size == bytes && base.cast() == *memory => *base,
792                _ => {
793                    // C's size: the samples, plus WEBP_ALIGN_CST samples for the
794                    // alignment of an ARGB plane (WebPPictureAllocARGB).
795                    let size = if elem == 1 {
796                        bytes
797                    } else {
798                        (samples.len() + WEBP_ALIGN_CST) * elem
799                    };
800                    let block = new_block(size);
801                    // SAFETY: the picture gives up its old memory.
802                    unsafe { release_block(*memory) };
803                    *memory = block.cast();
804                    if block.is_null() {
805                        return Err(());
806                    }
807                    if elem == 1 {
808                        block
809                    } else {
810                        // C: WEBP_ALIGN(memory), ((uintptr_t)memory + 31) & ~31,
811                        // which lies inside the block of WEBP_ALIGN_CST spare
812                        // samples.
813                        let address = block as usize;
814                        let aligned = (address + WEBP_ALIGN_CST) & !WEBP_ALIGN_CST;
815                        block.wrapping_add(aligned - address)
816                    }
817                }
818            };
819            // SAFETY: `data` starts `bytes` writable bytes of the picture's
820            // block, aligned for `T`, which no Rust slice views.
821            unsafe { ptr::copy_nonoverlapping(samples.as_ptr(), data.cast::<T>(), samples.len()) };
822            Ok(Some(plane_pointers::<T>(&[data], planes)))
823        }
824    }
825}
826
827/// Writes the translation's picture back into the C picture: the dimensions,
828/// `use_argb`, `colorspace`, the strides, `error_code`, the planes and the
829/// memory fields. Returns false when a block for new samples could not be
830/// allocated; the picture then records `VP8_ENC_ERROR_OUT_OF_MEMORY`.
831///
832/// # Safety
833///
834/// `c` is the picture that `converted` was converted from, and its memory
835/// fields are null or live blocks of the platform `malloc`.
836unsafe fn picture_to_c(c: &mut WebPPicture, converted: &Converted<'_>) -> bool {
837    let rs = &converted.picture;
838    c.use_argb = rs.use_argb;
839    c.colorspace = rs.colorspace;
840    c.width = rs.width;
841    c.height = rs.height;
842    c.y_stride = rs.y_stride;
843    c.uv_stride = rs.uv_stride;
844    c.a_stride = rs.a_stride;
845    c.argb_stride = rs.argb_stride;
846    c.error_code = rs.error_code;
847    let mut ok = true;
848    // SAFETY: the storage, origin and memory field of one conversion.
849    match unsafe {
850        storage_to_c(
851            &rs.yuva,
852            &[rs.y, rs.u, rs.v, rs.a],
853            &converted.yuva,
854            &mut c.memory_,
855        )
856    } {
857        Ok(None) => {}
858        Ok(Some(pointers)) => {
859            c.y = pointers[0];
860            c.u = pointers[1];
861            c.v = pointers[2];
862            c.a = pointers[3];
863        }
864        Err(()) => {
865            (c.y, c.u, c.v, c.a) = (
866                ptr::null_mut(),
867                ptr::null_mut(),
868                ptr::null_mut(),
869                ptr::null_mut(),
870            );
871            ok = false;
872        }
873    }
874    // SAFETY: as above.
875    match unsafe {
876        storage_to_c(
877            &rs.argb_storage,
878            &[rs.argb],
879            &converted.argb,
880            &mut c.memory_argb_,
881        )
882    } {
883        Ok(None) => {}
884        Ok(Some(pointers)) => c.argb = pointers[0].cast(),
885        Err(()) => {
886            c.argb = ptr::null_mut();
887            ok = false;
888        }
889    }
890    if !ok {
891        set_error(c, WebPEncodingError::VP8_ENC_ERROR_OUT_OF_MEMORY);
892    }
893    ok
894}
895
896/// Records `error` on a C picture with the first-error rule of
897/// `WebPEncodingSetError`.
898fn set_error(c: &mut WebPPicture, error: WebPEncodingError) {
899    if c.error_code == WebPEncodingError::VP8_ENC_OK {
900        c.error_code = error;
901    }
902}
903
904/// The mode for the storage that `use_argb` selects, and `Discard` for the other.
905fn selected(c: &WebPPicture, mode: Mode) -> (Mode, Mode) {
906    if c.use_argb != 0 {
907        (Mode::Discard, mode)
908    } else {
909        (mode, Mode::Discard)
910    }
911}
912
913/// Runs `call` on the converted C picture and writes the result back. Returns
914/// `None` when the picture cannot be converted; when `record` is set, the
915/// picture then records `VP8_ENC_ERROR_INVALID_CONFIGURATION` for a rejected
916/// layout and `VP8_ENC_ERROR_OUT_OF_MEMORY` when the host refused the copy of
917/// its block. The second value is false when the result could not be written
918/// back.
919///
920/// # Safety
921///
922/// `picture` points to a valid picture whose planes meet the contract of
923/// [`storage_to_rust`] for the given modes.
924pub(crate) unsafe fn with_picture<'a, R>(
925    picture: *mut WebPPicture,
926    modes: (Mode, Mode),
927    record: bool,
928    call: impl FnOnce(&mut RsPicture<'a>) -> R,
929) -> Option<(R, bool)> {
930    // SAFETY: a valid picture (caller's contract); the borrow ends before the
931    // call.
932    let c = unsafe { &mut *picture };
933    // SAFETY: the planes meet the contract for the modes (caller's contract).
934    let mut converted = match unsafe { picture_to_rust(c, modes.0, modes.1) } {
935        Ok(converted) => converted,
936        Err(refused) => {
937            if record {
938                set_error(
939                    c,
940                    if refused == Refused::Memory {
941                        WebPEncodingError::VP8_ENC_ERROR_OUT_OF_MEMORY
942                    } else {
943                        WebPEncodingError::VP8_ENC_ERROR_INVALID_CONFIGURATION
944                    },
945                );
946            }
947            return None;
948        }
949    };
950    let result = call(&mut converted.picture);
951    // SAFETY: as above; no Rust borrow of the C picture is live.
952    let c = unsafe { &mut *picture };
953    // SAFETY: `c` is the picture that was converted.
954    let written = unsafe { picture_to_c(c, &converted) };
955    Some((result, written))
956}
957
958/// The C picture with its buffers reset (C: `WebPPictureResetBuffers` on a copy).
959fn without_buffers(mut c: WebPPicture) -> WebPPicture {
960    c.memory_argb_ = ptr::null_mut();
961    c.argb = ptr::null_mut();
962    c.argb_stride = 0;
963    c.memory_ = ptr::null_mut();
964    (c.y, c.u, c.v, c.a) = (
965        ptr::null_mut(),
966        ptr::null_mut(),
967        ptr::null_mut(),
968        ptr::null_mut(),
969    );
970    c.y_stride = 0;
971    c.uv_stride = 0;
972    c.a_stride = 0;
973    c
974}
975
976//------------------------------------------------------------------------------
977// Packed input rows
978
979/// The packed rows of `height` rows of `width` pixels of `step` bytes at
980/// `input` with `stride` bytes between rows, as `Import` (`src/enc/picture_csp_enc.c`)
981/// reads them, and the stride to read them with. Rows with a positive stride
982/// are lent as they are; rows with a negative stride are copied into rows with
983/// a positive stride, which hold the same bytes. When `Import` fails before it
984/// reads (an empty picture, a stride shorter than its minimum), the rows are
985/// empty. `None` when the host refuses the memory for the copy.
986///
987/// # Safety
988///
989/// `input` is not null and points to the rows of the caller's contract, which
990/// nothing writes during the call.
991unsafe fn packed_rows<'a>(
992    input: *const u8,
993    width: i32,
994    height: i32,
995    stride: i32,
996    step: i32,
997    import_alpha: bool,
998) -> Option<(Cow<'a, [u8]>, i32)> {
999    let pixel = if import_alpha { 4 } else { 3 };
1000    let min_row = i64::from(pixel) * i64::from(width);
1001    if width <= 0 {
1002        // Import's stride test passes for every stride, and C reads no
1003        // sample; the stride 0 keeps every row position inside the empty rows.
1004        return Some((Cow::Borrowed(&[]), 0));
1005    }
1006    if height <= 0 || i64::from(stride).abs() < min_row {
1007        return Some((Cow::Borrowed(&[]), stride));
1008    }
1009    // The bytes of a row that Import reads: up to the last pixel's last channel.
1010    let last = i64::from(width - 1) * i64::from(step) + i64::from(pixel);
1011    let last = usize::try_from(last).unwrap_or(0);
1012    if stride >= 0 || height == 1 {
1013        let rows = if height > 1 {
1014            usize::try_from(i64::from(height - 1) * i64::from(stride)).unwrap_or(0)
1015        } else {
1016            0
1017        };
1018        // SAFETY: the caller's rows span `rows + last` initialized bytes from
1019        // `input`, which nothing writes during the call.
1020        let bytes = unsafe { slice::from_raw_parts(input, rows + last) };
1021        return Some((Cow::Borrowed(bytes), stride));
1022    }
1023    let up = stride.unsigned_abs() as usize;
1024    let copy_stride = up.max(last);
1025    let rows = usize::try_from(height).unwrap_or(0);
1026    let mut copy = Vec::new();
1027    copy.try_reserve_exact((rows - 1) * copy_stride + last)
1028        .ok()?;
1029    copy.resize((rows - 1) * copy_stride + last, 0_u8);
1030    for row in 0..rows {
1031        let start = input.wrapping_sub(row * up);
1032        // SAFETY: row `row` starts `row * |stride|` bytes before `input` and
1033        // holds `last` bytes inside the caller's rows.
1034        let bytes = unsafe { slice::from_raw_parts(start, last) };
1035        copy[row * copy_stride..row * copy_stride + last].copy_from_slice(bytes);
1036    }
1037    Some((
1038        Cow::Owned(copy),
1039        i32::try_from(copy_stride).unwrap_or(i32::MAX),
1040    ))
1041}
1042
1043//------------------------------------------------------------------------------
1044// Version and simple API
1045
1046// upstream: src/enc/webp_enc.c WebPGetEncoderVersion
1047/// Returns the encoder's version number, packed in hexadecimal using 8 bits for
1048/// each of major/minor/revision. E.g: v2.5.7 is 0x020507.
1049#[unsafe(export_name = "WebPGetEncoderVersion")]
1050#[must_use]
1051pub extern "C" fn webp_get_encoder_version() -> c_int {
1052    enc::webp_get_encoder_version()
1053}
1054
1055/// The translation of one lossless simple encoding function.
1056type SimpleEncode = fn(&[u8], i32, i32, i32) -> Option<Vec<u8>>;
1057
1058/// The translation of one lossy simple encoding function.
1059type SimpleEncodeLossy = fn(&[u8], i32, i32, i32, f32) -> Option<Vec<u8>>;
1060
1061/// The common part of the simple API (C: `Encode`): the `NULL` checks, the
1062/// configuration check that fails before `*output` is written, the packed rows,
1063/// and the output block that C releases with `WebPFree()`.
1064///
1065/// # Safety
1066///
1067/// `input` is null or points to the rows of `encode.h`'s contract; `output` is
1068/// null or writable.
1069#[expect(
1070    clippy::too_many_arguments,
1071    reason = "the C arguments plus the importer's step, alpha flag and quality"
1072)]
1073unsafe fn simple(
1074    input: *const u8,
1075    width: c_int,
1076    height: c_int,
1077    stride: c_int,
1078    step: i32,
1079    import_alpha: bool,
1080    quality_factor: f32,
1081    output: *mut *mut u8,
1082    encode: impl FnOnce(&[u8], i32) -> Option<Vec<u8>>,
1083) -> usize {
1084    if output.is_null() {
1085        return 0;
1086    }
1087    // C: `WebPConfigPreset` fails before `*output` is written.
1088    let mut config = WebPConfig::default();
1089    if !webp_config_preset(&mut config, WebPPreset::WEBP_PRESET_DEFAULT, quality_factor) {
1090        return 0;
1091    }
1092    // SAFETY: `output` is writable (caller's contract); C writes NULL on failure.
1093    unsafe { output.write(ptr::null_mut()) };
1094    if input.is_null() {
1095        return 0; // C: the importer fails.
1096    }
1097    // SAFETY: the caller's rows.
1098    let Some((rows, stride)) =
1099        (unsafe { packed_rows(input, width, height, stride, step, import_alpha) })
1100    else {
1101        return 0; // The host refused the copy of rows with a negative stride.
1102    };
1103    let Some(bytes) = encode(&rows, stride) else {
1104        return 0;
1105    };
1106    let block = malloc_copy(&bytes);
1107    if block.is_null() {
1108        return 0;
1109    }
1110    // SAFETY: as above.
1111    unsafe { output.write(block) };
1112    bytes.len()
1113}
1114
1115/// The lossy simple API through `simple`.
1116///
1117/// # Safety
1118///
1119/// As [`simple`].
1120#[expect(
1121    clippy::too_many_arguments,
1122    reason = "the C arguments plus the importer's"
1123)]
1124unsafe fn simple_lossy(
1125    input: *const u8,
1126    width: c_int,
1127    height: c_int,
1128    stride: c_int,
1129    quality_factor: f32,
1130    output: *mut *mut u8,
1131    step: i32,
1132    import_alpha: bool,
1133    encode: SimpleEncodeLossy,
1134) -> usize {
1135    // SAFETY: the caller's contract, passed on.
1136    unsafe {
1137        simple(
1138            input,
1139            width,
1140            height,
1141            stride,
1142            step,
1143            import_alpha,
1144            quality_factor,
1145            output,
1146            |rows, stride| encode(rows, width, height, stride, quality_factor),
1147        )
1148    }
1149}
1150
1151/// The lossless simple API through `simple`, at C's quality 70.
1152///
1153/// # Safety
1154///
1155/// As [`simple`].
1156#[expect(
1157    clippy::too_many_arguments,
1158    reason = "the C arguments plus the importer's"
1159)]
1160unsafe fn simple_lossless(
1161    input: *const u8,
1162    width: c_int,
1163    height: c_int,
1164    stride: c_int,
1165    output: *mut *mut u8,
1166    step: i32,
1167    import_alpha: bool,
1168    encode: SimpleEncode,
1169) -> usize {
1170    // SAFETY: the caller's contract, passed on.
1171    unsafe {
1172        simple(
1173            input,
1174            width,
1175            height,
1176            stride,
1177            step,
1178            import_alpha,
1179            70.,
1180            output,
1181            |rows, stride| encode(rows, width, height, stride),
1182        )
1183    }
1184}
1185
1186// upstream: src/enc/picture_enc.c WebPEncodeRGB
1187/// Encodes RGB rows into lossy WebP; release the output with `WebPFree()`.
1188/// Returns the size of the output, 0 on error.
1189///
1190/// # Safety
1191///
1192/// `rgb` is null or points to `height` rows of `stride` bytes; `output` is null
1193/// or writable.
1194#[unsafe(export_name = "WebPEncodeRGB")]
1195pub unsafe extern "C" fn webp_encode_rgb(
1196    rgb: *const u8,
1197    width: c_int,
1198    height: c_int,
1199    stride: c_int,
1200    quality_factor: f32,
1201    output: *mut *mut u8,
1202) -> usize {
1203    // SAFETY: the caller's contract, passed on.
1204    unsafe {
1205        simple_lossy(
1206            rgb,
1207            width,
1208            height,
1209            stride,
1210            quality_factor,
1211            output,
1212            3,
1213            false,
1214            picture_rs::webp_encode_rgb,
1215        )
1216    }
1217}
1218
1219// upstream: src/enc/picture_enc.c WebPEncodeBGR
1220/// Encodes BGR rows into lossy WebP; see [`webp_encode_rgb`].
1221///
1222/// # Safety
1223///
1224/// As [`webp_encode_rgb`].
1225#[unsafe(export_name = "WebPEncodeBGR")]
1226pub unsafe extern "C" fn webp_encode_bgr(
1227    bgr: *const u8,
1228    width: c_int,
1229    height: c_int,
1230    stride: c_int,
1231    quality_factor: f32,
1232    output: *mut *mut u8,
1233) -> usize {
1234    // SAFETY: the caller's contract, passed on.
1235    unsafe {
1236        simple_lossy(
1237            bgr,
1238            width,
1239            height,
1240            stride,
1241            quality_factor,
1242            output,
1243            3,
1244            false,
1245            picture_rs::webp_encode_bgr,
1246        )
1247    }
1248}
1249
1250// upstream: src/enc/picture_enc.c WebPEncodeRGBA
1251/// Encodes RGBA rows into lossy WebP; see [`webp_encode_rgb`].
1252///
1253/// # Safety
1254///
1255/// As [`webp_encode_rgb`].
1256#[unsafe(export_name = "WebPEncodeRGBA")]
1257pub unsafe extern "C" fn webp_encode_rgba(
1258    rgba: *const u8,
1259    width: c_int,
1260    height: c_int,
1261    stride: c_int,
1262    quality_factor: f32,
1263    output: *mut *mut u8,
1264) -> usize {
1265    // SAFETY: the caller's contract, passed on.
1266    unsafe {
1267        simple_lossy(
1268            rgba,
1269            width,
1270            height,
1271            stride,
1272            quality_factor,
1273            output,
1274            4,
1275            true,
1276            picture_rs::webp_encode_rgba,
1277        )
1278    }
1279}
1280
1281// upstream: src/enc/picture_enc.c WebPEncodeBGRA
1282/// Encodes BGRA rows into lossy WebP; see [`webp_encode_rgb`].
1283///
1284/// # Safety
1285///
1286/// As [`webp_encode_rgb`].
1287#[unsafe(export_name = "WebPEncodeBGRA")]
1288pub unsafe extern "C" fn webp_encode_bgra(
1289    bgra: *const u8,
1290    width: c_int,
1291    height: c_int,
1292    stride: c_int,
1293    quality_factor: f32,
1294    output: *mut *mut u8,
1295) -> usize {
1296    // SAFETY: the caller's contract, passed on.
1297    unsafe {
1298        simple_lossy(
1299            bgra,
1300            width,
1301            height,
1302            stride,
1303            quality_factor,
1304            output,
1305            4,
1306            true,
1307            picture_rs::webp_encode_bgra,
1308        )
1309    }
1310}
1311
1312// upstream: src/enc/picture_enc.c WebPEncodeLosslessRGB
1313/// Encodes RGB rows into lossless WebP; see [`webp_encode_rgb`].
1314///
1315/// # Safety
1316///
1317/// As [`webp_encode_rgb`].
1318#[unsafe(export_name = "WebPEncodeLosslessRGB")]
1319pub unsafe extern "C" fn webp_encode_lossless_rgb(
1320    rgb: *const u8,
1321    width: c_int,
1322    height: c_int,
1323    stride: c_int,
1324    output: *mut *mut u8,
1325) -> usize {
1326    // SAFETY: the caller's contract, passed on.
1327    unsafe {
1328        simple_lossless(
1329            rgb,
1330            width,
1331            height,
1332            stride,
1333            output,
1334            3,
1335            false,
1336            picture_rs::webp_encode_lossless_rgb,
1337        )
1338    }
1339}
1340
1341// upstream: src/enc/picture_enc.c WebPEncodeLosslessBGR
1342/// Encodes BGR rows into lossless WebP; see [`webp_encode_rgb`].
1343///
1344/// # Safety
1345///
1346/// As [`webp_encode_rgb`].
1347#[unsafe(export_name = "WebPEncodeLosslessBGR")]
1348pub unsafe extern "C" fn webp_encode_lossless_bgr(
1349    bgr: *const u8,
1350    width: c_int,
1351    height: c_int,
1352    stride: c_int,
1353    output: *mut *mut u8,
1354) -> usize {
1355    // SAFETY: the caller's contract, passed on.
1356    unsafe {
1357        simple_lossless(
1358            bgr,
1359            width,
1360            height,
1361            stride,
1362            output,
1363            3,
1364            false,
1365            picture_rs::webp_encode_lossless_bgr,
1366        )
1367    }
1368}
1369
1370// upstream: src/enc/picture_enc.c WebPEncodeLosslessRGBA
1371/// Encodes RGBA rows into lossless WebP; see [`webp_encode_rgb`].
1372///
1373/// # Safety
1374///
1375/// As [`webp_encode_rgb`].
1376#[unsafe(export_name = "WebPEncodeLosslessRGBA")]
1377pub unsafe extern "C" fn webp_encode_lossless_rgba(
1378    rgba: *const u8,
1379    width: c_int,
1380    height: c_int,
1381    stride: c_int,
1382    output: *mut *mut u8,
1383) -> usize {
1384    // SAFETY: the caller's contract, passed on.
1385    unsafe {
1386        simple_lossless(
1387            rgba,
1388            width,
1389            height,
1390            stride,
1391            output,
1392            4,
1393            true,
1394            picture_rs::webp_encode_lossless_rgba,
1395        )
1396    }
1397}
1398
1399// upstream: src/enc/picture_enc.c WebPEncodeLosslessBGRA
1400/// Encodes BGRA rows into lossless WebP; see [`webp_encode_rgb`].
1401///
1402/// # Safety
1403///
1404/// As [`webp_encode_rgb`].
1405#[unsafe(export_name = "WebPEncodeLosslessBGRA")]
1406pub unsafe extern "C" fn webp_encode_lossless_bgra(
1407    bgra: *const u8,
1408    width: c_int,
1409    height: c_int,
1410    stride: c_int,
1411    output: *mut *mut u8,
1412) -> usize {
1413    // SAFETY: the caller's contract, passed on.
1414    unsafe {
1415        simple_lossless(
1416            bgra,
1417            width,
1418            height,
1419            stride,
1420            output,
1421            4,
1422            true,
1423            picture_rs::webp_encode_lossless_bgra,
1424        )
1425    }
1426}
1427
1428//------------------------------------------------------------------------------
1429// Configuration
1430
1431// upstream: src/enc/config_enc.c WebPConfigInitInternal
1432/// Internal, version-checked entry point of `WebPConfigInit()` and
1433/// `WebPConfigPreset()`. A version mismatch and a `NULL` config return 0
1434/// without writing; otherwise every field but the reserved `use_delta_palette`
1435/// is written, and the result is that of `WebPValidateConfig()`.
1436///
1437/// # Safety
1438///
1439/// `config` is null or points to writable memory for a `WebPConfig`, which
1440/// may be uninitialized.
1441#[unsafe(export_name = "WebPConfigInitInternal")]
1442pub unsafe extern "C" fn webp_config_init_internal(
1443    config: *mut WebPConfig,
1444    preset: WebPPreset,
1445    quality: f32,
1446    version: c_int,
1447) -> c_int {
1448    if webp_abi_is_incompatible(version, WEBP_ENCODER_ABI_VERSION) {
1449        return 0; // caller/system version mismatch!
1450    }
1451    if config.is_null() {
1452        return 0;
1453    }
1454    let mut rs = WebPConfig::default();
1455    let ok = config_rs::webp_config_init_internal(&mut rs, preset, quality, version);
1456    // C does not write the reserved field, which may be uninitialized.
1457    let reserved = config
1458        .wrapping_byte_add(offset_of!(WebPConfig, use_delta_palette))
1459        .cast::<MaybeUninit<i32>>();
1460    // SAFETY: `reserved` is a field of the caller's `WebPConfig`, read as
1461    // possibly uninitialized bytes.
1462    let keep = unsafe { reserved.read() };
1463    // SAFETY: `config` is writable for a `WebPConfig`.
1464    unsafe { config.write(rs) };
1465    // SAFETY: as above, for the field.
1466    unsafe { reserved.write(keep) };
1467    c_int::from(ok)
1468}
1469
1470// upstream: src/enc/config_enc.c WebPConfigLosslessPreset
1471/// Activates the lossless compression mode with the desired efficiency level
1472/// between 0 (fastest) and 9 (slowest); returns 0 for a `NULL` config or a
1473/// level outside that range.
1474///
1475/// # Safety
1476///
1477/// `config` is null or points to a valid `WebPConfig`.
1478#[unsafe(export_name = "WebPConfigLosslessPreset")]
1479pub unsafe extern "C" fn webp_config_lossless_preset(
1480    config: *mut WebPConfig,
1481    level: c_int,
1482) -> c_int {
1483    // SAFETY: null or a valid config (caller's contract).
1484    let Some(config) = (unsafe { config.as_mut() }) else {
1485        return 0;
1486    };
1487    c_int::from(config_rs::webp_config_lossless_preset(config, level))
1488}
1489
1490// upstream: src/enc/config_enc.c WebPValidateConfig
1491/// Returns true if `config` is non-`NULL` and all configuration parameters are
1492/// within their valid ranges.
1493///
1494/// # Safety
1495///
1496/// `config` is null or points to a valid `WebPConfig`.
1497#[unsafe(export_name = "WebPValidateConfig")]
1498#[must_use]
1499pub unsafe extern "C" fn webp_validate_config(config: *const WebPConfig) -> c_int {
1500    // SAFETY: null or a valid config (caller's contract).
1501    let Some(config) = (unsafe { config.as_ref() }) else {
1502        return 0;
1503    };
1504    c_int::from(config_rs::webp_validate_config(config))
1505}
1506
1507//------------------------------------------------------------------------------
1508// Memory writer
1509
1510// upstream: src/enc/picture_enc.c WebPMemoryWriterInit
1511/// Initializes `writer` without releasing its previous buffer, as C does.
1512///
1513/// # Safety
1514///
1515/// `writer` is null or points to writable memory for a `WebPMemoryWriter`,
1516/// which may be uninitialized.
1517#[unsafe(export_name = "WebPMemoryWriterInit")]
1518pub unsafe extern "C" fn webp_memory_writer_init(writer: *mut WebPMemoryWriter) {
1519    if writer.is_null() {
1520        return; // C dereferences it.
1521    }
1522    let mut rs = RsMemoryWriter::default();
1523    picture_rs::webp_memory_writer_init(&mut rs);
1524    let field = |offset: usize| writer.wrapping_byte_add(offset);
1525    // SAFETY: a field of the caller's writable `WebPMemoryWriter`; `pad` is not
1526    // written, as in C.
1527    unsafe {
1528        field(offset_of!(WebPMemoryWriter, mem))
1529            .cast::<*mut u8>()
1530            .write(ptr::null_mut());
1531    }
1532    // SAFETY: as above.
1533    unsafe {
1534        field(offset_of!(WebPMemoryWriter, size))
1535            .cast::<usize>()
1536            .write(rs.size);
1537    }
1538    // SAFETY: as above.
1539    unsafe {
1540        field(offset_of!(WebPMemoryWriter, max_size))
1541            .cast::<usize>()
1542            .write(rs.max_size);
1543    }
1544}
1545
1546// upstream: src/enc/picture_enc.c WebPMemoryWriterClear
1547/// Releases the writer's buffer and empties it; a `NULL` writer is ignored.
1548///
1549/// # Safety
1550///
1551/// `writer` is null or points to a valid `WebPMemoryWriter` whose `mem` is null
1552/// or a block of the platform `malloc`.
1553#[unsafe(export_name = "WebPMemoryWriterClear")]
1554pub unsafe extern "C" fn webp_memory_writer_clear(writer: *mut WebPMemoryWriter) {
1555    // SAFETY: null or a valid writer (caller's contract).
1556    let Some(writer) = (unsafe { writer.as_mut() }) else {
1557        return;
1558    };
1559    // The translation releases the buffer, which the C block is here.
1560    let mut rs = RsMemoryWriter {
1561        mem: Vec::new(),
1562        size: writer.size,
1563        max_size: writer.max_size,
1564        pad: writer.pad,
1565    };
1566    picture_rs::webp_memory_writer_clear(&mut rs);
1567    // SAFETY: the writer gives up its block (C: WebPSafeFree(writer->mem)).
1568    unsafe { platform_free(writer.mem) };
1569    writer.mem = ptr::null_mut();
1570    writer.size = rs.size;
1571    writer.max_size = rs.max_size;
1572}
1573
1574// upstream: src/enc/picture_enc.c WebPMemoryWrite
1575/// The writer of `WebPMemoryWriter` as `picture->custom_ptr`: appends the data
1576/// to the buffer, which grows by doubling, with a minimum of 8192 bytes. Returns
1577/// 0 when the buffer cannot grow.
1578///
1579/// The translation works on a copy of the written bytes; the grown buffer is a
1580/// new block of the platform `malloc` of the translation's `max_size`.
1581///
1582/// # Safety
1583///
1584/// `picture` points to a valid picture whose `custom_ptr` is null or a valid
1585/// `WebPMemoryWriter`; `data` points to `data_size` readable bytes when
1586/// `data_size` is not 0.
1587#[unsafe(export_name = "WebPMemoryWrite")]
1588#[must_use]
1589pub unsafe extern "C" fn webp_memory_write(
1590    data: *const u8,
1591    data_size: usize,
1592    picture: *const WebPPicture,
1593) -> c_int {
1594    // SAFETY: a valid picture (caller's contract); C dereferences it.
1595    let Some(picture) = (unsafe { picture.as_ref() }) else {
1596        return 0;
1597    };
1598    let w = picture.custom_ptr.cast::<WebPMemoryWriter>();
1599    // SAFETY: null or a valid writer (caller's contract).
1600    let Some(w) = (unsafe { w.as_mut() }) else {
1601        return 1;
1602    };
1603    let data = if data_size == 0 || data.is_null() {
1604        &[][..]
1605    } else {
1606        // SAFETY: `data_size` readable bytes (caller's contract).
1607        unsafe { slice::from_raw_parts(data, data_size) }
1608    };
1609    let mut mem = Vec::new();
1610    if w.max_size > 0 {
1611        // A refused reservation fails as C's WebPSafeMalloc does.
1612        if mem.try_reserve_exact(w.max_size).is_err() {
1613            return 0;
1614        }
1615        mem.resize(w.max_size, 0_u8);
1616        if w.size > 0 {
1617            // SAFETY: `mem` holds the `size` written bytes of `max_size`.
1618            mem[..w.size].copy_from_slice(unsafe { slice::from_raw_parts(w.mem, w.size) });
1619        }
1620    }
1621    let old_size = w.size;
1622    let mut rs = RsMemoryWriter {
1623        mem,
1624        size: w.size,
1625        max_size: w.max_size,
1626        pad: w.pad,
1627    };
1628    if !picture_rs::webp_memory_write(&mut rs, data) {
1629        return 0;
1630    }
1631    if rs.max_size != w.max_size {
1632        let block = platform_malloc(rs.max_size);
1633        if block.is_null() {
1634            return 0;
1635        }
1636        // SAFETY: `block` holds `max_size` bytes, a new allocation.
1637        unsafe { ptr::copy_nonoverlapping(rs.mem.as_ptr(), block, rs.size) };
1638        // SAFETY: the writer gives up its old block (C: WebPSafeFree(w->mem)).
1639        unsafe { platform_free(w.mem) };
1640        w.mem = block;
1641        w.max_size = rs.max_size;
1642    } else if rs.size > old_size {
1643        let end = w.mem.wrapping_add(old_size);
1644        // SAFETY: the writer's block holds `max_size` bytes, of which the new
1645        // ones start at `old_size`.
1646        unsafe {
1647            ptr::copy_nonoverlapping(rs.mem[old_size..].as_ptr(), end, rs.size - old_size);
1648        }
1649    }
1650    w.size = rs.size;
1651    1
1652}
1653
1654//------------------------------------------------------------------------------
1655// Picture initialization, allocation and release
1656
1657/// The writer that `WebPPictureInit()` installs (C: `DummyWriter`), which
1658/// discards the data and reports success.
1659unsafe extern "C" fn dummy_writer(
1660    _data: *const u8,
1661    _data_size: usize,
1662    _picture: *const WebPPicture,
1663) -> c_int {
1664    1
1665}
1666
1667// upstream: src/enc/picture_enc.c WebPPictureInitInternal
1668/// Internal, version-checked entry point of `WebPPictureInit()`: clears the
1669/// picture, installs the discarding writer and records no error. Returns 0 on a
1670/// version mismatch, without writing, and 1 otherwise, also for a `NULL`
1671/// picture.
1672///
1673/// # Safety
1674///
1675/// `picture` is null or points to writable memory for a `WebPPicture`, which
1676/// may be uninitialized.
1677#[unsafe(export_name = "WebPPictureInitInternal")]
1678pub unsafe extern "C" fn webp_picture_init_internal(
1679    picture: *mut WebPPicture,
1680    version: c_int,
1681) -> c_int {
1682    let mut rs = RsPicture::default();
1683    if !picture_rs::webp_picture_init_internal(&mut rs, version) {
1684        return 0; // caller/system version mismatch!
1685    }
1686    if picture.is_null() {
1687        return 1;
1688    }
1689    // The translation's cleared picture: zero fields, the discarding writer and
1690    // no error.
1691    let c = WebPPicture {
1692        use_argb: rs.use_argb,
1693        colorspace: rs.colorspace,
1694        width: rs.width,
1695        height: rs.height,
1696        y: ptr::null_mut(),
1697        u: ptr::null_mut(),
1698        v: ptr::null_mut(),
1699        y_stride: rs.y_stride,
1700        uv_stride: rs.uv_stride,
1701        a: ptr::null_mut(),
1702        a_stride: rs.a_stride,
1703        pad1: rs.pad1,
1704        argb: ptr::null_mut(),
1705        argb_stride: rs.argb_stride,
1706        pad2: rs.pad2,
1707        writer: rs
1708            .writer
1709            .is_some()
1710            .then_some(dummy_writer as WebPWriterFunction),
1711        custom_ptr: ptr::null_mut(),
1712        extra_info_type: rs.extra_info_type,
1713        extra_info: ptr::null_mut(),
1714        stats: ptr::null_mut(),
1715        error_code: rs.error_code,
1716        progress_hook: None,
1717        user_data: ptr::null_mut(),
1718        pad3: rs.pad3,
1719        pad4: ptr::null_mut(),
1720        pad5: ptr::null_mut(),
1721        pad6: rs.pad6,
1722        memory_: ptr::null_mut(),
1723        memory_argb_: ptr::null_mut(),
1724        pad7: [ptr::null_mut(); 2],
1725    };
1726    // SAFETY: `picture` is writable for a `WebPPicture` (caller's contract).
1727    unsafe { picture.write(c) };
1728    1
1729}
1730
1731// upstream: src/enc/picture_enc.c WebPPictureAlloc
1732/// Releases the picture's planes and allocates new ones of its dimensions, in
1733/// the layout that `use_argb` selects. Returns 0 on error, recorded in
1734/// `error_code`; a `NULL` picture returns 1, as in C.
1735///
1736/// # Safety
1737///
1738/// `picture` is null or points to a valid picture whose `memory_` and
1739/// `memory_argb_` are null or blocks of the platform `malloc`.
1740#[unsafe(export_name = "WebPPictureAlloc")]
1741pub unsafe extern "C" fn webp_picture_alloc(picture: *mut WebPPicture) -> c_int {
1742    if picture.is_null() {
1743        return 1;
1744    }
1745    // SAFETY: a valid picture; nothing is lent.
1746    let result = unsafe {
1747        with_picture(picture, (Mode::Discard, Mode::Discard), false, |rs| {
1748            picture_rs::webp_picture_alloc(rs).is_ok()
1749        })
1750    };
1751    c_int::from(result.is_some_and(|(ok, written)| ok && written))
1752}
1753
1754// upstream: src/enc/picture_enc.c WebPPictureFree
1755/// Releases the memory that `WebPPictureAlloc()` or `WebPPictureImport*()`
1756/// allocated and resets the plane pointers; a `NULL` picture is ignored.
1757///
1758/// # Safety
1759///
1760/// As [`webp_picture_alloc`].
1761#[unsafe(export_name = "WebPPictureFree")]
1762pub unsafe extern "C" fn webp_picture_free(picture: *mut WebPPicture) {
1763    if picture.is_null() {
1764        return;
1765    }
1766    // SAFETY: a valid picture; nothing is lent.
1767    let _ = unsafe {
1768        with_picture(picture, (Mode::Discard, Mode::Discard), false, |rs| {
1769            picture_rs::webp_picture_free(rs);
1770        })
1771    };
1772}
1773
1774//------------------------------------------------------------------------------
1775// Copy, views, cropping and rescaling
1776
1777// upstream: src/enc/picture_rescale_enc.c WebPPictureCopy
1778/// Copies `src` into `dst` with new planes that `dst` owns. As C does, `dst`
1779/// receives every field of `src` first, and its previous memory is not
1780/// released. Returns 0 on error and for `NULL` pictures; `src == dst` returns 1.
1781///
1782/// # Safety
1783///
1784/// `src` and `dst` are null or valid pictures; the planes of `src` that
1785/// `use_argb` selects are readable for its dimensions.
1786#[unsafe(export_name = "WebPPictureCopy")]
1787pub unsafe extern "C" fn webp_picture_copy(
1788    src: *const WebPPicture,
1789    dst: *mut WebPPicture,
1790) -> c_int {
1791    if src.is_null() || dst.is_null() {
1792        return 0;
1793    }
1794    if src == dst.cast_const() {
1795        return 1;
1796    }
1797    // SAFETY: a valid picture (caller's contract).
1798    let c_src = unsafe { *src };
1799    let (yuva, argb) = selected(&c_src, Mode::Read);
1800    // SAFETY: the selected planes are readable (caller's contract).
1801    let Ok(source) = (unsafe { picture_to_rust(&c_src, yuva, argb) }) else {
1802        return 0;
1803    };
1804    let mut copy = RsPicture::default();
1805    let ok = rescale::webp_picture_copy(&source.picture, &mut copy).is_ok();
1806    // C: PictureGrabSpecs(src, dst), then WebPPictureAlloc(dst) and the copy.
1807    let mut c_dst = without_buffers(c_src);
1808    let converted = Converted {
1809        picture: copy,
1810        yuva: Origin::Nothing,
1811        argb: Origin::Nothing,
1812    };
1813    // SAFETY: `c_dst` holds no memory; new samples go into new blocks.
1814    let written = unsafe { picture_to_c(&mut c_dst, &converted) };
1815    // SAFETY: `dst` is a valid picture (caller's contract), distinct from `src`.
1816    unsafe { dst.write(c_dst) };
1817    c_int::from(ok && written)
1818}
1819
1820// upstream: src/enc/picture_rescale_enc.c WebPPictureIsView
1821/// Returns true if the picture does not own its memory (C: its `memory_` or
1822/// `memory_argb_`, as `use_argb` selects, is `NULL`); 0 for a `NULL` picture.
1823///
1824/// The translation reads only `use_argb` and whether the selected storage holds
1825/// memory, which this function passes as a one-sample owned storage for C's
1826/// non-null memory field.
1827///
1828/// # Safety
1829///
1830/// `picture` is null or a valid picture.
1831#[unsafe(export_name = "WebPPictureIsView")]
1832#[must_use]
1833pub unsafe extern "C" fn webp_picture_is_view(picture: *const WebPPicture) -> c_int {
1834    // SAFETY: null or a valid picture (caller's contract).
1835    let Some(c) = (unsafe { picture.as_ref() }) else {
1836        return 0;
1837    };
1838    let mut rs = RsPicture {
1839        use_argb: c.use_argb,
1840        ..RsPicture::default()
1841    };
1842    if !c.memory_.is_null() {
1843        rs.yuva = PlaneStorage::Internal(vec![0]);
1844    }
1845    if !c.memory_argb_.is_null() {
1846        rs.argb_storage = PlaneStorage::Internal(vec![0]);
1847    }
1848    c_int::from(rescale::webp_picture_is_view(&rs))
1849}
1850
1851// upstream: src/enc/picture_rescale_enc.c WebPPictureView
1852/// Makes `dst` a view of the rectangle of `src`: its planes point into those of
1853/// `src`, and it owns no memory. As C does, `dst` receives every field of `src`
1854/// first unless `src == dst`. Returns 0 for an invalid rectangle and for `NULL`
1855/// pictures.
1856///
1857/// # Safety
1858///
1859/// `src` and `dst` are null or valid pictures; the planes of `src` that
1860/// `use_argb` selects are addressable for its dimensions.
1861#[unsafe(export_name = "WebPPictureView")]
1862pub unsafe extern "C" fn webp_picture_view(
1863    src: *const WebPPicture,
1864    left: c_int,
1865    top: c_int,
1866    width: c_int,
1867    height: c_int,
1868    dst: *mut WebPPicture,
1869) -> c_int {
1870    if src.is_null() || dst.is_null() {
1871        return 0;
1872    }
1873    // SAFETY: a valid picture (caller's contract).
1874    let c_src = unsafe { *src };
1875    // C only computes the view's plane addresses: no sample is lent.
1876    let (yuva, argb) = selected(&c_src, Mode::Address);
1877    // SAFETY: `Mode::Address` lends no memory.
1878    let Ok(source) = (unsafe { picture_to_rust(&c_src, yuva, argb) }) else {
1879        return 0;
1880    };
1881    let Some(view) = rescale::webp_picture_view(&source.picture, left, top, width, height) else {
1882        return 0;
1883    };
1884    let bases = |origin: &Origin| match origin {
1885        Origin::Block { base, .. } => vec![*base],
1886        Origin::Lent(bases) => bases.clone(),
1887        Origin::Nothing => Vec::new(),
1888    };
1889    let mut c_dst = if src == dst.cast_const() {
1890        c_src
1891    } else {
1892        // C: PictureGrabSpecs(src, dst).
1893        without_buffers(c_src)
1894    };
1895    c_dst.width = view.width;
1896    c_dst.height = view.height;
1897    if c_src.use_argb == 0 {
1898        let pointers =
1899            plane_pointers::<u8>(&bases(&source.yuva), &[view.y, view.u, view.v, view.a]);
1900        c_dst.y = pointers[0];
1901        c_dst.u = pointers[1];
1902        c_dst.v = pointers[2];
1903        c_dst.y_stride = view.y_stride;
1904        c_dst.uv_stride = view.uv_stride;
1905        if !c_src.a.is_null() {
1906            c_dst.a = pointers[3];
1907            c_dst.a_stride = view.a_stride;
1908        }
1909    } else {
1910        c_dst.argb = plane_pointers::<u32>(&bases(&source.argb), &[view.argb])[0].cast();
1911        c_dst.argb_stride = view.argb_stride;
1912    }
1913    drop(view);
1914    drop(source);
1915    // SAFETY: `dst` is a valid picture (caller's contract); no Rust borrow of it
1916    // or of `src` is live.
1917    unsafe { dst.write(c_dst) };
1918    1
1919}
1920
1921// upstream: src/enc/picture_rescale_enc.c WebPPictureCrop
1922/// Crops the picture to the rectangle, replacing its planes with new ones.
1923/// Returns 0 for an invalid rectangle, on error (recorded in `error_code`) and
1924/// for a `NULL` picture.
1925///
1926/// # Safety
1927///
1928/// `picture` is null or a valid picture whose planes that `use_argb` selects
1929/// are readable for its dimensions, and whose memory fields are null or blocks
1930/// of the platform `malloc`.
1931#[unsafe(export_name = "WebPPictureCrop")]
1932pub unsafe extern "C" fn webp_picture_crop(
1933    picture: *mut WebPPicture,
1934    left: c_int,
1935    top: c_int,
1936    width: c_int,
1937    height: c_int,
1938) -> c_int {
1939    // SAFETY: null or a valid picture (caller's contract).
1940    let Some(c) = (unsafe { picture.as_ref() }) else {
1941        return 0;
1942    };
1943    let modes = selected(c, Mode::Read);
1944    // SAFETY: the selected planes are readable (caller's contract).
1945    let result = unsafe {
1946        with_picture(picture, modes, true, |rs| {
1947            rescale::webp_picture_crop(rs, left, top, width, height)
1948        })
1949    };
1950    c_int::from(result.is_some_and(|(ok, written)| ok && written))
1951}
1952
1953// upstream: src/enc/picture_rescale_enc.c WebPPictureRescale
1954/// Rescales the picture to `width` by `height`, replacing its planes with new
1955/// ones; a 0 dimension keeps the aspect ratio. Returns 0 on error (recorded in
1956/// `error_code`) and for a `NULL` picture.
1957///
1958/// # Safety
1959///
1960/// `picture` is null or a valid picture whose planes that `use_argb` selects
1961/// are writable for its dimensions, and whose memory fields are null or blocks
1962/// of the platform `malloc`.
1963#[unsafe(export_name = "WebPPictureRescale")]
1964pub unsafe extern "C" fn webp_picture_rescale(
1965    picture: *mut WebPPicture,
1966    width: c_int,
1967    height: c_int,
1968) -> c_int {
1969    // SAFETY: null or a valid picture (caller's contract).
1970    let Some(c) = (unsafe { picture.as_ref() }) else {
1971        return 0;
1972    };
1973    let modes = selected(c, Mode::Write);
1974    // SAFETY: the selected planes are writable (caller's contract).
1975    let result = unsafe {
1976        with_picture(picture, modes, true, |rs| {
1977            rescale::webp_picture_rescale(rs, width, height).is_ok()
1978        })
1979    };
1980    c_int::from(result.is_some_and(|(ok, written)| ok && written))
1981}
1982
1983//------------------------------------------------------------------------------
1984// Distortion
1985
1986// upstream: src/enc/picture_psnr_enc.c WebPPlaneDistortion
1987/// Computes the distortion of `ref` against `src` over a plane of `width` by
1988/// `height` samples, `x_step` bytes apart, with the metric `type` (0: PSNR,
1989/// 1: SSIM, 2: LSIM). Returns 0 for `NULL` arguments and short strides.
1990///
1991/// # Safety
1992///
1993/// The planes are null or readable for the samples that C reads: `width *
1994/// height` bytes when `x_step` is 1, the strided samples otherwise;
1995/// `distortion` and `result` are null or writable.
1996#[unsafe(export_name = "WebPPlaneDistortion")]
1997pub unsafe extern "C" fn webp_plane_distortion(
1998    src: *const u8,
1999    src_stride: usize,
2000    reference: *const u8,
2001    ref_stride: usize,
2002    width: c_int,
2003    height: c_int,
2004    x_step: usize,
2005    kind: c_int,
2006    distortion: *mut f32,
2007    result: *mut f32,
2008) -> c_int {
2009    if src.is_null() || reference.is_null() || result.is_null() || distortion.is_null() {
2010        return 0;
2011    }
2012    // The samples that C reads, or none when it fails before reading.
2013    let extent = |stride: usize| -> usize {
2014        let (Ok(w), Ok(h)) = (usize::try_from(width), usize::try_from(height)) else {
2015            return 0;
2016        };
2017        if w == 0
2018            || h == 0
2019            || src_stride < x_step.wrapping_mul(w)
2020            || ref_stride < x_step.wrapping_mul(w)
2021        {
2022            return 0;
2023        }
2024        if x_step == 1 {
2025            w * h
2026        } else {
2027            (h - 1) * stride + (w - 1) * x_step + 1
2028        }
2029    };
2030    // SAFETY: readable for the samples that C reads (caller's contract).
2031    let src = unsafe { slice::from_raw_parts(src, extent(src_stride)) };
2032    // SAFETY: as above.
2033    let reference = unsafe { slice::from_raw_parts(reference, extent(ref_stride)) };
2034    let mut d = 0.;
2035    let mut r = 0.;
2036    let ok = psnr::webp_plane_distortion(
2037        src, src_stride, reference, ref_stride, width, height, x_step, kind, &mut d, &mut r,
2038    );
2039    if ok {
2040        // SAFETY: writable (caller's contract).
2041        unsafe { distortion.write(d) };
2042        // SAFETY: as above.
2043        unsafe { result.write(r) };
2044    }
2045    c_int::from(ok)
2046}
2047
2048// upstream: src/enc/picture_psnr_enc.c WebPPictureDistortion
2049/// Computes the PSNR, SSIM or LSIM distortion of `ref` against `src`, per
2050/// channel (B, G, R, A) and over all channels, in `result[5]`. Returns 0 for
2051/// `NULL` arguments, different dimensions and errors; the results are then not
2052/// written.
2053///
2054/// # Safety
2055///
2056/// `src` and `ref` are null or valid pictures whose planes that `use_argb`
2057/// selects are readable for their dimensions; `result` is null or writable for
2058/// five floats.
2059#[unsafe(export_name = "WebPPictureDistortion")]
2060pub unsafe extern "C" fn webp_picture_distortion(
2061    src: *const WebPPicture,
2062    reference: *const WebPPicture,
2063    kind: c_int,
2064    result: *mut f32,
2065) -> c_int {
2066    if src.is_null() || reference.is_null() || result.is_null() {
2067        return 0;
2068    }
2069    // SAFETY: a valid picture (caller's contract).
2070    let c_src = unsafe { *src };
2071    // SAFETY: as above.
2072    let c_ref = unsafe { *reference };
2073    let (yuva, argb) = selected(&c_src, Mode::Read);
2074    // SAFETY: the selected planes are readable (caller's contract).
2075    let Ok(source) = (unsafe { picture_to_rust(&c_src, yuva, argb) }) else {
2076        return 0;
2077    };
2078    let (yuva, argb) = selected(&c_ref, Mode::Read);
2079    // SAFETY: as above.
2080    let Ok(target) = (unsafe { picture_to_rust(&c_ref, yuva, argb) }) else {
2081        return 0;
2082    };
2083    let mut results = [0_f32; 5];
2084    if !psnr::webp_picture_distortion(&source.picture, &target.picture, kind, &mut results) {
2085        return 0;
2086    }
2087    // SAFETY: writable for five floats (caller's contract).
2088    unsafe { ptr::copy_nonoverlapping(results.as_ptr(), result, results.len()) };
2089    1
2090}
2091
2092//------------------------------------------------------------------------------
2093// Import and colorspace conversion
2094
2095/// The importers through the C ABI: the `NULL` checks, the packed rows and the
2096/// converted picture, which lends nothing (an importer replaces the planes it
2097/// writes).
2098///
2099/// # Safety
2100///
2101/// `picture` is null or a valid picture whose memory fields are null or blocks
2102/// of the platform `malloc`; `input` is null or points to the picture's rows.
2103unsafe fn import(
2104    picture: *mut WebPPicture,
2105    input: *const u8,
2106    stride: c_int,
2107    step: i32,
2108    import_alpha: bool,
2109    importer: fn(&mut RsPicture<'_>, &[u8], i32) -> bool,
2110) -> c_int {
2111    if input.is_null() {
2112        return 0;
2113    }
2114    // SAFETY: null or a valid picture (caller's contract).
2115    let Some(c) = (unsafe { picture.as_ref() }) else {
2116        return 0;
2117    };
2118    // SAFETY: the picture's rows (caller's contract).
2119    let Some((rows, stride)) =
2120        (unsafe { packed_rows(input, c.width, c.height, stride, step, import_alpha) })
2121    else {
2122        // The host refused the copy of rows with a negative stride.
2123        // SAFETY: a valid picture (caller's contract), no other borrow.
2124        set_error(
2125            unsafe { &mut *picture },
2126            WebPEncodingError::VP8_ENC_ERROR_OUT_OF_MEMORY,
2127        );
2128        return 0;
2129    };
2130    // SAFETY: a valid picture; nothing is lent.
2131    let result = unsafe {
2132        with_picture(picture, (Mode::Discard, Mode::Discard), false, |rs| {
2133            importer(rs, &rows, stride)
2134        })
2135    };
2136    c_int::from(result.is_some_and(|(ok, written)| ok && written))
2137}
2138
2139// upstream: src/enc/picture_csp_enc.c WebPPictureImportRGB
2140/// Imports RGB rows of `rgb_stride` bytes into the picture, as `use_argb`
2141/// selects. Returns 0 on error and for `NULL` arguments.
2142///
2143/// # Safety
2144///
2145/// `picture` is null or a valid picture whose memory fields are null or blocks
2146/// of the platform `malloc`; the rows are null or point to `height` rows of
2147/// the stride, which nothing writes during the call.
2148#[unsafe(export_name = "WebPPictureImportRGB")]
2149pub unsafe extern "C" fn webp_picture_import_rgb(
2150    picture: *mut WebPPicture,
2151    rgb: *const u8,
2152    rgb_stride: c_int,
2153) -> c_int {
2154    // SAFETY: the caller's contract, passed on.
2155    unsafe {
2156        import(
2157            picture,
2158            rgb,
2159            rgb_stride,
2160            3,
2161            false,
2162            csp::webp_picture_import_rgb,
2163        )
2164    }
2165}
2166
2167// upstream: src/enc/picture_csp_enc.c WebPPictureImportRGBA
2168/// Imports RGBA rows; see [`webp_picture_import_rgb`].
2169///
2170/// # Safety
2171///
2172/// `picture` is null or a valid picture whose memory fields are null or blocks
2173/// of the platform `malloc`; the rows are null or point to `height` rows of
2174/// the stride, which nothing writes during the call.
2175#[unsafe(export_name = "WebPPictureImportRGBA")]
2176pub unsafe extern "C" fn webp_picture_import_rgba(
2177    picture: *mut WebPPicture,
2178    rgba: *const u8,
2179    rgba_stride: c_int,
2180) -> c_int {
2181    // SAFETY: the caller's contract, passed on.
2182    unsafe {
2183        import(
2184            picture,
2185            rgba,
2186            rgba_stride,
2187            4,
2188            true,
2189            csp::webp_picture_import_rgba,
2190        )
2191    }
2192}
2193
2194// upstream: src/enc/picture_csp_enc.c WebPPictureImportRGBX
2195/// Imports RGBX rows, ignoring the fourth byte; see [`webp_picture_import_rgb`].
2196///
2197/// # Safety
2198///
2199/// `picture` is null or a valid picture whose memory fields are null or blocks
2200/// of the platform `malloc`; the rows are null or point to `height` rows of
2201/// the stride, which nothing writes during the call.
2202#[unsafe(export_name = "WebPPictureImportRGBX")]
2203pub unsafe extern "C" fn webp_picture_import_rgbx(
2204    picture: *mut WebPPicture,
2205    rgbx: *const u8,
2206    rgbx_stride: c_int,
2207) -> c_int {
2208    // SAFETY: the caller's contract, passed on.
2209    unsafe {
2210        import(
2211            picture,
2212            rgbx,
2213            rgbx_stride,
2214            4,
2215            false,
2216            csp::webp_picture_import_rgbx,
2217        )
2218    }
2219}
2220
2221// upstream: src/enc/picture_csp_enc.c WebPPictureImportBGR
2222/// Imports BGR rows; see [`webp_picture_import_rgb`].
2223///
2224/// # Safety
2225///
2226/// `picture` is null or a valid picture whose memory fields are null or blocks
2227/// of the platform `malloc`; the rows are null or point to `height` rows of
2228/// the stride, which nothing writes during the call.
2229#[unsafe(export_name = "WebPPictureImportBGR")]
2230pub unsafe extern "C" fn webp_picture_import_bgr(
2231    picture: *mut WebPPicture,
2232    bgr: *const u8,
2233    bgr_stride: c_int,
2234) -> c_int {
2235    // SAFETY: the caller's contract, passed on.
2236    unsafe {
2237        import(
2238            picture,
2239            bgr,
2240            bgr_stride,
2241            3,
2242            false,
2243            csp::webp_picture_import_bgr,
2244        )
2245    }
2246}
2247
2248// upstream: src/enc/picture_csp_enc.c WebPPictureImportBGRA
2249/// Imports BGRA rows; see [`webp_picture_import_rgb`].
2250///
2251/// # Safety
2252///
2253/// `picture` is null or a valid picture whose memory fields are null or blocks
2254/// of the platform `malloc`; the rows are null or point to `height` rows of
2255/// the stride, which nothing writes during the call.
2256#[unsafe(export_name = "WebPPictureImportBGRA")]
2257pub unsafe extern "C" fn webp_picture_import_bgra(
2258    picture: *mut WebPPicture,
2259    bgra: *const u8,
2260    bgra_stride: c_int,
2261) -> c_int {
2262    // SAFETY: the caller's contract, passed on.
2263    unsafe {
2264        import(
2265            picture,
2266            bgra,
2267            bgra_stride,
2268            4,
2269            true,
2270            csp::webp_picture_import_bgra,
2271        )
2272    }
2273}
2274
2275// upstream: src/enc/picture_csp_enc.c WebPPictureImportBGRX
2276/// Imports BGRX rows, ignoring the fourth byte; see [`webp_picture_import_rgb`].
2277///
2278/// # Safety
2279///
2280/// `picture` is null or a valid picture whose memory fields are null or blocks
2281/// of the platform `malloc`; the rows are null or point to `height` rows of
2282/// the stride, which nothing writes during the call.
2283#[unsafe(export_name = "WebPPictureImportBGRX")]
2284pub unsafe extern "C" fn webp_picture_import_bgrx(
2285    picture: *mut WebPPicture,
2286    bgrx: *const u8,
2287    bgrx_stride: c_int,
2288) -> c_int {
2289    // SAFETY: the caller's contract, passed on.
2290    unsafe {
2291        import(
2292            picture,
2293            bgrx,
2294            bgrx_stride,
2295            4,
2296            false,
2297            csp::webp_picture_import_bgrx,
2298        )
2299    }
2300}
2301
2302/// A conversion from the ARGB plane to new YUVA planes: the ARGB plane is read,
2303/// the YUVA planes are replaced.
2304///
2305/// # Safety
2306///
2307/// `picture` is null or a valid picture whose ARGB plane is readable for its
2308/// dimensions and whose memory fields are null or blocks of the platform
2309/// `malloc`.
2310unsafe fn argb_to_yuva(
2311    picture: *mut WebPPicture,
2312    convert: impl FnOnce(&mut RsPicture<'_>) -> Result<(), WebPEncodingError>,
2313) -> c_int {
2314    if picture.is_null() {
2315        return 0;
2316    }
2317    // SAFETY: the ARGB plane is readable (caller's contract).
2318    let result = unsafe {
2319        with_picture(picture, (Mode::Discard, Mode::Read), true, |rs| {
2320            convert(rs).is_ok()
2321        })
2322    };
2323    c_int::from(result.is_some_and(|(ok, written)| ok && written))
2324}
2325
2326// upstream: src/enc/picture_csp_enc.c WebPPictureARGBToYUVA
2327/// Converts the ARGB samples to the YUV420(A) colorspace. Returns 0 on error
2328/// (recorded in `error_code`) and for a `NULL` picture.
2329///
2330/// # Safety
2331///
2332/// `picture` is null or a valid picture whose ARGB plane is readable for its
2333/// dimensions and whose memory fields are null or blocks of the platform
2334/// `malloc`.
2335#[unsafe(export_name = "WebPPictureARGBToYUVA")]
2336pub unsafe extern "C" fn webp_picture_argb_to_yuva(
2337    picture: *mut WebPPicture,
2338    colorspace: WebPEncCSP,
2339) -> c_int {
2340    // SAFETY: the caller's contract, passed on.
2341    unsafe { argb_to_yuva(picture, |rs| csp::webp_picture_argb_to_yuva(rs, colorspace)) }
2342}
2343
2344// upstream: src/enc/picture_csp_enc.c WebPPictureARGBToYUVADithered
2345/// As [`webp_picture_argb_to_yuva`], with dithering of strength `dithering`.
2346///
2347/// # Safety
2348///
2349/// `picture` is null or a valid picture whose ARGB plane is readable for its
2350/// dimensions and whose memory fields are null or blocks of the platform
2351/// `malloc`.
2352#[unsafe(export_name = "WebPPictureARGBToYUVADithered")]
2353pub unsafe extern "C" fn webp_picture_argb_to_yuva_dithered(
2354    picture: *mut WebPPicture,
2355    colorspace: WebPEncCSP,
2356    dithering: f32,
2357) -> c_int {
2358    // SAFETY: the caller's contract, passed on.
2359    unsafe {
2360        argb_to_yuva(picture, |rs| {
2361            csp::webp_picture_argb_to_yuva_dithered(rs, colorspace, dithering)
2362        })
2363    }
2364}
2365
2366// upstream: src/enc/picture_csp_enc.c WebPPictureSharpARGBToYUVA
2367/// As [`webp_picture_argb_to_yuva`], with the sharp (iterative) conversion.
2368///
2369/// # Safety
2370///
2371/// `picture` is null or a valid picture whose ARGB plane is readable for its
2372/// dimensions and whose memory fields are null or blocks of the platform
2373/// `malloc`.
2374#[unsafe(export_name = "WebPPictureSharpARGBToYUVA")]
2375pub unsafe extern "C" fn webp_picture_sharp_argb_to_yuva(picture: *mut WebPPicture) -> c_int {
2376    // SAFETY: the caller's contract, passed on.
2377    unsafe { argb_to_yuva(picture, csp::webp_picture_sharp_argb_to_yuva) }
2378}
2379
2380// upstream: src/enc/picture_csp_enc.c WebPPictureSmartARGBToYUVA
2381/// Kept for backward compatibility: [`webp_picture_sharp_argb_to_yuva`].
2382///
2383/// # Safety
2384///
2385/// `picture` is null or a valid picture whose ARGB plane is readable for its
2386/// dimensions and whose memory fields are null or blocks of the platform
2387/// `malloc`.
2388#[unsafe(export_name = "WebPPictureSmartARGBToYUVA")]
2389pub unsafe extern "C" fn webp_picture_smart_argb_to_yuva(picture: *mut WebPPicture) -> c_int {
2390    // SAFETY: the caller's contract, passed on.
2391    unsafe { argb_to_yuva(picture, csp::webp_picture_smart_argb_to_yuva) }
2392}
2393
2394// upstream: src/enc/picture_csp_enc.c WebPPictureYUVAToARGB
2395/// Converts the YUV420(A) planes to a new ARGB plane and sets `use_argb`.
2396/// Returns 0 on error (recorded in `error_code`) and for a `NULL` picture.
2397///
2398/// # Safety
2399///
2400/// `picture` is null or a valid picture whose YUVA planes are readable for its
2401/// dimensions and whose memory fields are null or blocks of the platform
2402/// `malloc`.
2403#[unsafe(export_name = "WebPPictureYUVAToARGB")]
2404pub unsafe extern "C" fn webp_picture_yuva_to_argb(picture: *mut WebPPicture) -> c_int {
2405    if picture.is_null() {
2406        return 0;
2407    }
2408    // SAFETY: the YUVA planes are readable (caller's contract).
2409    let result = unsafe {
2410        with_picture(picture, (Mode::Read, Mode::Discard), true, |rs| {
2411            csp::webp_picture_yuva_to_argb(rs).is_ok()
2412        })
2413    };
2414    c_int::from(result.is_some_and(|(ok, written)| ok && written))
2415}
2416
2417//------------------------------------------------------------------------------
2418// Picture tools
2419
2420// upstream: src/enc/picture_tools_enc.c WebPCleanupTransparentArea
2421/// Flattens the samples under fully transparent areas, so they compress
2422/// better; a `NULL` picture is ignored.
2423///
2424/// # Safety
2425///
2426/// `picture` is null or a valid picture whose planes that `use_argb` selects
2427/// are writable for its dimensions.
2428#[unsafe(export_name = "WebPCleanupTransparentArea")]
2429pub unsafe extern "C" fn webp_cleanup_transparent_area(picture: *mut WebPPicture) {
2430    // SAFETY: null or a valid picture (caller's contract).
2431    let Some(c) = (unsafe { picture.as_ref() }) else {
2432        return;
2433    };
2434    let modes = selected(c, Mode::Write);
2435    // SAFETY: the selected planes are writable (caller's contract).
2436    let _ = unsafe { with_picture(picture, modes, false, tools::webp_cleanup_transparent_area) };
2437}
2438
2439// upstream: src/enc/picture_tools_enc.c WebPPictureHasTransparency
2440/// Returns true if the picture has an alpha sample below 0xff; 0 for a `NULL`
2441/// picture.
2442///
2443/// # Safety
2444///
2445/// `picture` is null or a valid picture whose planes that `use_argb` selects
2446/// are readable for its dimensions.
2447#[unsafe(export_name = "WebPPictureHasTransparency")]
2448#[must_use]
2449pub unsafe extern "C" fn webp_picture_has_transparency(picture: *const WebPPicture) -> c_int {
2450    // SAFETY: null or a valid picture (caller's contract).
2451    let Some(c) = (unsafe { picture.as_ref() }) else {
2452        return 0;
2453    };
2454    // C reads only the alpha plane of a YUV picture, and the ARGB plane of an
2455    // ARGB picture.
2456    let mut read = *c;
2457    if read.use_argb == 0 {
2458        (read.y, read.u, read.v) = (ptr::null_mut(), ptr::null_mut(), ptr::null_mut());
2459    }
2460    let (yuva, argb) = selected(&read, Mode::Read);
2461    // SAFETY: the plane that C reads is readable (caller's contract).
2462    let Ok(converted) = (unsafe { picture_to_rust(&read, yuva, argb) }) else {
2463        return 0;
2464    };
2465    c_int::from(csp::webp_picture_has_transparency(&converted.picture))
2466}
2467
2468// upstream: src/enc/picture_tools_enc.c WebPBlendAlpha
2469/// Blends the samples with the background color `background_rgb` (0x00RRGGBB)
2470/// and makes them opaque; a `NULL` picture is ignored.
2471///
2472/// # Safety
2473///
2474/// As [`webp_cleanup_transparent_area`].
2475#[unsafe(export_name = "WebPBlendAlpha")]
2476pub unsafe extern "C" fn webp_blend_alpha(picture: *mut WebPPicture, background_rgb: u32) {
2477    // SAFETY: null or a valid picture (caller's contract).
2478    let Some(c) = (unsafe { picture.as_ref() }) else {
2479        return;
2480    };
2481    let modes = selected(c, Mode::Write);
2482    // SAFETY: the selected planes are writable (caller's contract).
2483    let _ = unsafe {
2484        with_picture(picture, modes, false, |rs| {
2485            tools::webp_blend_alpha(rs, background_rgb);
2486        })
2487    };
2488}
2489
2490//------------------------------------------------------------------------------
2491// Encoding
2492
2493/// The C writer as the translation's writer: it passes the caller's picture
2494/// pointer, as C does.
2495fn writer_closure<'a>(
2496    writer: WebPWriterFunction,
2497    picture: *const WebPPicture,
2498) -> RsWriterFunction<'a> {
2499    Box::new(move |data: &[u8]| {
2500        // SAFETY: the caller's writer, called with the data, its size and the
2501        // caller's picture, which no Rust reference borrows during the call.
2502        unsafe { writer(data.as_ptr(), data.len(), picture) != 0 }
2503    })
2504}
2505
2506/// The C progress hook as the translation's hook: it passes the caller's
2507/// picture pointer, as C does.
2508pub(crate) fn progress_closure<'a>(
2509    hook: WebPProgressHook,
2510    picture: *const WebPPicture,
2511) -> RsProgressHook<'a> {
2512    Box::new(move |percent: i32| {
2513        // SAFETY: the caller's hook, called with the percent and the caller's
2514        // picture, which no Rust reference borrows during the call.
2515        unsafe { hook(percent, picture) != 0 }
2516    })
2517}
2518
2519// upstream: src/enc/webp_enc.c WebPEncode
2520/// Main encoding call: compresses the picture with `config` and writes the
2521/// data through `picture->writer`. Returns 0 on error, recorded in
2522/// `picture->error_code`; `NULL` arguments return 0.
2523///
2524/// The call lends the planes that C's path reads or writes, and nothing when the
2525/// configuration or the picture fails C's validation. The translation encodes
2526/// with zeroed copies of the statistics and of the `extra_info` map (one byte
2527/// per macroblock): the statistics go back to `*picture->stats` once the
2528/// validation has passed, where C resets and fills them. The map goes back to
2529/// `picture->extra_info` when the lossy encoder ran, also after a failure (C
2530/// fills it one macroblock at a time; the entries it did not reach are zero
2531/// here and untouched in C), and when a lossless encoding succeeds, where C
2532/// zeroes it.
2533///
2534/// # Safety
2535///
2536/// `config` is null or a valid configuration; `picture` is null or a valid
2537/// picture whose planes are writable for its dimensions, whose memory fields are
2538/// null or blocks of the platform `malloc`, and whose `writer`, `stats` and
2539/// `extra_info` meet `encode.h`'s contract.
2540#[unsafe(export_name = "WebPEncode")]
2541pub unsafe extern "C" fn webp_encode(
2542    config: *const WebPConfig,
2543    picture: *mut WebPPicture,
2544) -> c_int {
2545    // SAFETY: null or a valid picture (caller's contract); the borrow ends
2546    // before the encoding.
2547    let Some(c) = (unsafe { picture.as_mut() }) else {
2548        return 0;
2549    };
2550    c.error_code = WebPEncodingError::VP8_ENC_OK; // all ok so far
2551    // SAFETY: null or a valid configuration (caller's contract).
2552    let Some(config) = (unsafe { config.as_ref() }).copied() else {
2553        set_error(c, WebPEncodingError::VP8_ENC_ERROR_NULL_PARAMETER);
2554        return 0;
2555    };
2556    let (c_stats, c_extra) = (c.stats, c.extra_info);
2557    // C's validation, before WebPEncode touches the statistics or a plane:
2558    // WebPValidateConfig, WebPValidatePicture and the dimension limit.
2559    let mut dimensions = RsPicture {
2560        width: c.width,
2561        height: c.height,
2562        colorspace: c.colorspace,
2563        ..RsPicture::default()
2564    };
2565    let validated = config_rs::webp_validate_config(&config)
2566        && picture_rs::webp_validate_picture(&mut dimensions).is_ok()
2567        && c.width <= WEBP_MAX_DIMENSION
2568        && c.height <= WEBP_MAX_DIMENSION;
2569    // The planes that C's path reads or writes.
2570    let has_yuv = !c.y.is_null() && !c.u.is_null() && !c.v.is_null();
2571    let modes = if !validated {
2572        (Mode::Discard, Mode::Discard)
2573    } else if config.lossless == 0 {
2574        if c.use_argb == 0 && has_yuv {
2575            // The cleanup and show_compressed write the YUVA planes.
2576            (Mode::Write, Mode::Discard)
2577        } else {
2578            // The conversion reads the ARGB plane and replaces the YUVA planes.
2579            (Mode::Discard, Mode::Read)
2580        }
2581    } else if !c.argb.is_null() {
2582        // WebPReplaceTransparentPixels writes the ARGB plane of an ARGB picture.
2583        let write = c.use_argb != 0 && config.exact == 0;
2584        (Mode::Discard, if write { Mode::Write } else { Mode::Read })
2585    } else {
2586        // WebPPictureYUVAToARGB reads the YUVA planes and makes the ARGB plane.
2587        (Mode::Read, Mode::Discard)
2588    };
2589    let wants_stats = !c_stats.is_null();
2590    let mut stats = WebPAuxStats::default();
2591    let mb_count = if validated && !c_extra.is_null() {
2592        usize::try_from(((c.width + 15) >> 4) * ((c.height + 15) >> 4)).unwrap_or(0)
2593    } else {
2594        0
2595    };
2596    let mut extra = Vec::new();
2597    if extra.try_reserve_exact(mb_count).is_err() {
2598        set_error(c, WebPEncodingError::VP8_ENC_ERROR_OUT_OF_MEMORY);
2599        return 0;
2600    }
2601    extra.resize(mb_count, 0_u8);
2602    let (writer, hook) = (c.writer, c.progress_hook);
2603    // SAFETY: the planes of the modes are readable, or writable for `Write`
2604    // (caller's contract).
2605    let result = unsafe {
2606        with_picture(picture, modes, true, |rs| {
2607            rs.writer = writer.map(|writer| writer_closure(writer, picture));
2608            rs.progress_hook = hook.map(|hook| progress_closure(hook, picture));
2609            rs.stats = wants_stats.then_some(&mut stats);
2610            rs.extra_info = (mb_count > 0).then_some(extra.as_mut_slice());
2611            let ok = enc::webp_encode(&config, rs);
2612            rs.writer = None;
2613            rs.progress_hook = None;
2614            rs.stats = None;
2615            rs.extra_info = None;
2616            ok
2617        })
2618    };
2619    // C resets the statistics once the validation has passed, also when this
2620    // module then refuses the picture (the zeroed copy is written back then).
2621    if validated && wants_stats {
2622        // SAFETY: the caller's writable `WebPAuxStats` (caller's contract).
2623        unsafe { c_stats.write(stats) };
2624    }
2625    // The map, which is only lent once the validation has passed: whatever the
2626    // lossy encoder filled, or a successful lossless encoding's zeros.
2627    let lossy = config.lossless == 0;
2628    if mb_count > 0 && result.is_some_and(|(encoded, _)| lossy || encoded) {
2629        // SAFETY: one writable byte per macroblock (caller's contract).
2630        unsafe { ptr::copy_nonoverlapping(extra.as_ptr(), c_extra, mb_count) };
2631    }
2632    c_int::from(result.is_some_and(|(ok, written)| ok && written))
2633}