openexr 0.11.0

High-level bindings to OpenEXR 3.0.5
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
use openexr_sys as sys;
pub use sys::Imf_Channel_t as Channel;

use crate::core::{
    cppstd::CppString,
    refptr::{OpaquePtr, Ref, RefMut},
};

use std::ffi::{CStr, CString};
use std::marker::PhantomData;

#[repr(transparent)]
pub struct ChannelList(pub(crate) *mut sys::Imf_ChannelList_t);

#[repr(transparent)]
#[derive(Clone)]
pub(crate) struct ChannelListConstIterator(
    pub(crate) sys::Imf_ChannelList_ConstIterator_t,
);

// #[repr(transparent)]
// pub(crate) struct ChannelListIterator(
//     pub(crate) sys::Imf_ChannelList_Iterator_t,
// );

pub const CHANNEL_HALF: Channel = Channel {
    type_: sys::Imf_PixelType_HALF,
    x_sampling: 1,
    y_sampling: 1,
    p_linear: true,
};
pub const CHANNEL_FLOAT: Channel = Channel {
    type_: sys::Imf_PixelType_FLOAT,
    x_sampling: 1,
    y_sampling: 1,
    p_linear: true,
};
pub const CHANNEL_UINT: Channel = Channel {
    type_: sys::Imf_PixelType_UINT,
    x_sampling: 1,
    y_sampling: 1,
    p_linear: true,
};

unsafe impl OpaquePtr for ChannelList {
    type SysPointee = sys::Imf_ChannelList_t;
    type Pointee = ChannelList;
}

pub type ChannelListRef<'a, P = ChannelList> = Ref<'a, P>;
pub type ChannelListRefMut<'a, P = ChannelList> = RefMut<'a, P>;

impl ChannelList {
    /// Create a Default channel list
    ///
    pub fn new() -> ChannelList {
        ChannelList::default()
    }

    /// Insert a channel
    ///
    pub fn insert(&mut self, name: &str, channel: &Channel) {
        unsafe {
            let cname = CString::new(name).expect("Inner NUL bytes in name");
            sys::Imf_ChannelList_insert(self.0, cname.as_ptr(), channel)
                .into_result()
                .unwrap();
        }
    }

    /// Get a reference to a channel by name.
    ///
    /// # Returns
    /// * `Some(&Channel)` - if the channel called `name` exists
    /// * `None` - otherwise
    ///
    pub fn get(&self, name: &str) -> Option<&Channel> {
        unsafe {
            let cname = CString::new(name).expect("Inner NUL bytes in name");
            let mut ptr = std::ptr::null();
            sys::Imf_ChannelList_findChannel_const(
                self.0,
                &mut ptr,
                cname.as_ptr(),
            )
            .into_result()
            .unwrap();

            if ptr.is_null() {
                None
            } else {
                Some(&*ptr)
            }
        }
    }

    /// Get a mutable reference to a channel by name.
    ///
    /// # Returns
    /// * `Some(&Channel)` - if the channel called `name` exists
    /// * `None` - otherwise
    ///
    pub fn get_mut(&mut self, name: &str) -> Option<&mut Channel> {
        unsafe {
            let cname = CString::new(name).expect("Inner NUL bytes in name");
            let mut ptr = std::ptr::null_mut();

            sys::Imf_ChannelList_findChannel(self.0, &mut ptr, cname.as_ptr())
                .into_result()
                .unwrap();

            if ptr.is_null() {
                None
            } else {
                Some(&mut *ptr)
            }
        }
    }

    /// Get an iterator over the channels in the channel list
    ///
    pub fn iter(&self) -> ChannelListIter {
        unsafe {
            let mut ptr = sys::Imf_ChannelList_ConstIterator_t::default();
            sys::Imf_ChannelList_begin_const(self.0, &mut ptr)
                .into_result()
                .unwrap();
            let ptr = ChannelListConstIterator(ptr);

            let mut end = sys::Imf_ChannelList_ConstIterator_t::default();
            sys::Imf_ChannelList_end_const(self.0, &mut end)
                .into_result()
                .unwrap();
            let end = ChannelListConstIterator(end);

            ChannelListIter {
                ptr,
                end,
                _p: PhantomData,
            }
        }
    }
}

