vfxpreopenexr 0.0.4

openexr test package
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
430
use openexr_sys as sys;

use crate::{
    core::{error::Error, frame_buffer::Frame, header::HeaderRef},
    deep::deep_frame_buffer::{DeepFrame, DeepFrameBuffer, DeepFrameBufferRef},
};

use std::ffi::CString;
use std::path::Path;

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

#[repr(transparent)]
pub struct DeepScanLineInputFile(
    pub(crate) *mut sys::Imf_DeepScanLineInputFile_t,
);

impl DeepScanLineInputFile {
    /// Open the file at path `filename` and read the header.
    ///
    /// # Errors
    /// * [`Error::Base`] - if the file cannot be opened
    ///
    pub fn new<P: AsRef<Path>>(
        filename: P,
        num_threads: i32,
    ) -> Result<DeepScanLineInputFile> {
        let c_filename = CString::new(
            filename
                .as_ref()
                .to_str()
                .expect("Invalid bytes in filename"),
        )
        .expect("Internal null bytes in filename");

        let mut ptr = std::ptr::null_mut();
        unsafe {
            sys::Imf_DeepScanLineInputFile_ctor(
                &mut ptr,
                c_filename.as_ptr(),
                num_threads,
            )
            .into_result()?;
        }

        Ok(DeepScanLineInputFile(ptr))
    }

    /// Access to the file [`Header`](crate::core::header::Header)
    ///
    pub fn header(&self) -> HeaderRef {
        unsafe {
            let mut ptr = std::ptr::null();
            sys::Imf_DeepScanLineInputFile_header(self.0, &mut ptr);
            if ptr.is_null() {
                panic!("Received null ptr from sys::Imf_DeepScanLineInputFile_header");
            }

            HeaderRef::new(ptr)
        }
    }

    /// Access to the file format version
    ///
    pub fn version(&self) -> i32 {
        let mut v = 0;
        unsafe {
            sys::Imf_DeepScanLineInputFile_version(self.0, &mut v);
        }
        v
    }

    /// Set the current frame buffer -- copies the FrameBuffer
    /// object into the DeepScanLineInputFile object.
    ///
    /// The current frame buffer is the destination for the pixel
    /// data read from the file.  The current frame buffer must be
    /// set at least once before `read_pixels()` is called.
    /// The current frame buffer can be changed after each call
    /// to `read_pixels()`.
    ///
    /// # Errors
    /// * [`Error::InvalidArgument`] - if the sampling factors do not match or
    /// if the frame buffer does not have a sample count slice.
    ///
    pub fn set_frame_buffer(
        &mut self,
        frame_buffer: &DeepFrameBuffer,
    ) -> Result<()> {
        unsafe {
            sys::Imf_DeepScanLineInputFile_setFrameBuffer(
                self.0,
                frame_buffer.ptr,
            )
            .into_result()?;
        }

        Ok(())
    }

    /// Access to the current frame buffer
    ///
    pub fn frame_buffer(&self) -> DeepFrameBufferRef {
        let mut ptr = std::ptr::null();
        unsafe {
            sys::Imf_DeepScanLineInputFile_frameBuffer(self.0, &mut ptr);
        }

        DeepFrameBufferRef::new(ptr)
    }

    /// Check if all pixels in the data window are present in the input file
    ///
    pub fn is_complete(&self) -> bool {
        let mut v = false;
        unsafe {
            sys::Imf_DeepScanLineInputFile_isComplete(self.0, &mut v);
        }

        v
    }

    /// Read all scanlines in the range [s1, s2] and put them in the current
    /// frame buffer.
    ///
    /// `read_pixel_sample_counts()` must be called before calling this method.
    ///
    /// # Errors
    /// * [`Error::InvalidArgument`] - if no frame buffer has been set, if `s1`
    /// or `s2` are outside the data window, or if the sample counts have not been
    /// read yet
    /// * [`Error::Base`] - if any other error occurs
    ///
    pub fn read_pixels(&mut self, s1: i32, s2: i32) -> Result<()> {
        unsafe {
            sys::Imf_DeepScanLineInputFile_readPixels(self.0, s1, s2)
                .into_result()?;
        }
        Ok(())
    }

