webp/abi/demux.rs
1// libwebp v1.6.0, src/webp/demux.h:
2//
3// Copyright 2012 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// Demux API.
13// Enables extraction of image and extended format data from WebP files.
14
15//! C ABI export of `src/webp/demux.h` from libwebp v1.6.0.
16//!
17//! Mirrors the header's structs with `repr(C)` and converts them to the
18//! safe representations at the boundary; see
19//! `docs/adr/0004-c-abi-boundary.md`.
20//!
21//! Work package: WP14 (animation decode and demux ABI).
22//!
23//! # Objects
24//!
25//! - The translation's demuxer borrows the `WebPData` value that it parses
26//! (WP8). The C caller's `WebPData` struct need not outlive the demuxer, only
27//! its bytes, which `demux.h` requires to stay valid and unchanged until
28//! `WebPDemuxDelete()` ("`WebPDemuxer` keeps internal pointers to 'data'
29//! memory segment"). `WebPDemuxInternal()` therefore leaks a `Box<WebPData<'static>>`
30//! that borrows the caller's bytes under that contract, creates the demuxer
31//! from it and returns a heap handle whose first field is the demuxer; the
32//! handle also keeps the data box, and `WebPDemuxDelete()` drops the demuxer
33//! before it frees the box. The animation decoder is kept the same way
34//! (`WebPAnimDecoderNew()` requires the bitstream to "remain unchanged during
35//! the lifetime of the output `WebPAnimDecoder` object").
36//! - A C `WebPDemuxer*` points at the translation's demuxer itself, whether it
37//! comes from `WebPDemuxInternal()` or from `WebPAnimDecoderGetDemuxer()`, so
38//! the demux functions accept both. The demuxer is immutable after
39//! construction, so the pointers stay valid while their owner lives.
40//! - `WebPIterator` and `WebPChunkIterator` are mirrored with C's field order;
41//! `private_` is the demuxer pointer. `Next` and `Prev` rebuild the Rust
42//! iterator from the C struct and write back the fields that C writes. The
43//! chunk tag that C reads from the four bytes before `chunk.bytes` is taken
44//! from the demuxer's input at that position.
45//! - `WebPAnimDecoderOptions` and `WebPAnimInfo` have no pointers and are shared
46//! with `src/webp/demux.rs`; `WebPDemuxState` and `WebPFormatFeature` are WP1's
47//! newtypes over C's enum type. `tests/wp14_abi_layout.rs` checks the layouts.
48//!
49//! # Restrictions
50//!
51//! The caller's bytes are borrowed as an immutable Rust slice for the lifetime
52//! of the demuxer or the animation decoder, so they must not change while it
53//! lives, which the header asks for; C itself would only read the changed
54//! bytes. The canvas that `WebPAnimDecoderGetNext()` returns may be read until
55//! the next call on the decoder, as the header says.
56//!
57//! # Deviations from upstream
58//!
59//! Changes of representation that the ADRs allow, or behavior that the Rust
60//! side cannot reproduce exactly. Each records the reason.
61//!
62//! 1. **`WebPData` mirror.** `mux_types.h` has no ABI module, so
63//! `src/abi/demux.rs` defines the `repr(C)` `WebPData` (public, for
64//! `src/abi/mux.rs`).
65//! 2. **C ABI iterators.** `Next` and `Prev` rebuild the Rust iterator from
66//! `frame_num` (or `chunk_num`) and `private_` and write back the fields
67//! that C writes on success (none on failure); `pad` and `private_` are
68//! never written after `Get`. `WebPDemuxGetFrame` and `WebPDemuxGetChunk`
69//! write the caller's iterator whole, so it may be uninitialized.
70//!
71//! # Excluded undefined behavior
72//!
73//! Inputs that are undefined behavior (or assertion failures) in C and are
74//! therefore excluded from the oracle comparison (PORTING rule 8):
75//!
76//! 1. **`WebPDemuxNextChunk` and `WebPDemuxPrevChunk` on an iterator whose
77//! `chunk.bytes` is `NULL`** (a failed `WebPDemuxGetChunk` with a demuxer),
78//! or points outside the input: C computes the tag address from it and reads
79//! there. The C ABI returns 0 (`chunk_tag`); the probe never calls it.
80//! 2. **`WebPDemuxNextFrame` and `WebPDemuxNextChunk` with `frame_num` or
81//! `chunk_num` at `INT_MAX`:** the `int` sum overflows. The C ABI returns 0,
82//! which is what the wrapped value gives in C.
83//!
84//! # Checks not applicable
85//!
86//! These checks do not apply, or cannot be made, with the reason:
87//!
88//! 1. **`NULL` arguments** exist only at the C ABI (PORTING rule 8); every
89//! `NULL` case of `demux.h` is compared there
90//! (`abi_answers_null_and_invalid_arguments_as_c`).
91
92use core::ffi::{c_char, c_int, c_void};
93use core::mem::ManuallyDrop;
94use core::ptr;
95use core::slice;
96use std::borrow::Cow;
97
98use crate::demux::anim_decode::{self as anim, WebPAnimDecoder as RsAnimDecoder};
99use crate::demux::demux::{self as dmx, WebPDemuxer as RsDemuxer};
100use crate::webp::demux::{
101 WEBP_DEMUX_ABI_VERSION, WebPAnimDecoderOptions, WebPAnimInfo,
102 WebPChunkIterator as RsChunkIterator, WebPDemuxState, WebPFormatFeature,
103 WebPIterator as RsIterator,
104};
105use crate::webp::mux_types::{WebPData as RsData, WebPMuxAnimBlend, WebPMuxAnimDispose};
106use crate::webp::types::webp_abi_is_incompatible;
107
108// upstream: src/webp/format_constants.h CHUNK_HEADER_SIZE
109const CHUNK_HEADER_SIZE: usize = 8;
110// upstream: src/webp/format_constants.h TAG_SIZE
111const TAG_SIZE: usize = 4;
112
113//------------------------------------------------------------------------------
114// Mirrors of the structs with pointers
115
116// upstream: src/webp/mux_types.h WebPData
117/// Data type used to describe 'raw' data, e.g., chunk data (C layout).
118#[repr(C)]
119#[derive(Clone, Copy, Debug)]
120pub struct WebPData {
121 /// The bytes.
122 pub bytes: *const u8,
123 /// Their number.
124 pub size: usize,
125}
126
127// upstream: src/webp/demux.h WebPIterator
128/// Iterator over the frames of a demuxer (C layout).
129#[repr(C)]
130#[derive(Clone, Copy, Debug)]
131pub struct WebPIterator {
132 /// The frame number of this frame.
133 pub frame_num: c_int,
134 /// Equivalent to `WEBP_FF_FRAME_COUNT`.
135 pub num_frames: c_int,
136 /// Offset relative to the canvas.
137 pub x_offset: c_int,
138 /// Offset relative to the canvas.
139 pub y_offset: c_int,
140 /// Dimensions of this frame.
141 pub width: c_int,
142 /// Dimensions of this frame.
143 pub height: c_int,
144 /// Display duration in milliseconds.
145 pub duration: c_int,
146 /// Dispose method for the frame.
147 pub dispose_method: WebPMuxAnimDispose,
148 /// True if `fragment` contains a full frame.
149 pub complete: c_int,
150 /// The frame given by `frame_num`.
151 pub fragment: WebPData,
152 /// True if the frame contains transparency.
153 pub has_alpha: c_int,
154 /// Blend operation for the frame.
155 pub blend_method: WebPMuxAnimBlend,
156 /// Padding for later use.
157 pub pad: [u32; 2],
158 /// The demuxer (C: for internal use only).
159 pub private_: *mut c_void,
160}
161
162// upstream: src/webp/demux.h WebPChunkIterator
163/// Iterator over the chunks with one tag of a demuxer (C layout).
164#[repr(C)]
165#[derive(Clone, Copy, Debug)]
166pub struct WebPChunkIterator {
167 /// The current chunk number with the tag.
168 pub chunk_num: c_int,
169 /// The number of chunks with the tag.
170 pub num_chunks: c_int,
171 /// The payload of the chunk.
172 pub chunk: WebPData,
173 /// Padding for later use.
174 pub pad: [u32; 6],
175 /// The demuxer (C: for internal use only).
176 pub private_: *mut c_void,
177}
178
179/// The object behind a C `WebPDemuxer*`: the translation's demuxer over the
180/// caller's bytes (C: `struct WebPDemuxer`, opaque in the header).
181pub type WebPDemuxer = RsDemuxer<'static>;
182
183/// The heap object that `WebPDemuxInternal()` returns. `dmux` comes first, so a
184/// pointer to the handle is a pointer to its demuxer.
185#[repr(C)]
186struct DemuxHandle {
187 /// The demuxer; dropped by `WebPDemuxDelete()` before `data`.
188 dmux: ManuallyDrop<RsDemuxer<'static>>,
189 /// The leaked box that the demuxer borrows.
190 data: *mut RsData<'static>,
191}
192
193/// The object behind a C `WebPAnimDecoder*` (C: `struct WebPAnimDecoder`).
194pub struct WebPAnimDecoder {
195 /// The translation's decoder; dropped by `WebPAnimDecoderDelete()` before
196 /// `data`.
197 dec: ManuallyDrop<RsAnimDecoder<'static>>,
198 /// The leaked box that the decoder's demuxer borrows.
199 data: *mut RsData<'static>,
200}
201
202//------------------------------------------------------------------------------
203// Helpers
204
205/// Writes an optional output parameter.
206///
207/// # Safety
208///
209/// `ptr` is null or points to a writable `T`.
210unsafe fn set<T>(ptr: *mut T, value: T) {
211 if !ptr.is_null() {
212 // SAFETY: a valid, writable `T` (caller's contract).
213 unsafe { ptr.write(value) };
214 }
215}
216
217/// Leaks a `WebPData` over the caller's bytes, for an object that keeps it until
218/// it is deleted.
219///
220/// # Safety
221///
222/// `bytes` is not null and points to `size` bytes that stay readable and
223/// unchanged until the box is freed (the header's contract).
224unsafe fn leak_data(bytes: *const u8, size: usize) -> *mut RsData<'static> {
225 // SAFETY: the caller's bytes, valid and unchanged for the object's lifetime
226 // under `demux.h`; the object frees the box before the bytes may go away.
227 let bytes: &'static [u8] = unsafe { slice::from_raw_parts(bytes, size) };
228 Box::into_raw(Box::new(RsData {
229 bytes: Cow::Borrowed(bytes),
230 }))
231}
232
233/// The demuxer behind a C `WebPDemuxer*`, or `None` for null.
234///
235/// # Safety
236///
237/// `dmux` is null or a live demuxer of this library.
238unsafe fn demuxer<'d>(dmux: *const WebPDemuxer) -> Option<&'d RsDemuxer<'static>> {
239 // SAFETY: null or a live demuxer (caller's contract), which is never written
240 // after construction.
241 unsafe { dmux.as_ref() }
242}
243
244/// A zeroed C iterator over `dmux` (C: `memset(iter, 0, sizeof(*iter))` and
245/// `iter->private_ = (void*)dmux`).
246fn zeroed_iterator(dmux: *const WebPDemuxer) -> WebPIterator {
247 WebPIterator {
248 frame_num: 0,
249 num_frames: 0,
250 x_offset: 0,
251 y_offset: 0,
252 width: 0,
253 height: 0,
254 duration: 0,
255 dispose_method: WebPMuxAnimDispose(0),
256 complete: 0,
257 fragment: WebPData {
258 bytes: ptr::null(),
259 size: 0,
260 },
261 has_alpha: 0,
262 blend_method: WebPMuxAnimBlend(0),
263 pad: [0; 2],
264 private_: dmux.cast_mut().cast(),
265 }
266}
267
268/// A zeroed C chunk iterator over `dmux`.
269fn zeroed_chunk_iterator(dmux: *const WebPDemuxer) -> WebPChunkIterator {
270 WebPChunkIterator {
271 chunk_num: 0,
272 num_chunks: 0,
273 chunk: WebPData {
274 bytes: ptr::null(),
275 size: 0,
276 },
277 pad: [0; 6],
278 private_: dmux.cast_mut().cast(),
279 }
280}
281
282/// The C view of a Rust byte slice that borrows the caller's bytes.
283fn data_to_c(data: &RsData<'_>) -> WebPData {
284 WebPData {
285 bytes: data.bytes.as_ptr(),
286 size: data.bytes.len(),
287 }
288}
289
290/// Writes the fields that C's `SynthesizeFrame` writes.
291fn iterator_to_c(it: &RsIterator<'_>, c: &mut WebPIterator) {
292 c.frame_num = it.frame_num;
293 c.num_frames = it.num_frames;
294 c.x_offset = it.x_offset;
295 c.y_offset = it.y_offset;
296 c.width = it.width;
297 c.height = it.height;
298 c.has_alpha = it.has_alpha;
299 c.duration = it.duration;
300 c.dispose_method = it.dispose_method;
301 c.blend_method = it.blend_method;
302 c.complete = it.complete;
303 c.fragment = data_to_c(&it.fragment);
304}
305
306/// The Rust iterator over `dmux` at the C iterator's frame, as `Next` and `Prev`
307/// read it: only `frame_num` and the demuxer matter to them.
308fn iterator_to_rust<'d>(c: &WebPIterator, dmux: &'d RsDemuxer<'d>) -> RsIterator<'d> {
309 RsIterator {
310 frame_num: c.frame_num,
311 num_frames: c.num_frames,
312 x_offset: c.x_offset,
313 y_offset: c.y_offset,
314 width: c.width,
315 height: c.height,
316 duration: c.duration,
317 dispose_method: c.dispose_method,
318 complete: c.complete,
319 fragment: RsData::default(),
320 has_alpha: c.has_alpha,
321 blend_method: c.blend_method,
322 pad: c.pad,
323 dmux,
324 }
325}
326
327/// Writes the fields that C's `SetChunk` writes.
328fn chunk_iterator_to_c(it: &RsChunkIterator<'_>, c: &mut WebPChunkIterator) {
329 c.chunk = data_to_c(&it.chunk);
330 c.num_chunks = it.num_chunks;
331 c.chunk_num = it.chunk_num;
332}
333
334/// The tag that C reads at `chunk.bytes - CHUNK_HEADER_SIZE`, taken from the
335/// demuxer's input. `None` when those four bytes are not inside the input, which
336/// an iterator that `WebPDemuxGetChunk()` filled never gives: a zeroed iterator
337/// (C computes the tag address from `NULL`) or a changed `chunk.bytes` make C
338/// read outside the input, which is undefined (the module documentation,
339/// `# Excluded undefined behavior`, item 1).
340fn chunk_tag(c: &WebPChunkIterator, dmux: &RsDemuxer<'_>) -> Option<[u8; TAG_SIZE]> {
341 let input = dmux.input();
342 if c.chunk.bytes.is_null() {
343 return None;
344 }
345 let offset = (c.chunk.bytes as usize).wrapping_sub(input.as_ptr() as usize);
346 if offset < CHUNK_HEADER_SIZE || offset > input.len() {
347 return None;
348 }
349 let start = offset - CHUNK_HEADER_SIZE;
350 input[start..start + TAG_SIZE].try_into().ok()
351}
352
353/// The Rust chunk iterator over `dmux` at the C iterator's chunk with `fourcc`.
354fn chunk_iterator_to_rust<'d>(
355 c: &WebPChunkIterator,
356 dmux: &'d RsDemuxer<'d>,
357 fourcc: [u8; TAG_SIZE],
358) -> RsChunkIterator<'d> {
359 RsChunkIterator {
360 chunk_num: c.chunk_num,
361 num_chunks: c.num_chunks,
362 chunk: RsData::default(),
363 pad: c.pad,
364 dmux,
365 fourcc,
366 }
367}
368
369//------------------------------------------------------------------------------
370// Demux API
371
372// upstream: src/demux/demux.c WebPGetDemuxVersion
373/// Returns the version number of the demux library, packed in hexadecimal using
374/// 8 bits for each of major/minor/revision. E.g: v2.5.7 is 0x020507.
375#[unsafe(export_name = "WebPGetDemuxVersion")]
376#[must_use]
377pub extern "C" fn webp_get_demux_version() -> c_int {
378 dmx::webp_get_demux_version()
379}
380
381// upstream: src/demux/demux.c WebPDemuxInternal
382/// Internal, version-checked, entry point of `WebPDemux()` and
383/// `WebPDemuxPartial()`.
384///
385/// # Safety
386///
387/// `data` is null or a valid `WebPData` whose bytes stay readable and unchanged
388/// until `WebPDemuxDelete()`; `state` is null or writable.
389#[unsafe(export_name = "WebPDemuxInternal")]
390pub unsafe extern "C" fn webp_demux_internal(
391 data: *const WebPData,
392 allow_partial: c_int,
393 state: *mut WebPDemuxState,
394 version: c_int,
395) -> *mut WebPDemuxer {
396 // SAFETY: null or writable (caller's contract).
397 unsafe { set(state, WebPDemuxState::WEBP_DEMUX_PARSE_ERROR) };
398
399 if webp_abi_is_incompatible(version, WEBP_DEMUX_ABI_VERSION) {
400 return ptr::null_mut();
401 }
402 // SAFETY: null or a valid `WebPData` (caller's contract).
403 let Some(data) = (unsafe { data.as_ref() }) else {
404 return ptr::null_mut();
405 };
406 if data.bytes.is_null() || data.size == 0 {
407 return ptr::null_mut();
408 }
409
410 // SAFETY: the caller's bytes, valid and unchanged until WebPDemuxDelete
411 // (the header's contract), which frees the box.
412 let rs_data = unsafe { leak_data(data.bytes, data.size) };
413 // SAFETY: the box leaked above, freed only after the demuxer is dropped.
414 let rs_data_ref: &'static RsData<'static> = unsafe { &*rs_data };
415 let (dmux, rs_state) = dmx::webp_demux_internal(rs_data_ref, allow_partial != 0, version);
416 // SAFETY: null or writable (caller's contract).
417 unsafe { set(state, rs_state) };
418 let Some(dmux) = dmux else {
419 // SAFETY: the box leaked above; no demuxer borrows it.
420 drop(unsafe { Box::from_raw(rs_data) });
421 return ptr::null_mut();
422 };
423 let handle = Box::into_raw(Box::new(DemuxHandle {
424 dmux: ManuallyDrop::new(dmux),
425 data: rs_data,
426 }));
427 // The demuxer is the handle's first field (`repr(C)`).
428 handle.cast()
429}
430
431// upstream: src/demux/demux.c WebPDemuxDelete
432/// Frees memory associated with `dmux`.
433///
434/// # Safety
435///
436/// `dmux` is null or a demuxer that `WebPDemuxInternal()` returned and that is
437/// not used again (not one of `WebPAnimDecoderGetDemuxer()`).
438#[unsafe(export_name = "WebPDemuxDelete")]
439pub unsafe extern "C" fn webp_demux_delete(dmux: *mut WebPDemuxer) {
440 if dmux.is_null() {
441 return;
442 }
443 // SAFETY: a handle of WebPDemuxInternal, whose first field is the demuxer,
444 // which the caller gives up.
445 let mut handle = unsafe { Box::from_raw(dmux.cast::<DemuxHandle>()) };
446 // SAFETY: dropped once, before the box that it borrows.
447 unsafe { ManuallyDrop::drop(&mut handle.dmux) };
448 // SAFETY: the box leaked by WebPDemuxInternal, no longer borrowed.
449 drop(unsafe { Box::from_raw(handle.data) });
450}
451
452// upstream: src/demux/demux.c WebPDemuxGetI
453/// Gets the `feature` value from the `dmux`. Returns 0 for a null demuxer or an
454/// unknown feature.
455///
456/// # Safety
457///
458/// `dmux` is null or a live demuxer of this library.
459#[unsafe(export_name = "WebPDemuxGetI")]
460#[must_use]
461pub unsafe extern "C" fn webp_demux_get_i(
462 dmux: *const WebPDemuxer,
463 feature: WebPFormatFeature,
464) -> u32 {
465 // SAFETY: null or a live demuxer (caller's contract).
466 let Some(dmux) = (unsafe { demuxer(dmux) }) else {
467 return 0;
468 };
469 dmx::webp_demux_get_i(dmux, feature)
470}
471
472// upstream: src/demux/demux.c WebPDemuxGetFrame
473/// Retrieves frame `frame` from `dmux`; 0 gives the last frame. On failure the
474/// iterator is zeroed with `private_` set to `dmux`, as in C.
475///
476/// # Safety
477///
478/// `dmux` is null or a live demuxer of this library; `iter` is null or
479/// writable.
480#[unsafe(export_name = "WebPDemuxGetFrame")]
481#[must_use]
482pub unsafe extern "C" fn webp_demux_get_frame(
483 dmux: *const WebPDemuxer,
484 frame: c_int,
485 iter: *mut WebPIterator,
486) -> c_int {
487 if iter.is_null() {
488 return 0;
489 }
490 let mut c = zeroed_iterator(dmux);
491 let mut ok = 0;
492 // SAFETY: null or a live demuxer (caller's contract).
493 if let Some(rs_dmux) = unsafe { demuxer(dmux) }
494 && let Some(it) = dmx::webp_demux_get_frame(rs_dmux, frame)
495 {
496 iterator_to_c(&it, &mut c);
497 ok = 1;
498 }
499 // SAFETY: a writable iterator (checked non-null); it may be uninitialized,
500 // so it is written whole.
501 unsafe { iter.write(c) };
502 ok
503}
504
505/// The common part of `WebPDemuxNextFrame()` and `WebPDemuxPrevFrame()`.
506///
507/// # Safety
508///
509/// `iter` is null or an initialized iterator whose `private_` is null or a live
510/// demuxer of this library.
511unsafe fn step_frame(iter: *mut WebPIterator, step: fn(&mut RsIterator<'_>) -> bool) -> c_int {
512 // SAFETY: null or a valid iterator (caller's contract).
513 let Some(c) = (unsafe { iter.as_mut() }) else {
514 return 0;
515 };
516 // SAFETY: null or a live demuxer (caller's contract).
517 let Some(dmux) = (unsafe { demuxer(c.private_.cast_const().cast()) }) else {
518 return 0; // SetFrame: dmux == NULL
519 };
520 let mut it = iterator_to_rust(c, dmux);
521 if !step(&mut it) {
522 return 0;
523 }
524 iterator_to_c(&it, c);
525 1
526}
527
528// upstream: src/demux/demux.c WebPDemuxNextFrame
529/// Sets `iter` to the next frame. Returns false if there is none. On a zeroed
530/// iterator whose `private_` is a demuxer it gives frame 1, as in C.
531///
532/// # Safety
533///
534/// `iter` is null or an initialized iterator whose `private_` is null or a live
535/// demuxer of this library.
536#[unsafe(export_name = "WebPDemuxNextFrame")]
537#[must_use]
538pub unsafe extern "C" fn webp_demux_next_frame(iter: *mut WebPIterator) -> c_int {
539 // C: SetFrame(iter->frame_num + 1, iter). The `int` sum overflows for
540 // INT_MAX, which is undefined; wrapped, it is negative and fails.
541 // SAFETY: null or a valid iterator (caller's contract).
542 if let Some(c) = unsafe { iter.as_ref() }
543 && c.frame_num == c_int::MAX
544 {
545 return 0;
546 }
547 // SAFETY: the caller's contract, passed on.
548 unsafe { step_frame(iter, dmx::webp_demux_next_frame) }
549}
550
551// upstream: src/demux/demux.c WebPDemuxPrevFrame
552/// Sets `iter` to the previous frame. Returns false if there is none.
553///
554/// # Safety
555///
556/// `iter` is null or an initialized iterator whose `private_` is null or a live
557/// demuxer of this library.
558#[unsafe(export_name = "WebPDemuxPrevFrame")]
559#[must_use]
560pub unsafe extern "C" fn webp_demux_prev_frame(iter: *mut WebPIterator) -> c_int {
561 // SAFETY: null or a valid iterator (caller's contract).
562 let Some(c) = (unsafe { iter.as_ref() }) else {
563 return 0;
564 };
565 if c.frame_num <= 1 {
566 return 0;
567 }
568 // SAFETY: the caller's contract, passed on.
569 unsafe { step_frame(iter, dmx::webp_demux_prev_frame) }
570}
571
572// upstream: src/demux/demux.c WebPDemuxReleaseIterator
573/// Releases any memory associated with `iter`. C frees nothing.
574#[unsafe(export_name = "WebPDemuxReleaseIterator")]
575pub extern "C" fn webp_demux_release_iterator(iter: *mut WebPIterator) {
576 let _ = iter;
577}
578
579// upstream: src/demux/demux.c WebPDemuxGetChunk
580/// Retrieves the `chunk_number` instance of the chunk with id `fourcc` from
581/// `dmux`; 0 gives the last one. On failure the iterator is zeroed with
582/// `private_` set to `dmux`, as in C.
583///
584/// # Safety
585///
586/// `dmux` is null or a live demuxer of this library; `fourcc` is null or points
587/// to four readable bytes; `iter` is null or writable.
588#[unsafe(export_name = "WebPDemuxGetChunk")]
589#[must_use]
590pub unsafe extern "C" fn webp_demux_get_chunk(
591 dmux: *const WebPDemuxer,
592 fourcc: *const c_char,
593 chunk_number: c_int,
594 iter: *mut WebPChunkIterator,
595) -> c_int {
596 if iter.is_null() {
597 return 0;
598 }
599 let mut c = zeroed_chunk_iterator(dmux);
600 let mut ok = 0;
601 // SAFETY: null or a live demuxer (caller's contract).
602 if let Some(rs_dmux) = unsafe { demuxer(dmux) }
603 && !fourcc.is_null()
604 {
605 // SAFETY: four readable bytes (caller's contract), without alignment.
606 let tag = unsafe { fourcc.cast::<[u8; TAG_SIZE]>().read() };
607 if let Some(it) = dmx::webp_demux_get_chunk(rs_dmux, tag, chunk_number) {
608 chunk_iterator_to_c(&it, &mut c);
609 ok = 1;
610 }
611 }
612 // SAFETY: a writable iterator (checked non-null); it may be uninitialized,
613 // so it is written whole.
614 unsafe { iter.write(c) };
615 ok
616}
617
618/// The common part of `WebPDemuxNextChunk()` and `WebPDemuxPrevChunk()`.
619///
620/// # Safety
621///
622/// `iter` is an initialized iterator whose `private_` is null or a live demuxer
623/// of this library.
624unsafe fn step_chunk(
625 c: &mut WebPChunkIterator,
626 step: fn(&mut RsChunkIterator<'_>) -> bool,
627) -> c_int {
628 // SAFETY: null or a live demuxer (caller's contract).
629 let Some(dmux) = (unsafe { demuxer(c.private_.cast_const().cast()) }) else {
630 return 0; // SetChunk: dmux == NULL
631 };
632 let Some(fourcc) = chunk_tag(c, dmux) else {
633 return 0;
634 };
635 let mut it = chunk_iterator_to_rust(c, dmux, fourcc);
636 if !step(&mut it) {
637 return 0;
638 }
639 chunk_iterator_to_c(&it, c);
640 1
641}
642
643// upstream: src/demux/demux.c WebPDemuxNextChunk
644/// Sets `iter` to the next chunk with the same id. Returns false if there is
645/// none.
646///
647/// # Safety
648///
649/// `iter` is null or an iterator that `WebPDemuxGetChunk()` filled, whose
650/// `private_` is null or a live demuxer of this library.
651#[unsafe(export_name = "WebPDemuxNextChunk")]
652#[must_use]
653pub unsafe extern "C" fn webp_demux_next_chunk(iter: *mut WebPChunkIterator) -> c_int {
654 // SAFETY: null or a valid iterator (caller's contract).
655 let Some(c) = (unsafe { iter.as_mut() }) else {
656 return 0;
657 };
658 // C: SetChunk(fourcc, iter->chunk_num + 1, iter). The `int` sum overflows
659 // for INT_MAX, which is undefined; wrapped, it is negative and fails.
660 if c.chunk_num == c_int::MAX {
661 return 0;
662 }
663 // SAFETY: the caller's contract, passed on.
664 unsafe { step_chunk(c, dmx::webp_demux_next_chunk) }
665}
666
667// upstream: src/demux/demux.c WebPDemuxPrevChunk
668/// Sets `iter` to the previous chunk with the same id. Returns false if there is
669/// none.
670///
671/// # Safety
672///
673/// `iter` is null or an iterator that `WebPDemuxGetChunk()` filled, whose
674/// `private_` is null or a live demuxer of this library.
675#[unsafe(export_name = "WebPDemuxPrevChunk")]
676#[must_use]
677pub unsafe extern "C" fn webp_demux_prev_chunk(iter: *mut WebPChunkIterator) -> c_int {
678 // SAFETY: null or a valid iterator (caller's contract).
679 let Some(c) = (unsafe { iter.as_mut() }) else {
680 return 0;
681 };
682 if c.chunk_num <= 1 {
683 return 0;
684 }
685 // SAFETY: the caller's contract, passed on.
686 unsafe { step_chunk(c, dmx::webp_demux_prev_chunk) }
687}
688
689// upstream: src/demux/demux.c WebPDemuxReleaseChunkIterator
690/// Releases any memory associated with `iter`. C frees nothing.
691#[unsafe(export_name = "WebPDemuxReleaseChunkIterator")]
692pub extern "C" fn webp_demux_release_chunk_iterator(iter: *mut WebPChunkIterator) {
693 let _ = iter;
694}
695
696//------------------------------------------------------------------------------
697// WebPAnimDecoder API
698
699// upstream: src/demux/anim_decode.c WebPAnimDecoderOptionsInitInternal
700/// Internal, version-checked, entry point of `WebPAnimDecoderOptionsInit()`.
701/// Writes `color_mode` and `use_threads` and leaves the padding, as C does.
702///
703/// # Safety
704///
705/// `dec_options` is null or writable; its padding may be uninitialized.
706#[unsafe(export_name = "WebPAnimDecoderOptionsInitInternal")]
707#[must_use]
708pub unsafe extern "C" fn webp_anim_decoder_options_init_internal(
709 dec_options: *mut WebPAnimDecoderOptions,
710 abi_version: c_int,
711) -> c_int {
712 if dec_options.is_null() {
713 return 0;
714 }
715 let mut options = WebPAnimDecoderOptions::default();
716 if !anim::webp_anim_decoder_options_init_internal(&mut options, abi_version) {
717 return 0;
718 }
719 // SAFETY: the address of a field of the caller's structure (checked
720 // non-null); nothing is read.
721 let color_mode = unsafe { &raw mut (*dec_options).color_mode };
722 // SAFETY: as above.
723 let use_threads = unsafe { &raw mut (*dec_options).use_threads };
724 // SAFETY: a writable field; only the two fields that C writes are written,
725 // so uninitialized padding stays as it is.
726 unsafe { color_mode.write(options.color_mode) };
727 // SAFETY: as above.
728 unsafe { use_threads.write(options.use_threads) };
729 1
730}
731
732// upstream: src/demux/anim_decode.c WebPAnimDecoderNewInternal
733/// Internal, version-checked, entry point of `WebPAnimDecoderNew()`.
734///
735/// # Safety
736///
737/// `webp_data` is null or a valid `WebPData` whose bytes stay readable and
738/// unchanged until `WebPAnimDecoderDelete()`; `dec_options` is null or
739/// readable (its padding is not read).
740#[unsafe(export_name = "WebPAnimDecoderNewInternal")]
741#[must_use]
742pub unsafe extern "C" fn webp_anim_decoder_new_internal(
743 webp_data: *const WebPData,
744 dec_options: *const WebPAnimDecoderOptions,
745 abi_version: c_int,
746) -> *mut WebPAnimDecoder {
747 // SAFETY: null or a valid `WebPData` (caller's contract).
748 let Some(data) = (unsafe { webp_data.as_ref() }) else {
749 return ptr::null_mut();
750 };
751 if webp_abi_is_incompatible(abi_version, WEBP_DEMUX_ABI_VERSION) {
752 return ptr::null_mut();
753 }
754 // C: WebPGetFeatures(NULL, ...) fails, so does a NULL bitstream here.
755 if data.bytes.is_null() {
756 return ptr::null_mut();
757 }
758 // C copies the options (`options = *dec_options`); only the color mode and
759 // the threads flag are read, so the padding is not copied.
760 let options = if dec_options.is_null() {
761 None
762 } else {
763 // SAFETY: the address of a field of the caller's structure (checked
764 // non-null); nothing is read.
765 let color_mode = unsafe { &raw const (*dec_options).color_mode };
766 // SAFETY: as above.
767 let use_threads = unsafe { &raw const (*dec_options).use_threads };
768 // SAFETY: an initialized field of a readable structure (caller's
769 // contract); the padding, which may be uninitialized, is not read.
770 let color_mode = unsafe { color_mode.read() };
771 // SAFETY: as above.
772 let use_threads = unsafe { use_threads.read() };
773 Some(WebPAnimDecoderOptions {
774 color_mode,
775 use_threads,
776 padding: [0; 7],
777 })
778 };
779
780 // SAFETY: the caller's bytes, valid and unchanged until
781 // WebPAnimDecoderDelete (the header's contract), which frees the box.
782 let rs_data = unsafe { leak_data(data.bytes, data.size) };
783 // SAFETY: the box leaked above, freed only after the decoder is dropped.
784 let rs_data_ref: &'static RsData<'static> = unsafe { &*rs_data };
785 let Some(dec) =
786 anim::webp_anim_decoder_new_internal(rs_data_ref, options.as_ref(), abi_version)
787 else {
788 // SAFETY: the box leaked above; no decoder borrows it.
789 drop(unsafe { Box::from_raw(rs_data) });
790 return ptr::null_mut();
791 };
792 Box::into_raw(Box::new(WebPAnimDecoder {
793 dec: ManuallyDrop::new(dec),
794 data: rs_data,
795 }))
796}
797
798// upstream: src/demux/anim_decode.c WebPAnimDecoderGetInfo
799/// Gets global information about the animation. Returns false for null
800/// arguments.
801///
802/// # Safety
803///
804/// `dec` is null or a live decoder of this library; `info` is null or writable.
805#[unsafe(export_name = "WebPAnimDecoderGetInfo")]
806#[must_use]
807pub unsafe extern "C" fn webp_anim_decoder_get_info(
808 dec: *const WebPAnimDecoder,
809 info: *mut WebPAnimInfo,
810) -> c_int {
811 // SAFETY: null or a live decoder (caller's contract).
812 let Some(dec) = (unsafe { dec.as_ref() }) else {
813 return 0;
814 };
815 if info.is_null() {
816 return 0;
817 }
818 // SAFETY: writable (checked non-null); written whole, as `*info = dec->info`.
819 unsafe { info.write(anim::webp_anim_decoder_get_info(&dec.dec)) };
820 1
821}
822
823// upstream: src/demux/anim_decode.c WebPAnimDecoderGetNext
824/// Fetches the next frame: the canvas in `*buf` and its timestamp in
825/// `*timestamp`. Returns false for null arguments, a parsing or decoding error,
826/// or when there are no more frames; the outputs are then not written.
827///
828/// # Safety
829///
830/// `dec` is null or a live decoder of this library; `buf` and `timestamp` are
831/// null or writable.
832#[unsafe(export_name = "WebPAnimDecoderGetNext")]
833#[must_use]
834pub unsafe extern "C" fn webp_anim_decoder_get_next(
835 dec: *mut WebPAnimDecoder,
836 buf: *mut *mut u8,
837 timestamp: *mut c_int,
838) -> c_int {
839 if dec.is_null() || buf.is_null() || timestamp.is_null() {
840 return 0;
841 }
842 // SAFETY: a live decoder (checked non-null; caller's contract). The demuxer
843 // pointer that WebPAnimDecoderGetDemuxer handed out stays valid: the decoder
844 // never writes its demuxer.
845 let decoder = unsafe { &mut *dec };
846 let Some((_, ts)) = anim::webp_anim_decoder_get_next(&mut decoder.dec) else {
847 return 0;
848 };
849 let canvas = decoder.dec.canvas_mut().as_mut_ptr();
850 // SAFETY: writable (checked non-null). The canvas stays at this address
851 // until the decoder is deleted; C may read it until the next call.
852 unsafe { buf.write(canvas) };
853 // SAFETY: writable (checked non-null).
854 unsafe { timestamp.write(ts) };
855 1
856}
857
858// upstream: src/demux/anim_decode.c WebPAnimDecoderHasMoreFrames
859/// Returns true if `dec` is not null and some frames are yet to be decoded.
860///
861/// # Safety
862///
863/// `dec` is null or a live decoder of this library.
864#[unsafe(export_name = "WebPAnimDecoderHasMoreFrames")]
865#[must_use]
866pub unsafe extern "C" fn webp_anim_decoder_has_more_frames(dec: *const WebPAnimDecoder) -> c_int {
867 // SAFETY: null or a live decoder (caller's contract).
868 let Some(dec) = (unsafe { dec.as_ref() }) else {
869 return 0;
870 };
871 c_int::from(anim::webp_anim_decoder_has_more_frames(&dec.dec))
872}
873
874// upstream: src/demux/anim_decode.c WebPAnimDecoderReset
875/// Resets `dec`, so that the next `WebPAnimDecoderGetNext()` restarts from the
876/// first frame. Does nothing for null.
877///
878/// # Safety
879///
880/// `dec` is null or a live decoder of this library.
881#[unsafe(export_name = "WebPAnimDecoderReset")]
882pub unsafe extern "C" fn webp_anim_decoder_reset(dec: *mut WebPAnimDecoder) {
883 // SAFETY: null or a live decoder (caller's contract).
884 if let Some(dec) = unsafe { dec.as_mut() } {
885 anim::webp_anim_decoder_reset(&mut dec.dec);
886 }
887}
888
889// upstream: src/demux/anim_decode.c WebPAnimDecoderGetDemuxer
890/// Grabs the internal demuxer object, owned by `dec` and valid until
891/// `WebPAnimDecoderDelete()`; null for a null decoder.
892///
893/// # Safety
894///
895/// `dec` is null or a live decoder of this library.
896#[unsafe(export_name = "WebPAnimDecoderGetDemuxer")]
897#[must_use]
898pub unsafe extern "C" fn webp_anim_decoder_get_demuxer(
899 dec: *const WebPAnimDecoder,
900) -> *const WebPDemuxer {
901 // SAFETY: null or a live decoder (caller's contract).
902 let Some(dec) = (unsafe { dec.as_ref() }) else {
903 return ptr::null();
904 };
905 let dmux: &RsDemuxer<'static> = anim::webp_anim_decoder_get_demuxer(&dec.dec);
906 dmux
907}
908
909// upstream: src/demux/anim_decode.c WebPAnimDecoderDelete
910/// Deletes the decoder object.
911///
912/// # Safety
913///
914/// `dec` is null or a decoder of this library that is not used again, and
915/// neither is its demuxer.
916#[unsafe(export_name = "WebPAnimDecoderDelete")]
917pub unsafe extern "C" fn webp_anim_decoder_delete(dec: *mut WebPAnimDecoder) {
918 if dec.is_null() {
919 return;
920 }
921 // SAFETY: a decoder of this library, which the caller gives up.
922 let mut decoder = unsafe { Box::from_raw(dec) };
923 // SAFETY: dropped once, before the box that it borrows.
924 unsafe { ManuallyDrop::drop(&mut decoder.dec) };
925 // SAFETY: the box leaked by WebPAnimDecoderNewInternal, no longer borrowed.
926 drop(unsafe { Box::from_raw(decoder.data) });
927}