impl ChannelList {
    //! # Layers
    //! In an image file with many channels it is sometimes useful to
    //! group the channels into "layers", that is, into sets of channels
    //! that logically belong together.  Grouping channels into layers
    //! is done using a naming convention:  channel C in layer L is
    //! called "L.C".
    //!
    //! For example, a computer graphic image may contain separate
    //! R, G and B channels for light that originated at each of
    //! several different virtual light sources.  The channels in
    //! this image might be called "light1.R", "light1.G", "light1.B",
    //! "light2.R", "light2.G", "light2.B", etc.
    //!
    //! Note that this naming convention allows layers to be nested;
    //! for example, "light1.specular.R" identifies the "R" channel
    //! in the "specular" sub-layer of layer "light1".
    //!
    //! Channel names that don't contain a "." or that contain a
    //! "." only at the beginning or at the end are not considered
    //! to be part of any layer.

    /// Get the set of layers in the file.
    ///
    ///
    pub fn layers(&self) -> Vec<String> {
        unsafe {
            // FIXME: dealing with STL at the boundary is pretty gnarly.
            // Should probably provide a high-level pub(crate) mod for these
            let mut set = std::ptr::null_mut();
            sys::std_set_string_ctor(&mut set);
            sys::Imf_ChannelList_layers(self.0, set);

            let mut ptr = sys::std_set_string_iterator_t::default();
            sys::std_set_string_cbegin(set, &mut ptr)
                .into_result()
                .unwrap();
            let mut end = sys::std_set_string_iterator_t::default();
            sys::std_set_string_cend(set, &mut end)
                .into_result()
                .unwrap();

            let mut size = 0;
            sys::std_set_string_size(set, &mut size)
                .into_result()
                .unwrap();

            let mut result = Vec::with_capacity(size as usize);

            loop {
                let mut eq = false;
                sys::std_set_string_const_iterator_eq(&mut eq, &ptr, &end);
                if eq {
                    break;
                }

                let mut str_ptr = std::ptr::null();
                sys::std_set_string_iterator_deref(&ptr, &mut str_ptr)
                    .into_result()
                    .unwrap();

                let mut char_ptr = std::ptr::null();
                sys::std_string_c_str(str_ptr, &mut char_ptr)
                    .into_result()
                    .unwrap();

                result.push(
                    CStr::from_ptr(char_ptr).to_string_lossy().to_string(),
                );

                let mut dummy = std::ptr::null_mut();
                sys::std_set_string_iterator_inc(&mut ptr, &mut dummy)
                    .into_result()
                    .unwrap();
            }

            result
        }
    }

    /// Get an iterator over the channels belonging to a particular layer
    ///
    pub fn channels_in_layer(&self, layer: &str) -> ChannelListIter {
        let mut ptr = sys::Imf_ChannelList_ConstIterator_t::default();
        let mut end = sys::Imf_ChannelList_ConstIterator_t::default();
        unsafe {
            let s = CppString::new(layer);
            sys::Imf_ChannelList_channelsInLayer_const(
                self.0, s.0, &mut ptr, &mut end,
            )
            .into_result()
            .unwrap();

            ChannelListIter {
                ptr: ChannelListConstIterator(ptr),
                end: ChannelListConstIterator(end),
                _p: PhantomData,
            }
        }
    }

