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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
use openexr_sys as sys;

pub use crate::core::{
    error::Error,
    refptr::{OpaquePtr, Ref, RefMut},
    PixelType,
};
use std::marker::PhantomData;

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

use imath_traits::{Bound2, Vec2, Zero};

type Result<T, E = Error> = std::result::Result<T, E>;

pub struct FrameBuffer {
    pub(crate) ptr: *mut sys::Imf_FrameBuffer_t,
    pub(crate) frames: Option<Vec<Frame>>,
}

unsafe impl OpaquePtr for FrameBuffer {
    type SysPointee = sys::Imf_FrameBuffer_t;
    type Pointee = FrameBuffer;
}

pub type FrameBufferRef<'a> = Ref<'a, FrameBuffer>;

impl FrameBuffer {
    /// Create a new `FrameBuffer`.
    pub fn new() -> FrameBuffer {
        let mut ptr = std::ptr::null_mut();
        unsafe {
            sys::Imf_FrameBuffer_ctor(&mut ptr);
        }
        FrameBuffer {
            ptr,
            frames: Some(Vec::new()),
        }
    }

    /// Insert a [`Slice`] into the `FrameBuffer`.
    ///
    /// # Safety
    /// On the C++ side `slice` is converted to a raw pointer, so it is the
    /// caller's responsibility to ensure that `slice` is correctly sized and
    /// still alive for any future reads or writes.
    ///
    /// # Errors
    /// * [`Error::InvalidArgument`] - if name is the empty string
    ///
    pub fn insert(&mut self, name: &str, slice: &Slice) -> Result<()> {
        let c_name =
            CString::new(name).expect("Internal null bytes in filename");

        unsafe {
            sys::Imf_FrameBuffer_insert(self.ptr, c_name.as_ptr(), &slice.0)
                .into_result()?;
        }

        Ok(())
    }

    /// Find the [`Slice`] with the given `name` in the `FrameBuffer`
    ///
    /// # Returns
    /// * `Some([`SliceRef`])` - if the [`Slice`] is found
    /// * `None` - otherwise
    ///
    pub fn get_slice<'a>(&'a self, name: &str) -> Option<SliceRef<'a>> {
        let c_name =
            CString::new(name).expect("Internal null bytes in filename");

        let mut ptr = std::ptr::null();
        unsafe {
            sys::Imf_FrameBuffer_findSlice_const(
                self.ptr,
                &mut ptr,
                c_name.as_ptr(),
            );
        }

        if ptr.is_null() {
            None
        } else {
            Some(SliceRef::new(ptr))
        }
    }

    /// Find the [`Slice`] with the given `name` in the `FrameBuffer` and get a
    /// mutable Ref to it
    ///
    /// # Returns
    /// * `Some([`SliceRefMut`])` - if the [`Slice`] is found
    /// * `None` - otherwise
    ///
    pub fn get_slice_mut<'a>(
        &'a mut self,
        name: &str,
    ) -> Option<SliceRefMut<'a>> {
        let c_name =
            CString::new(name).expect("Internal null bytes in filename");

        let mut ptr = std::ptr::null_mut();
        unsafe {
            sys::Imf_FrameBuffer_findSlice(self.ptr, &mut ptr, c_name.as_ptr());
        }

        if ptr.is_null() {
            None
        } else {
            Some(SliceRefMut::new(ptr))
        }
    }

    /// Get an iterator over the [`Slice`]s in this `FrameBuffer`
    ///
    pub fn iter(&self) -> FrameBufferIter {
        unsafe {
            let mut ptr = sys::Imf_FrameBuffer_ConstIterator_t::default();
            sys::Imf_FrameBuffer_begin_const(self.ptr, &mut ptr)
                .into_result()
                .unwrap();
            let ptr = FrameBufferConstIterator(ptr);

            let mut end = sys::Imf_FrameBuffer_ConstIterator_t::default();
            sys::Imf_FrameBuffer_end_const(self.ptr, &mut end)
                .into_result()
                .unwrap();
            let end = FrameBufferConstIterator(end);

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

    pub fn insert_frame(&mut self, frame: Frame) -> Result<FrameHandle> {
        let mut ptr = frame.ptr;
        let w = frame.data_window[2] - frame.data_window[0] + 1;
        let ystride = w as usize * frame.stride;
        for chan in &frame.channel_names {
            self.insert(
                &chan,
                &Slice::with_data_window(
                    frame.channel_type,
                    ptr,
                    frame.data_window,
                )
                .x_stride(frame.stride)
                .y_stride(ystride)
                .build()?,
            )?;

            ptr = unsafe { ptr.add(frame.channel_stride) };
        }

        let handle = match &mut self.frames {
            Some(v) => {
                let handle = v.len();
                v.push(frame);
                FrameHandle(handle)
            }
            _ => unreachable!(),
        };

        Ok(handle)
    }
}

impl Drop for FrameBuffer {
    fn drop(&mut self) {
        unsafe {
            sys::Imf_FrameBuffer_dtor(self.ptr);
        }
    }
}

impl Default for FrameBuffer {
    fn default() -> Self {
        FrameBuffer::new()
    }
}

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

// #[repr(transparent)]
// pub(crate) struct FrameBufferIterator(
//     pub(crate) sys::Imf_FrameBuffer_Iterator_t,
// );

pub struct FrameBufferIter<'a> {
    ptr: FrameBufferConstIterator,
    end: FrameBufferConstIterator,
    _p: PhantomData<&'a FrameBuffer>,
}

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

    fn next(&mut self) -> Option<(&'a str, SliceRef<'a>)> {
        let ptr_curr = self.ptr.clone();
        let mut ptr_next = self.ptr.clone();
        unsafe {
            let mut dummy = std::ptr::null_mut();
            sys::Imf_FrameBuffer_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_FrameBuffer_ConstIterator_name(
                    &ptr_curr.0,
                    &mut nameptr,
                )
                .into_result()
                .unwrap();

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

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

                Some((
                    CStr::from_ptr(nameptr)
                        .to_str()
                        .expect("NUL bytes in channel name"),
                    SliceRef::new(sliceptr),
                ))
            }
        }
    }
}

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

            result
        }
    }
}

