libheif-rs 2.2.0

Safe wrapper around the libheif-sys crate for parsing heif/heic files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use std::collections::HashMap;
use std::ffi::CString;
use std::fmt::{Debug, Formatter};
use std::marker::PhantomData;
use std::ptr;
use std::sync::Mutex;

use libheif_sys as lh;

use crate::utils::cstr_to_str;
use crate::{
    ChromaDownsamplingAlgorithm, ChromaUpsamplingAlgorithm, ColorConversionOptions, HeifError,
    HeifErrorCode, HeifErrorSubCode, ImageOrientation, Result,
};

static ENCODER_MUTEX: Mutex<()> = Mutex::new(());

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, enumn::N)]
#[non_exhaustive]
#[repr(C)]
pub enum CompressionFormat {
    /// Rust equivalent of [lh::heif_compression_format_heif_compression_undefined]
    Undefined = lh::heif_compression_format_heif_compression_undefined as _,
    /// Rust equivalent of [lh::heif_compression_format_heif_compression_HEVC]
    Hevc = lh::heif_compression_format_heif_compression_HEVC as _,
    /// Rust equivalent of [lh::heif_compression_format_heif_compression_AVC]
    Avc = lh::heif_compression_format_heif_compression_AVC as _,
    /// Rust equivalent of [lh::heif_compression_format_heif_compression_JPEG]
    Jpeg = lh::heif_compression_format_heif_compression_JPEG as _,
    /// Rust equivalent of [lh::heif_compression_format_heif_compression_AV1]    
    Av1 = lh::heif_compression_format_heif_compression_AV1 as _,
    /// Rust equivalent of [lh::heif_compression_format_heif_compression_VVC]
    Vvc = lh::heif_compression_format_heif_compression_VVC as _,
    /// Rust equivalent of [lh::heif_compression_format_heif_compression_EVC]
    Evc = lh::heif_compression_format_heif_compression_EVC as _,
    /// Rust equivalent of [lh::heif_compression_format_heif_compression_JPEG2000]
    Jpeg2000 = lh::heif_compression_format_heif_compression_JPEG2000 as _,
    /// Rust equivalent of [lh::heif_compression_format_heif_compression_uncompressed]
    Uncompressed = lh::heif_compression_format_heif_compression_uncompressed as _,
    /// Rust equivalent of [lh::heif_compression_format_heif_compression_mask]
    Mask = lh::heif_compression_format_heif_compression_mask as _,
    /// Rust equivalent of [lh::heif_compression_format_heif_compression_HTJ2K]
    #[cfg(feature = "v1_18")]
    HtJ2k = lh::heif_compression_format_heif_compression_HTJ2K as _,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, enumn::N)]
#[repr(C)]
pub enum EncoderParameterType {
    Int = lh::heif_encoder_parameter_type_heif_encoder_parameter_type_integer as _,
    Bool = lh::heif_encoder_parameter_type_heif_encoder_parameter_type_boolean as _,
    String = lh::heif_encoder_parameter_type_heif_encoder_parameter_type_string as _,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum EncoderParameterValue {
    Int(i32),
    Bool(bool),
    String(String),
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum EncoderQuality {
    LossLess,
    /// Value inside variant is a 'quality' factor (0-100).
    /// How this is mapped to actual encoding parameters is encoder dependent.
    Lossy(u8),
}

pub type EncoderParametersTypes = HashMap<String, EncoderParameterType>;

pub struct Encoder<'a> {
    pub(crate) inner: *mut lh::heif_encoder,
    pub(crate) parameters_types: EncoderParametersTypes,
    phantom: PhantomData<&'a mut lh::heif_encoder>,
}

impl<'a> Encoder<'a> {
    pub(crate) fn new(c_encoder: &'a mut lh::heif_encoder) -> Result<Self> {
        let parameters_types = parameters_types(c_encoder)?;
        Ok(Self {
            inner: c_encoder,
            parameters_types,
            phantom: PhantomData::default(),
        })
    }
}

impl<'a> Drop for Encoder<'a> {
    fn drop(&mut self) {
        unsafe { lh::heif_encoder_release(self.inner) };
    }
}

impl<'a> Encoder<'a> {
    /// Name of encoder.
    pub fn name(&self) -> String {
        // Name of encoder in `libheif` is mutable static array of chars.
        // So we must use mutex to get access this array.
        let _lock = ENCODER_MUTEX.lock();
        let res = unsafe { lh::heif_encoder_get_name(self.inner) };
        cstr_to_str(res).unwrap_or("").to_owned()
    }

