Skip to main content

ocio_rs/
image_desc.rs

1use std::ffi::c_void;
2use std::marker::PhantomData;
3use std::ptr::NonNull;
4
5/// Interleaved image with independent channel offsets within each pixel.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub struct CustomImageLayout {
8    /// Dimensions, origin of the first logical pixel, signed strides and bit depth.
9    pub layout: crate::SignedPlanarByteLayout,
10    /// Byte offsets from each pixel origin, in R, G, B order.
11    pub rgb_offsets: [usize; 3],
12    /// Optional byte offset of alpha from each pixel origin.
13    pub alpha_offset: Option<usize>,
14}
15
16/// Logical pixel channel queried by a Rust-defined native descriptor.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum ImageDescChannel {
19    Red,
20    Green,
21    Blue,
22    Alpha,
23}
24
25/// Implements OCIO's virtual image descriptor getters in Rust.
26///
27/// For ordinary pixel buffers, prefer the checked fixed-layout constructors
28/// on [NativeImageDesc].
29///
30/// # Safety
31/// Getters must describe one coherent, valid layout for an entire native
32/// operation, including repeated queries. RGB pointers must be non-null;
33/// alpha may be null. Pixels must be initialized, aligned, correctly typed,
34/// writable, and exclusively accessible to the operation. Pointer provenance
35/// must permit writes; pointers derived from shared references to pixel
36/// storage without interior mutability are not sufficient.
37///
38/// Dimensions, strides, and storage must permit native index arithmetic and
39/// pointer stepping, including steps past the final sample. Source and
40/// destination may not overlap when used for conversion. True packed and
41/// float predicates must satisfy OCIO's corresponding fast-path contracts.
42/// Getters must not reenter or destroy the descriptor.
43pub unsafe trait ImageDescProvider {
44    /// Address of this channel at the first logical pixel.
45    fn channel_data(&self, channel: ImageDescChannel) -> *mut c_void;
46    fn width(&self) -> i64;
47    fn height(&self) -> i64;
48    fn x_stride_bytes(&self) -> isize;
49    fn y_stride_bytes(&self) -> isize;
50    fn bit_depth(&self) -> crate::BitDepth;
51
52    /// True only for tightly ordered RGBA storage as defined by OCIO.
53    fn is_rgba_packed(&self) -> bool {
54        false
55    }
56
57    fn is_float(&self) -> bool {
58        self.bit_depth() == crate::BitDepth::F32
59    }
60}
61
62unsafe extern "C" fn query_image_desc<P: ImageDescProvider>(
63    context: *const c_void,
64    query: ocio_sys::OcioImageDescQuery,
65    out: *mut ocio_sys::OcioImageDescValue,
66) -> bool {
67    use ocio_sys::OcioImageDescQuery::*;
68    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
69        let provider = unsafe { &*context.cast::<P>() };
70        let out = unsafe { &mut *out };
71        let channel = match query {
72            Red => ImageDescChannel::Red,
73            Green => ImageDescChannel::Green,
74            Blue => ImageDescChannel::Blue,
75            Alpha => ImageDescChannel::Alpha,
76            other => {
77                out.scalar = match other {
78                    Width => provider.width(),
79                    Height => provider.height(),
80                    XStride => provider.x_stride_bytes() as i64,
81                    YStride => provider.y_stride_bytes() as i64,
82                    BitDepth => i64::from(provider.bit_depth() as i32),
83                    Packed => i64::from(provider.is_rgba_packed()),
84                    Float => i64::from(provider.is_float()),
85                    _ => unreachable!(),
86                };
87                return;
88            }
89        };
90        out.pointer = provider.channel_data(channel);
91    }));
92    match result {
93        Ok(()) => true,
94        Err(payload) => {
95            crate::discard_callback_panic(payload);
96            false
97        }
98    }
99}
100
101unsafe extern "C" fn release_image_desc<P: ImageDescProvider>(context: *mut c_void) {
102    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
103        drop(unsafe { Box::from_raw(context.cast::<P>()) });
104    }));
105    if let Err(payload) = result {
106        crate::discard_callback_panic(payload);
107    }
108}
109
110/// An owned OCIO descriptor with exclusive access to its pixel storage.
111/// Fixed-layout descriptors do not own their pixels. Callback descriptors
112/// own their Rust provider, which may itself own or borrow the storage.
113///
114/// For ordinary CPU processing, prefer the slice-based processor methods:
115/// they accept unpadded layouts that need special tail handling.
116///
117/// ```compile_fail
118/// use ocio_rs::{NativeImageDesc, PackedImageLayout};
119/// fn modify_while_borrowed(data: &mut [u8], layout: PackedImageLayout) {
120///     let image = NativeImageDesc::packed(data, layout).unwrap();
121///     data[0] = 0;
122///     drop(image);
123/// }
124/// ```
125pub struct NativeImageDesc<'a> {
126    handle: NonNull<c_void>,
127    _data: PhantomData<&'a mut [u8]>,
128}
129
130impl<'a> NativeImageDesc<'a> {
131    /// Create a native descriptor that owns a Rust virtual getter provider.
132    ///
133    /// OCIO queries the provider for descriptor data, not once per pixel.
134    /// A panicking getter aborts that native operation with an error. A
135    /// provider destructor cannot unwind through the native bridge.
136    pub fn from_provider<P: ImageDescProvider + 'a>(provider: P) -> crate::Result<Self> {
137        let context = Box::into_raw(Box::new(provider));
138        crate::clear_last_error();
139        let handle = unsafe {
140            ocio_sys::ocio_image_desc_create_callback(
141                context.cast(),
142                query_image_desc::<P>,
143                release_image_desc::<P>,
144            )
145        };
146        let result = Self::from_created_handle(handle);
147        if handle.is_null() {
148            // Native ownership transfers only on successful construction.
149            drop(unsafe { Box::from_raw(context) });
150        }
151        result
152    }
153
154    /// Construct a native packed descriptor from a checked byte layout.
155    /// Layouts requiring a separate tail are rejected.
156    pub fn packed(data: &'a mut [u8], layout: crate::PackedImageLayout) -> crate::Result<Self> {
157        let (mut raw, split) = crate::processor::packed_image_samples(layout, data)?;
158        Self::require_native_layout(split)?;
159        raw.data = data.as_mut_ptr().wrapping_add(layout.origin).cast();
160        crate::clear_last_error();
161        let handle = unsafe { ocio_sys::ocio_image_desc_create_packed(&raw) };
162        Self::from_created_handle(handle)
163    }
164
165    /// Construct a native planar descriptor from checked channel slices.
166    /// Layouts requiring a separate tail are rejected.
167    pub fn planar(mut image: crate::SignedPlanarBytesMut<'a>) -> crate::Result<Self> {
168        let (raw, split) = crate::processor::signed_planar_destination(&mut image)?;
169        Self::require_native_layout(split)?;
170        crate::clear_last_error();
171        let handle = unsafe { ocio_sys::ocio_image_desc_create_planar(&raw) };
172        Self::from_created_handle(handle)
173    }
174
175    /// Construct an OCIO custom descriptor with irregular channel placement.
176    ///
177    /// Offsets must be distinct, sample-aligned and fit within the absolute
178    /// pixel stride. This uses OCIO's generic packing path, so any required
179    /// pointer-step padding must be present in the slice.
180    pub fn custom(data: &'a mut [u8], layout: CustomImageLayout) -> crate::Result<Self> {
181        let base = layout.layout;
182        let size = crate::processor::bit_depth_bytes_per_channel(
183            "NativeImageDesc::custom",
184            base.bit_depth,
185        )?;
186        let invalid =
187            || crate::OcioError::InvalidInput("invalid custom image channel offsets".into());
188        let offsets = layout.rgb_offsets;
189        let offsets = [
190            Some(offsets[0]),
191            Some(offsets[1]),
192            Some(offsets[2]),
193            layout.alpha_offset,
194        ];
195        let pixel_stride = base.x_stride.unsigned_abs();
196        let mut origins = [None; 4];
197        let mut dimensions = [0; 4];
198        for (index, offset) in offsets.into_iter().enumerate() {
199            let Some(offset) = offset else { continue };
200            if !offset.is_multiple_of(size)
201                || offset
202                    .checked_add(size)
203                    .is_none_or(|end| end > pixel_stride)
204                || offsets[..index].contains(&Some(offset))
205            {
206                return Err(invalid());
207            }
208            let origin = base.origin.checked_add(offset).ok_or_else(invalid)?;
209            let (dims, split) = crate::processor::validate_signed_planar_samples(
210                crate::SignedPlanarByteLayout { origin, ..base },
211                &[data],
212            )?;
213            Self::require_native_layout(split)?;
214            dimensions = dims;
215            origins[index] = Some(origin);
216        }
217        let ptr = data.as_mut_ptr();
218        let [red, green, blue, alpha] = origins.map(|origin| {
219            origin.map_or(std::ptr::null_mut(), |origin| {
220                ptr.wrapping_add(origin).cast()
221            })
222        });
223        let [width, height, x_stride, y_stride] = dimensions;
224        let raw = ocio_sys::OcioPlanarBuffer {
225            red,
226            green,
227            blue,
228            alpha,
229            width,
230            height,
231            x_stride,
232            y_stride,
233            bit_depth: base.bit_depth as i32,
234        };
235        crate::clear_last_error();
236        let handle = unsafe { ocio_sys::ocio_image_desc_create_custom(&raw) };
237        Self::from_created_handle(handle)
238    }
239
240    fn require_native_layout(split: bool) -> crate::Result<()> {
241        if split {
242            Err(crate::OcioError::InvalidInput(
243                "image needs native pointer-step padding; use a slice-based processor method"
244                    .into(),
245            ))
246        } else {
247            Ok(())
248        }
249    }
250
251    fn from_created_handle(handle: *mut c_void) -> crate::Result<Self> {
252        Ok(Self {
253            handle: crate::handle_result(handle)?,
254            _data: PhantomData,
255        })
256    }
257
258    /// Query the native descriptor without accessing pixel contents.
259    pub fn info(&self) -> crate::Result<NativeImageDescInfo> {
260        unsafe { NativeImageDescInfo::inspect(self.handle.as_ptr()) }
261    }
262
263    /// Get the native first-pixel pointers for raw buffer interop.
264    /// The pointers do not grant access beyond the original buffer borrows.
265    pub fn data_ptrs(&mut self) -> crate::Result<NativeImageDataPointers> {
266        unsafe { NativeImageDataPointers::inspect(self.handle.as_ptr()) }
267    }
268
269    /// Format the descriptor using OCIO's stream operator.
270    /// This includes buffer addresses; it is not serialization.
271    pub fn diagnostic_text(&self) -> crate::Result<String> {
272        unsafe { Self::diagnostic_text_from_ptr(self.handle.as_ptr()) }
273    }
274
275    /// Format an externally owned descriptor using OCIO's stream operator.
276    /// The diagnostic contains buffer addresses; avoid logging it publicly.
277    ///
278    /// # Safety
279    /// Except for null, which returns an error, `image` must point to a live
280    /// OCIO `ImageDesc` base compiled for the active ABI. Its getters must be
281    /// callable and may not race with mutation or destruction.
282    pub unsafe fn diagnostic_text_from_ptr(image: *const c_void) -> crate::Result<String> {
283        crate::clear_last_error();
284        let text = unsafe { ocio_sys::ocio_image_desc_diagnostic_text(image) };
285        crate::ocio_call_status()?;
286        unsafe { crate::cstr_to_opt_string(text.cast()) }
287            .ok_or_else(|| crate::OcioError::Ocio("null image descriptor diagnostic text".into()))
288    }
289
290    /// Return the borrowed native `ImageDesc` base pointer for C++ interop.
291    /// Do not retain or destroy it. Any use must respect the descriptor and
292    /// pixel buffer lifetimes and the native API's preconditions.
293    pub fn as_mut_ptr(&mut self) -> *mut c_void {
294        self.handle.as_ptr()
295    }
296}
297
298impl Drop for NativeImageDesc<'_> {
299    fn drop(&mut self) {
300        unsafe { ocio_sys::ocio_image_desc_destroy(self.handle.as_ptr()) }
301    }
302}
303
304/// First-pixel addresses returned by OCIO without reading pixel contents.
305///
306/// These are raw pointers, not Rust references. In particular, they do not
307/// establish buffer bounds, validity, lifetime, or exclusivity.
308#[derive(Debug, Clone, Copy, PartialEq, Eq)]
309pub struct NativeImageDataPointers {
310    pub red: *mut c_void,
311    pub green: *mut c_void,
312    pub blue: *mut c_void,
313    /// Null when no alpha channel is present.
314    pub alpha: *mut c_void,
315    /// First channel in storage order, or null for a non-packed descriptor.
316    pub packed: *mut c_void,
317}
318
319impl NativeImageDataPointers {
320    /// Query the native channel and packed-data getters.
321    ///
322    /// # Safety
323    /// Except for null, which returns an error, `image` must point to a live
324    /// OCIO `ImageDesc` base compiled for the active ABI. Its getters must be
325    /// callable and may not race with mutation or destruction.
326    pub unsafe fn inspect(image: *const c_void) -> crate::Result<Self> {
327        let mut raw = ocio_sys::OcioImageDescPointers::default();
328        crate::clear_last_error();
329        unsafe { ocio_sys::ocio_image_desc_pointers(image, &mut raw) };
330        crate::ocio_call_status()?;
331        Ok(Self {
332            red: raw.red,
333            green: raw.green,
334            blue: raw.blue,
335            alpha: raw.alpha,
336            packed: raw.packed,
337        })
338    }
339}
340
341/// Concrete layout of an existing OCIO image descriptor.
342#[derive(Debug, Clone, Copy, PartialEq, Eq)]
343pub enum NativeImageLayout {
344    Packed {
345        /// Native discriminant corresponding to [`crate::ChannelOrdering`].
346        channel_order: i32,
347        channels: i64,
348        channel_stride_bytes: i64,
349    },
350    Planar,
351    Custom,
352}
353
354/// Snapshot of a native image descriptor. This does not expose buffer
355/// addresses or certify that the descriptor is safe to process.
356#[derive(Debug, Clone, Copy, PartialEq, Eq)]
357pub struct NativeImageDescInfo {
358    pub width: i64,
359    pub height: i64,
360    pub x_stride_bytes: i64,
361    pub y_stride_bytes: i64,
362    /// Native discriminant corresponding to [`crate::BitDepth`].
363    pub bit_depth: i32,
364    pub has_alpha: bool,
365    /// OCIO's tight-RGBA predicate, not a test for the packed descriptor class.
366    pub is_rgba_packed: bool,
367    /// OCIO's 32-bit-float predicate.
368    pub is_float: bool,
369    pub layout: NativeImageLayout,
370}
371
372impl NativeImageDescInfo {
373    /// Query metadata from a C++-owned descriptor without transferring ownership.
374    /// No pixels are read by this binding.
375    ///
376    /// # Safety
377    /// Except for null, which returns an error, `image` must point to a live
378    /// OCIO `ImageDesc` base compiled for the active ABI. Its getters must be
379    /// callable for the duration of this operation and may not race with
380    /// mutation or destruction. For custom implementations this includes any
381    /// state the virtual getters access.
382    pub unsafe fn inspect(image: *const c_void) -> crate::Result<Self> {
383        let mut raw = ocio_sys::OcioImageDescInfo::default();
384        crate::clear_last_error();
385        unsafe { ocio_sys::ocio_image_desc_info(image, &mut raw) };
386        crate::ocio_call_status()?;
387        let layout = if raw.is_packed {
388            NativeImageLayout::Packed {
389                channel_order: raw.channel_order,
390                channels: raw.num_channels,
391                channel_stride_bytes: raw.channel_stride,
392            }
393        } else if raw.is_planar {
394            NativeImageLayout::Planar
395        } else {
396            NativeImageLayout::Custom
397        };
398        Ok(Self {
399            width: raw.width,
400            height: raw.height,
401            x_stride_bytes: raw.x_stride,
402            y_stride_bytes: raw.y_stride,
403            bit_depth: raw.bit_depth,
404            has_alpha: raw.has_alpha,
405            is_rgba_packed: raw.is_rgba_packed,
406            is_float: raw.is_float,
407            layout,
408        })
409    }
410}