#[repr(transparent)]
pub struct Slice(pub(crate) sys::Imf_Slice_t);
pub type SliceRef<'a, P = Slice> = Ref<'a, P>;
pub type SliceRefMut<'a, P = Slice> = RefMut<'a, P>;

unsafe impl OpaquePtr for Slice {
    type SysPointee = sys::Imf_Slice_t;
    type Pointee = Slice;
}

pub struct SliceBuilder {
    pixel_type: PixelType,
    data: *const u8,
    origin: [i32; 2],
    w: i64,
    h: i64,
    x_stride: usize,
    y_stride: usize,
    x_sampling: i32,
    y_sampling: i32,
    fill_value: f64,
    x_tile_coords: bool,
    y_tile_coords: bool,
}

impl SliceBuilder {
    pub fn build(self) -> Result<Slice> {
        let mut slice = sys::Imf_Slice_t::default();
        unsafe {
            sys::Imf_Slice_with_origin(
                &mut slice,
                self.pixel_type.into(),
                self.data as *const std::os::raw::c_void,
                self.origin.as_ptr() as *const sys::Imath_V2i_t,
                self.w,
                self.h,
                self.x_stride,
                self.y_stride,
                self.x_sampling,
                self.y_sampling,
                self.fill_value,
                self.x_tile_coords,
                self.y_tile_coords,
            )
            .into_result()?;
        }

        Ok(Slice(slice))
    }

    /// Set the data window origin.
    ///
    pub fn origin<V>(mut self, o: V) -> Self
    where
        V: Vec2<i32>,
    {
        let o = o.as_slice();
        self.origin = *o;
        self
    }

    pub fn fill_value(mut self, v: f64) -> Self {
        self.fill_value = v;
        self
    }

    pub fn x_stride(mut self, x: usize) -> Self {
        self.x_stride = x;
        self
    }

    pub fn y_stride(mut self, y: usize) -> Self {
        self.y_stride = y;
        self
    }

    pub fn x_sampling(mut self, x: i32) -> Self {
        self.x_sampling = x;
        self
    }

