Skip to main content

webp/abi/
decode.rs

1// libwebp v1.6.0, src/webp/decode.h:
2//
3// Copyright 2010 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//  Main decoding functions for WebP images.
13//
14// Author: Skal (pascal.massimino@gmail.com)
15
16//! C ABI export of `src/webp/decode.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: WP12 (decoder integration).
23//!
24//! # Memory
25//!
26//! - Decoded samples that C receives are in blocks of the platform `malloc`
27//!   ([`crate::abi::types`]): the simple API copies the translation's buffer into
28//!   one, which C releases with `WebPFree()` or `free()`; a buffer whose memory
29//!   the library allocates (`private_memory`) receives one after the call that
30//!   allocated it, and `WebPFreeDecBuffer()` releases it. This module records the
31//!   size of every such block, so that a buffer that still holds one can be
32//!   decoded into again, as C allows.
33//! - Caller memory (`is_external_memory`, the `...Into` functions and the
34//!   incremental decoder's output) is lent to the translation for the duration of
35//!   one call: the Rust buffer views it through slices that end with the call, so
36//!   that no Rust borrow of C memory survives while C reads or writes it. Planes
37//!   whose memory overlaps share one region of the Rust storage, with their
38//!   offsets in it.
39//! - Inputs are borrowed for the duration of the call.
40//!
41//! # Cases that this module rejects
42//!
43//! C writes rows at `pointer + y * stride`; a negative stride in caller memory
44//! writes before the pointer, outside the buffer that `decode.h` describes, and
45//! input that overlaps the output memory would be read while it is written.
46//! Rust cannot form those slices, so such calls fail as an invalid buffer does
47//! (`NULL` or `VP8_STATUS_INVALID_PARAM`); see `# Deviations from upstream`,
48//! item 2, and `# Excluded undefined behavior`, items 1 and 2.
49//!
50//! # Deviations from upstream
51//!
52//! Changes of representation that the ADRs allow, or behavior that the Rust
53//! side cannot reproduce exactly. Each records the reason.
54//!
55//! 1. **C ABI memory.** One extra copy per decoding: the simple API copies the
56//!    translation's buffer into a `malloc` block; a library buffer of
57//!    `WebPDecode` and of the incremental decoder moves into one after the call
58//!    that allocated it. If that `malloc` fails, the incremental decoder keeps
59//!    the translation's memory and hands out pointers into it, which live as
60//!    long as the decoder. Plane pointers of a library buffer whose memory was
61//!    never allocated, or was released after a failed decoding, keep their
62//!    previous C values (C: pointers to the freed memory).
63//! 2. **C ABI rejects** caller memory with a negative stride, input that
64//!    overlaps caller output memory, and overlapping planes passed as separate
65//!    slices (`WebPDecodeYUVInto`, `WebPINewYUVA`), with C's failure result
66//!    (`NULL` or `VP8_STATUS_INVALID_PARAM`): Rust cannot form those slices
67//!    (`# Excluded undefined behavior`, items 1 and 2). Overlapping planes of a
68//!    `WebPDecBuffer` (`WebPDecode`, `WebPIDecode`, `WebPINewDecoder`) share
69//!    one region and decode as in C.
70//! 3. **C ABI configuration copies.** `WebPIDecode` and `WebPINewDecoder`
71//!    convert the caller's options and output buffer when the decoder is
72//!    created; later changes by the caller are not seen, where C reads through
73//!    its pointers. The caller's buffer receives the dimensions, strides, plane
74//!    pointers and `private_memory` after every call.
75//!
76//! # Excluded undefined behavior
77//!
78//! Inputs that are undefined behavior (or assertion failures) in C and are
79//! therefore excluded from the oracle comparison (PORTING rule 8):
80//!
81//! 1. **Caller memory with a negative stride**: C writes before the pointer,
82//!    outside the buffer that `decode.h` describes; the C ABI rejects it
83//!    (`# Deviations from upstream`, item 2).
84//! 2. **Input that overlaps caller output memory**, and overlapping planes
85//!    passed to `WebPDecodeYUVInto` or `WebPINewYUVA`: the C ABI rejects them
86//!    (`# Deviations from upstream`, item 2).
87//!
88//! # The CPU query
89//!
90//! `VP8GetCPUInfo` points at the translation's `x86CPUInfo` on x86, and, with
91//! the `simd` feature on 64-bit ARM, at its `armCPUInfo`, which answers `kNEON`
92//! as upstream's NEON build installs it (WP20, ADR 0008). Elsewhere, and in the
93//! scalar build on 64-bit ARM, it is `NULL`, as in the reference
94//! configuration. The tools' `-noasm` stores `NULL`, which turns off every
95//! selection that consults the query; the NEON variants that upstream
96//! compiles in unconditionally stay selected. Rust callers cannot write this
97//! data symbol directly: safe functions select `NULL` or the built-in query,
98//! and a typed unsafe setter accepts custom callbacks.
99
100use core::ffi::{c_int, c_void};
101use core::mem::ManuallyDrop;
102use core::ptr;
103use core::slice;
104use std::collections::BTreeMap;
105use std::sync::atomic::{AtomicPtr, Ordering};
106use std::sync::{Mutex, PoisonError};
107
108use crate::abi::types::{malloc_copy, platform_free};
109use crate::dec::buffer_dec::{is_null_plane, webp_init_dec_buffer_internal};
110use crate::dec::idec_dec as idec;
111use crate::dec::vp8_dec::webp_get_decoder_version as rs_webp_get_decoder_version;
112use crate::dec::webp_dec as dec;
113use crate::dsp::cpu::CPUFeature;
114use crate::webp::decode::{
115    VP8StatusCode, WEBP_CSP_MODE, WebPBitstreamFeatures, WebPDecBuffer as RsDecBuffer,
116    WebPDecBufferPlanes, WebPDecoderConfig as RsDecoderConfig, WebPDecoderOptions,
117    WebPRGBABuffer as RsRGBABuffer, WebPYUVABuffer as RsYUVABuffer, webp_is_rgb_mode,
118};
119use crate::webp::types::{PlaneOffset, PlaneStorage};
120
121//------------------------------------------------------------------------------
122// Mirrors of the structs with pointers
123
124// upstream: src/webp/decode.h WebPRGBABuffer
125/// View as RGBA (C layout).
126#[repr(C)]
127#[derive(Clone, Copy, Debug)]
128pub struct WebPRGBABuffer {
129    /// Pointer to RGBA samples.
130    pub rgba: *mut u8,
131    /// Stride in bytes from one scanline to the next.
132    pub stride: c_int,
133    /// Total size of the `rgba` buffer.
134    pub size: usize,
135}
136
137// upstream: src/webp/decode.h WebPYUVABuffer
138/// View as YUVA (C layout).
139#[repr(C)]
140#[derive(Clone, Copy, Debug)]
141pub struct WebPYUVABuffer {
142    /// Pointer to luma samples.
143    pub y: *mut u8,
144    /// Pointer to chroma U samples.
145    pub u: *mut u8,
146    /// Pointer to chroma V samples.
147    pub v: *mut u8,
148    /// Pointer to alpha samples.
149    pub a: *mut u8,
150    /// Luma stride.
151    pub y_stride: c_int,
152    /// Chroma U stride.
153    pub u_stride: c_int,
154    /// Chroma V stride.
155    pub v_stride: c_int,
156    /// Alpha stride.
157    pub a_stride: c_int,
158    /// Luma plane size.
159    pub y_size: usize,
160    /// Chroma U plane size.
161    pub u_size: usize,
162    /// Chroma V plane size.
163    pub v_size: usize,
164    /// Alpha plane size.
165    pub a_size: usize,
166}
167
168/// The nameless union `u` of `WebPDecBuffer` (C layout).
169#[expect(
170    non_snake_case,
171    reason = "the C member names RGBA and YUVA of the WebPDecBuffer union"
172)]
173#[repr(C)]
174#[derive(Clone, Copy)]
175pub union WebPDecBufferUnion {
176    /// The RGBA view.
177    pub RGBA: WebPRGBABuffer,
178    /// The YUVA view.
179    pub YUVA: WebPYUVABuffer,
180}
181
182// upstream: src/webp/decode.h WebPDecBuffer
183/// Output buffer (C layout).
184#[repr(C)]
185pub struct WebPDecBuffer {
186    /// Colorspace.
187    pub colorspace: WEBP_CSP_MODE,
188    /// Width.
189    pub width: c_int,
190    /// Height.
191    pub height: c_int,
192    /// If non-zero, `private_memory` is not used; 2 or more marks slow memory.
193    pub is_external_memory: c_int,
194    /// Nameless union of buffer parameters.
195    pub u: WebPDecBufferUnion,
196    /// Padding for later use.
197    pub pad: [u32; 4],
198    /// Internally allocated memory (only when `is_external_memory` is 0).
199    pub private_memory: *mut u8,
200}
201
202// upstream: src/webp/decode.h WebPDecoderConfig
203/// Main object storing the configuration for advanced decoding (C layout).
204#[repr(C)]
205pub struct WebPDecoderConfig {
206    /// Immutable bitstream features (optional).
207    pub input: WebPBitstreamFeatures,
208    /// Output buffer (can point to external memory).
209    pub output: WebPDecBuffer,
210    /// Decoding options.
211    pub options: WebPDecoderOptions,
212}
213
214//------------------------------------------------------------------------------
215// Library memory blocks
216
217/// The blocks of samples that this module gave to C buffers as
218/// `private_memory`, with their sizes.
219static LIBRARY_BLOCKS: Mutex<BTreeMap<usize, usize>> = Mutex::new(BTreeMap::new());
220
221fn library_blocks() -> std::sync::MutexGuard<'static, BTreeMap<usize, usize>> {
222    LIBRARY_BLOCKS
223        .lock()
224        .unwrap_or_else(PoisonError::into_inner)
225}
226
227/// The size of a library block, or `None` for memory this module did not
228/// allocate.
229fn library_block_size(block: *mut u8) -> Option<usize> {
230    library_blocks().get(&(block as usize)).copied()
231}
232
233/// Gives a library block to a C buffer, or copies the samples into the block
234/// it already holds when the sizes agree. Returns null when `malloc` fails.
235fn give_library_block(held: *mut u8, samples: &[u8]) -> *mut u8 {
236    if !held.is_null() && library_block_size(held) == Some(samples.len()) {
237        // SAFETY: `held` is a live library block of `samples.len()` bytes,
238        // which no Rust slice views (the translation worked on a copy).
239        unsafe { ptr::copy_nonoverlapping(samples.as_ptr(), held, samples.len()) };
240        return held;
241    }
242    let block = malloc_copy(samples);
243    if !block.is_null() {
244        library_blocks().insert(block as usize, samples.len());
245    }
246    block
247}
248
249/// Releases a library block that a C buffer gives up.
250///
251/// # Safety
252///
253/// `block` is null or a block of this module that is not used again.
254unsafe fn release_library_block(block: *mut u8) {
255    library_blocks().remove(&(block as usize));
256    // SAFETY: the caller gives up a block of the platform `malloc`.
257    unsafe { platform_free(block) }
258}
259
260//------------------------------------------------------------------------------
261// Caller memory
262
263/// Memory that C lends to the translation: the start and the length of each
264/// region of a Rust storage.
265#[derive(Clone, Debug, Default)]
266struct Lent(Vec<(*mut u8, usize)>);
267
268impl Lent {
269    /// The external storage over the regions, for the duration of one call.
270    ///
271    /// # Safety
272    ///
273    /// Every region is writable memory of its length that only the returned
274    /// slices access until they are dropped, and the regions do not overlap.
275    unsafe fn storage(&self) -> PlaneStorage<'static, u8> {
276        PlaneStorage::External(
277            self.0
278                .iter()
279                .map(|&(start, len)| {
280                    // SAFETY: the caller guarantees that the region is valid,
281                    // exclusive for the call and disjoint from the others.
282                    unsafe { slice::from_raw_parts_mut(start, len) }
283                })
284                .collect(),
285        )
286    }
287
288    /// Whether `[start, start + len)` overlaps a region.
289    fn overlaps(&self, start: *const u8, len: usize) -> bool {
290        self.0
291            .iter()
292            .any(|&(region, size)| ranges_overlap(region, size, start, len))
293    }
294}
295
296/// Whether two byte ranges overlap.
297fn ranges_overlap(a: *const u8, a_len: usize, b: *const u8, b_len: usize) -> bool {
298    let (a, b) = (a as usize, b as usize);
299    a < b.saturating_add(b_len) && b < a.saturating_add(a_len)
300}
301
302/// Caller planes `(pointer, size)` as regions: overlapping planes share one
303/// region. Returns the regions and, per plane, its region and offset (`None`
304/// for a null plane).
305fn merge_planes(planes: &[(*mut u8, usize)]) -> (Lent, Vec<Option<PlaneOffset>>) {
306    let mut order: Vec<usize> = (0..planes.len())
307        .filter(|&i| !planes[i].0.is_null())
308        .collect();
309    order.sort_by_key(|&i| planes[i].0 as usize);
310    let mut regions: Vec<(*mut u8, usize)> = Vec::new();
311    let mut offsets = vec![None; planes.len()];
312    for i in order {
313        let (start, size) = planes[i];
314        let address = start as usize;
315        match regions.last_mut() {
316            Some((region, len)) if address < (*region as usize).saturating_add(*len) => {
317                let offset = address - *region as usize;
318                *len = (*len).max(offset.saturating_add(size));
319                offsets[i] = Some(PlaneOffset {
320                    region: regions.len() - 1,
321                    offset,
322                });
323            }
324            _ => {
325                regions.push((start, size));
326                offsets[i] = Some(PlaneOffset {
327                    region: regions.len() - 1,
328                    offset: 0,
329                });
330            }
331        }
332    }
333    (Lent(regions), offsets)
334}
335
336/// A plane offset for a region that does not exist: C's `NULL` in caller
337/// memory (`src/dec/buffer_dec.rs`).
338const NULL_PLANE: PlaneOffset = PlaneOffset {
339    region: usize::MAX,
340    offset: 0,
341};
342
343/// The memory of a C buffer as the translation sees it during one call.
344enum BufferMemory {
345    /// Library memory that the translation allocates (C: `private_memory`).
346    Library,
347    /// Caller memory, or library memory that this module cannot copy.
348    Lent(Lent),
349}
350
351/// Converts a C output buffer into the translation's form. The storage holds
352/// slices of caller memory for the duration of the call (see [`Lent`]).
353/// Returns `None` for caller memory with a negative stride, which this module
354/// rejects (see the module documentation).
355///
356/// # Safety
357///
358/// For `is_external_memory > 0`, the planes point to their declared sizes of
359/// writable memory, which only the translation accesses during the call
360/// (`decode.h`); `private_memory` is null or a live block.
361unsafe fn buffer_to_rust(c: &WebPDecBuffer) -> Option<(RsDecBuffer<'static>, BufferMemory)> {
362    let is_rgb = webp_is_rgb_mode(c.colorspace);
363    let mut buffer = RsDecBuffer {
364        colorspace: c.colorspace,
365        width: c.width,
366        height: c.height,
367        pad: c.pad,
368        ..RsDecBuffer::default()
369    };
370    // The view that C reads, which the colorspace selects.
371    let planes: Vec<(*mut u8, usize, c_int)> = if is_rgb {
372        // SAFETY: both members are plain data, so either view is initialized.
373        let rgba = unsafe { c.u.RGBA };
374        vec![(rgba.rgba, rgba.size, rgba.stride)]
375    } else {
376        // SAFETY: as above.
377        let yuva = unsafe { c.u.YUVA };
378        vec![
379            (yuva.y, yuva.y_size, yuva.y_stride),
380            (yuva.u, yuva.u_size, yuva.u_stride),
381            (yuva.v, yuva.v_size, yuva.v_stride),
382            (yuva.a, yuva.a_size, yuva.a_stride),
383        ]
384    };
385    let library = c.is_external_memory <= 0;
386    let memory;
387    let offsets: Vec<Option<PlaneOffset>>;
388    if library && c.private_memory.is_null() {
389        // The translation allocates; C ignores the plane pointers until then.
390        memory = BufferMemory::Library;
391        offsets = vec![Some(PlaneOffset::default()); planes.len()];
392    } else if let Some(size) = library
393        .then(|| library_block_size(c.private_memory))
394        .flatten()
395        .filter(|&size| {
396            planes.iter().all(|&(plane, _, _)| {
397                plane.is_null() || ranges_overlap(c.private_memory, size, plane, 1)
398            })
399        })
400    {
401        // A library block that the buffer still holds: the translation works on
402        // a copy, which goes back into the block after the call.
403        // SAFETY: the block is a live library block of `size` bytes.
404        let block = unsafe { slice::from_raw_parts(c.private_memory, size) };
405        buffer.storage = PlaneStorage::Internal(block.to_vec());
406        memory = BufferMemory::Library;
407        offsets = planes
408            .iter()
409            .map(|&(plane, _, _)| {
410                (!plane.is_null()).then(|| PlaneOffset {
411                    region: 0,
412                    offset: plane as usize - c.private_memory as usize,
413                })
414            })
415            .collect();
416    } else {
417        if planes
418            .iter()
419            .any(|&(plane, _, stride)| !plane.is_null() && stride < 0)
420        {
421            return None;
422        }
423        let (lent, plane_offsets) = merge_planes(
424            &planes
425                .iter()
426                .map(|&(plane, size, _)| (plane, size))
427                .collect::<Vec<_>>(),
428        );
429        // SAFETY: the caller lends the planes for the call; merged, the
430        // regions are disjoint.
431        buffer.storage = unsafe { lent.storage() };
432        // C: is_external_memory >= 2 marks slow external memory.
433        buffer.slow_memory = c.is_external_memory >= 2;
434        memory = BufferMemory::Lent(lent);
435        offsets = plane_offsets;
436    }
437    let plane = |i: usize| offsets[i].unwrap_or(NULL_PLANE);
438    buffer.u = if is_rgb {
439        // SAFETY: plain data, see above.
440        let rgba = unsafe { c.u.RGBA };
441        WebPDecBufferPlanes::RGBA(RsRGBABuffer {
442            rgba: plane(0),
443            stride: rgba.stride,
444            size: rgba.size,
445        })
446    } else {
447        // SAFETY: plain data, see above.
448        let yuva = unsafe { c.u.YUVA };
449        WebPDecBufferPlanes::YUVA(RsYUVABuffer {
450            y: plane(0),
451            u: plane(1),
452            v: plane(2),
453            a: if matches!(memory, BufferMemory::Library) && buffer.storage_is_empty() {
454                None
455            } else {
456                offsets[3]
457            },
458            y_stride: yuva.y_stride,
459            u_stride: yuva.u_stride,
460            v_stride: yuva.v_stride,
461            a_stride: yuva.a_stride,
462            y_size: yuva.y_size,
463            u_size: yuva.u_size,
464            v_size: yuva.v_size,
465            a_size: yuva.a_size,
466        })
467    };
468    Some((buffer, memory))
469}
470
471/// Whether a buffer holds no memory (no C counterpart).
472trait StorageIsEmpty {
473    fn storage_is_empty(&self) -> bool;
474}
475
476impl StorageIsEmpty for RsDecBuffer<'_> {
477    fn storage_is_empty(&self) -> bool {
478        matches!(&self.storage, PlaneStorage::Internal(memory) if memory.is_empty())
479    }
480}
481
482/// The C pointer of a plane: the start of its region plus its offset, or
483/// null. `bases` are the starts of the regions.
484fn plane_pointer(bases: &[*mut u8], storage: &PlaneStorage<'_, u8>, plane: PlaneOffset) -> *mut u8 {
485    if is_null_plane(storage, plane) {
486        return ptr::null_mut();
487    }
488    bases
489        .get(plane.region)
490        .map_or(ptr::null_mut(), |&base| base.wrapping_add(plane.offset))
491}
492
493/// Writes the translation's buffer back into the C buffer: dimensions,
494/// strides, sizes and plane pointers, and `private_memory` for library memory.
495/// Library samples move into a library block. A plane pointer of a buffer
496/// whose library memory was never allocated or was released keeps its C value,
497/// as C leaves it. Empty library memory releases the C buffer's block when
498/// `released` says that the translation released it (C: `WebPFreeDecBuffer`
499/// in `DecodeInto`). Returns false when the block for the samples could not be
500/// allocated.
501///
502/// # Safety
503///
504/// `c` is the buffer that `buffer` was converted from, and `memory` its memory.
505unsafe fn buffer_to_c(
506    c: &mut WebPDecBuffer,
507    buffer: &RsDecBuffer<'_>,
508    memory: &BufferMemory,
509    released: bool,
510) -> bool {
511    let mut ok = true;
512    c.width = buffer.width;
513    c.height = buffer.height;
514    c.pad = buffer.pad;
515    let bases: Vec<*mut u8> = match (&buffer.storage, memory) {
516        (PlaneStorage::Internal(samples), BufferMemory::Library) if !samples.is_empty() => {
517            let block = give_library_block(c.private_memory, samples);
518            if block != c.private_memory && !c.private_memory.is_null() {
519                // SAFETY: the buffer gives up the block it held.
520                unsafe { release_library_block(c.private_memory) };
521            }
522            c.private_memory = block;
523            ok = !block.is_null();
524            if block.is_null() {
525                Vec::new()
526            } else {
527                vec![block]
528            }
529        }
530        (PlaneStorage::Internal(_), BufferMemory::Library) => {
531            if released && !c.private_memory.is_null() {
532                // The translation released the buffer's memory.
533                // SAFETY: the buffer gives up its library block.
534                unsafe { release_library_block(c.private_memory) };
535                c.private_memory = ptr::null_mut();
536            }
537            Vec::new()
538        }
539        (_, BufferMemory::Lent(lent)) => lent.0.iter().map(|&(start, _)| start).collect(),
540        (_, BufferMemory::Library) => Vec::new(),
541    };
542    let keep_pointers = bases.is_empty() && matches!(memory, BufferMemory::Library);
543    match &buffer.u {
544        WebPDecBufferPlanes::RGBA(rgba) if webp_is_rgb_mode(buffer.colorspace) => {
545            // SAFETY: writing plain data into the RGBA view.
546            let view = unsafe { &mut c.u.RGBA };
547            if !keep_pointers {
548                view.rgba = plane_pointer(&bases, &buffer.storage, rgba.rgba);
549            }
550            view.stride = rgba.stride;
551            view.size = rgba.size;
552        }
553        WebPDecBufferPlanes::YUVA(yuva) if !webp_is_rgb_mode(buffer.colorspace) => {
554            // SAFETY: writing plain data into the YUVA view.
555            let view = unsafe { &mut c.u.YUVA };
556            if !keep_pointers {
557                view.y = plane_pointer(&bases, &buffer.storage, yuva.y);
558                view.u = plane_pointer(&bases, &buffer.storage, yuva.u);
559                view.v = plane_pointer(&bases, &buffer.storage, yuva.v);
560                if let Some(a) = yuva.a {
561                    view.a = plane_pointer(&bases, &buffer.storage, a);
562                } else if matches!(memory, BufferMemory::Lent(_)) {
563                    view.a = ptr::null_mut();
564                }
565            }
566            view.y_stride = yuva.y_stride;
567            view.u_stride = yuva.u_stride;
568            view.v_stride = yuva.v_stride;
569            view.a_stride = yuva.a_stride;
570            view.y_size = yuva.y_size;
571            view.u_size = yuva.u_size;
572            view.v_size = yuva.v_size;
573            view.a_size = yuva.a_size;
574        }
575        // A member that the colorspace does not select was never written by
576        // the translation (`src/dec/buffer_dec.rs`): C's view is unchanged.
577        _ => {}
578    }
579    ok
580}
581
582//------------------------------------------------------------------------------
583// Helpers
584
585/// The caller's input of `size` bytes.
586///
587/// # Safety
588///
589/// `data` is not null and points to `size` readable bytes that nothing writes
590/// during the call.
591unsafe fn input<'a>(data: *const u8, size: usize) -> &'a [u8] {
592    // SAFETY: the caller's contract of `decode.h`.
593    unsafe { slice::from_raw_parts(data, size) }
594}
595
596/// An optional `int` output parameter.
597///
598/// # Safety
599///
600/// `ptr` is null or points to a writable `int`.
601unsafe fn out<'a>(ptr: *mut c_int) -> Option<&'a mut i32> {
602    // SAFETY: null or a valid, exclusive `int` (caller's contract).
603    unsafe { ptr.as_mut() }
604}
605
606/// Writes an optional output parameter.
607///
608/// # Safety
609///
610/// `ptr` is null or points to a writable `T`.
611unsafe fn set<T>(ptr: *mut T, value: T) {
612    if !ptr.is_null() {
613        // SAFETY: a valid, writable `T` (caller's contract).
614        unsafe { ptr.write(value) };
615    }
616}
617
618//------------------------------------------------------------------------------
619// Decoder version and CPU information
620
621// upstream: src/dec/vp8_dec.c WebPGetDecoderVersion
622/// Returns the decoder's version number, packed in hexadecimal using 8 bits
623/// for each of major/minor/revision. E.g: v2.5.7 is 0x020507.
624#[unsafe(export_name = "WebPGetDecoderVersion")]
625#[must_use]
626pub extern "C" fn webp_get_decoder_version() -> c_int {
627    rs_webp_get_decoder_version()
628}
629
630/// `VP8GetCPUInfo` as C calls it (C: `x86CPUInfo`).
631#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
632extern "C" fn x86_cpu_info(feature: CPUFeature) -> c_int {
633    c_int::from(crate::dsp::cpu::vp8_get_cpu_info(feature))
634}
635
636// upstream: src/dsp/cpu.c VP8GetCPUInfo
637/// The CPU query that `src/dsp/cpu.h` declares as a function pointer, which the
638/// upstream tools set to `NULL` for `-noasm` (ADR 0004, data symbols). It points
639/// at the translation's query on x86, and is `NULL` elsewhere, as in the
640/// reference configuration. Dispatch reads it through ADR 0008's feature cache.
641/// Exported here because `dwebp` assigns it. Rust callers use the setters
642/// below; exposing the atomic would let safe code install an invalid address.
643#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
644#[unsafe(export_name = "VP8GetCPUInfo")]
645static VP8_GET_CPU_INFO: AtomicPtr<c_void> = AtomicPtr::new(x86_cpu_info as *mut c_void);
646
647/// `VP8GetCPUInfo` as C calls it in the NEON build (C: `armCPUInfo`).
648#[cfg(all(feature = "simd", target_arch = "aarch64"))]
649extern "C" fn arm_cpu_info(feature: CPUFeature) -> c_int {
650    c_int::from(crate::dsp::cpu::vp8_get_cpu_info(feature))
651}
652
653// upstream: src/dsp/cpu.c VP8GetCPUInfo
654/// See the x86 definition. With the `simd` feature on 64-bit ARM the pointer
655/// is `armCPUInfo`, as in upstream's NEON build, which answers `kNEON`
656/// (WP20, ADR 0008); the tools' `-noasm` sets it to `NULL`.
657#[cfg(all(feature = "simd", target_arch = "aarch64"))]
658#[unsafe(export_name = "VP8GetCPUInfo")]
659static VP8_GET_CPU_INFO: AtomicPtr<c_void> = AtomicPtr::new(arm_cpu_info as *mut c_void);
660
661// upstream: src/dsp/cpu.c VP8GetCPUInfo
662/// See the x86 definition: `NULL` without an x86 query, and in the scalar
663/// build on 64-bit ARM, as in the reference configuration.
664#[cfg(not(any(
665    target_arch = "x86",
666    target_arch = "x86_64",
667    all(feature = "simd", target_arch = "aarch64")
668)))]
669#[unsafe(export_name = "VP8GetCPUInfo")]
670static VP8_GET_CPU_INFO: AtomicPtr<c_void> = AtomicPtr::new(ptr::null_mut());
671
672/// Disables the CPU query, as the C tools' `-noasm` option does.
673///
674/// This changes process-wide dispatch selection. Concurrent dispatch remains
675/// memory-safe when every installed callback meets its safety contract, but
676/// coordinate changes with codec use when a particular mode must apply to a
677/// complete operation.
678pub fn disable_cpu_query() {
679    VP8_GET_CPU_INFO.store(ptr::null_mut(), Ordering::Release);
680}
681
682/// Restores the built-in query for this build and target. On targets without
683/// a built-in query, this selects the same `NULL` state as [`disable_cpu_query`].
684///
685/// This changes process-wide dispatch selection. Concurrent dispatch remains
686/// memory-safe when every installed callback meets its safety contract, but
687/// coordinate changes with codec use when a particular mode must apply to a
688/// complete operation.
689pub fn use_builtin_cpu_query() {
690    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
691    let pointer = x86_cpu_info as *mut c_void;
692    #[cfg(all(feature = "simd", target_arch = "aarch64"))]
693    let pointer = arm_cpu_info as *mut c_void;
694    #[cfg(not(any(
695        target_arch = "x86",
696        target_arch = "x86_64",
697        all(feature = "simd", target_arch = "aarch64")
698    )))]
699    let pointer = ptr::null_mut();
700    VP8_GET_CPU_INFO.store(pointer, Ordering::Release);
701}
702
703/// Whether the C ABI's CPU query pointer is non-null.
704#[must_use]
705pub fn cpu_query_is_installed() -> bool {
706    !VP8_GET_CPU_INFO.load(Ordering::Acquire).is_null()
707}
708
709/// Installs a typed CPU query in the exported `VP8GetCPUInfo` pointer.
710///
711/// # Safety
712///
713/// `query` must remain callable for as long as it can be observed, including
714/// calls already in progress when it is replaced. It must return nonzero only
715/// for features supported by the running CPU and OS; a false positive can run
716/// unsupported SIMD instructions. The callback must be safe to invoke
717/// concurrently from codec threads. Coordinate changes to this process-wide
718/// query with codec use and other query changes, including C callers, if a
719/// particular mode must apply to a complete operation. Mixing truthful feature
720/// sets is memory-safe but can change dispatch results.
721///
722/// ```compile_fail
723/// use webp::abi::decode::set_cpu_query_callback;
724/// use webp::dsp::cpu::CPUFeature;
725/// extern "C" fn query(_: CPUFeature) -> i32 { 0 }
726/// set_cpu_query_callback(query); // A custom callback requires unsafe.
727/// ```
728///
729/// ```compile_fail
730/// use webp::abi::decode::VP8_GET_CPU_INFO;
731/// let _ = VP8_GET_CPU_INFO; // The raw C symbol is private to this module.
732/// ```
733pub unsafe fn set_cpu_query_callback(query: extern "C" fn(CPUFeature) -> c_int) {
734    VP8_GET_CPU_INFO.store(query as *mut c_void, Ordering::Release);
735}
736
737/// A token of the current `VP8GetCPUInfo` pointer for the dispatch cache of
738/// `crate::dsp::cpu::features` (ADR 0008): 0 for `NULL` (`-noasm`), 1 for the
739/// translation's own query, and a fold of the address of a query that the
740/// caller installed, with its low bits set apart from the two fixed tokens.
741/// Inlined into the dispatch functions' cache test.
742#[inline]
743pub(crate) fn cpu_query_token() -> u32 {
744    let pointer = VP8_GET_CPU_INFO.load(Ordering::Acquire);
745    if pointer.is_null() {
746        return 0;
747    }
748    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
749    if pointer == x86_cpu_info as *mut c_void {
750        return 1;
751    }
752    #[cfg(all(feature = "simd", target_arch = "aarch64"))]
753    if pointer == arm_cpu_info as *mut c_void {
754        return 1;
755    }
756    let address = u64::try_from(pointer.addr()).unwrap_or(u64::MAX);
757    #[expect(
758        clippy::cast_possible_truncation,
759        reason = "a 32-bit fold of the address"
760    )]
761    let fold = (address ^ (address >> 32)) as u32;
762    (fold & !0b11) | 0b10
763}
764
765/// Answers `VP8GetCPUInfo(feature)` as C's `Init` functions call it (ADR
766/// 0008): `None` for a `NULL` pointer, the translation's own query for its own
767/// address, and the caller's function otherwise.
768pub(crate) fn cpu_feature_query(feature: CPUFeature) -> Option<bool> {
769    let pointer = VP8_GET_CPU_INFO.load(Ordering::Acquire);
770    if pointer.is_null() {
771        return None;
772    }
773    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
774    if pointer == x86_cpu_info as *mut c_void {
775        return Some(crate::dsp::cpu::vp8_get_cpu_info(feature));
776    }
777    #[cfg(all(feature = "simd", target_arch = "aarch64"))]
778    if pointer == arm_cpu_info as *mut c_void {
779        return Some(crate::dsp::cpu::vp8_get_cpu_info(feature));
780    }
781    // SAFETY: Rust can install a custom pointer only through the unsafe typed
782    // setter, whose contract requires a callable callback. C writes to the
783    // exported symbol carry the same C-side contract. `feature` has the C
784    // `CPUFeature` representation and the callback returns `int`.
785    let query =
786        unsafe { core::mem::transmute::<*mut c_void, extern "C" fn(CPUFeature) -> c_int>(pointer) };
787    Some(query(feature) != 0)
788}
789
790//------------------------------------------------------------------------------
791// Simple API
792
793// upstream: src/dec/webp_dec.c WebPGetInfo
794/// Retrieves basic header information: width, height.
795///
796/// # Safety
797///
798/// `data` is null or points to `data_size` readable bytes; `width` and
799/// `height` are null or writable.
800#[unsafe(export_name = "WebPGetInfo")]
801pub unsafe extern "C" fn webp_get_info(
802    data: *const u8,
803    data_size: usize,
804    width: *mut c_int,
805    height: *mut c_int,
806) -> c_int {
807    if data.is_null() {
808        return 0; // C: GetFeatures returns VP8_STATUS_INVALID_PARAM.
809    }
810    // SAFETY: non-null input of `data_size` bytes under the caller's contract.
811    let data = unsafe { input(data, data_size) };
812    // SAFETY: null or writable, under the caller's contract.
813    let width = unsafe { out(width) };
814    // SAFETY: as above.
815    let height = unsafe { out(height) };
816    c_int::from(dec::webp_get_info(data, width, height))
817}
818
819/// A function of the translation's simple API.
820type SimpleDecode = fn(&[u8], Option<&mut i32>, Option<&mut i32>) -> Option<Vec<u8>>;
821
822/// A function of the translation's `...Into` API for RGB samples.
823type IntoDecode = for<'a> fn(&[u8], &'a mut [u8], i32) -> Option<&'a mut [u8]>;
824
825/// The simple API: decodes with `decode` and copies the samples into a
826/// `malloc` block.
827///
828/// # Safety
829///
830/// As [`webp_get_info`].
831unsafe fn simple(
832    data: *const u8,
833    data_size: usize,
834    width: *mut c_int,
835    height: *mut c_int,
836    decode: SimpleDecode,
837) -> *mut u8 {
838    if data.is_null() {
839        return ptr::null_mut(); // C: WebPGetInfo fails.
840    }
841    // SAFETY: non-null input of `data_size` bytes under the caller's contract.
842    let data = unsafe { input(data, data_size) };
843    // SAFETY: null or writable, under the caller's contract.
844    let width = unsafe { out(width) };
845    // SAFETY: as above.
846    let height = unsafe { out(height) };
847    decode(data, width, height).map_or(ptr::null_mut(), |samples| malloc_copy(&samples))
848}
849
850// upstream: src/dec/webp_dec.c WebPDecodeRGBA
851/// Decodes into RGBA samples; release the result with `WebPFree()`.
852///
853/// # Safety
854///
855/// As [`webp_get_info`].
856#[unsafe(export_name = "WebPDecodeRGBA")]
857pub unsafe extern "C" fn webp_decode_rgba(
858    data: *const u8,
859    data_size: usize,
860    width: *mut c_int,
861    height: *mut c_int,
862) -> *mut u8 {
863    // SAFETY: the caller's contract, passed on.
864    unsafe { simple(data, data_size, width, height, dec::webp_decode_rgba) }
865}
866
867// upstream: src/dec/webp_dec.c WebPDecodeARGB
868/// Decodes into ARGB samples; release the result with `WebPFree()`.
869///
870/// # Safety
871///
872/// As [`webp_get_info`].
873#[unsafe(export_name = "WebPDecodeARGB")]
874pub unsafe extern "C" fn webp_decode_argb(
875    data: *const u8,
876    data_size: usize,
877    width: *mut c_int,
878    height: *mut c_int,
879) -> *mut u8 {
880    // SAFETY: the caller's contract, passed on.
881    unsafe { simple(data, data_size, width, height, dec::webp_decode_argb) }
882}
883
884// upstream: src/dec/webp_dec.c WebPDecodeBGRA
885/// Decodes into BGRA samples; release the result with `WebPFree()`.
886///
887/// # Safety
888///
889/// As [`webp_get_info`].
890#[unsafe(export_name = "WebPDecodeBGRA")]
891pub unsafe extern "C" fn webp_decode_bgra(
892    data: *const u8,
893    data_size: usize,
894    width: *mut c_int,
895    height: *mut c_int,
896) -> *mut u8 {
897    // SAFETY: the caller's contract, passed on.
898    unsafe { simple(data, data_size, width, height, dec::webp_decode_bgra) }
899}
900
901// upstream: src/dec/webp_dec.c WebPDecodeRGB
902/// Decodes into RGB samples; release the result with `WebPFree()`.
903///
904/// # Safety
905///
906/// As [`webp_get_info`].
907#[unsafe(export_name = "WebPDecodeRGB")]
908pub unsafe extern "C" fn webp_decode_rgb(
909    data: *const u8,
910    data_size: usize,
911    width: *mut c_int,
912    height: *mut c_int,
913) -> *mut u8 {
914    // SAFETY: the caller's contract, passed on.
915    unsafe { simple(data, data_size, width, height, dec::webp_decode_rgb) }
916}
917
918// upstream: src/dec/webp_dec.c WebPDecodeBGR
919/// Decodes into BGR samples; release the result with `WebPFree()`.
920///
921/// # Safety
922///
923/// As [`webp_get_info`].
924#[unsafe(export_name = "WebPDecodeBGR")]
925pub unsafe extern "C" fn webp_decode_bgr(
926    data: *const u8,
927    data_size: usize,
928    width: *mut c_int,
929    height: *mut c_int,
930) -> *mut u8 {
931    // SAFETY: the caller's contract, passed on.
932    unsafe { simple(data, data_size, width, height, dec::webp_decode_bgr) }
933}
934
935// upstream: src/dec/webp_dec.c WebPDecodeYUV
936/// Decodes into Y, U and V planes in one block, which starts at the returned
937/// luma pointer; release it with `WebPFree()`.
938///
939/// # Safety
940///
941/// As [`webp_get_info`]; `u`, `v`, `stride` and `uv_stride` are null or
942/// writable.
943#[unsafe(export_name = "WebPDecodeYUV")]
944pub unsafe extern "C" fn webp_decode_yuv(
945    data: *const u8,
946    data_size: usize,
947    width: *mut c_int,
948    height: *mut c_int,
949    u: *mut *mut u8,
950    v: *mut *mut u8,
951    stride: *mut c_int,
952    uv_stride: *mut c_int,
953) -> *mut u8 {
954    // data, width and height are checked by Decode().
955    if u.is_null() || v.is_null() || stride.is_null() || uv_stride.is_null() || data.is_null() {
956        return ptr::null_mut();
957    }
958    // SAFETY: non-null input of `data_size` bytes under the caller's contract.
959    let data = unsafe { input(data, data_size) };
960    // SAFETY: null or writable, under the caller's contract.
961    let width = unsafe { out(width) };
962    // SAFETY: as above.
963    let height = unsafe { out(height) };
964    let Some(buffer) = dec::webp_decode_yuv(data, width, height) else {
965        return ptr::null_mut();
966    };
967    let (PlaneStorage::Internal(samples), WebPDecBufferPlanes::YUVA(yuva)) =
968        (&buffer.storage, &buffer.u)
969    else {
970        return ptr::null_mut();
971    };
972    let block = malloc_copy(samples);
973    if block.is_null() {
974        return ptr::null_mut();
975    }
976    // SAFETY: the four output parameters are writable (checked above and the
977    // caller's contract).
978    unsafe {
979        set(u, block.wrapping_add(yuva.u.offset));
980    }
981    // SAFETY: as above.
982    unsafe {
983        set(v, block.wrapping_add(yuva.v.offset));
984    }
985    // SAFETY: as above.
986    unsafe {
987        set(stride, yuva.y_stride);
988    }
989    // SAFETY: as above.
990    unsafe {
991        set(uv_stride, yuva.u_stride);
992    }
993    block.wrapping_add(yuva.y.offset)
994}
995
996/// The `...Into` functions for RGB samples.
997///
998/// # Safety
999///
1000/// `data` as in [`webp_get_info`]; `output` is null or points to
1001/// `output_buffer_size` writable bytes.
1002unsafe fn into_rgb(
1003    data: *const u8,
1004    data_size: usize,
1005    output: *mut u8,
1006    output_buffer_size: usize,
1007    output_stride: c_int,
1008    decode: IntoDecode,
1009) -> *mut u8 {
1010    if output.is_null() || data.is_null() || output_stride < 0 {
1011        return ptr::null_mut();
1012    }
1013    if ranges_overlap(data, data_size, output, output_buffer_size) {
1014        return ptr::null_mut();
1015    }
1016    // SAFETY: the caller's input, which does not overlap the output.
1017    let data = unsafe { input(data, data_size) };
1018    // SAFETY: the caller lends `output_buffer_size` writable bytes for the
1019    // call, which nothing else accesses during it.
1020    let buffer = unsafe { slice::from_raw_parts_mut(output, output_buffer_size) };
1021    match decode(data, buffer, output_stride) {
1022        Some(_) => output,
1023        None => ptr::null_mut(),
1024    }
1025}
1026
1027// upstream: src/dec/webp_dec.c WebPDecodeRGBAInto
1028/// Decodes into a pre-allocated buffer of `output_buffer_size` bytes with
1029/// `output_stride`. Returns `output`, or null on failure.
1030///
1031/// # Safety
1032///
1033/// See [`into_rgb`].
1034#[unsafe(export_name = "WebPDecodeRGBAInto")]
1035pub unsafe extern "C" fn webp_decode_rgba_into(
1036    data: *const u8,
1037    data_size: usize,
1038    output: *mut u8,
1039    output_buffer_size: usize,
1040    output_stride: c_int,
1041) -> *mut u8 {
1042    // SAFETY: the caller's contract, passed on.
1043    unsafe {
1044        into_rgb(
1045            data,
1046            data_size,
1047            output,
1048            output_buffer_size,
1049            output_stride,
1050            dec::webp_decode_rgba_into,
1051        )
1052    }
1053}
1054
1055// upstream: src/dec/webp_dec.c WebPDecodeARGBInto
1056/// See [`webp_decode_rgba_into`].
1057///
1058/// # Safety
1059///
1060/// See [`into_rgb`].
1061#[unsafe(export_name = "WebPDecodeARGBInto")]
1062pub unsafe extern "C" fn webp_decode_argb_into(
1063    data: *const u8,
1064    data_size: usize,
1065    output: *mut u8,
1066    output_buffer_size: usize,
1067    output_stride: c_int,
1068) -> *mut u8 {
1069    // SAFETY: the caller's contract, passed on.
1070    unsafe {
1071        into_rgb(
1072            data,
1073            data_size,
1074            output,
1075            output_buffer_size,
1076            output_stride,
1077            dec::webp_decode_argb_into,
1078        )
1079    }
1080}
1081
1082// upstream: src/dec/webp_dec.c WebPDecodeBGRAInto
1083/// See [`webp_decode_rgba_into`].
1084///
1085/// # Safety
1086///
1087/// See [`into_rgb`].
1088#[unsafe(export_name = "WebPDecodeBGRAInto")]
1089pub unsafe extern "C" fn webp_decode_bgra_into(
1090    data: *const u8,
1091    data_size: usize,
1092    output: *mut u8,
1093    output_buffer_size: usize,
1094    output_stride: c_int,
1095) -> *mut u8 {
1096    // SAFETY: the caller's contract, passed on.
1097    unsafe {
1098        into_rgb(
1099            data,
1100            data_size,
1101            output,
1102            output_buffer_size,
1103            output_stride,
1104            dec::webp_decode_bgra_into,
1105        )
1106    }
1107}
1108
1109// upstream: src/dec/webp_dec.c WebPDecodeRGBInto
1110/// See [`webp_decode_rgba_into`].
1111///
1112/// # Safety
1113///
1114/// See [`into_rgb`].
1115#[unsafe(export_name = "WebPDecodeRGBInto")]
1116pub unsafe extern "C" fn webp_decode_rgb_into(
1117    data: *const u8,
1118    data_size: usize,
1119    output: *mut u8,
1120    output_buffer_size: usize,
1121    output_stride: c_int,
1122) -> *mut u8 {
1123    // SAFETY: the caller's contract, passed on.
1124    unsafe {
1125        into_rgb(
1126            data,
1127            data_size,
1128            output,
1129            output_buffer_size,
1130            output_stride,
1131            dec::webp_decode_rgb_into,
1132        )
1133    }
1134}
1135
1136// upstream: src/dec/webp_dec.c WebPDecodeBGRInto
1137/// See [`webp_decode_rgba_into`].
1138///
1139/// # Safety
1140///
1141/// See [`into_rgb`].
1142#[unsafe(export_name = "WebPDecodeBGRInto")]
1143pub unsafe extern "C" fn webp_decode_bgr_into(
1144    data: *const u8,
1145    data_size: usize,
1146    output: *mut u8,
1147    output_buffer_size: usize,
1148    output_stride: c_int,
1149) -> *mut u8 {
1150    // SAFETY: the caller's contract, passed on.
1151    unsafe {
1152        into_rgb(
1153            data,
1154            data_size,
1155            output,
1156            output_buffer_size,
1157            output_stride,
1158            dec::webp_decode_bgr_into,
1159        )
1160    }
1161}
1162
1163/// Whether any two of the planes overlap.
1164fn planes_overlap(planes: &[(*mut u8, usize)]) -> bool {
1165    planes.iter().enumerate().any(|(i, &(a, a_len))| {
1166        planes[i + 1..]
1167            .iter()
1168            .any(|&(b, b_len)| ranges_overlap(a, a_len, b, b_len))
1169    })
1170}
1171
1172// upstream: src/dec/webp_dec.c WebPDecodeYUVInto
1173/// Decodes the Y, U and V planes into pre-allocated buffers. Returns `luma`,
1174/// or null on failure.
1175///
1176/// # Safety
1177///
1178/// `data` as in [`webp_get_info`]; `luma`, `u` and `v` are null or point to
1179/// their sizes of writable bytes.
1180#[unsafe(export_name = "WebPDecodeYUVInto")]
1181pub unsafe extern "C" fn webp_decode_yuv_into(
1182    data: *const u8,
1183    data_size: usize,
1184    luma: *mut u8,
1185    luma_size: usize,
1186    luma_stride: c_int,
1187    u: *mut u8,
1188    u_size: usize,
1189    u_stride: c_int,
1190    v: *mut u8,
1191    v_size: usize,
1192    v_stride: c_int,
1193) -> *mut u8 {
1194    // C: a NULL luma fails at once; NULL chroma fails the buffer check before
1195    // anything is written.
1196    if luma.is_null() || u.is_null() || v.is_null() || data.is_null() {
1197        return ptr::null_mut();
1198    }
1199    if luma_stride < 0 || u_stride < 0 || v_stride < 0 {
1200        return ptr::null_mut();
1201    }
1202    let planes = [(luma, luma_size), (u, u_size), (v, v_size)];
1203    if planes_overlap(&planes)
1204        || planes
1205            .iter()
1206            .any(|&(plane, size)| ranges_overlap(data, data_size, plane, size))
1207    {
1208        return ptr::null_mut();
1209    }
1210    // SAFETY: the caller's input, which does not overlap the planes.
1211    let data = unsafe { input(data, data_size) };
1212    // SAFETY: the caller lends each plane for the call; they are disjoint.
1213    let luma_slice = unsafe { slice::from_raw_parts_mut(luma, luma_size) };
1214    // SAFETY: as above.
1215    let u_slice = unsafe { slice::from_raw_parts_mut(u, u_size) };
1216    // SAFETY: as above.
1217    let v_slice = unsafe { slice::from_raw_parts_mut(v, v_size) };
1218    match dec::webp_decode_yuv_into(
1219        data,
1220        luma_slice,
1221        luma_stride,
1222        u_slice,
1223        u_stride,
1224        v_slice,
1225        v_stride,
1226    ) {
1227        Some(_) => luma,
1228        None => ptr::null_mut(),
1229    }
1230}
1231
1232//------------------------------------------------------------------------------
1233// Output buffers
1234
1235// upstream: src/dec/buffer_dec.c WebPInitDecBufferInternal
1236/// Internal, version-checked, entry point of `WebPInitDecBuffer`.
1237///
1238/// # Safety
1239///
1240/// `buffer` is null or points to a writable `WebPDecBuffer`.
1241#[unsafe(export_name = "WebPInitDecBufferInternal")]
1242pub unsafe extern "C" fn webp_init_dec_buffer_internal_c(
1243    buffer: *mut WebPDecBuffer,
1244    version: c_int,
1245) -> c_int {
1246    let mut rust = RsDecBuffer::default();
1247    if !webp_init_dec_buffer_internal(&mut rust, version) || buffer.is_null() {
1248        return 0; // version mismatch, or NULL
1249    }
1250    // SAFETY: a writable buffer (checked non-null); all-zero bytes are a valid
1251    // `WebPDecBuffer` (null pointers, zero integers), as C's memset makes it.
1252    unsafe { ptr::write_bytes(buffer, 0, 1) };
1253    1
1254}
1255
1256// upstream: src/dec/buffer_dec.c WebPFreeDecBuffer
1257/// Frees any memory associated with the buffer. Must always be called last.
1258/// Doesn't free the `buffer` structure itself.
1259///
1260/// # Safety
1261///
1262/// `buffer` is null or points to a `WebPDecBuffer` whose `private_memory` is
1263/// null or a block of this library.
1264#[unsafe(export_name = "WebPFreeDecBuffer")]
1265pub unsafe extern "C" fn webp_free_dec_buffer(buffer: *mut WebPDecBuffer) {
1266    // SAFETY: null or a valid buffer (caller's contract).
1267    let Some(buffer) = (unsafe { buffer.as_mut() }) else {
1268        return;
1269    };
1270    if buffer.is_external_memory <= 0 {
1271        // C: WebPSafeFree(buffer->private_memory).
1272        // SAFETY: the buffer's library block, which it gives up.
1273        unsafe { release_library_block(buffer.private_memory) };
1274    }
1275    buffer.private_memory = ptr::null_mut();
1276}
1277
1278//------------------------------------------------------------------------------
1279// Advanced decoding API
1280
1281// upstream: src/dec/webp_dec.c WebPGetFeaturesInternal
1282/// Internal, version-checked, entry point of `WebPGetFeatures`.
1283///
1284/// # Safety
1285///
1286/// `data` is null or points to `data_size` readable bytes; `features` is null
1287/// or writable.
1288#[unsafe(export_name = "WebPGetFeaturesInternal")]
1289pub unsafe extern "C" fn webp_get_features_internal(
1290    data: *const u8,
1291    data_size: usize,
1292    features: *mut WebPBitstreamFeatures,
1293    version: c_int,
1294) -> VP8StatusCode {
1295    // SAFETY: null or a valid, exclusive features structure.
1296    let Some(features) = (unsafe { features.as_mut() }) else {
1297        return VP8StatusCode::VP8_STATUS_INVALID_PARAM;
1298    };
1299    if data.is_null() {
1300        // C: the version is checked first, with the same result.
1301        return VP8StatusCode::VP8_STATUS_INVALID_PARAM;
1302    }
1303    // SAFETY: non-null input under the caller's contract.
1304    let data = unsafe { input(data, data_size) };
1305    status_code(dec::webp_get_features_internal(data, features, version))
1306}
1307
1308/// A `Result` as the C status.
1309fn status_code(result: Result<(), VP8StatusCode>) -> VP8StatusCode {
1310    result.err().unwrap_or(VP8StatusCode::VP8_STATUS_OK)
1311}
1312
1313// upstream: src/dec/webp_dec.c WebPInitDecoderConfigInternal
1314/// Internal, version-checked, entry point of `WebPInitDecoderConfig`.
1315///
1316/// # Safety
1317///
1318/// `config` is null or points to a writable `WebPDecoderConfig`.
1319#[unsafe(export_name = "WebPInitDecoderConfigInternal")]
1320pub unsafe extern "C" fn webp_init_decoder_config_internal(
1321    config: *mut WebPDecoderConfig,
1322    version: c_int,
1323) -> c_int {
1324    let mut rust = RsDecoderConfig::default();
1325    if !dec::webp_init_decoder_config_internal(&mut rust, version) || config.is_null() {
1326        return 0;
1327    }
1328    // SAFETY: a writable configuration (checked non-null); all-zero bytes are
1329    // a valid configuration, which is what C's memset, DefaultFeatures and
1330    // WebPInitDecBuffer leave.
1331    unsafe { ptr::write_bytes(config, 0, 1) };
1332    1
1333}
1334
1335/// The options and features of a C configuration with the colorspace of its
1336/// output, for the functions that read nothing else of the output.
1337fn config_without_memory(config: &WebPDecoderConfig) -> RsDecoderConfig<'static> {
1338    let mut rust = RsDecoderConfig {
1339        input: config.input,
1340        options: config.options,
1341        ..RsDecoderConfig::default()
1342    };
1343    rust.output.colorspace = config.output.colorspace;
1344    rust
1345}
1346
1347// upstream: src/dec/webp_dec.c WebPValidateDecoderConfig
1348/// Checks that `config` is non-null and valid.
1349///
1350/// # Safety
1351///
1352/// `config` is null or points to a `WebPDecoderConfig`.
1353#[unsafe(export_name = "WebPValidateDecoderConfig")]
1354#[must_use]
1355pub unsafe extern "C" fn webp_validate_decoder_config(config: *const WebPDecoderConfig) -> c_int {
1356    // SAFETY: null or a valid configuration.
1357    let Some(config) = (unsafe { config.as_ref() }) else {
1358        return 0;
1359    };
1360    c_int::from(dec::webp_validate_decoder_config(&config_without_memory(
1361        config,
1362    )))
1363}
1364
1365// upstream: src/dec/webp_dec.c WebPDecode
1366/// Non-incremental version: decodes `data` into `config->output`.
1367///
1368/// # Safety
1369///
1370/// `data` is null or points to `data_size` readable bytes; `config` is null or
1371/// a valid configuration whose output buffer follows `decode.h`.
1372#[unsafe(export_name = "WebPDecode")]
1373pub unsafe extern "C" fn webp_decode(
1374    data: *const u8,
1375    data_size: usize,
1376    config: *mut WebPDecoderConfig,
1377) -> VP8StatusCode {
1378    // SAFETY: null or a valid, exclusive configuration.
1379    let Some(config) = (unsafe { config.as_mut() }) else {
1380        return VP8StatusCode::VP8_STATUS_INVALID_PARAM;
1381    };
1382    if data.is_null() {
1383        return VP8StatusCode::VP8_STATUS_INVALID_PARAM; // C: GetFeatures
1384    }
1385    // SAFETY: the caller's output buffer under `decode.h`.
1386    let Some((output, memory)) = (unsafe { buffer_to_rust(&config.output) }) else {
1387        return VP8StatusCode::VP8_STATUS_INVALID_PARAM;
1388    };
1389    if let BufferMemory::Lent(lent) = &memory
1390        && lent.overlaps(data, data_size)
1391    {
1392        return VP8StatusCode::VP8_STATUS_INVALID_PARAM;
1393    }
1394    // SAFETY: the caller's input, which does not overlap the output.
1395    let data = unsafe { input(data, data_size) };
1396    let mut rust = RsDecoderConfig {
1397        input: config.input,
1398        output,
1399        options: config.options,
1400    };
1401    let status = dec::webp_decode(data, &mut rust);
1402    config.input = rust.input;
1403    // SAFETY: the output was converted from this buffer with this memory.
1404    if !unsafe { buffer_to_c(&mut config.output, &rust.output, &memory, true) } {
1405        // The samples could not reach C: as C's failed allocation.
1406        return VP8StatusCode::VP8_STATUS_OUT_OF_MEMORY;
1407    }
1408    status_code(status)
1409}
1410
1411//------------------------------------------------------------------------------
1412// Incremental decoding
1413
1414/// The incremental decoder behind C's opaque `WebPIDecoder*`.
1415///
1416/// The translation's decoder borrows the Rust forms of the caller's
1417/// configuration or output buffer, which live in leaked boxes until
1418/// `WebPIDelete()` drops the decoder and frees them. The memory of both its own
1419/// output buffer and the caller's is lent per call (`own_lent`, `user_lent`);
1420/// library samples move into a block after the call that allocates them: the
1421/// caller's buffer receives it as `private_memory`, and the decoder's own block
1422/// is freed at `WebPIDelete()`. With slow memory the decoder works in its own
1423/// buffer and copies into the caller's at the end.
1424pub struct WebPIDecoder {
1425    /// The translation's decoder.
1426    idec: ManuallyDrop<idec::WebPIDecoder<'static, 'static>>,
1427    /// The Rust configuration of `WebPIDecode`, or null.
1428    config: *mut RsDecoderConfig<'static>,
1429    /// The Rust output buffer of `WebPINewDecoder`, or null.
1430    user_buffer: *mut RsDecBuffer<'static>,
1431    /// The caller's C buffer (C: `params.output` or `final_output`), or null.
1432    user: *mut WebPDecBuffer,
1433    /// The memory of the decoder's own output buffer, lent for each call.
1434    own_lent: Lent,
1435    /// Whether `own_lent` is the decoder's library block.
1436    own_library_block: bool,
1437    /// The library block of the decoder's own output buffer, or null.
1438    own_block: *mut u8,
1439    /// The memory of the caller's output buffer, lent for each call.
1440    user_lent: Lent,
1441    /// The C view of the decoder's own output buffer (C: `idec->output`).
1442    own: WebPDecBuffer,
1443}
1444
1445/// A zeroed C buffer.
1446fn zeroed_buffer() -> WebPDecBuffer {
1447    WebPDecBuffer {
1448        colorspace: WEBP_CSP_MODE::MODE_RGB,
1449        width: 0,
1450        height: 0,
1451        is_external_memory: 0,
1452        u: WebPDecBufferUnion {
1453            YUVA: WebPYUVABuffer {
1454                y: ptr::null_mut(),
1455                u: ptr::null_mut(),
1456                v: ptr::null_mut(),
1457                a: ptr::null_mut(),
1458                y_stride: 0,
1459                u_stride: 0,
1460                v_stride: 0,
1461                a_stride: 0,
1462                y_size: 0,
1463                u_size: 0,
1464                v_size: 0,
1465                a_size: 0,
1466            },
1467        },
1468        pad: [0; 4],
1469        private_memory: ptr::null_mut(),
1470    }
1471}
1472
1473/// Lends `lent` to `buffer` for one call, if it holds caller or block memory.
1474///
1475/// # Safety
1476///
1477/// As [`Lent::storage`].
1478unsafe fn lend(buffer: &mut RsDecBuffer<'static>, lent: &Lent) {
1479    if !lent.0.is_empty() {
1480        // SAFETY: the caller's guarantee, passed on.
1481        buffer.storage = unsafe { lent.storage() };
1482    }
1483}
1484
1485/// Ends the loan of a buffer's memory.
1486fn take_back(buffer: &mut RsDecBuffer<'static>) {
1487    if matches!(buffer.storage, PlaneStorage::External(_)) {
1488        buffer.storage = PlaneStorage::External(Vec::new());
1489    }
1490}
1491
1492/// Moves the library samples of `buffer` into a library block, which the
1493/// buffer then views as lent memory. `held` is the block that the C buffer
1494/// already holds, or null. Returns the block, or null when there were no
1495/// samples or no block could be allocated.
1496fn move_samples(buffer: &mut RsDecBuffer<'static>, lent: &mut Lent, held: *mut u8) -> *mut u8 {
1497    let PlaneStorage::Internal(samples) = &buffer.storage else {
1498        return ptr::null_mut();
1499    };
1500    if samples.is_empty() {
1501        return ptr::null_mut();
1502    }
1503    let block = give_library_block(held, samples);
1504    if !block.is_null() {
1505        *lent = Lent(vec![(block, samples.len())]);
1506        // The block replaces the samples for the rest of the call.
1507        // SAFETY: a new block that only this storage views until the decoder
1508        // takes it back.
1509        buffer.storage = unsafe { lent.storage() };
1510    }
1511    block
1512}
1513
1514/// The memory from which the C view of a buffer is written: its lent regions,
1515/// the translation's own samples when no block could be allocated, or none yet.
1516fn view_memory(buffer: &mut RsDecBuffer<'static>, lent: &Lent) -> BufferMemory {
1517    match &mut buffer.storage {
1518        PlaneStorage::Internal(samples) if !samples.is_empty() => {
1519            BufferMemory::Lent(Lent(vec![(samples.as_mut_ptr(), samples.len())]))
1520        }
1521        // Not allocated yet: C's plane pointers stay as they are.
1522        PlaneStorage::Internal(_) => BufferMemory::Library,
1523        _ => BufferMemory::Lent(lent.clone()),
1524    }
1525}
1526
1527impl WebPIDecoder {
1528    /// Wraps a translation decoder whose own output memory is `own_lent` and
1529    /// whose caller output memory is `user_lent`.
1530    fn boxed(
1531        idec: idec::WebPIDecoder<'static, 'static>,
1532        own_lent: Lent,
1533        user_lent: Lent,
1534        config: *mut RsDecoderConfig<'static>,
1535        user_buffer: *mut RsDecBuffer<'static>,
1536        user: *mut WebPDecBuffer,
1537    ) -> *mut Self {
1538        let mut decoder = Box::new(Self {
1539            idec: ManuallyDrop::new(idec),
1540            config,
1541            user_buffer,
1542            user,
1543            own_lent,
1544            own_library_block: false,
1545            own_block: ptr::null_mut(),
1546            user_lent,
1547            own: zeroed_buffer(),
1548        });
1549        // The translation's buffers still view the lent memory, as during a
1550        // call: write the C views, then end the loan.
1551        // SAFETY: the views are written from the translation's buffers, which
1552        // were converted from them.
1553        unsafe { decoder.sync() };
1554        decoder.detach();
1555        Box::into_raw(decoder)
1556    }
1557
1558    /// Lends the output memory to the translation's buffers for one call.
1559    ///
1560    /// # Safety
1561    ///
1562    /// The lent memory is valid and nothing else accesses it until
1563    /// [`Self::detach`].
1564    unsafe fn attach(&mut self) {
1565        // SAFETY: the caller's guarantee; each buffer's regions are disjoint.
1566        unsafe { lend(self.idec.own_output_mut(), &self.own_lent) };
1567        if let Some(caller) = self.idec.caller_output_mut() {
1568            // SAFETY: as above.
1569            unsafe { lend(caller, &self.user_lent) };
1570        }
1571    }
1572
1573    /// Ends the loan of the output memory.
1574    fn detach(&mut self) {
1575        take_back(self.idec.own_output_mut());
1576        if let Some(caller) = self.idec.caller_output_mut() {
1577            take_back(caller);
1578        }
1579    }
1580
1581    /// After a call: moves library samples into blocks and writes the C views
1582    /// of both output buffers.
1583    ///
1584    /// # Safety
1585    ///
1586    /// `self.user` is null or the caller's live buffer.
1587    unsafe fn sync(&mut self) {
1588        let user = self.user;
1589        // The decoder's own buffer.
1590        {
1591            let own = self.idec.own_output_mut();
1592            let block = move_samples(own, &mut self.own_lent, ptr::null_mut());
1593            if !block.is_null() {
1594                library_blocks().remove(&(block as usize));
1595                self.own_block = block;
1596                self.own_library_block = true;
1597                self.own.private_memory = block;
1598            }
1599            let memory = view_memory(own, &self.own_lent);
1600            let own: &RsDecBuffer<'_> = own;
1601            self.own.colorspace = own.colorspace;
1602            self.own.is_external_memory =
1603                c_int::from(!self.own_library_block && !self.own_lent.0.is_empty());
1604            // SAFETY: the decoder's own view, written from its own buffer. The
1605            // incremental decoder never releases output memory before it is
1606            // deleted (C frees the own buffer's memory only at the slow copy,
1607            // after which C's view is the caller's structure).
1608            let _ = unsafe { buffer_to_c(&mut self.own, own, &memory, false) };
1609        }
1610        // The caller's buffer.
1611        if let Some(caller) = self.idec.caller_output_mut() {
1612            // SAFETY: the caller's live buffer.
1613            let view = unsafe { &mut *user };
1614            let block = move_samples(caller, &mut self.user_lent, view.private_memory);
1615            if !block.is_null() {
1616                view.private_memory = block;
1617            }
1618            let memory = view_memory(caller, &self.user_lent);
1619            let caller: &RsDecBuffer<'_> = caller;
1620            // SAFETY: the caller's view, written from the buffer that was
1621            // converted from it.
1622            let _ = unsafe { buffer_to_c(view, caller, &memory, false) };
1623        }
1624    }
1625
1626    /// Runs `call` with the output memory lent, then writes the C views.
1627    ///
1628    /// # Safety
1629    ///
1630    /// As [`Self::attach`] and [`Self::sync`].
1631    unsafe fn with<T>(
1632        &mut self,
1633        call: impl FnOnce(&mut idec::WebPIDecoder<'static, 'static>) -> T,
1634    ) -> T {
1635        // SAFETY: the caller's guarantee, passed on.
1636        unsafe { self.attach() };
1637        let result = call(&mut self.idec);
1638        // SAFETY: as above.
1639        unsafe { self.sync() };
1640        self.detach();
1641        result
1642    }
1643
1644    /// Whether `[start, start + len)` overlaps the lent memory.
1645    fn overlaps(&self, start: *const u8, len: usize) -> bool {
1646        self.own_lent.overlaps(start, len) || self.user_lent.overlaps(start, len)
1647    }
1648}
1649
1650/// The C view of a caller plane or of a plane in the decoder's memory: the
1651/// pointer that C returns.
1652fn rows_pointer(decoder: &WebPIDecoder, rows: idec::PlaneRows<'_>) -> *mut u8 {
1653    let Some((region, offset)) = rows else {
1654        return ptr::null_mut();
1655    };
1656    let base = region.as_ptr();
1657    let start = decoder
1658        .own_lent
1659        .0
1660        .iter()
1661        .chain(&decoder.user_lent.0)
1662        .find(|&&(start, _)| ptr::eq(start, base))
1663        .map_or(base.cast_mut(), |&(start, _)| start);
1664    start.wrapping_add(offset)
1665}
1666
1667// upstream: src/dec/idec_dec.c WebPINewDecoder
1668/// Creates a new incremental decoder with the supplied buffer parameter, or a
1669/// default output buffer (`MODE_RGB`) for null.
1670///
1671/// # Safety
1672///
1673/// `output_buffer` is null or a valid buffer that outlives the decoder, whose
1674/// memory follows `decode.h`.
1675#[unsafe(export_name = "WebPINewDecoder")]
1676pub unsafe extern "C" fn webp_i_new_decoder(
1677    output_buffer: *mut WebPDecBuffer,
1678) -> *mut WebPIDecoder {
1679    if output_buffer.is_null() {
1680        let Some(idec) = idec::webp_i_new_decoder(None) else {
1681            return ptr::null_mut();
1682        };
1683        return WebPIDecoder::boxed(
1684            idec,
1685            Lent::default(),
1686            Lent::default(),
1687            ptr::null_mut(),
1688            ptr::null_mut(),
1689            ptr::null_mut(),
1690        );
1691    }
1692    // SAFETY: a valid buffer (checked non-null).
1693    let output = unsafe { &*output_buffer };
1694    // SAFETY: the caller's output buffer under `decode.h`.
1695    let Some((buffer, memory)) = (unsafe { buffer_to_rust(output) }) else {
1696        return ptr::null_mut();
1697    };
1698    let lent = match memory {
1699        BufferMemory::Lent(lent) => lent,
1700        BufferMemory::Library => Lent::default(),
1701    };
1702    let user_buffer = Box::into_raw(Box::new(buffer));
1703    // SAFETY: a leaked box, which the decoder borrows until WebPIDelete.
1704    let Some(idec) = idec::webp_i_new_decoder(Some(unsafe { &mut *user_buffer })) else {
1705        // SAFETY: the box that was leaked above, no longer borrowed.
1706        drop(unsafe { Box::from_raw(user_buffer) });
1707        return ptr::null_mut();
1708    };
1709    WebPIDecoder::boxed(
1710        idec,
1711        Lent::default(),
1712        lent,
1713        ptr::null_mut(),
1714        user_buffer,
1715        output_buffer,
1716    )
1717}
1718
1719// upstream: src/dec/idec_dec.c WebPIDecode
1720/// Instantiates a new incremental decoder object with the requested
1721/// configuration.
1722///
1723/// # Safety
1724///
1725/// `data` is null or points to `data_size` readable bytes; `config` is null or
1726/// a valid configuration that outlives the decoder.
1727#[unsafe(export_name = "WebPIDecode")]
1728pub unsafe extern "C" fn webp_i_decode(
1729    data: *const u8,
1730    data_size: usize,
1731    config: *mut WebPDecoderConfig,
1732) -> *mut WebPIDecoder {
1733    // C: data != NULL && data_size > 0 parses the features.
1734    let data: &[u8] = if data.is_null() {
1735        &[]
1736    } else {
1737        // SAFETY: non-null input under the caller's contract.
1738        unsafe { input(data, data_size) }
1739    };
1740    if config.is_null() {
1741        let Some(idec) = idec::webp_i_decode(data, None) else {
1742            return ptr::null_mut();
1743        };
1744        return WebPIDecoder::boxed(
1745            idec,
1746            Lent::default(),
1747            Lent::default(),
1748            ptr::null_mut(),
1749            ptr::null_mut(),
1750            ptr::null_mut(),
1751        );
1752    }
1753    // SAFETY: a valid configuration (checked non-null).
1754    let c = unsafe { &mut *config };
1755    // SAFETY: the caller's output buffer under `decode.h`.
1756    let Some((output, memory)) = (unsafe { buffer_to_rust(&c.output) }) else {
1757        return ptr::null_mut();
1758    };
1759    let lent = match memory {
1760        BufferMemory::Lent(lent) => lent,
1761        BufferMemory::Library => Lent::default(),
1762    };
1763    if lent.overlaps(data.as_ptr(), data.len()) {
1764        return ptr::null_mut();
1765    }
1766    let rust = Box::into_raw(Box::new(RsDecoderConfig {
1767        input: c.input,
1768        output,
1769        options: c.options,
1770    }));
1771    // SAFETY: a leaked box, which the decoder borrows until WebPIDelete.
1772    let idec = idec::webp_i_decode(data, Some(unsafe { &mut *rust }));
1773    // C: the features were written into config->input.
1774    // SAFETY: `input` is a field that the decoder does not borrow.
1775    c.input = unsafe { (*rust).input };
1776    let Some(idec) = idec else {
1777        // SAFETY: the box that was leaked above, no longer borrowed.
1778        drop(unsafe { Box::from_raw(rust) });
1779        return ptr::null_mut();
1780    };
1781    let user = &raw mut c.output;
1782    WebPIDecoder::boxed(idec, Lent::default(), lent, rust, ptr::null_mut(), user)
1783}
1784
1785// upstream: src/dec/idec_dec.c WebPINewRGB
1786/// Creates a decoder that outputs RGB samples into `output_buffer`, or into
1787/// memory it allocates for null.
1788///
1789/// # Safety
1790///
1791/// `output_buffer` is null or points to `output_buffer_size` writable bytes
1792/// that outlive the decoder.
1793#[unsafe(export_name = "WebPINewRGB")]
1794pub unsafe extern "C" fn webp_i_new_rgb(
1795    csp: WEBP_CSP_MODE,
1796    output_buffer: *mut u8,
1797    output_buffer_size: usize,
1798    output_stride: c_int,
1799) -> *mut WebPIDecoder {
1800    if !output_buffer.is_null() && output_stride < 0 {
1801        return ptr::null_mut();
1802    }
1803    let lent = if output_buffer.is_null() {
1804        Lent::default()
1805    } else {
1806        Lent(vec![(output_buffer, output_buffer_size)])
1807    };
1808    let buffer = (!output_buffer.is_null()).then(|| {
1809        // SAFETY: the caller lends the buffer; the decoder detaches it before
1810        // the call returns.
1811        unsafe { slice::from_raw_parts_mut(output_buffer, output_buffer_size) }
1812    });
1813    let Some(idec) = idec::webp_i_new_rgb(csp, buffer, output_stride) else {
1814        return ptr::null_mut();
1815    };
1816    WebPIDecoder::boxed(
1817        idec,
1818        lent,
1819        Lent::default(),
1820        ptr::null_mut(),
1821        ptr::null_mut(),
1822        ptr::null_mut(),
1823    )
1824}
1825
1826// upstream: src/dec/idec_dec.c WebPINewYUVA
1827/// Creates a decoder that outputs YUV(A) samples into the caller's planes, or
1828/// into memory it allocates when `luma` is null.
1829///
1830/// # Safety
1831///
1832/// When `luma` is not null, each non-null plane points to its size of
1833/// writable bytes that outlive the decoder.
1834#[unsafe(export_name = "WebPINewYUVA")]
1835pub unsafe extern "C" fn webp_i_new_yuva(
1836    luma: *mut u8,
1837    luma_size: usize,
1838    luma_stride: c_int,
1839    u: *mut u8,
1840    u_size: usize,
1841    u_stride: c_int,
1842    v: *mut u8,
1843    v_size: usize,
1844    v_stride: c_int,
1845    a: *mut u8,
1846    a_size: usize,
1847    a_stride: c_int,
1848) -> *mut WebPIDecoder {
1849    if luma.is_null() {
1850        // C ignores the other arguments.
1851        let Some(idec) = idec::webp_i_new_yuva(None, 0, None, 0, None, 0, None, 0) else {
1852            return ptr::null_mut();
1853        };
1854        return WebPIDecoder::boxed(
1855            idec,
1856            Lent::default(),
1857            Lent::default(),
1858            ptr::null_mut(),
1859            ptr::null_mut(),
1860            ptr::null_mut(),
1861        );
1862    }
1863    let planes: Vec<(*mut u8, usize, c_int)> = [
1864        (luma, luma_size, luma_stride),
1865        (u, u_size, u_stride),
1866        (v, v_size, v_stride),
1867        (a, a_size, a_stride),
1868    ]
1869    .into_iter()
1870    .filter(|&(plane, _, _)| !plane.is_null())
1871    .collect();
1872    let ranges: Vec<(*mut u8, usize)> = planes.iter().map(|&(p, size, _)| (p, size)).collect();
1873    if planes_overlap(&ranges) || planes.iter().any(|&(_, _, stride)| stride < 0) {
1874        return ptr::null_mut();
1875    }
1876    let slice_of = |plane: *mut u8, size: usize| {
1877        (!plane.is_null()).then(|| {
1878            // SAFETY: the caller lends the plane; the planes are disjoint, and
1879            // the decoder detaches them before the call returns.
1880            unsafe { slice::from_raw_parts_mut(plane, size) }
1881        })
1882    };
1883    let Some(idec) = idec::webp_i_new_yuva(
1884        slice_of(luma, luma_size),
1885        luma_stride,
1886        slice_of(u, u_size),
1887        u_stride,
1888        slice_of(v, v_size),
1889        v_stride,
1890        slice_of(a, a_size),
1891        a_stride,
1892    ) else {
1893        return ptr::null_mut();
1894    };
1895    // The translation keeps the planes in the order Y, U, V and A.
1896    WebPIDecoder::boxed(
1897        idec,
1898        Lent(ranges),
1899        Lent::default(),
1900        ptr::null_mut(),
1901        ptr::null_mut(),
1902        ptr::null_mut(),
1903    )
1904}
1905
1906// upstream: src/dec/idec_dec.c WebPINewYUV
1907/// Deprecated version of `WebPINewYUVA()`, without alpha.
1908///
1909/// # Safety
1910///
1911/// As [`webp_i_new_yuva`].
1912#[unsafe(export_name = "WebPINewYUV")]
1913pub unsafe extern "C" fn webp_i_new_yuv(
1914    luma: *mut u8,
1915    luma_size: usize,
1916    luma_stride: c_int,
1917    u: *mut u8,
1918    u_size: usize,
1919    u_stride: c_int,
1920    v: *mut u8,
1921    v_size: usize,
1922    v_stride: c_int,
1923) -> *mut WebPIDecoder {
1924    // SAFETY: the caller's contract, passed on.
1925    unsafe {
1926        webp_i_new_yuva(
1927            luma,
1928            luma_size,
1929            luma_stride,
1930            u,
1931            u_size,
1932            u_stride,
1933            v,
1934            v_size,
1935            v_stride,
1936            ptr::null_mut(),
1937            0,
1938            0,
1939        )
1940    }
1941}
1942
1943// upstream: src/dec/idec_dec.c WebPIDelete
1944/// Deletes the decoder object and associated memory. The caller's output
1945/// buffer keeps its memory.
1946///
1947/// # Safety
1948///
1949/// `idec` is null or a decoder of this library that is not used again.
1950#[unsafe(export_name = "WebPIDelete")]
1951pub unsafe extern "C" fn webp_i_delete(idec: *mut WebPIDecoder) {
1952    if idec.is_null() {
1953        return;
1954    }
1955    // SAFETY: a decoder of this library, which the caller gives up.
1956    let mut decoder = unsafe { Box::from_raw(idec) };
1957    // SAFETY: the output memory is valid until the decoder is deleted.
1958    unsafe { decoder.attach() };
1959    // SAFETY: dropped once, before the boxes that it borrows.
1960    unsafe { ManuallyDrop::drop(&mut decoder.idec) };
1961    if !decoder.config.is_null() {
1962        // SAFETY: the leaked configuration, no longer borrowed.
1963        drop(unsafe { Box::from_raw(decoder.config) });
1964    }
1965    if !decoder.user_buffer.is_null() {
1966        // SAFETY: the leaked buffer, no longer borrowed.
1967        drop(unsafe { Box::from_raw(decoder.user_buffer) });
1968    }
1969    // C: WebPFreeDecBuffer(&idec->output).
1970    // SAFETY: the decoder's own block, which nothing uses any more.
1971    unsafe { platform_free(decoder.own_block) };
1972}
1973
1974// upstream: src/dec/idec_dec.c WebPIAppend
1975/// Copies and decodes the next available data.
1976///
1977/// # Safety
1978///
1979/// `idec` is null or a live decoder; `data` is null or points to `data_size`
1980/// readable bytes.
1981#[unsafe(export_name = "WebPIAppend")]
1982pub unsafe extern "C" fn webp_i_append(
1983    idec: *mut WebPIDecoder,
1984    data: *const u8,
1985    data_size: usize,
1986) -> VP8StatusCode {
1987    // SAFETY: null or a live decoder.
1988    let Some(decoder) = (unsafe { idec.as_mut() }) else {
1989        return VP8StatusCode::VP8_STATUS_INVALID_PARAM;
1990    };
1991    if data.is_null() || decoder.overlaps(data, data_size) {
1992        return VP8StatusCode::VP8_STATUS_INVALID_PARAM;
1993    }
1994    // SAFETY: the caller's input, which does not overlap the output memory.
1995    let data = unsafe { input(data, data_size) };
1996    // SAFETY: the output memory is valid while the decoder lives.
1997    status_code(unsafe { decoder.with(|idec| idec::webp_i_append(idec, data)) })
1998}
1999
2000// upstream: src/dec/idec_dec.c WebPIUpdate
2001/// A variant of `WebPIAppend()` for a buffer that holds all the data so far.
2002///
2003/// # Safety
2004///
2005/// As [`webp_i_append`].
2006#[unsafe(export_name = "WebPIUpdate")]
2007pub unsafe extern "C" fn webp_i_update(
2008    idec: *mut WebPIDecoder,
2009    data: *const u8,
2010    data_size: usize,
2011) -> VP8StatusCode {
2012    // SAFETY: null or a live decoder.
2013    let Some(decoder) = (unsafe { idec.as_mut() }) else {
2014        return VP8StatusCode::VP8_STATUS_INVALID_PARAM;
2015    };
2016    if data.is_null() || decoder.overlaps(data, data_size) {
2017        return VP8StatusCode::VP8_STATUS_INVALID_PARAM;
2018    }
2019    // SAFETY: the caller's input, which does not overlap the output memory.
2020    let data = unsafe { input(data, data_size) };
2021    // SAFETY: the output memory is valid while the decoder lives.
2022    status_code(unsafe { decoder.with(|idec| idec::webp_i_update(idec, data)) })
2023}
2024
2025// upstream: src/dec/idec_dec.c WebPIDecGetRGB
2026/// Returns the RGB/A image decoded so far, or null.
2027///
2028/// # Safety
2029///
2030/// `idec` is null or a live decoder; the output parameters are null or
2031/// writable.
2032#[unsafe(export_name = "WebPIDecGetRGB")]
2033pub unsafe extern "C" fn webp_i_dec_get_rgb(
2034    idec: *const WebPIDecoder,
2035    last_y: *mut c_int,
2036    width: *mut c_int,
2037    height: *mut c_int,
2038    stride: *mut c_int,
2039) -> *mut u8 {
2040    // SAFETY: null or a live decoder; C takes a const pointer and changes
2041    // nothing, and this function only lends and takes back the memory.
2042    let Some(decoder) = (unsafe { idec.cast_mut().as_mut() }) else {
2043        return ptr::null_mut();
2044    };
2045    // SAFETY: the output memory is valid while the decoder lives.
2046    unsafe { decoder.attach() };
2047    // SAFETY: null or writable output parameters (caller's contract).
2048    let last_y = unsafe { out(last_y) };
2049    // SAFETY: as above.
2050    let width = unsafe { out(width) };
2051    // SAFETY: as above.
2052    let height = unsafe { out(height) };
2053    // SAFETY: as above.
2054    let stride = unsafe { out(stride) };
2055    let rows = idec::webp_i_dec_get_rgb(&decoder.idec, last_y, width, height, stride);
2056    let pointer = rows_pointer(decoder, rows);
2057    decoder.detach();
2058    pointer
2059}
2060
2061// upstream: src/dec/idec_dec.c WebPIDecGetYUVA
2062/// Same as `WebPIDecGetRGB()` but to retrieve the Y, U, V and A planes.
2063///
2064/// # Safety
2065///
2066/// As [`webp_i_dec_get_rgb`].
2067#[unsafe(export_name = "WebPIDecGetYUVA")]
2068pub unsafe extern "C" fn webp_i_dec_get_yuva(
2069    idec: *const WebPIDecoder,
2070    last_y: *mut c_int,
2071    u: *mut *mut u8,
2072    v: *mut *mut u8,
2073    a: *mut *mut u8,
2074    width: *mut c_int,
2075    height: *mut c_int,
2076    stride: *mut c_int,
2077    uv_stride: *mut c_int,
2078    a_stride: *mut c_int,
2079) -> *mut u8 {
2080    // SAFETY: see `webp_i_dec_get_rgb`.
2081    let Some(decoder) = (unsafe { idec.cast_mut().as_mut() }) else {
2082        return ptr::null_mut();
2083    };
2084    // SAFETY: the output memory is valid while the decoder lives.
2085    unsafe { decoder.attach() };
2086    let (mut u_rows, mut v_rows, mut a_rows) = (None, None, None);
2087    // SAFETY: null or writable output parameters (caller's contract).
2088    let last_y_out = unsafe { out(last_y) };
2089    // SAFETY: as above.
2090    let width = unsafe { out(width) };
2091    // SAFETY: as above.
2092    let height = unsafe { out(height) };
2093    // SAFETY: as above.
2094    let stride = unsafe { out(stride) };
2095    // SAFETY: as above.
2096    let uv_stride = unsafe { out(uv_stride) };
2097    // SAFETY: as above.
2098    let a_stride_out = unsafe { out(a_stride) };
2099    let y = idec::webp_i_dec_get_yuva(
2100        &decoder.idec,
2101        last_y_out,
2102        (!u.is_null()).then_some(&mut u_rows),
2103        (!v.is_null()).then_some(&mut v_rows),
2104        (!a.is_null()).then_some(&mut a_rows),
2105        width,
2106        height,
2107        stride,
2108        uv_stride,
2109        a_stride_out,
2110    );
2111    let pointers = y.map(|_| {
2112        (
2113            rows_pointer(decoder, u_rows),
2114            rows_pointer(decoder, v_rows),
2115            rows_pointer(decoder, a_rows),
2116        )
2117    });
2118    let y = rows_pointer(decoder, y);
2119    decoder.detach();
2120    if let Some((u_ptr, v_ptr, a_ptr)) = pointers {
2121        // SAFETY: null or writable output parameters.
2122        unsafe { set(u, u_ptr) };
2123        // SAFETY: as above.
2124        unsafe { set(v, v_ptr) };
2125        // SAFETY: as above.
2126        unsafe { set(a, a_ptr) };
2127    }
2128    y
2129}
2130
2131// upstream: src/dec/idec_dec.c WebPIDecodedArea
2132/// Retrieves information about the displayable area: returns the output
2133/// buffer, or null in case the decoder is in an invalid state.
2134///
2135/// # Safety
2136///
2137/// As [`webp_i_dec_get_rgb`].
2138#[unsafe(export_name = "WebPIDecodedArea")]
2139pub unsafe extern "C" fn webp_i_decoded_area(
2140    idec: *const WebPIDecoder,
2141    left: *mut c_int,
2142    top: *mut c_int,
2143    width: *mut c_int,
2144    height: *mut c_int,
2145) -> *const WebPDecBuffer {
2146    // SAFETY: null or writable output parameters (caller's contract).
2147    let left = unsafe { out(left) };
2148    // SAFETY: as above.
2149    let top = unsafe { out(top) };
2150    // SAFETY: as above.
2151    let width = unsafe { out(width) };
2152    // SAFETY: as above.
2153    let height = unsafe { out(height) };
2154    // SAFETY: see `webp_i_dec_get_rgb`.
2155    let Some(decoder) = (unsafe { idec.cast_mut().as_mut() }) else {
2156        // C: GetOutputBuffer(NULL) is NULL, and the area is empty.
2157        for value in [left, top, width, height].into_iter().flatten() {
2158            *value = 0;
2159        }
2160        return ptr::null();
2161    };
2162    // SAFETY: the output memory is valid while the decoder lives.
2163    unsafe { decoder.attach() };
2164    let area = idec::webp_i_decoded_area(&decoder.idec, left, top, width, height).is_some();
2165    decoder.detach();
2166    if !area {
2167        ptr::null()
2168    } else if decoder.idec.has_user_output() && decoder.idec.was_slow() {
2169        // C: after the slow copy, `*output = *idec->final_output`: the
2170        // decoder's own buffer holds a copy of the caller's structure.
2171        // SAFETY: the caller's live buffer, read as plain data.
2172        decoder.own = unsafe { ptr::read(decoder.user) };
2173        &raw const decoder.own
2174    } else if decoder.idec.has_user_output() {
2175        decoder.user
2176    } else {
2177        &raw const decoder.own
2178    }
2179}