    /// Get an iterator over all channels whose name starts with prefix `prefix`
    ///
    pub fn channels_with_prefix(&self, prefix: &str) -> ChannelListIter {
        let mut ptr = sys::Imf_ChannelList_ConstIterator_t::default();
        let mut end = sys::Imf_ChannelList_ConstIterator_t::default();
        unsafe {
            let cprefix = CString::new(prefix).expect("NUL bytes in prefix");
            sys::Imf_ChannelList_channelsWithPrefix_const(
                self.0,
                cprefix.as_ptr(),
                &mut ptr,
                &mut end,
            )
            .into_result()
            .unwrap();

            ChannelListIter {
                ptr: ChannelListConstIterator(ptr),
                end: ChannelListConstIterator(end),
                _p: PhantomData,
            }
        }
    }
}

impl Default for ChannelList {
    fn default() -> ChannelList {
        unsafe {
            let mut ptr = std::ptr::null_mut();
            sys::Imf_ChannelList_ctor(&mut ptr);
            ChannelList(ptr)
        }
    }
}

impl PartialEq for ChannelList {
    fn eq(&self, rhs: &ChannelList) -> bool {
        unsafe {
            let mut result = false;
            sys::Imf_ChannelList__eq(self.0, &mut result, rhs.0)
                .into_result()
                .unwrap();

            result
        }
    }
}

pub struct ChannelListIter<'a> {
    ptr: ChannelListConstIterator,
    end: ChannelListConstIterator,
    _p: PhantomData<&'a ChannelList>,
}

impl<'a> IntoIterator for &'a ChannelList {
    type Item = (&'a str, &'a Channel);
    type IntoIter = ChannelListIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a> Iterator for ChannelListIter<'a> {
    type Item = (&'a str, &'a Channel);

    fn next(&mut self) -> Option<(&'a str, &'a Channel)> {
        let ptr_curr = self.ptr.clone();
        let mut ptr_next = self.ptr.clone();
        unsafe {
            let mut dummy = std::ptr::null_mut();
            sys::Imf_ChannelList_ConstIterator__op_inc(
                &mut ptr_next.0,
                &mut dummy,
            )
            .into_result()
            .unwrap();
        }

        if ptr_curr == self.end {
            None
        } else {
            self.ptr = ptr_next;
            unsafe {
                let mut nameptr = std::ptr::null();
                sys::Imf_ChannelList_ConstIterator_name(
                    &ptr_curr.0,
                    &mut nameptr,
                )
                .into_result()
                .unwrap();

                if nameptr.is_null() {
                    panic!("ChannelList::ConstIterator::name() returned NULL");
                }

                let mut chanptr = std::ptr::null();
                sys::Imf_ChannelList_ConstIterator_channel(
                    &ptr_curr.0,
                    &mut chanptr,
                )
                .into_result()
                .unwrap();

                Some((
                    CStr::from_ptr(nameptr)
                        .to_str()
                        .expect("NUL bytes in channel name"),
                    &*chanptr,
                ))
            }
        }
    }
}

impl PartialEq for ChannelListConstIterator {
    fn eq(&self, rhs: &ChannelListConstIterator) -> bool {
        unsafe {
            let mut result = false;
            sys::Imf_channel_list_const_iter_eq(&mut result, &self.0, &rhs.0)
                .into_result()
                .unwrap();

            result
        }
    }
}

#[cfg(test)]
#[test]
fn iter1() {
    use crate::core::PixelType;
    let mut list = ChannelList::new();
    let channel = Channel {
        type_: PixelType::Half.into(),
        x_sampling: 1,
        y_sampling: 1,
        p_linear: true,
    };

    list.insert("R", &channel);
    list.insert("G", &channel);
    list.insert("B", &channel);
    list.insert("A", &channel);

    assert_eq!(
        list.iter().map(|(name, _)| { name }).collect::<Vec<&str>>(),
        ["A", "B", "G", "R"]
    )
}

#[cfg(test)]
#[test]
fn iter2() {
    use crate::core::PixelType;
    let mut list = ChannelList::new();
    let channel = Channel {
        type_: PixelType::Half.into(),
        x_sampling: 1,
        y_sampling: 1,
        p_linear: true,
    };

    list.insert("R", &channel);
    list.insert("G", &channel);
    list.insert("B", &channel);
    list.insert("A", &channel);

    for (_name, _channel) in &list {
        // ...
    }
}