    pub fn y_sampling(mut self, y: i32) -> Self {
        self.y_sampling = y;
        self
    }

    pub fn x_tile_coords(mut self, x: bool) -> Self {
        self.x_tile_coords = x;
        self
    }

    pub fn y_tile_coords(mut self, y: bool) -> Self {
        self.y_tile_coords = y;
        self
    }
}

impl Slice {
    pub fn builder(
        pixel_type: PixelType,
        data: *const u8,
        w: i64,
        h: i64,
    ) -> SliceBuilder {
        SliceBuilder {
            pixel_type,
            data,
            origin: [0i32; 2],
            w,
            h,
            x_stride: 0,
            y_stride: 0,
            x_sampling: 1,
            y_sampling: 1,
            fill_value: 0.0,
            x_tile_coords: false,
            y_tile_coords: false,
        }
    }

    pub fn with_origin(
        pixel_type: PixelType,
        data: *const u8,
        origin: [i32; 2],
        w: i64,
        h: i64,
    ) -> SliceBuilder {
        SliceBuilder {
            pixel_type,
            data,
            origin,
            w,
            h,
            x_stride: 0,
            y_stride: 0,
            x_sampling: 1,
            y_sampling: 1,
            fill_value: 0.0,
            x_tile_coords: false,
            y_tile_coords: false,
        }
    }

    pub fn with_data_window<B>(
        pixel_type: PixelType,
        data: *const u8,
        data_window: B,
    ) -> SliceBuilder
    where
        B: Bound2<i32>,
    {
        let b = data_window.as_slice();

        SliceBuilder {
            pixel_type,
            data,
            origin: [b[0], b[1]],
            w: b[2] as i64 + 1,
            h: b[3] as i64 + 1,
            x_stride: 0,
            y_stride: 0,
            x_sampling: 1,
            y_sampling: 1,
            fill_value: 0.0,
            x_tile_coords: false,
            y_tile_coords: false,
        }
    }
}

impl Drop for Slice {
    fn drop(&mut self) {
        unsafe {
            sys::Imf_Slice_dtor(&mut self.0);
        }
    }
}

pub trait Pixel: Zero + Clone {
    const CHANNEL_TYPE: PixelType;
    const NUM_CHANNELS: usize;
    const STRIDE: usize = std::mem::size_of::<Self>();
    const CHANNEL_STRIDE: usize = std::mem::size_of::<Self>();
}

impl Pixel for half::f16 {
    // type Type = Self;
    const CHANNEL_TYPE: PixelType = PixelType::Half;
    const NUM_CHANNELS: usize = 1;
}

impl Pixel for f32 {
    // type Type = Self;
    const CHANNEL_TYPE: PixelType = PixelType::Float;
    const NUM_CHANNELS: usize = 1;
}

impl Pixel for u32 {
    // type Type = Self;
    const CHANNEL_TYPE: PixelType = PixelType::Uint;
    const NUM_CHANNELS: usize = 1;
}

impl Pixel for crate::rgba::rgba::Rgba {
    // type Type = Self;
    const CHANNEL_TYPE: PixelType = PixelType::Half;
    const NUM_CHANNELS: usize = 4;
    const CHANNEL_STRIDE: usize = std::mem::size_of::<half::f16>();
}

#[cfg(feature = "imath_cgmath")]
mod impl_cgmath {
    use super::{Pixel, PixelType};

    impl Pixel for cgmath::Vector2<half::f16> {
        const CHANNEL_TYPE: PixelType = half::f16::CHANNEL_TYPE;
        const NUM_CHANNELS: usize = 2;
        const CHANNEL_STRIDE: usize = half::f16::CHANNEL_STRIDE;
    }

    impl Pixel for cgmath::Vector2<f32> {
        const CHANNEL_TYPE: PixelType = f32::CHANNEL_TYPE;
        const NUM_CHANNELS: usize = 2;
        const CHANNEL_STRIDE: usize = f32::CHANNEL_STRIDE;
    }

