avif_parse/
c_api.rs

1use crate::AvifData as AvifDataRust;
2
3/// Result of parsing an AVIF file. Contains AV1-compressed data.
4#[allow(bad_style)]
5#[repr(C)]
6pub struct avif_data_t {
7    /// AV1 data for color channels
8    pub primary_data: *const u8,
9    pub primary_size: usize,
10    /// AV1 data for alpha channel (may be NULL if the image is fully opaque)
11    pub alpha_data: *const u8,
12    pub alpha_size: usize,
13    /// 0 = normal, uncorrelated alpha channel
14    /// 1 = premultiplied alpha. You must divide RGB values by alpha.
15    ///
16    /// ```c
17    /// if (a != 0) {r = r * 255 / a}
18    /// ```
19    pub premultiplied_alpha: u8,
20    rusty_handle: *mut AvifDataRust,
21}
22
23/// Parse AVIF image file and return results. Returns `NULL` if the file can't be parsed.
24///
25/// Call [`avif_data_free`] on the result when done.
26#[no_mangle]
27pub unsafe extern "C" fn avif_parse(bytes: *const u8, bytes_len: usize) -> *const avif_data_t {
28    if bytes.is_null() || bytes_len == 0 {
29        return std::ptr::null();
30    }
31    let mut data = std::slice::from_raw_parts(bytes, bytes_len);
32    match crate::read_avif(&mut data) {
33        Ok(data) => Box::into_raw(Box::new(avif_data_t {
34            primary_data: data.primary_item.as_ptr(),
35            primary_size: data.primary_item.len(),
36            alpha_data: data
37                .alpha_item
38                .as_ref()
39                .map_or(std::ptr::null(), |a| a.as_ptr()),
40            alpha_size: data.alpha_item.as_ref().map_or(0, |a| a.len()),
41            premultiplied_alpha: u8::from(data.premultiplied_alpha),
42            rusty_handle: Box::into_raw(Box::new(data)),
43        })),
44        Err(_) => std::ptr::null(),
45    }
46}
47
48/// Free all data related to [`avif_data_t`]
49#[no_mangle]
50pub unsafe extern "C" fn avif_data_free(data: *const avif_data_t) {
51    if data.is_null() {
52        return;
53    }
54    let _ = Box::from_raw((*data).rusty_handle);
55    let _ = Box::from_raw(data.cast_mut());
56}