#[cfg(test)]
#[test]
fn eq() {
    use crate::core::PixelType;
    let mut list1 = ChannelList::new();
    let mut list2 = ChannelList::new();
    let mut list3 = ChannelList::new();
    let channel = Channel {
        type_: PixelType::Half.into(),
        x_sampling: 1,
        y_sampling: 1,
        p_linear: true,
    };

    list1.insert("R", &channel);
    list1.insert("G", &channel);
    list1.insert("B", &channel);
    list1.insert("A", &channel);

    list2.insert("R", &channel);
    list2.insert("G", &channel);
    list2.insert("B", &channel);
    list2.insert("A", &channel);

    list3.insert("R", &channel);
    list3.insert("G", &channel);
    list3.insert("B", &channel);

    assert!(list1 == list2);
    assert!(list1 != list3);
}

#[cfg(test)]
#[test]
fn layers() {
    use crate::core::PixelType;
    let mut list = ChannelList::new();
    let channel = Channel {
        type_: PixelType::Half.into(),
        x_sampling: 1,
        y_sampling: 1,
        p_linear: true,
    };

    list.insert("diffuse.R", &channel);
    list.insert("diffuse.G", &channel);
    list.insert("diffuse.B", &channel);

    list.insert("specular.R", &channel);
    list.insert("specular.G", &channel);
    list.insert("specular.B", &channel);

    let layers = list.layers();

    assert_eq!(layers, ["diffuse", "specular"]);
}

#[cfg(test)]
#[test]
fn channels_in_layer() {
    use crate::core::PixelType;
    let mut list = ChannelList::new();
    let channel = Channel {
        type_: PixelType::Half.into(),
        x_sampling: 1,
        y_sampling: 1,
        p_linear: true,
    };

    list.insert("diffuse.R", &channel);
    list.insert("diffuse.G", &channel);
    list.insert("diffuse.B", &channel);

    list.insert("specular.R", &channel);
    list.insert("specular.G", &channel);
    list.insert("specular.B", &channel);

    assert_eq!(
        list.channels_in_layer("diffuse")
            .map(|(name, _)| { name })
            .collect::<Vec<&str>>(),
        ["diffuse.B", "diffuse.G", "diffuse.R"]
    )
}

#[cfg(test)]
#[test]
fn channels_with_prefix() {
    use crate::core::PixelType;
    let mut list = ChannelList::new();
    let channel = Channel {
        type_: PixelType::Half.into(),
        x_sampling: 1,
        y_sampling: 1,
        p_linear: true,
    };

    list.insert("diffuse.R", &channel);
    list.insert("diffuse.G", &channel);
    list.insert("diffuse.B", &channel);

    list.insert("specular.R", &channel);
    list.insert("specular.G", &channel);
    list.insert("specular.B", &channel);

    assert_eq!(
        list.channels_with_prefix("spec")
            .map(|(name, _)| { name })
            .collect::<Vec<&str>>(),
        ["specular.B", "specular.G", "specular.R"]
    )
}

// pub struct ChannelListIterMut {
//     ptr: ChannelListIterator,
//     end: ChannelListIterator,
// }

// impl PartialEq for ChannelListIterator {
//     fn eq(&self, rhs: &ChannelListIterator) -> bool {
//         let mut a = sys::Imf_ChannelList_ConstIterator_t::default();
//         let mut b = sys::Imf_ChannelList_ConstIterator_t::default();
//         unsafe {
//             sys::Imf_ChannelList_ConstIterator_from_mut(&mut a, &self.0);
//             sys::Imf_ChannelList_ConstIterator_from_mut(&mut b, &rhs.0);
//             sys::Imf_channel_list_const_iter_eq(&a, &b)
//         }
//     }
// }