    pub fn set_quality(&mut self, quality: EncoderQuality) -> Result<()> {
        let err = match quality {
            EncoderQuality::LossLess => unsafe { lh::heif_encoder_set_lossless(self.inner, 1) },
            EncoderQuality::Lossy(value) => unsafe {
                let middle_err = lh::heif_encoder_set_lossless(self.inner, 0);
                HeifError::from_heif_error(middle_err)?;
                lh::heif_encoder_set_lossy_quality(self.inner, i32::from(value))
            },
        };
        HeifError::from_heif_error(err)
    }

    fn parameter_value(
        &self,
        name: &str,
        parameter_type: EncoderParameterType,
    ) -> Result<EncoderParameterValue> {
        let c_param_name = CString::new(name).unwrap();
        let param_value = match parameter_type {
            EncoderParameterType::Int => {
                let mut value = 0;
                let err = unsafe {
                    lh::heif_encoder_get_parameter_integer(
                        self.inner,
                        c_param_name.as_ptr(),
                        &mut value as _,
                    )
                };
                HeifError::from_heif_error(err)?;
                EncoderParameterValue::Int(value)
            }
            EncoderParameterType::Bool => {
                let mut value = 0;
                let err = unsafe {
                    lh::heif_encoder_get_parameter_boolean(
                        self.inner,
                        c_param_name.as_ptr(),
                        &mut value as _,
                    )
                };
                HeifError::from_heif_error(err)?;
                EncoderParameterValue::Bool(value > 0)
            }
            EncoderParameterType::String => {
                let value: Vec<u8> = vec![0; 51];
                let err = unsafe {
                    lh::heif_encoder_get_parameter_string(
                        self.inner,
                        c_param_name.as_ptr(),
                        value.as_ptr() as _,
                        50,
                    )
                };
                HeifError::from_heif_error(err)?;
                EncoderParameterValue::String(
                    cstr_to_str(value.as_ptr() as _).unwrap_or("").to_string(),
                )
            }
        };

        Ok(param_value)
    }

    pub fn parameters_names(&self) -> Vec<String> {
        self.parameters_types.keys().cloned().collect()
    }

    /// Get value of encoder's parameter.
    pub fn parameter(&self, name: &str) -> Result<Option<EncoderParameterValue>> {
        match self.parameters_types.get(name) {
            Some(param_type) => {
                let value = self.parameter_value(name, *param_type)?;
                Ok(Some(value))
            }
            None => Ok(None),
        }
    }