    impl Pixel for cgmath::Vector2<u32> {
        const CHANNEL_TYPE: PixelType = u32::CHANNEL_TYPE;
        const NUM_CHANNELS: usize = 2;
        const CHANNEL_STRIDE: usize = u32::CHANNEL_STRIDE;
    }

    impl Pixel for cgmath::Vector3<half::f16> {
        const CHANNEL_TYPE: PixelType = half::f16::CHANNEL_TYPE;
        const NUM_CHANNELS: usize = 3;
        const CHANNEL_STRIDE: usize = half::f16::CHANNEL_STRIDE;
    }

    impl Pixel for cgmath::Vector3<f32> {
        const CHANNEL_TYPE: PixelType = f32::CHANNEL_TYPE;
        const NUM_CHANNELS: usize = 3;
        const CHANNEL_STRIDE: usize = f32::CHANNEL_STRIDE;
    }

    impl Pixel for cgmath::Vector3<u32> {
        const CHANNEL_TYPE: PixelType = u32::CHANNEL_TYPE;
        const NUM_CHANNELS: usize = 3;
        const CHANNEL_STRIDE: usize = u32::CHANNEL_STRIDE;
    }

    impl Pixel for cgmath::Vector4<half::f16> {
        const CHANNEL_TYPE: PixelType = half::f16::CHANNEL_TYPE;
        const NUM_CHANNELS: usize = 4;
        const CHANNEL_STRIDE: usize = half::f16::CHANNEL_STRIDE;
    }

    impl Pixel for cgmath::Vector4<f32> {
        const CHANNEL_TYPE: PixelType = f32::CHANNEL_TYPE;
        const NUM_CHANNELS: usize = 4;
        const CHANNEL_STRIDE: usize = f32::CHANNEL_STRIDE;
    }

    impl Pixel for cgmath::Vector4<u32> {
        const CHANNEL_TYPE: PixelType = u32::CHANNEL_TYPE;
        const NUM_CHANNELS: usize = 4;
        const CHANNEL_STRIDE: usize = u32::CHANNEL_STRIDE;
    }
}

/// `Frame` attempts to provide a safer API on top of OpenEXR's
/// [`Slice`](crate::core::frame_buffer::Slice) type.
///
/// Instead of providing a pointer and calculating offsets based on the data
/// window offset, as [`Slice`](crate::core::frame_buffer::Slice) does, `Frame` wraps up the data window offset
/// and handles memory allocation internally so that you can't get it wrong.
///
/// # Examples
/// ```no_run
/// # fn foo() -> Result<(), openexr::Error> {
/// use openexr::prelude::*;
///
/// let file = InputFile::new("test.exr", 4)?;
/// let data_window: [i32; 4] = *file.header().data_window();
///
/// let frame_rgba =
///     Frame::new::<Rgba, _, _>(
///         &["R", "G", "B", "A"],
///         data_window
///         )?;
///
/// let (file, frames) = file
///     .into_reader(vec![frame_rgba])?
///     .read_pixels(data_window[1], data_window[3])?;
///
/// # Ok(())
/// # }
/// ```
pub struct Frame {
    pub(crate) channel_type: PixelType,
    pub(crate) data_window: [i32; 4],
    pub(crate) channel_names: Vec<String>,
    pub(crate) stride: usize,
    pub(crate) channel_stride: usize,
    pub(crate) ptr: *mut u8,
    pub(crate) byte_len: usize,
    pub(crate) align: usize,
}

#[repr(transparent)]
#[derive(Copy, Clone, PartialEq, Hash)]
pub struct FrameHandle(usize);

