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
use std::collections::HashMap;
use std::ffi::CString;
use std::fmt::{Debug, Formatter};
use std::marker::PhantomData;
use std::sync::Mutex;
use libheif_sys as lh;
use crate::utils::cstr_to_str;
use crate::{HeifError, HeifErrorCode, HeifErrorSubCode, ImageOrientation, Result};
static ENCODER_MUTEX: Mutex<()> = Mutex::new(());
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, enumn::N)]
#[repr(C)]
pub enum CompressionFormat {
Undefined = lh::heif_compression_format_heif_compression_undefined as _,
Hevc = lh::heif_compression_format_heif_compression_HEVC as _,
Avc = lh::heif_compression_format_heif_compression_AVC as _,
Jpeg = lh::heif_compression_format_heif_compression_JPEG as _,
Av1 = lh::heif_compression_format_heif_compression_AV1 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,
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> {
pub fn name(&self) -> String {
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()
}
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),
}
}
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 {
pub(crate) inner: *mut lh::heif_encoding_options,
}
impl EncodingOptions {
pub fn new() -> Result<Self> {
let inner = unsafe { lh::heif_encoding_options_alloc() };
if inner.is_null() {
return Err(HeifError {
code: HeifErrorCode::MemoryAllocationError,
sub_code: HeifErrorSubCode::Unspecified,
message: Default::default(),
});
}
Ok(Self { inner })
}
}
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);
}
}
}
impl EncodingOptions {
#[inline]
pub fn version(&self) -> u8 {
unsafe { (*self.inner).version }
}
#[inline]
pub fn save_alpha_channel(&self) -> bool {
unsafe { (*self.inner).save_alpha_channel != 0 }
}
#[inline]
pub fn set_save_alpha_channel(&mut self, enable: bool) {
unsafe { (*self.inner).save_alpha_channel = if enable { 1 } else { 0 } }
}
#[inline]
pub fn mac_os_compatibility_workaround(&self) -> bool {
unsafe { (*self.inner).macOS_compatibility_workaround != 0 }
}
#[inline]
pub fn set_mac_os_compatibility_workaround(&mut self, enable: bool) {
unsafe { (*self.inner).macOS_compatibility_workaround = if enable { 1 } else { 0 } }
}
#[inline]
pub fn save_two_colr_boxes_when_icc_and_nclx_available(&self) -> bool {
unsafe { (*self.inner).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) {
unsafe {
(*self.inner).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 {
unsafe { (*self.inner).macOS_compatibility_workaround_no_nclx_profile != 0 }
}
#[inline]
pub fn set_mac_os_compatibility_workaround_no_nclx_profile(&mut self, enable: bool) {
unsafe {
(*self.inner).macOS_compatibility_workaround_no_nclx_profile =
if enable { 1 } else { 0 }
}
}
#[inline]
pub fn image_orientation(&self) -> ImageOrientation {
let orientation = unsafe { (*self.inner).image_orientation };
ImageOrientation::n(orientation).unwrap_or(ImageOrientation::Normal)
}
#[inline]
pub fn set_image_orientation(&mut self, orientation: ImageOrientation) {
unsafe {
(*self.inner).image_orientation = orientation as _;
}
}
}
#[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 }
}
pub fn id(&self) -> &str {
let name = unsafe { lh::heif_encoder_descriptor_get_id_name(self.inner) };
cstr_to_str(name).unwrap_or_default()
}
pub fn name(&self) -> String {
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()
}
}