Skip to main content

ocio_rs/transform/
mod.rs

1//! OCIO transform wrappers.
2//!
3//! Each struct in this module wraps a single OpenColorIO transform type
4//! (e.g. [`ColorSpaceTransform`], [`GradingRGBCurveTransform`]) and exposes
5//! safe Rust accessors for its properties.
6//!
7//! All transform types follow a consistent pattern:
8//!
9//! - **Constructor**: [`create`](std::result::Result) returns `Result<Self>`.
10//! - **Getters**: Return the current property value (often infallible).
11//! - **Setters**: Legacy void setters panic on error; checked `try_*` variants
12//!   return `Result<()>` and surface OCIO validation errors.
13//! - **Direction**: Every transform that supports forward/inverse evaluation
14//!   provides `direction()` / `try_set_direction()`. Import [`TransformHandle`]
15//!   for the shared fallible `try_direction()` query on editable transforms.
16//! - **Editable copy**: Native copy semantics apply. In particular, copying a
17//!   [`GroupTransform`] copies its container but keeps its children shared;
18//!   use [`GroupTransform::create_deep_copy`] for an independent built-in graph.
19
20mod allocation;
21mod builtin;
22mod cdl;
23mod color_space;
24mod display_view;
25mod exponent;
26mod exponent_with_linear;
27mod exposure_contrast;
28mod file;
29mod fixed_function;
30#[cfg(feature = "v2_5")]
31mod grading_hue_curve;
32mod grading_primary;
33mod grading_rgb_curve;
34mod grading_tone;
35mod group;
36mod log;
37mod log_affine;
38mod log_camera;
39mod look_transform;
40mod lut1d;
41mod lut3d;
42mod matrix;
43mod range;
44
45use std::ffi::c_void;
46use std::ptr::NonNull;
47
48use ocio_sys;
49
50fn transform_diagnostic_text(handle: *mut c_void, is_const: bool) -> crate::Result<String> {
51    crate::clear_last_error();
52    let ptr = unsafe { ocio_sys::ocio_transform_diagnostic_text(handle, is_const) };
53    crate::ocio_call_status()?;
54    unsafe { crate::cstr_to_opt_string(ptr) }
55        .ok_or_else(|| crate::OcioError::Ocio("null transform diagnostic text".into()))
56}
57
58/// Shared immutable native transform, which can be processed without copying.
59pub struct ConstTransform {
60    pub(crate) handle: NonNull<c_void>,
61}
62impl ConstTransform {
63    /// Count children of a native group without copying it. A non-group
64    /// transform returns an error.
65    pub fn group_child_count(&self) -> crate::Result<i32> {
66        crate::clear_last_error();
67        let count =
68            unsafe { ocio_sys::ocio_const_transform_group_child_count(self.handle.as_ptr()) };
69        crate::ocio_call_status()?;
70        Ok(count)
71    }
72
73    /// Retain one native group child without copying the group or transform.
74    /// Invalid indices and non-group handles return errors. The returned
75    /// child can outlive the group.
76    pub fn group_child(&self, index: i32) -> crate::Result<Option<Self>> {
77        Self::from_parent(self.handle.as_ptr(), 12, index)
78    }
79
80    /// Return OCIO's diagnostic representation, which may include file paths.
81    /// This text is not a stable interchange format.
82    pub fn diagnostic_text(&self) -> crate::Result<String> {
83        transform_diagnostic_text(self.handle.as_ptr(), true)
84    }
85    pub(crate) fn from_parent(
86        parent: *mut c_void,
87        kind: i32,
88        direction: i32,
89    ) -> crate::Result<Option<Self>> {
90        crate::clear_last_error();
91        let handle = unsafe { ocio_sys::ocio_get_const_child_transform(parent, kind, direction) };
92        crate::ocio_call_status()?;
93        Ok(NonNull::new(handle).map(|handle| Self { handle }))
94    }
95    /// Version-independent discriminant corresponding to [`crate::TransformType`].
96    pub fn type_tag(&self) -> crate::Result<i32> {
97        crate::clear_last_error();
98        let result = unsafe { ocio_sys::ocio_const_transform_get_type(self.handle.as_ptr()) };
99        crate::ocio_call_status()?;
100        Ok(result)
101    }
102    /// Query the native direction, rejecting unrecognized values.
103    pub fn try_direction(&self) -> crate::Result<crate::TransformDirection> {
104        crate::clear_last_error();
105        let raw = unsafe { ocio_sys::ocio_const_transform_get_direction(self.handle.as_ptr()) };
106        crate::ocio_call_status()?;
107        direction_from_raw(raw)
108    }
109    /// Validate this transform using OCIO without creating an editable copy.
110    ///
111    /// This checks the transform's parameters; it does not build a processor
112    /// or resolve external files.
113    pub fn validate(&self) -> crate::Result<()> {
114        crate::clear_last_error();
115        unsafe { ocio_sys::ocio_const_transform_validate(self.handle.as_ptr()) };
116        crate::ocio_call_status()
117    }
118
119    /// Create an editable copy using the concrete transform's native semantics.
120    /// A copied group shares its children with the original. For an independent
121    /// built-in group graph, use [`GroupTransform::create_deep_copy`].
122    pub fn create_editable_copy(&self) -> crate::Result<Transform> {
123        crate::clear_last_error();
124        let handle =
125            unsafe { ocio_sys::ocio_const_transform_create_editable_copy(self.handle.as_ptr()) };
126        crate::ocio_call_status()?;
127        transform_from_raw_handle(handle)
128            .ok_or_else(|| crate::OcioError::Ocio("unsupported or null transform copy".into()))
129    }
130
131    /// Access existing low-level getters without copying the native transform.
132    ///
133    /// This creates a temporary typed FFI handle sharing the same native
134    /// object; it is destroyed when `read` returns or unwinds. Use `type_tag`
135    /// to select getters for the concrete transform type. An unsupported or
136    /// inconsistent native type returns an error. Errors from FFI calls inside
137    /// `read` must be handled by the callback itself.
138    ///
139    /// # Safety
140    /// Call only FFI operations corresponding to native `const` methods. Do
141    /// not mutate the transform or its descendants, and do not access mutable
142    /// aliases concurrently. The handle, descendant handles and any pointers
143    /// or references derived from them must not escape `read`. Native getters
144    /// may have additional pointer, buffer, and synchronization requirements.
145    /// In particular, `ocio_transform_get_format_metadata` selects the native
146    /// mutable overload; use [`Self::with_readonly_metadata`] instead.
147    pub unsafe fn with_readonly_raw_handle<R>(
148        &self,
149        read: impl FnOnce(*mut c_void) -> R,
150    ) -> crate::Result<R> {
151        struct RawHandle(NonNull<c_void>);
152        impl Drop for RawHandle {
153            fn drop(&mut self) {
154                unsafe { ocio_sys::ocio_transform_destroy(self.0.as_ptr()) }
155            }
156        }
157
158        crate::clear_last_error();
159        let handle =
160            unsafe { ocio_sys::ocio_const_transform_create_readonly_handle(self.handle.as_ptr()) };
161        let handle = RawHandle(crate::handle_result(handle)?);
162        Ok(read(handle.0.as_ptr()))
163    }
164
165    /// Inspect native const metadata without copying the transform or metadata.
166    /// The callback receives `None` for transform types without metadata.
167    ///
168    /// # Safety
169    /// Do not mutate this transform or its metadata through any alias while
170    /// `read` runs. Neither borrowed metadata nor any child handles, pointers,
171    /// or references derived from it may escape the callback.
172    pub unsafe fn with_readonly_metadata<R>(
173        &self,
174        read: impl FnOnce(Option<&crate::ConstFormatMetadata>) -> R,
175    ) -> crate::Result<R> {
176        crate::clear_last_error();
177        let handle =
178            unsafe { ocio_sys::ocio_const_transform_get_const_metadata(self.handle.as_ptr()) };
179        crate::ocio_call_status()?;
180        let metadata = NonNull::new(handle).map(|handle| crate::ConstFormatMetadata { handle });
181        Ok(read(metadata.as_ref()))
182    }
183}
184impl Drop for ConstTransform {
185    fn drop(&mut self) {
186        unsafe { ocio_sys::ocio_const_transform_destroy(self.handle.as_ptr()) }
187    }
188}
189
190pub use allocation::AllocationTransform;
191pub use builtin::BuiltinTransform;
192pub use cdl::CDLTransform;
193pub use color_space::ColorSpaceTransform;
194pub use display_view::DisplayViewTransform;
195pub use exponent::ExponentTransform;
196pub use exponent_with_linear::ExponentWithLinearTransform;
197pub use exposure_contrast::ExposureContrastTransform;
198pub use file::FileTransform;
199pub use fixed_function::FixedFunctionTransform;
200#[cfg(feature = "v2_5")]
201pub use grading_hue_curve::GradingHueCurveTransform;
202pub use grading_primary::GradingPrimaryTransform;
203pub use grading_rgb_curve::GradingRGBCurveTransform;
204pub use grading_tone::GradingToneTransform;
205pub use group::GroupTransform;
206pub use log::LogTransform;
207pub use log_affine::LogAffineTransform;
208pub use log_camera::LogCameraTransform;
209pub use look_transform::LookTransform;
210pub use lut1d::Lut1DTransform;
211pub use lut3d::Lut3DTransform;
212pub use matrix::MatrixTransform;
213pub use range::RangeTransform;
214
215mod sealed {
216    pub trait Sealed {}
217}
218
219macro_rules! seal_transform_handles {
220    ($($ty:ty),+ $(,)?) => { $(impl sealed::Sealed for $ty {})+ };
221}
222seal_transform_handles!(
223    FileTransform,
224    CDLTransform,
225    ExponentTransform,
226    ExponentWithLinearTransform,
227    MatrixTransform,
228    LogTransform,
229    RangeTransform,
230    GroupTransform,
231    BuiltinTransform,
232    FixedFunctionTransform,
233    Lut1DTransform,
234    Lut3DTransform,
235    ExposureContrastTransform,
236    ColorSpaceTransform,
237    LookTransform,
238    DisplayViewTransform,
239    AllocationTransform,
240    LogAffineTransform,
241    LogCameraTransform,
242    GradingRGBCurveTransform,
243    GradingPrimaryTransform,
244    GradingToneTransform,
245    Transform,
246);
247#[cfg(feature = "v2_5")]
248seal_transform_handles!(GradingHueCurveTransform);
249
250fn direction_from_raw(raw: i32) -> crate::Result<crate::TransformDirection> {
251    match raw {
252        0 => Ok(crate::TransformDirection::Forward),
253        1 => Ok(crate::TransformDirection::Inverse),
254        _ => Err(crate::OcioError::ValidationFailed(format!(
255            "unknown OCIO transform direction {raw}"
256        ))),
257    }
258}
259
260pub(crate) fn checked_native_count(count: i32, operation: &'static str) -> crate::Result<usize> {
261    usize::try_from(count).map_err(|_| {
262        crate::OcioError::ValidationFailed(format!("{operation}: negative native count {count}"))
263    })
264}
265
266pub(crate) fn checked_curve_count(count: usize) -> crate::Result<i32> {
267    i32::try_from(count)
268        .map_err(|_| crate::OcioError::InvalidInput("too many control points".into()))
269}
270
271pub(crate) fn reserve_native_items<T>(
272    count: usize,
273    operation: &'static str,
274) -> crate::Result<Vec<T>> {
275    let mut result = Vec::new();
276    result.try_reserve_exact(count).map_err(|error| {
277        crate::OcioError::ValidationFailed(format!(
278            "{operation}: cannot allocate {count} items: {error}"
279        ))
280    })?;
281    Ok(result)
282}
283
284#[cfg(test)]
285#[test]
286fn direction_conversion_rejects_unrecognized_native_values() {
287    assert_eq!(
288        direction_from_raw(0).unwrap(),
289        crate::TransformDirection::Forward
290    );
291    assert_eq!(
292        direction_from_raw(1).unwrap(),
293        crate::TransformDirection::Inverse
294    );
295    assert!(direction_from_raw(-1).is_err());
296    assert!(direction_from_raw(2).is_err());
297}
298
299#[cfg(test)]
300#[test]
301fn native_collection_count_validation_rejects_negative_and_capacity_overflow() {
302    assert!(checked_native_count(-1, "test").is_err());
303    assert_eq!(checked_native_count(0, "test").unwrap(), 0);
304    assert!(reserve_native_items::<u64>(usize::MAX, "test").is_err());
305    assert_eq!(checked_curve_count(i32::MAX as usize).unwrap(), i32::MAX);
306    assert!(checked_curve_count(i32::MAX as usize + 1).is_err());
307}
308
309/// A native transform handle supplied by this crate.
310///
311/// This trait is sealed: arbitrary raw pointers cannot satisfy the internal
312/// bridge ownership and type invariants. Use the built-in transform wrappers or
313/// [`Transform`] in generic code.
314///
315/// ```compile_fail
316/// use ocio_rs::transform::TransformHandle;
317/// struct Forged;
318/// impl TransformHandle for Forged {
319///     fn as_ptr(&self) -> *mut std::ffi::c_void { std::ptr::null_mut() }
320/// }
321/// ```
322pub trait TransformHandle: sealed::Sealed {
323    fn as_ptr(&self) -> *mut c_void;
324
325    /// Return OCIO's diagnostic representation, which may include file paths.
326    /// This text is not a stable interchange format.
327    fn diagnostic_text(&self) -> crate::Result<String> {
328        transform_diagnostic_text(self.as_ptr(), false)
329    }
330
331    /// Return the version-independent tag corresponding to [`crate::TransformType`].
332    fn try_type_tag(&self) -> crate::Result<i32> {
333        let tag = unsafe { ocio_sys::ocio_transform_get_transform_type(self.as_ptr()) };
334        if tag < 0 {
335            Err(crate::OcioError::Ocio(
336                "native transform type unavailable".into(),
337            ))
338        } else {
339            Ok(tag)
340        }
341    }
342
343    /// Change the native evaluation direction without modifying the stored parameters.
344    fn try_set_direction(&mut self, direction: crate::TransformDirection) -> crate::Result<()> {
345        crate::clear_last_error();
346        unsafe { ocio_sys::ocio_transform_set_direction(self.as_ptr(), direction as i32) };
347        crate::ocio_call_status()
348    }
349
350    /// Validate the native transform without copying it or building a processor.
351    fn try_validate(&self) -> crate::Result<()> {
352        crate::clear_last_error();
353        unsafe { ocio_sys::ocio_transform_validate(self.as_ptr()) };
354        crate::ocio_call_status()
355    }
356
357    /// Create a native editable copy, preserving the concrete transform type.
358    /// A copied group shares its children with the original. For an independent
359    /// built-in group graph, use [`GroupTransform::create_deep_copy`].
360    fn try_create_editable_copy(&self) -> crate::Result<Transform> {
361        crate::clear_last_error();
362        let handle = unsafe { ocio_sys::ocio_transform_create_editable_copy(self.as_ptr()) };
363        crate::ocio_call_status()?;
364        transform_from_raw_handle(handle)
365            .ok_or_else(|| crate::OcioError::Ocio("unsupported or null transform copy".into()))
366    }
367
368    /// Query the native direction with validation, for any supported transform.
369    fn try_direction(&self) -> crate::Result<crate::TransformDirection> {
370        crate::clear_last_error();
371        let raw = unsafe { ocio_sys::ocio_transform_get_direction(self.as_ptr()) };
372        crate::ocio_call_status()?;
373        direction_from_raw(raw)
374    }
375}
376
377impl TransformHandle for FileTransform {
378    fn as_ptr(&self) -> *mut c_void {
379        self.handle.as_ptr()
380    }
381}
382impl TransformHandle for CDLTransform {
383    fn as_ptr(&self) -> *mut c_void {
384        self.handle.as_ptr()
385    }
386}
387impl TransformHandle for ExponentTransform {
388    fn as_ptr(&self) -> *mut c_void {
389        self.handle.as_ptr()
390    }
391}
392impl TransformHandle for ExponentWithLinearTransform {
393    fn as_ptr(&self) -> *mut c_void {
394        self.handle.as_ptr()
395    }
396}
397impl TransformHandle for MatrixTransform {
398    fn as_ptr(&self) -> *mut c_void {
399        self.handle.as_ptr()
400    }
401}
402impl TransformHandle for LogTransform {
403    fn as_ptr(&self) -> *mut c_void {
404        self.handle.as_ptr()
405    }
406}
407impl TransformHandle for RangeTransform {
408    fn as_ptr(&self) -> *mut c_void {
409        self.handle.as_ptr()
410    }
411}
412impl TransformHandle for GroupTransform {
413    fn as_ptr(&self) -> *mut c_void {
414        self.handle.as_ptr()
415    }
416}
417impl TransformHandle for BuiltinTransform {
418    fn as_ptr(&self) -> *mut c_void {
419        self.handle.as_ptr()
420    }
421}
422impl TransformHandle for FixedFunctionTransform {
423    fn as_ptr(&self) -> *mut c_void {
424        self.handle.as_ptr()
425    }
426}
427impl TransformHandle for Lut1DTransform {
428    fn as_ptr(&self) -> *mut c_void {
429        self.handle.as_ptr()
430    }
431}
432impl TransformHandle for Lut3DTransform {
433    fn as_ptr(&self) -> *mut c_void {
434        self.handle.as_ptr()
435    }
436}
437impl TransformHandle for ExposureContrastTransform {
438    fn as_ptr(&self) -> *mut c_void {
439        self.handle.as_ptr()
440    }
441}
442impl TransformHandle for ColorSpaceTransform {
443    fn as_ptr(&self) -> *mut c_void {
444        self.handle.as_ptr()
445    }
446}
447impl TransformHandle for LookTransform {
448    fn as_ptr(&self) -> *mut c_void {
449        self.handle.as_ptr()
450    }
451}
452impl TransformHandle for DisplayViewTransform {
453    fn as_ptr(&self) -> *mut c_void {
454        self.handle.as_ptr()
455    }
456}
457impl TransformHandle for AllocationTransform {
458    fn as_ptr(&self) -> *mut c_void {
459        self.handle.as_ptr()
460    }
461}
462impl TransformHandle for LogAffineTransform {
463    fn as_ptr(&self) -> *mut c_void {
464        self.handle.as_ptr()
465    }
466}
467impl TransformHandle for LogCameraTransform {
468    fn as_ptr(&self) -> *mut c_void {
469        self.handle.as_ptr()
470    }
471}
472impl TransformHandle for GradingRGBCurveTransform {
473    fn as_ptr(&self) -> *mut c_void {
474        self.handle.as_ptr()
475    }
476}
477#[cfg(feature = "v2_5")]
478impl TransformHandle for GradingHueCurveTransform {
479    fn as_ptr(&self) -> *mut c_void {
480        self.handle.as_ptr()
481    }
482}
483impl TransformHandle for GradingPrimaryTransform {
484    fn as_ptr(&self) -> *mut c_void {
485        self.handle.as_ptr()
486    }
487}
488impl TransformHandle for GradingToneTransform {
489    fn as_ptr(&self) -> *mut c_void {
490        self.handle.as_ptr()
491    }
492}
493
494pub enum Transform {
495    File(FileTransform),
496    CDL(CDLTransform),
497    Exponent(ExponentTransform),
498    ExponentWithLinear(ExponentWithLinearTransform),
499    Matrix(MatrixTransform),
500    Log(LogTransform),
501    Range(RangeTransform),
502    Group(GroupTransform),
503    Builtin(BuiltinTransform),
504    FixedFunction(FixedFunctionTransform),
505    Lut1D(Lut1DTransform),
506    Lut3D(Lut3DTransform),
507    ExposureContrast(ExposureContrastTransform),
508    ColorSpace(ColorSpaceTransform),
509    Look(LookTransform),
510    DisplayView(DisplayViewTransform),
511    Allocation(AllocationTransform),
512    LogAffine(LogAffineTransform),
513    LogCamera(LogCameraTransform),
514    GradingPrimary(GradingPrimaryTransform),
515    GradingRGBCurve(GradingRGBCurveTransform),
516    #[cfg(feature = "v2_5")]
517    GradingHueCurve(GradingHueCurveTransform),
518    GradingTone(GradingToneTransform),
519}
520
521impl TransformHandle for Transform {
522    fn as_ptr(&self) -> *mut c_void {
523        match self {
524            Transform::File(t) => t.as_ptr(),
525            Transform::CDL(t) => t.as_ptr(),
526            Transform::Exponent(t) => t.as_ptr(),
527            Transform::ExponentWithLinear(t) => t.as_ptr(),
528            Transform::Matrix(t) => t.as_ptr(),
529            Transform::Log(t) => t.as_ptr(),
530            Transform::Range(t) => t.as_ptr(),
531            Transform::Group(t) => t.as_ptr(),
532            Transform::Builtin(t) => t.as_ptr(),
533            Transform::FixedFunction(t) => t.as_ptr(),
534            Transform::Lut1D(t) => t.as_ptr(),
535            Transform::Lut3D(t) => t.as_ptr(),
536            Transform::ExposureContrast(t) => t.as_ptr(),
537            Transform::ColorSpace(t) => t.as_ptr(),
538            Transform::Look(t) => t.as_ptr(),
539            Transform::DisplayView(t) => t.as_ptr(),
540            Transform::Allocation(t) => t.as_ptr(),
541            Transform::LogAffine(t) => t.as_ptr(),
542            Transform::LogCamera(t) => t.as_ptr(),
543            Transform::GradingPrimary(t) => t.as_ptr(),
544            Transform::GradingRGBCurve(t) => t.as_ptr(),
545            #[cfg(feature = "v2_5")]
546            Transform::GradingHueCurve(t) => t.as_ptr(),
547            Transform::GradingTone(t) => t.as_ptr(),
548        }
549    }
550}
551
552/// Convert an owned bridge transform handle into its typed Rust wrapper.
553///
554/// Callers transfer ownership of `handle` to this function. Unknown future OCIO
555/// type tags are rejected after releasing the handle rather than leaking it.
556pub(crate) fn transform_from_raw_handle(handle: *mut c_void) -> Option<Transform> {
557    if handle.is_null() {
558        return None;
559    }
560    let type_tag = unsafe { ocio_sys::ocio_transform_get_transform_type(handle) };
561    let nn = NonNull::new(handle).unwrap();
562    match type_tag {
563        1 => Some(Transform::Builtin(BuiltinTransform { handle: nn })),
564        2 => Some(Transform::CDL(CDLTransform { handle: nn })),
565        5 => Some(Transform::Exponent(ExponentTransform { handle: nn })),
566        6 => Some(Transform::ExponentWithLinear(ExponentWithLinearTransform {
567            handle: nn,
568        })),
569        8 => Some(Transform::File(FileTransform { handle: nn })),
570        9 => Some(Transform::FixedFunction(FixedFunctionTransform {
571            handle: nn,
572        })),
573        14 => Some(Transform::Group(GroupTransform { handle: nn })),
574        17 => Some(Transform::Log(LogTransform { handle: nn })),
575        19 => Some(Transform::Lut1D(Lut1DTransform { handle: nn })),
576        20 => Some(Transform::Lut3D(Lut3DTransform { handle: nn })),
577        21 => Some(Transform::Matrix(MatrixTransform { handle: nn })),
578        22 => Some(Transform::Range(RangeTransform { handle: nn })),
579        7 => Some(Transform::ExposureContrast(ExposureContrastTransform {
580            handle: nn,
581        })),
582        3 => Some(Transform::ColorSpace(ColorSpaceTransform { handle: nn })),
583        18 => Some(Transform::Look(LookTransform { handle: nn })),
584        4 => Some(Transform::DisplayView(DisplayViewTransform { handle: nn })),
585        0 => Some(Transform::Allocation(AllocationTransform { handle: nn })),
586        15 => Some(Transform::LogAffine(LogAffineTransform { handle: nn })),
587        16 => Some(Transform::LogCamera(LogCameraTransform { handle: nn })),
588        11 => Some(Transform::GradingPrimary(GradingPrimaryTransform {
589            handle: nn,
590        })),
591        #[cfg(feature = "v2_5")]
592        10 => Some(Transform::GradingHueCurve(GradingHueCurveTransform {
593            handle: nn,
594        })),
595        12 => Some(Transform::GradingRGBCurve(GradingRGBCurveTransform {
596            handle: nn,
597        })),
598        13 => Some(Transform::GradingTone(GradingToneTransform { handle: nn })),
599        _ => {
600            unsafe { ocio_sys::ocio_transform_destroy(handle) };
601            None
602        }
603    }
604}