use std::alloc::{GlobalAlloc, Layout, System};
impl Frame {
    /// Constructs a new frame for the given `channel_names` and `data_window`
    /// and allocates storage to hold the pixel data.
    ///
    /// # Errors
    /// [`Error::InvalidArgument`] - if the length of the `channel_names` slice
    /// is not a multiple of `Pixel::NUM_CHANNELS`
    ///
    pub fn new<T: Pixel, B: Bound2<i32>, S: AsRef<str>>(
        channel_names: &[S],
        data_window: B,
    ) -> Result<Frame> {
        let channel_names = channel_names
            .iter()
            .map(|s| s.as_ref().to_string())
            .collect::<Vec<String>>();

        if channel_names.len() % T::NUM_CHANNELS != 0 {
            return Err(Error::InvalidArgument(format!("channel_names ({:?}) has {} channels but pixel type has {} channels. Channel names length must be a multiple of pixel type num channels in order to pack.", channel_names, channel_names.len(), T::NUM_CHANNELS)));
        }

        let data_window = *data_window.as_slice();
        let w = data_window[2] - data_window[0] + 1;
        let h = data_window[3] - data_window[1] + 1;

        // We're packing the data into an array where elements may have multiple
        // channels themselves
        let num_packed = channel_names.len() / T::NUM_CHANNELS;
        let len = (w * h) as usize * num_packed;
        let byte_len = len * std::mem::size_of::<T>();
        let align = std::mem::align_of::<T>();
        let ptr = unsafe { System.alloc(Layout::array::<T>(len).unwrap()) };

        Ok(Frame {
            channel_type: T::CHANNEL_TYPE,
            data_window,
            channel_names,
            stride: T::STRIDE * num_packed,
            channel_stride: T::CHANNEL_STRIDE,
            ptr,
            byte_len,
            align,
        })
    }

    /// Construct a new `Frame` using the storage provided in `vec`.
    ///
    /// This can either be used to provide pixel data for writing, or to re-use
    /// storage between reads.
    ///
    /// # Errors
    /// [`Error::InvalidArgument`] - if the length of the `channel_names` slice
    /// is not a multiple of `Pixel::NUM_CHANNELS`
    ///
    pub fn with_vec<T: Pixel, B: Bound2<i32>, S: AsRef<str>>(
        channel_names: &[S],
        mut vec: Vec<T>,
        data_window: B,
    ) -> Result<Frame> {
        let channel_names = channel_names
            .iter()
            .map(|s| s.as_ref().to_string())
            .collect::<Vec<String>>();

        if channel_names.len() != T::NUM_CHANNELS {
            return Err(Error::InvalidArgument(format!("channel_names ({:?}) has {} channels but pixel type has {} channels.", channel_names, channel_names.len(), T::NUM_CHANNELS)));
        }

        let data_window = *data_window.as_slice();
        let w = data_window[2] - data_window[0] + 1;
        let h = data_window[3] - data_window[1] + 1;
        let len = (w * h) as usize;

        vec.resize(len, T::zero());
        let mut vec = vec.into_boxed_slice();
        let ptr = vec.as_mut_ptr() as *mut u8;
        Box::leak(vec);

        let byte_len = len * std::mem::size_of::<T>();
        let align = std::mem::align_of::<T>();

        Ok(Frame {
            channel_type: T::CHANNEL_TYPE,
            data_window,
            channel_names,
            stride: T::STRIDE,
            channel_stride: T::CHANNEL_STRIDE,
            ptr,
            byte_len,
            align,
        })
    }

    /// Get a reference to the pixel data slice.
    ///
    pub fn as_slice<T: Pixel>(&self) -> &[T] {
        let stride = std::mem::size_of::<T>();
        if T::STRIDE != stride {
            panic!("Attempt to get a slice with a different type");
        }

        unsafe {
            std::slice::from_raw_parts(
                self.ptr as *const T,
                self.byte_len / stride,
            )
        }
    }

    /// Get a mutable reference to the pixel data slice.
    ///
    pub fn as_mut_slice<T: Pixel>(&mut self) -> &mut [T] {
        let stride = std::mem::size_of::<T>();
        if T::STRIDE != stride {
            panic!("Attempt to get a slice with a different type");
        }

        unsafe {
            std::slice::from_raw_parts_mut(
                self.ptr as *mut T,
                self.byte_len / stride,
            )
        }
    }

    /// Consume this `Frame` and return the pixel data as a `Vec`.
    ///
    pub fn into_vec<T: Pixel>(self) -> Vec<T> {
        self.as_slice().to_vec()
    }
}

impl Drop for Frame {
    fn drop(&mut self) {
        unsafe {
            System.dealloc(
                self.ptr,
                Layout::from_size_align(self.byte_len, self.align).unwrap(),
            )
        }
    }
}