    /// Read the sample counts for each pixel and place them in the sample
    /// count slice in the frame buffer.
    ///
    /// # Errors
    /// * [`Error::InvalidArgument`] - if `s1` or `s2` are outside the data
    /// window.
    ///
    pub fn read_pixel_sample_counts(&mut self, s1: i32, s2: i32) -> Result<()> {
        unsafe {
            sys::Imf_DeepScanLineInputFile_readPixelSampleCounts(
                self.0, s1, s2,
            )
            .into_result()?;
        }

        Ok(())
    }

    pub fn into_reader(
        mut self,
        frames: Vec<DeepFrame>,
    ) -> Result<DeepScanLineInputFileReader> {
        // we need to know the union of all the frames passed in to know which
        // pixels to read sample counts for
        let mut data_window =
            [std::i32::MAX, std::i32::MAX, std::i32::MIN, std::i32::MIN];
        for f in &frames {
            data_window[0] = data_window[0].min(f.data_window[0]);
            data_window[1] = data_window[1].min(f.data_window[1]);
            data_window[2] = data_window[2].max(f.data_window[2]);
            data_window[3] = data_window[3].max(f.data_window[3]);
        }

        // create a Frame for the sample counts, which we'll need to
        // allocate storage for the DeepFrames
        let sample_count_frame =
            Frame::new::<u32, _, _>(&["sampleCounts"], data_window).unwrap();

        let mut frame_buffer = DeepFrameBuffer::new();

        // insert the sample count and all user-provided frames
        frame_buffer
            .set_sample_count_frame(sample_count_frame)
            .unwrap();

        for f in frames {
            frame_buffer.insert_deep_frame(f)?;
        }

        // read the sample counts and get a slice to them
        self.read_pixel_sample_counts(data_window[0], data_window[2])?;

        let DeepFrameBuffer {
            ref sample_count_frame,
            ref mut frames,
            ..
        } = frame_buffer;
        let counts = sample_count_frame.as_ref().unwrap().as_slice();

        // Now allocate sample storage for each frame's pixels
        let mut i = 0;
        for y in data_window[1]..=data_window[3] {
            for x in data_window[0]..=data_window[2] {
                let v = frames.as_mut().unwrap();
                for f in v {
                    let count = counts[i];
                    unsafe { f.allocate_pixel_storage(x, y, count) };
                }
                i += 1;
            }
        }

        Ok(DeepScanLineInputFileReader {
            inner: self.0,
            frame_buffer,
        })
    }
}

pub struct DeepScanLineInputFileReader {
    pub(crate) inner: *mut sys::Imf_DeepScanLineInputFile_t,
    frame_buffer: DeepFrameBuffer,
}