    /// Set value of encoder's parameter.
    pub fn set_parameter_value(&self, name: &str, value: EncoderParameterValue) -> Result<()> {
        let c_param_name = CString::new(name).unwrap();
        let err = match value {
            EncoderParameterValue::Bool(v) => unsafe {
                lh::heif_encoder_set_parameter_boolean(self.inner, c_param_name.as_ptr(), v.into())
            },
            EncoderParameterValue::Int(v) => unsafe {
                lh::heif_encoder_set_parameter_integer(self.inner, c_param_name.as_ptr(), v)
            },
            EncoderParameterValue::String(v) => unsafe {
                let c_param_value = CString::new(v).unwrap();
                lh::heif_encoder_set_parameter_string(
                    self.inner,
                    c_param_name.as_ptr(),
                    c_param_value.as_ptr(),
                )
            },
        };
        HeifError::from_heif_error(err)?;
        Ok(())
    }
}

fn parameters_types(c_encoder: &mut lh::heif_encoder) -> Result<EncoderParametersTypes> {
    let mut res = EncoderParametersTypes::new();
    unsafe {
        let mut param_pointers = lh::heif_encoder_list_parameters(c_encoder);
        if !param_pointers.is_null() {
            while let Some(raw_param) = (*param_pointers).as_ref() {
                let c_param_type = lh::heif_encoder_parameter_get_type(raw_param);
                let param_type = match EncoderParameterType::n(c_param_type) {
                    Some(res) => res,
                    None => {
                        return Err(HeifError {
                            code: HeifErrorCode::EncoderPluginError,
                            sub_code: HeifErrorSubCode::UnsupportedParameter,
                            message: format!("{} is unknown type of parameter", c_param_type),
                        });
                    }
                };
                let c_param_name = lh::heif_encoder_parameter_get_name(raw_param);
                let name = cstr_to_str(c_param_name).unwrap_or("").to_string();
                res.insert(name, param_type);
                param_pointers = param_pointers.offset(1);
            }
        }
    }
    Ok(res)
}

#[derive(Debug)]
pub struct EncodingOptions {
    inner: ptr::NonNull<lh::heif_encoding_options>,
}

impl EncodingOptions {
    pub fn new() -> Result<Self> {
        let inner_ptr = unsafe { lh::heif_encoding_options_alloc() };
        match ptr::NonNull::new(inner_ptr) {
            Some(inner) => Ok(Self { inner }),
            None => Err(HeifError {
                code: HeifErrorCode::MemoryAllocationError,
                sub_code: HeifErrorSubCode::Unspecified,
                message: Default::default(),
            }),
        }
    }
}

impl Default for EncodingOptions {
    fn default() -> Self {
        Self::new().expect("heif_encoding_options_alloc() returns a null pointer")
    }
}

impl Drop for EncodingOptions {
    fn drop(&mut self) {
        unsafe {
            lh::heif_encoding_options_free(self.inner.as_ptr());
        }
    }
}

impl EncodingOptions {
    #[inline(always)]
    fn inner_ref(&self) -> &lh::heif_encoding_options {
        unsafe { self.inner.as_ref() }
    }

    #[inline(always)]
    fn inner_mut(&mut self) -> &mut lh::heif_encoding_options {
        unsafe { self.inner.as_mut() }
    }

    #[inline]
    pub fn version(&self) -> u8 {
        self.inner_ref().version
    }

    #[inline]
    pub fn save_alpha_channel(&self) -> bool {
        self.inner_ref().save_alpha_channel != 0
    }

    #[inline]
    pub fn set_save_alpha_channel(&mut self, enable: bool) {
        self.inner_mut().save_alpha_channel = if enable { 1 } else { 0 };
    }

    #[inline]
    pub fn mac_os_compatibility_workaround(&self) -> bool {
        self.inner_ref().macOS_compatibility_workaround != 0
    }

    #[inline]
    pub fn set_mac_os_compatibility_workaround(&mut self, enable: bool) {
        self.inner_mut().macOS_compatibility_workaround = if enable { 1 } else { 0 };
    }

    #[inline]
    pub fn save_two_colr_boxes_when_icc_and_nclx_available(&self) -> bool {
        self.inner_ref()
            .save_two_colr_boxes_when_ICC_and_nclx_available
            != 0
    }

    #[inline]
    pub fn set_save_two_colr_boxes_when_icc_and_nclx_available(&mut self, enable: bool) {
        self.inner_mut()
            .save_two_colr_boxes_when_ICC_and_nclx_available = if enable { 1 } else { 0 };
    }

    #[inline]
    pub fn mac_os_compatibility_workaround_no_nclx_profile(&self) -> bool {
        self.inner_ref()
            .macOS_compatibility_workaround_no_nclx_profile
            != 0
    }

    #[inline]
    pub fn set_mac_os_compatibility_workaround_no_nclx_profile(&mut self, enable: bool) {
        self.inner_mut()
            .macOS_compatibility_workaround_no_nclx_profile = if enable { 1 } else { 0 };
    }

