Skip to main content

ocio_rs/transform/
cdl.rs

1use std::ffi::c_void;
2use std::ptr::NonNull;
3
4use crate::{
5    cstr_from_mut, cstr_to_opt_string, cstring, transform::GroupTransform, CDLStyle, OcioError,
6    Result, TransformDirection,
7};
8use ocio_sys;
9
10/// ASC CDL slope/offset/power and saturation transform.
11///
12/// Fallible getters preserve native errors; compatibility getters retain their
13/// fallback values when a native query fails.
14pub struct CDLTransform {
15    pub(crate) handle: NonNull<c_void>,
16}
17
18impl CDLTransform {
19    /// Create a new empty CDL transform.
20    pub fn create() -> Result<Self> {
21        crate::clear_last_error();
22        let handle = unsafe { ocio_sys::ocio_cdl_transform_create() };
23        crate::handle_result(handle).map(|handle| Self { handle })
24    }
25
26    /// Create a CDL transform from a CCC file and optional id.
27    pub fn create_from_file(src: impl AsRef<str>, ccc_id: impl AsRef<str>) -> Result<Self> {
28        let src = cstring(src)?;
29        let ccc_id = cstring(ccc_id)?;
30        crate::clear_last_error();
31        let handle = unsafe {
32            ocio_sys::ocio_cdl_transform_create_from_file(
33                src.as_ptr().cast(),
34                ccc_id.as_ptr().cast(),
35            )
36        };
37        crate::handle_result(handle).map(|handle| Self { handle })
38    }
39
40    #[doc(hidden)]
41    #[deprecated(since = "0.2.0", note = "compat alias; prefer create_from_file()")]
42    pub fn from_file(src: impl AsRef<str>, ccc_id: impl AsRef<str>) -> Result<Self> {
43        let src = cstring(src)?;
44        let ccc_id = cstring(ccc_id)?;
45        crate::clear_last_error();
46        let handle = unsafe {
47            ocio_sys::ocio_cdl_transform_from_file(src.as_ptr().cast(), ccc_id.as_ptr().cast())
48        };
49        crate::handle_result(handle).map(|handle| Self { handle })
50    }
51
52    /// Create a group transform from a CCC file.
53    pub fn create_group_from_file(src: impl AsRef<str>) -> Result<GroupTransform> {
54        let src = cstring(src)?;
55        crate::clear_last_error();
56        let handle =
57            unsafe { ocio_sys::ocio_cdl_transform_create_group_from_file(src.as_ptr().cast()) };
58        crate::handle_result(handle).map(|handle| GroupTransform { handle })
59    }
60
61    /// Return the per-channel slope values.
62    pub fn try_slope(&self) -> Result<[f64; 3]> {
63        let mut rgb = [1.0f64; 3];
64        crate::clear_last_error();
65        unsafe {
66            ocio_sys::ocio_cdl_transform_get_slope(
67                self.handle.as_ptr(),
68                rgb.as_mut_ptr() as *mut c_void,
69            )
70        };
71        crate::ocio_call_status()?;
72        Ok(rgb)
73    }
74
75    /// Return the per-channel slope values.
76    pub fn slope(&self) -> [f64; 3] {
77        self.try_slope().unwrap_or([1.0, 1.0, 1.0])
78    }
79
80    /// Set the per-channel slope values.
81    pub fn set_slope(&self, rgb: &[f64; 3]) {
82        self.try_set_slope(rgb).expect("failed to set CDL slope");
83    }
84
85    /// Set slope values and surface any OCIO validation error.
86    pub fn try_set_slope(&self, rgb: &[f64; 3]) -> Result<()> {
87        crate::clear_last_error();
88        unsafe {
89            ocio_sys::ocio_cdl_transform_set_slope(
90                self.handle.as_ptr(),
91                rgb.as_ptr() as *mut c_void,
92            )
93        };
94        crate::ocio_call_status()
95    }
96
97    /// Return the per-channel offset values.
98    pub fn try_offset(&self) -> Result<[f64; 3]> {
99        let mut rgb = [0.0f64; 3];
100        crate::clear_last_error();
101        unsafe {
102            ocio_sys::ocio_cdl_transform_get_offset(
103                self.handle.as_ptr(),
104                rgb.as_mut_ptr() as *mut c_void,
105            )
106        };
107        crate::ocio_call_status()?;
108        Ok(rgb)
109    }
110
111    /// Return the per-channel offset values.
112    pub fn offset(&self) -> [f64; 3] {
113        self.try_offset().unwrap_or([0.0, 0.0, 0.0])
114    }
115
116    /// Set the per-channel offset values.
117    pub fn set_offset(&self, rgb: &[f64; 3]) {
118        self.try_set_offset(rgb).expect("failed to set CDL offset");
119    }
120
121    /// Set offset values and surface any OCIO validation error.
122    pub fn try_set_offset(&self, rgb: &[f64; 3]) -> Result<()> {
123        crate::clear_last_error();
124        unsafe {
125            ocio_sys::ocio_cdl_transform_set_offset(
126                self.handle.as_ptr(),
127                rgb.as_ptr() as *mut c_void,
128            )
129        };
130        crate::ocio_call_status()
131    }
132
133    /// Return the per-channel power values.
134    pub fn try_power_(&self) -> Result<[f64; 3]> {
135        let mut rgb = [1.0f64; 3];
136        crate::clear_last_error();
137        unsafe {
138            ocio_sys::ocio_cdl_transform_get_power(
139                self.handle.as_ptr(),
140                rgb.as_mut_ptr() as *mut c_void,
141            )
142        };
143        crate::ocio_call_status()?;
144        Ok(rgb)
145    }
146
147    /// Return the per-channel power values.
148    pub fn power_(&self) -> [f64; 3] {
149        self.try_power_().unwrap_or([1.0, 1.0, 1.0])
150    }
151
152    /// Set the per-channel power values.
153    pub fn set_power(&self, rgb: &[f64; 3]) {
154        self.try_set_power(rgb).expect("failed to set CDL power");
155    }
156
157    /// Set power values and surface any OCIO validation error.
158    pub fn try_set_power(&self, rgb: &[f64; 3]) -> Result<()> {
159        crate::clear_last_error();
160        unsafe {
161            ocio_sys::ocio_cdl_transform_set_power(
162                self.handle.as_ptr(),
163                rgb.as_ptr() as *mut c_void,
164            )
165        };
166        crate::ocio_call_status()
167    }
168
169    /// Return the saturation value.
170    pub fn try_sat(&self) -> Result<f64> {
171        crate::clear_last_error();
172        let v = unsafe { ocio_sys::ocio_cdl_transform_get_sat(self.handle.as_ptr()) };
173        crate::ocio_call_status()?;
174        Ok(v)
175    }
176
177    /// Return the saturation value.
178    pub fn sat(&self) -> f64 {
179        self.try_sat().unwrap_or(0.0)
180    }
181
182    /// Set the saturation value.
183    pub fn set_sat(&self, sat: f64) {
184        self.try_set_sat(sat).expect("failed to set CDL saturation");
185    }
186
187    /// Set saturation and surface any OCIO validation error.
188    pub fn try_set_sat(&self, sat: f64) -> Result<()> {
189        crate::clear_last_error();
190        unsafe { ocio_sys::ocio_cdl_transform_set_sat(self.handle.as_ptr(), sat) };
191        crate::ocio_call_status()
192    }
193
194    /// Return the luma coefficients used for saturation.
195    pub fn try_sat_luma_coefs(&self) -> Result<[f64; 3]> {
196        let mut rgb = [0.0f64; 3];
197        crate::clear_last_error();
198        unsafe {
199            ocio_sys::ocio_cdl_transform_get_sat_luma_coefs(
200                self.handle.as_ptr(),
201                rgb.as_mut_ptr() as *mut c_void,
202            );
203        }
204        crate::ocio_call_status()?;
205        Ok(rgb)
206    }
207
208    /// Return the luma coefficients used for saturation.
209    pub fn sat_luma_coefs(&self) -> [f64; 3] {
210        self.try_sat_luma_coefs().unwrap_or([0.0, 0.0, 0.0])
211    }
212
213    /// Return the current CDL style, or `Asc` if the query fails.
214    pub fn style(&self) -> CDLStyle {
215        let s = unsafe { ocio_sys::ocio_cdl_transform_get_style(self.handle.as_ptr()) };
216        match s {
217            1 => CDLStyle::NoClamp,
218            _ => CDLStyle::Asc,
219        }
220    }
221
222    /// Return the current CDL style, preserving native query errors.
223    pub fn try_style(&self) -> Result<CDLStyle> {
224        if cfg!(ocio_stub) {
225            return Err(OcioError::Ocio(
226                "CDL query requires native OpenColorIO".into(),
227            ));
228        }
229        crate::clear_last_error();
230        let value = unsafe { ocio_sys::ocio_cdl_transform_get_style(self.handle.as_ptr()) };
231        crate::ocio_call_status()?;
232        match value {
233            0 => Ok(CDLStyle::Asc),
234            1 => Ok(CDLStyle::NoClamp),
235            _ => Err(OcioError::Ocio(format!("unknown CDL style {value}"))),
236        }
237    }
238
239    /// Set the CDL style.
240    pub fn set_style(&self, style: CDLStyle) {
241        self.try_set_style(style).expect("failed to set CDL style");
242    }
243
244    /// Set the CDL style and surface any OCIO validation error.
245    pub fn try_set_style(&self, style: CDLStyle) -> Result<()> {
246        crate::clear_last_error();
247        unsafe { ocio_sys::ocio_cdl_transform_set_style(self.handle.as_ptr(), style as i32) };
248        crate::ocio_call_status()
249    }
250
251    /// Return the CDL transform id, or `None` if the query fails.
252    pub fn id(&self) -> Option<String> {
253        unsafe { cstr_from_mut(ocio_sys::ocio_cdl_transform_get_id(self.handle.as_ptr())) }
254    }
255
256    /// Return the CDL id, preserving native query errors.
257    pub fn try_id(&self) -> Result<Option<String>> {
258        if cfg!(ocio_stub) {
259            return Err(OcioError::Ocio(
260                "CDL query requires native OpenColorIO".into(),
261            ));
262        }
263        crate::clear_last_error();
264        let ptr = unsafe { ocio_sys::ocio_cdl_transform_get_id(self.handle.as_ptr()) };
265        crate::ocio_call_status()?;
266        Ok(unsafe { cstr_from_mut(ptr) })
267    }
268
269    /// Set the CDL transform id.
270    pub fn set_id(&self, id: impl AsRef<str>) -> Result<()> {
271        let id = cstring(id)?;
272        crate::clear_last_error();
273        unsafe { ocio_sys::ocio_cdl_transform_set_id(self.handle.as_ptr(), id.as_ptr().cast()) };
274        crate::ocio_call_status()
275    }
276
277    /// Return the transform direction.
278    pub fn direction(&self) -> TransformDirection {
279        let dir = unsafe { ocio_sys::ocio_cdl_transform_get_direction(self.handle.as_ptr()) };
280        match dir {
281            1 => TransformDirection::Inverse,
282            _ => TransformDirection::Forward,
283        }
284    }
285
286    /// Set the transform direction.
287    pub fn set_direction(&self, direction: TransformDirection) {
288        self.try_set_direction(direction)
289            .expect("failed to set CDL transform direction");
290    }
291
292    /// Set the transform direction and surface any OCIO validation error.
293    pub fn try_set_direction(&self, direction: TransformDirection) -> crate::Result<()> {
294        crate::clear_last_error();
295        unsafe {
296            ocio_sys::ocio_cdl_transform_set_direction(self.handle.as_ptr(), direction as i32);
297        }
298        crate::ocio_call_status()
299    }
300
301    /// Return the slope, offset, and power values as a 9-element array.
302    pub fn try_sop(&self) -> Result<[f64; 9]> {
303        let mut vec9 = [0.0f64; 9];
304        crate::clear_last_error();
305        unsafe {
306            ocio_sys::ocio_cdl_transform_get_sop(
307                self.handle.as_ptr(),
308                vec9.as_mut_ptr() as *mut c_void,
309            )
310        };
311        crate::ocio_call_status()?;
312        Ok(vec9)
313    }
314
315    /// Return the slope, offset, and power values as a 9-element array.
316    pub fn sop(&self) -> [f64; 9] {
317        self.try_sop().unwrap_or([0.0; 9])
318    }
319
320    /// Set the slope, offset, and power values from a 9-element array.
321    pub fn set_sop(&self, vec9: &[f64; 9]) {
322        self.try_set_sop(vec9).expect("failed to set CDL SOP");
323    }
324
325    /// Set slope, offset, and power in one call and surface any OCIO validation error.
326    pub fn try_set_sop(&self, vec9: &[f64; 9]) -> Result<()> {
327        crate::clear_last_error();
328        unsafe {
329            ocio_sys::ocio_cdl_transform_set_sop(self.handle.as_ptr(), vec9.as_ptr() as *mut c_void)
330        };
331        crate::ocio_call_status()
332    }
333
334    /// Return the first SOP description, or `None` if the query fails.
335    pub fn first_sop_description(&self) -> Option<String> {
336        unsafe {
337            cstr_from_mut(ocio_sys::ocio_cdl_transform_get_first_sop_description(
338                self.handle.as_ptr(),
339            ))
340        }
341    }
342
343    /// Return the first SOP description, preserving native query errors.
344    pub fn try_first_sop_description(&self) -> Result<Option<String>> {
345        if cfg!(ocio_stub) {
346            return Err(OcioError::Ocio(
347                "CDL query requires native OpenColorIO".into(),
348            ));
349        }
350        crate::clear_last_error();
351        let ptr =
352            unsafe { ocio_sys::ocio_cdl_transform_get_first_sop_description(self.handle.as_ptr()) };
353        crate::ocio_call_status()?;
354        Ok(unsafe { cstr_from_mut(ptr) })
355    }
356
357    /// Set the first SOP description.
358    pub fn set_first_sop_description(&self, desc: impl AsRef<str>) -> Result<()> {
359        let d = cstring(desc)?;
360        crate::clear_last_error();
361        unsafe {
362            ocio_sys::ocio_cdl_transform_set_first_sop_description(
363                self.handle.as_ptr(),
364                d.as_ptr().cast(),
365            )
366        };
367        crate::ocio_call_status()
368    }
369
370    /// Create an independent copy of this transform.
371    pub fn create_editable_copy(&self) -> Result<Self> {
372        crate::clear_last_error();
373        let handle = unsafe { ocio_sys::ocio_transform_create_editable_copy(self.handle.as_ptr()) };
374        crate::handle_result(handle).map(|handle| Self { handle })
375    }
376
377    /// Return format metadata attached to the transform, when available.
378    pub fn format_metadata(&self) -> Option<crate::FormatMetadata> {
379        let handle = unsafe { ocio_sys::ocio_transform_get_format_metadata(self.handle.as_ptr()) };
380        NonNull::new(handle).map(|h| crate::FormatMetadata { handle: h })
381    }
382
383    #[deprecated(since = "0.2.0", note = "compat alias; prefer format_metadata()")]
384    pub fn format_metadata_v1(&self) -> Option<crate::FormatMetadata> {
385        self.format_metadata()
386    }
387
388    #[deprecated(since = "0.2.0", note = "compat alias; prefer format_metadata()")]
389    pub fn format_metadata_v2(&self) -> Option<crate::FormatMetadata> {
390        self.format_metadata()
391    }
392
393    /// Return whether this transform is equivalent to `other`.
394    pub fn equals(&self, other: &Self) -> bool {
395        unsafe { ocio_sys::ocio_cdl_transform_equals(self.handle.as_ptr(), other.handle.as_ptr()) }
396    }
397}
398
399impl Drop for CDLTransform {
400    fn drop(&mut self) {
401        unsafe { ocio_sys::ocio_cdl_transform_destroy(self.handle.as_ptr()) };
402    }
403}
404
405#[cfg(test)]
406mod tests {
407    use super::*;
408
409    #[test]
410    #[cfg(ocio_stub)]
411    fn fallible_metadata_queries_require_native_backend() {
412        let cdl = CDLTransform::create().unwrap();
413        assert!(cdl.try_style().is_err());
414        assert!(cdl.try_id().is_err());
415        assert!(cdl.try_first_sop_description().is_err());
416    }
417
418    #[test]
419    fn create_cdl() {
420        let cdl = CDLTransform::create();
421        assert!(cdl.is_ok());
422    }
423
424    #[test]
425    fn slope_offset_power_no_crash() {
426        let cdl = CDLTransform::create().unwrap();
427        let _ = cdl.slope();
428        let _ = cdl.offset();
429        let _ = cdl.power_();
430        cdl.set_slope(&[1.2, 1.0, 0.9]);
431        cdl.set_offset(&[0.1, 0.0, -0.1]);
432        cdl.set_power(&[1.1, 1.0, 0.95]);
433    }
434
435    #[test]
436    fn saturation_no_crash() {
437        let cdl = CDLTransform::create().unwrap();
438        let _ = cdl.sat();
439        cdl.set_sat(1.5);
440    }
441
442    #[test]
443    fn style_no_crash() {
444        let cdl = CDLTransform::create().unwrap();
445        let _ = cdl.style();
446        cdl.set_style(CDLStyle::NoClamp);
447    }
448
449    #[test]
450    fn id_no_crash() {
451        let cdl = CDLTransform::create().unwrap();
452        let _ = cdl.id();
453        assert!(cdl.set_id("MyID").is_ok());
454    }
455
456    #[test]
457    fn sop_no_crash() {
458        let cdl = CDLTransform::create().unwrap();
459        let _ = cdl.sop();
460        cdl.set_sop(&[1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
461        let _ = cdl.first_sop_description();
462        assert!(cdl.set_first_sop_description("desc").is_ok());
463    }
464
465    #[test]
466    fn create_editable_copy_no_crash() {
467        let cdl = CDLTransform::create().unwrap();
468        let _ = cdl.create_editable_copy();
469    }
470
471    #[test]
472    fn format_metadata_no_crash() {
473        let cdl = CDLTransform::create().unwrap();
474        let _ = cdl.format_metadata();
475    }
476
477    #[test]
478    fn equals_no_crash() {
479        let a = CDLTransform::create().unwrap();
480        let b = CDLTransform::create().unwrap();
481        let _ = a.equals(&b);
482    }
483}