#[cfg(test)]
#[test]
fn read_deep1() {
    use crate::{
        core::frame_buffer::Frame, deep::deep_frame_buffer::DeepSlice,
    };
    use half::f16;
    use itertools::izip;
    use std::alloc::{GlobalAlloc, Layout, System};
    use std::path::PathBuf;

    let path_cyl = PathBuf::from(
        std::env::var("CARGO_MANIFEST_DIR")
            .expect("CARGO_MANIFEST_DIR not set"),
    )
    .join("images")
    .join("deep_plane.exr");

    let mut file = DeepScanLineInputFile::new(&path_cyl, 4).unwrap();
    let header = file.header();

    let data_window = *header.data_window::<[i32; 4]>();

    let data_width = data_window[2] - data_window[0] + 1;
    let data_height = data_window[3] - data_window[1] + 1;

    let offset = (-data_window[0] - data_window[1] * data_width) as isize;

    let mut data_z = vec![
        std::ptr::null_mut() as *mut f32;
        (data_width * data_height) as usize
    ];
    let mut data_zback = vec![
        std::ptr::null_mut() as *mut f32;
        (data_width * data_height) as usize
    ];
    let mut data_r = vec![
        std::ptr::null_mut() as *mut f16;
        (data_width * data_height) as usize
    ];
    let mut data_g = vec![
        std::ptr::null_mut() as *mut f16;
        (data_width * data_height) as usize
    ];
    let mut data_b = vec![
        std::ptr::null_mut() as *mut f16;
        (data_width * data_height) as usize
    ];
    let mut data_a = vec![
        std::ptr::null_mut() as *mut f16;
        (data_width * data_height) as usize
    ];

    let mut frame_buffer = DeepFrameBuffer::new();

    let sample_count_frame =
        Frame::new::<u32, _, _>(&["sampleCounts"], data_window).unwrap();

    frame_buffer
        .set_sample_count_frame(sample_count_frame)
        .unwrap();

    // add slices for all the data we're interested in
    unsafe {
        frame_buffer
            .insert(
                "Z",
                &DeepSlice::builder(
                    sys::PixelType::Float,
                    data_z.as_mut_ptr().offset(offset) as *mut i8,
                )
                .x_stride(std::mem::size_of::<*const f32>())
                .y_stride(
                    std::mem::size_of::<*const f32>() * data_width as usize,
                )
                .sample_stride(std::mem::size_of::<f32>())
                .build()
                .unwrap(),
            )
            .unwrap();

        frame_buffer
            .insert(
                "ZBack",
                &DeepSlice::builder(
                    sys::PixelType::Float,
                    data_zback.as_mut_ptr().offset(offset) as *mut i8,
                )
                .x_stride(std::mem::size_of::<*const f32>())
                .y_stride(
                    std::mem::size_of::<*const f32>() * data_width as usize,
                )
                .sample_stride(std::mem::size_of::<f32>())
                .build()
                .unwrap(),
            )
            .unwrap();

        frame_buffer
            .insert(
                "R",
                &DeepSlice::builder(
                    sys::PixelType::Half,
                    data_r.as_mut_ptr().offset(offset) as *mut i8,
                )
                .x_stride(std::mem::size_of::<*const f16>())
                .y_stride(
                    std::mem::size_of::<*const f16>() * data_width as usize,
                )
                .sample_stride(std::mem::size_of::<f16>())
                .build()
                .unwrap(),
            )
            .unwrap();

        frame_buffer
            .insert(
                "G",
                &DeepSlice::builder(
                    sys::PixelType::Half,
                    data_g.as_mut_ptr().offset(offset) as *mut i8,
                )
                .x_stride(std::mem::size_of::<*const f16>())
                .y_stride(
                    std::mem::size_of::<*const f16>() * data_width as usize,
                )
                .sample_stride(std::mem::size_of::<f16>())
                .build()
                .unwrap(),
            )
            .unwrap();

        frame_buffer
            .insert(
                "B",
                &DeepSlice::builder(
                    sys::PixelType::Half,
                    data_b.as_mut_ptr().offset(offset) as *mut i8,
                )
                .x_stride(std::mem::size_of::<*const f16>())
                .y_stride(
                    std::mem::size_of::<*const f16>() * data_width as usize,
                )
                .sample_stride(std::mem::size_of::<f16>())
                .build()
                .unwrap(),
            )
            .unwrap();

        frame_buffer
            .insert(
                "A",
                &DeepSlice::builder(
                    sys::PixelType::Half,
                    data_a.as_mut_ptr().offset(offset) as *mut i8,
                )
                .x_stride(std::mem::size_of::<*const f16>())
                .y_stride(
                    std::mem::size_of::<*const f16>() * data_width as usize,
                )
                .sample_stride(std::mem::size_of::<f16>())
                .build()
                .unwrap(),
            )
            .unwrap();
    }

    // set the frame buffer and read the sample counts channel
    file.set_frame_buffer(&frame_buffer).unwrap();
    file.read_pixel_sample_counts(data_window[1], data_window[3])
        .unwrap();

    let sample_count_frame = frame_buffer.sample_count_frame.take().unwrap();

    // pre-allocate the memory for the sample data using the sample counts
    // channel
    for (sc, z, zback, r, g, b, a) in izip!(
        sample_count_frame.as_slice::<u32>(),
        &mut data_z,
        &mut data_zback,
        &mut data_r,
        &mut data_g,
        &mut data_b,
        &mut data_a
    ) {
        let sz = *sc as usize;

        unsafe {
            *z = System.alloc(Layout::array::<f32>(sz).unwrap()) as *mut f32;
            *zback =
                System.alloc(Layout::array::<f32>(sz).unwrap()) as *mut f32;
            *r = System.alloc(Layout::array::<f16>(sz).unwrap()) as *mut f16;
            *g = System.alloc(Layout::array::<f16>(sz).unwrap()) as *mut f16;
            *b = System.alloc(Layout::array::<f16>(sz).unwrap()) as *mut f16;
            *a = System.alloc(Layout::array::<f16>(sz).unwrap()) as *mut f16;
        }
    }

    frame_buffer
        .set_sample_count_frame(sample_count_frame)
        .unwrap();

    // read the data
    file.read_pixels(data_window[1], data_window[3]).unwrap();
}