    #[inline]
    pub fn image_orientation(&self) -> ImageOrientation {
        let orientation = self.inner_ref().image_orientation;
        ImageOrientation::n(orientation).unwrap_or(ImageOrientation::Normal)
    }

    #[inline]
    pub fn set_image_orientation(&mut self, orientation: ImageOrientation) {
        self.inner_mut().image_orientation = orientation as _;
    }

    pub fn color_conversion_options(&self) -> ColorConversionOptions {
        let lh_options = self.inner_ref().color_conversion_options;
        ColorConversionOptions {
            preferred_chroma_downsampling_algorithm: ChromaDownsamplingAlgorithm::n(
                lh_options.preferred_chroma_downsampling_algorithm,
            )
            .unwrap_or(ChromaDownsamplingAlgorithm::Average),
            preferred_chroma_upsampling_algorithm: ChromaUpsamplingAlgorithm::n(
                lh_options.preferred_chroma_upsampling_algorithm,
            )
            .unwrap_or(ChromaUpsamplingAlgorithm::Bilinear),
            only_use_preferred_chroma_algorithm: lh_options.only_use_preferred_chroma_algorithm
                != 0,
        }
    }

    pub fn set_color_conversion_options(&mut self, options: ColorConversionOptions) {
        let lh_options = &mut self.inner_mut().color_conversion_options;
        lh_options.preferred_chroma_downsampling_algorithm =
            options.preferred_chroma_downsampling_algorithm as _;
        lh_options.preferred_chroma_upsampling_algorithm =
            options.preferred_chroma_upsampling_algorithm as _;
        lh_options.only_use_preferred_chroma_algorithm =
            options.only_use_preferred_chroma_algorithm as _;
    }
}

/// This function makes sure the encoding options
/// won't be freed too early.
pub(crate) fn get_encoding_options_ptr(
    options: &Option<EncodingOptions>,
) -> *mut lh::heif_encoding_options {
    options
        .as_ref()
        .map(|o| o.inner.as_ptr())
        .unwrap_or_else(ptr::null_mut)
}

#[derive(Copy, Clone)]
pub struct EncoderDescriptor<'a> {
    pub(crate) inner: &'a lh::heif_encoder_descriptor,
}

impl<'a> EncoderDescriptor<'a> {
    pub(crate) fn new(inner: &'a lh::heif_encoder_descriptor) -> Self {
        Self { inner }
    }

    /// A short, symbolic name for identifying the encoder.
    /// This name should stay constant over different encoder versions.
    pub fn id(&self) -> &str {
        let name = unsafe { lh::heif_encoder_descriptor_get_id_name(self.inner) };
        cstr_to_str(name).unwrap_or_default()
    }

    /// A long, descriptive name of the encoder
    /// (including version information).
    pub fn name(&self) -> String {
        // Name of encoder in `libheif` is mutable static array of chars.
        // So we must use mutex to get access this array.
        let _lock = ENCODER_MUTEX.lock();
        let name = unsafe { lh::heif_encoder_descriptor_get_name(self.inner) };
        cstr_to_str(name).unwrap_or_default().to_owned()
    }

    pub fn compression_format(&self) -> CompressionFormat {
        let c_format = unsafe { lh::heif_encoder_descriptor_get_compression_format(self.inner) };
        match CompressionFormat::n(c_format) {
            Some(res) => res,
            None => CompressionFormat::Undefined,
        }
    }

    pub fn supports_lossy_compression(&self) -> bool {
        unsafe { lh::heif_encoder_descriptor_supports_lossy_compression(self.inner) != 0 }
    }

    pub fn supports_lossless_compression(&self) -> bool {
        unsafe { lh::heif_encoder_descriptor_supports_lossless_compression(self.inner) != 0 }
    }
}

impl<'a> Debug for EncoderDescriptor<'a> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EncoderDescriptor")
            .field("id", &self.id())
            .field("name", &self.name())
            .finish()
    }
}