Skip to main content

ocio_rs/transform/
matrix.rs

1use std::ffi::c_void;
2use std::ptr::NonNull;
3
4use crate::{BitDepth, OcioError, Result, TransformDirection};
5use ocio_sys;
6
7/// A 4x4 matrix transform plus RGBA offset.
8///
9/// Matrix transforms are commonly used for channel scaling, saturation,
10/// luminance views, and fitted range remapping.
11pub struct MatrixTransform {
12    pub(crate) handle: NonNull<c_void>,
13}
14
15impl MatrixTransform {
16    /// Write OCIO's fitted matrix and offset into caller-owned arrays.
17    /// On error, the output arrays may have been partially modified by OCIO.
18    pub fn fit_into(
19        m: &mut [f64; 16],
20        o: &mut [f64; 4],
21        old_min: &[f64; 4],
22        old_max: &[f64; 4],
23        new_min: &[f64; 4],
24        new_max: &[f64; 4],
25    ) -> Result<()> {
26        crate::clear_last_error();
27        unsafe {
28            ocio_sys::ocio_matrix_transform_fit_into(
29                m.as_mut_ptr(),
30                o.as_mut_ptr(),
31                old_min.as_ptr(),
32                old_max.as_ptr(),
33                new_min.as_ptr(),
34                new_max.as_ptr(),
35            )
36        };
37        crate::ocio_call_status()
38    }
39
40    /// Write OCIO's saturation matrix and offset without creating a transform.
41    pub fn sat_into(m: &mut [f64; 16], o: &mut [f64; 4], sat: f64, luma: &[f64; 3]) -> Result<()> {
42        crate::clear_last_error();
43        unsafe {
44            ocio_sys::ocio_matrix_transform_sat_into(
45                m.as_mut_ptr(),
46                o.as_mut_ptr(),
47                sat,
48                luma.as_ptr(),
49            )
50        };
51        crate::ocio_call_status()
52    }
53
54    /// Write OCIO's channel-scale matrix and offset without creating a transform.
55    pub fn scale_into(m: &mut [f64; 16], o: &mut [f64; 4], scale: &[f64; 4]) -> Result<()> {
56        crate::clear_last_error();
57        unsafe {
58            ocio_sys::ocio_matrix_transform_scale_into(
59                m.as_mut_ptr(),
60                o.as_mut_ptr(),
61                scale.as_ptr(),
62            )
63        };
64        crate::ocio_call_status()
65    }
66
67    /// Write OCIO's view matrix and offset, preserving native channel-mask semantics.
68    pub fn view_into(
69        m: &mut [f64; 16],
70        o: &mut [f64; 4],
71        channels: &mut [i32; 4],
72        luma: &[f64; 3],
73    ) -> Result<()> {
74        crate::clear_last_error();
75        unsafe {
76            ocio_sys::ocio_matrix_transform_view_into(
77                m.as_mut_ptr(),
78                o.as_mut_ptr(),
79                channels.as_mut_ptr(),
80                luma.as_ptr(),
81            )
82        };
83        crate::ocio_call_status()
84    }
85
86    /// Create a new identity matrix transform.
87    pub fn create() -> Result<Self> {
88        crate::clear_last_error();
89        let handle = unsafe { ocio_sys::ocio_matrix_transform_create() };
90        crate::handle_result(handle).map(|handle| Self { handle })
91    }
92
93    /// Return the current 4x4 matrix in row-major order.
94    pub fn try_matrix(&self) -> Result<[f64; 16]> {
95        let mut m = [0.0f64; 16];
96        for i in 0..4 {
97            m[i * 5] = 1.0;
98        }
99        crate::clear_last_error();
100        unsafe {
101            ocio_sys::ocio_matrix_transform_get_matrix(
102                self.handle.as_ptr(),
103                m.as_mut_ptr() as *mut c_void,
104            )
105        };
106        crate::ocio_call_status()?;
107        Ok(m)
108    }
109
110    /// Return the current 4x4 matrix in row-major order.
111    pub fn matrix(&self) -> [f64; 16] {
112        self.try_matrix().unwrap_or_else(|_| {
113            let mut m = [0.0f64; 16];
114            for i in 0..4 {
115                m[i * 5] = 1.0;
116            }
117            m
118        })
119    }
120
121    /// Replace the current 4x4 matrix in row-major order.
122    pub fn set_matrix(&self, m44: &[f64; 16]) -> Result<()> {
123        crate::clear_last_error();
124        unsafe {
125            ocio_sys::ocio_matrix_transform_set_matrix(
126                self.handle.as_ptr(),
127                m44.as_ptr() as *mut c_void,
128            )
129        };
130        crate::ocio_call_status()
131    }
132
133    /// Return the current RGBA offset vector.
134    pub fn try_offset(&self) -> Result<[f64; 4]> {
135        let mut o = [0.0f64; 4];
136        crate::clear_last_error();
137        unsafe {
138            ocio_sys::ocio_matrix_transform_get_offset(
139                self.handle.as_ptr(),
140                o.as_mut_ptr() as *mut c_void,
141            )
142        };
143        crate::ocio_call_status()?;
144        Ok(o)
145    }
146
147    /// Return the current RGBA offset vector.
148    pub fn offset(&self) -> [f64; 4] {
149        self.try_offset().unwrap_or([0.0; 4])
150    }
151
152    /// Replace the current RGBA offset vector.
153    pub fn set_offset(&self, offset4: &[f64; 4]) -> Result<()> {
154        crate::clear_last_error();
155        unsafe {
156            ocio_sys::ocio_matrix_transform_set_offset(
157                self.handle.as_ptr(),
158                offset4.as_ptr() as *mut c_void,
159            )
160        };
161        crate::ocio_call_status()
162    }
163
164    /// Return the transform direction used when this op is evaluated.
165    pub fn direction(&self) -> TransformDirection {
166        let dir = unsafe {
167            ocio_sys::ocio_matrix_transform_get_direction(self.handle.as_ptr() as *mut c_void)
168        };
169        match dir {
170            1 => TransformDirection::Inverse,
171            _ => TransformDirection::Forward,
172        }
173    }
174
175    /// Set the transform direction used when this op is evaluated.
176    pub fn set_direction(&self, direction: TransformDirection) {
177        self.try_set_direction(direction)
178            .expect("failed to set matrix transform direction");
179    }
180
181    /// Set the transform direction and surface any OCIO validation error.
182    pub fn try_set_direction(&self, direction: TransformDirection) -> crate::Result<()> {
183        crate::clear_last_error();
184        unsafe {
185            ocio_sys::ocio_matrix_transform_set_direction(self.handle.as_ptr(), direction as i32);
186        }
187        crate::ocio_call_status()
188    }
189
190    /// Create an editable copy that is independent from the original transform.
191    pub fn create_editable_copy(&self) -> Result<Self> {
192        crate::clear_last_error();
193        let handle = unsafe {
194            ocio_sys::ocio_transform_create_editable_copy(self.handle.as_ptr() as *mut c_void)
195        };
196        crate::handle_result(handle).map(|handle| Self { handle })
197    }
198
199    /// Return the bit depth declared for file-based input serialization.
200    pub fn file_input_bit_depth(&self) -> BitDepth {
201        let b = unsafe {
202            ocio_sys::ocio_matrix_transform_get_file_input_bit_depth(
203                self.handle.as_ptr() as *mut c_void
204            )
205        };
206        match b {
207            1 => BitDepth::Uint8,
208            2 => BitDepth::Uint10,
209            3 => BitDepth::Uint12,
210            4 => BitDepth::Uint14,
211            5 => BitDepth::Uint16,
212            6 => BitDepth::Uint32,
213            7 => BitDepth::F16,
214            8 => BitDepth::F32,
215            _ => BitDepth::Unknown,
216        }
217    }
218
219    /// Set the bit depth declared for file-based input serialization.
220    pub fn set_file_input_bit_depth(&self, bit_depth: BitDepth) {
221        self.try_set_file_input_bit_depth(bit_depth)
222            .expect("failed to set matrix file input bit depth");
223    }
224
225    /// Set the serialized input bit depth and surface any OCIO validation error.
226    pub fn try_set_file_input_bit_depth(&self, bit_depth: BitDepth) -> Result<()> {
227        crate::clear_last_error();
228        unsafe {
229            ocio_sys::ocio_matrix_transform_set_file_input_bit_depth(
230                self.handle.as_ptr(),
231                bit_depth as i32,
232            )
233        };
234        crate::ocio_call_status()
235    }
236
237    /// Return the bit depth declared for file-based output serialization.
238    pub fn file_output_bit_depth(&self) -> BitDepth {
239        let b = unsafe {
240            ocio_sys::ocio_matrix_transform_get_file_output_bit_depth(
241                self.handle.as_ptr() as *mut c_void
242            )
243        };
244        match b {
245            1 => BitDepth::Uint8,
246            2 => BitDepth::Uint10,
247            3 => BitDepth::Uint12,
248            4 => BitDepth::Uint14,
249            5 => BitDepth::Uint16,
250            6 => BitDepth::Uint32,
251            7 => BitDepth::F16,
252            8 => BitDepth::F32,
253            _ => BitDepth::Unknown,
254        }
255    }
256
257    /// Set the bit depth declared for file-based output serialization.
258    pub fn set_file_output_bit_depth(&self, bit_depth: BitDepth) {
259        self.try_set_file_output_bit_depth(bit_depth)
260            .expect("failed to set matrix file output bit depth");
261    }
262
263    /// Set the serialized output bit depth and surface any OCIO validation error.
264    pub fn try_set_file_output_bit_depth(&self, bit_depth: BitDepth) -> Result<()> {
265        crate::clear_last_error();
266        unsafe {
267            ocio_sys::ocio_matrix_transform_set_file_output_bit_depth(
268                self.handle.as_ptr(),
269                bit_depth as i32,
270            )
271        };
272        crate::ocio_call_status()
273    }
274
275    /// Return format metadata attached to the transform, when available.
276    pub fn format_metadata(&self) -> Option<crate::FormatMetadata> {
277        let handle = unsafe { ocio_sys::ocio_transform_get_format_metadata(self.handle.as_ptr()) };
278        NonNull::new(handle).map(|h| crate::FormatMetadata { handle: h })
279    }
280
281    #[deprecated(since = "0.2.0", note = "compat alias; prefer format_metadata()")]
282    pub fn format_metadata_v1(&self) -> Option<crate::FormatMetadata> {
283        self.format_metadata()
284    }
285
286    #[deprecated(since = "0.2.0", note = "compat alias; prefer format_metadata()")]
287    pub fn format_metadata_v2(&self) -> Option<crate::FormatMetadata> {
288        self.format_metadata()
289    }
290
291    /// Return whether this transform is equivalent to `other`.
292    pub fn equals(&self, other: &Self) -> bool {
293        unsafe {
294            ocio_sys::ocio_matrix_transform_equals(self.handle.as_ptr(), other.handle.as_ptr())
295        }
296    }
297}
298
299impl MatrixTransform {
300    /// Create a matrix transform that remaps the inclusive range
301    /// `old_min..old_max` into `new_min..new_max`.
302    pub fn fit(
303        old_min: &[f64; 4],
304        old_max: &[f64; 4],
305        new_min: &[f64; 4],
306        new_max: &[f64; 4],
307    ) -> Result<Self> {
308        crate::clear_last_error();
309        let handle = unsafe {
310            ocio_sys::ocio_matrix_transform_create_fit(
311                old_min.as_ptr(),
312                old_max.as_ptr(),
313                new_min.as_ptr(),
314                new_max.as_ptr(),
315            )
316        };
317        crate::handle_result(handle).map(|handle| Self { handle })
318    }
319
320    /// Create an identity matrix transform.
321    pub fn identity() -> Result<Self> {
322        crate::clear_last_error();
323        let handle = unsafe { ocio_sys::ocio_matrix_transform_create_identity() };
324        crate::handle_result(handle).map(|handle| Self { handle })
325    }
326
327    /// Create a saturation matrix using the provided luma coefficients.
328    pub fn sat(sat: f64, luma: &[f64; 3]) -> Result<Self> {
329        crate::clear_last_error();
330        let handle = unsafe { ocio_sys::ocio_matrix_transform_create_sat(sat, luma.as_ptr()) };
331        crate::handle_result(handle).map(|handle| Self { handle })
332    }
333
334    /// Create a per-channel scale matrix.
335    pub fn scale(scale: &[f64; 4]) -> Result<Self> {
336        crate::clear_last_error();
337        let handle = unsafe { ocio_sys::ocio_matrix_transform_create_scale(scale.as_ptr()) };
338        crate::handle_result(handle).map(|handle| Self { handle })
339    }
340
341    /// Create a matrix that remaps channels according to a canonical OCIO view mask.
342    pub fn view(channels: &mut [i32; 4], luma: &[f64; 3]) -> Result<Self> {
343        crate::clear_last_error();
344        let handle = unsafe {
345            ocio_sys::ocio_matrix_transform_create_view(channels.as_mut_ptr(), luma.as_ptr())
346        };
347        crate::handle_result(handle).map(|handle| Self { handle })
348    }
349}
350
351impl Drop for MatrixTransform {
352    fn drop(&mut self) {
353        unsafe { ocio_sys::ocio_matrix_transform_destroy(self.handle.as_ptr() as *mut c_void) };
354    }
355}
356
357#[cfg(test)]
358mod tests {
359    use super::*;
360
361    #[test]
362    fn create_matrix() {
363        let mt = MatrixTransform::create();
364        assert!(mt.is_ok());
365    }
366
367    #[test]
368    fn matrix_and_offset() {
369        let mt = MatrixTransform::create().unwrap();
370        // Default is identity matrix
371        let m = mt.matrix();
372        assert_eq!(m[0], 1.0);
373        assert_eq!(m[5], 1.0);
374        assert_eq!(m[10], 1.0);
375        assert_eq!(m[15], 1.0);
376        // Default offset is zero
377        let o = mt.offset();
378        assert_eq!(o, [0.0, 0.0, 0.0, 0.0]);
379    }
380
381    #[test]
382    fn create_editable_copy_no_crash() {
383        let mt = MatrixTransform::create().unwrap();
384        let _ = mt.create_editable_copy();
385    }
386
387    #[test]
388    fn bit_depth_no_crash() {
389        let mt = MatrixTransform::create().unwrap();
390        let _ = mt.file_input_bit_depth();
391        mt.try_set_file_input_bit_depth(BitDepth::F32).unwrap();
392        let _ = mt.file_output_bit_depth();
393        mt.try_set_file_output_bit_depth(BitDepth::F32).unwrap();
394    }
395
396    #[test]
397    fn static_helpers_no_crash() {
398        let _ = MatrixTransform::identity();
399        let _ = MatrixTransform::fit(
400            &[0.0, 0.0, 0.0, 0.0],
401            &[1.0, 1.0, 1.0, 1.0],
402            &[0.0, 0.0, 0.0, 0.0],
403            &[1.0, 1.0, 1.0, 1.0],
404        );
405        let _ = MatrixTransform::sat(1.5, &[0.2126, 0.7152, 0.0722]);
406        let _ = MatrixTransform::scale(&[1.0, 1.0, 1.0, 1.0]);
407        let mut channels = [0i32; 4];
408        let _ = MatrixTransform::view(&mut channels, &[0.2126, 0.7152, 0.0722]);
409    }
410
411    #[test]
412    fn format_metadata_no_crash() {
413        let mt = MatrixTransform::create().unwrap();
414        let _ = mt.format_metadata();
415    }
416
417    #[test]
418    fn equals_no_crash() {
419        let a = MatrixTransform::create().unwrap();
420        let b = MatrixTransform::create().unwrap();
421        let _ = a.equals(&b);
422    }
423}