Skip to main content

ocio_rs/transform/
file.rs

1use std::ffi::c_void;
2use std::ptr::NonNull;
3
4use crate::{
5    cstr_from_mut, cstr_to_opt_string, cstring, CDLStyle, Interpolation, OcioError, Result,
6    TransformDirection,
7};
8use ocio_sys;
9
10/// A transform backed by an external LUT or color-correction file.
11///
12/// The source path is resolved by OCIO using the active config/context.
13pub struct FileTransform {
14    pub(crate) handle: NonNull<c_void>,
15}
16
17impl FileTransform {
18    /// Create an empty file transform.
19    pub fn create() -> Result<Self> {
20        crate::clear_last_error();
21        let handle = unsafe { ocio_sys::ocio_file_transform_create() };
22        crate::handle_result(handle).map(|handle| Self { handle })
23    }
24
25    /// Return the source path or URI attached to the transform.
26    pub fn src(&self) -> Option<String> {
27        unsafe { cstr_from_mut(ocio_sys::ocio_file_transform_get_src(self.handle.as_ptr())) }
28    }
29
30    /// Set the source path or URI used to load the external transform data.
31    pub fn set_src(&self, src: impl AsRef<str>) -> Result<()> {
32        let src = cstring(src)?;
33        crate::clear_last_error();
34        unsafe { ocio_sys::ocio_file_transform_set_src(self.handle.as_ptr(), src.as_ptr().cast()) };
35        crate::ocio_call_status()
36    }
37
38    /// Return the optional CCC identifier used with multi-grade CDL files.
39    pub fn ccc_id(&self) -> Option<String> {
40        unsafe {
41            cstr_from_mut(ocio_sys::ocio_file_transform_get_ccc_id(
42                self.handle.as_ptr(),
43            ))
44        }
45    }
46
47    /// Set the optional CCC identifier used with multi-grade CDL files.
48    pub fn set_ccc_id(&self, id: impl AsRef<str>) -> Result<()> {
49        let id = cstring(id)?;
50        crate::clear_last_error();
51        unsafe {
52            ocio_sys::ocio_file_transform_set_ccc_id(self.handle.as_ptr(), id.as_ptr().cast())
53        };
54        crate::ocio_call_status()
55    }
56
57    /// Return the interpolation mode requested for LUT sampling.
58    pub fn interpolation(&self) -> Interpolation {
59        let interp =
60            unsafe { ocio_sys::ocio_file_transform_get_interpolation(self.handle.as_ptr()) };
61        match interp {
62            1 => Interpolation::Nearest,
63            2 => Interpolation::Linear,
64            3 => Interpolation::Tetrahedral,
65            4 => Interpolation::Cubic,
66            254 => Interpolation::Default,
67            255 => Interpolation::Best,
68            _ => Interpolation::Unknown,
69        }
70    }
71
72    /// Set the interpolation mode requested for LUT sampling.
73    pub fn set_interpolation(&self, interp: Interpolation) {
74        self.try_set_interpolation(interp)
75            .expect("failed to set file transform interpolation");
76    }
77
78    /// Set interpolation and surface any OCIO validation error.
79    pub fn try_set_interpolation(&self, interp: Interpolation) -> Result<()> {
80        crate::clear_last_error();
81        unsafe {
82            ocio_sys::ocio_file_transform_set_interpolation(self.handle.as_ptr(), interp as i32);
83        }
84        crate::ocio_call_status()
85    }
86
87    /// Return the CDL style used when the file source is CDL-based.
88    pub fn cdl_style(&self) -> CDLStyle {
89        let s = unsafe { ocio_sys::ocio_file_transform_get_cdl_style(self.handle.as_ptr()) };
90        match s {
91            1 => CDLStyle::NoClamp,
92            _ => CDLStyle::Asc,
93        }
94    }
95
96    /// Set the CDL style used when the file source is CDL-based.
97    pub fn set_cdl_style(&self, style: CDLStyle) {
98        self.try_set_cdl_style(style)
99            .expect("failed to set file transform CDL style");
100    }
101
102    /// Set the CDL style and surface any OCIO validation error.
103    pub fn try_set_cdl_style(&self, style: CDLStyle) -> Result<()> {
104        crate::clear_last_error();
105        unsafe {
106            ocio_sys::ocio_file_transform_set_cdl_style(self.handle.as_ptr(), style as i32);
107        }
108        crate::ocio_call_status()
109    }
110
111    /// Return the transform direction used when this op is evaluated.
112    pub fn direction(&self) -> TransformDirection {
113        let dir = unsafe { ocio_sys::ocio_file_transform_get_direction(self.handle.as_ptr()) };
114        match dir {
115            1 => TransformDirection::Inverse,
116            _ => TransformDirection::Forward,
117        }
118    }
119
120    /// Set the transform direction used when this op is evaluated.
121    pub fn set_direction(&self, direction: TransformDirection) {
122        self.try_set_direction(direction)
123            .expect("failed to set file transform direction");
124    }
125
126    /// Set the transform direction and surface any OCIO validation error.
127    pub fn try_set_direction(&self, direction: TransformDirection) -> Result<()> {
128        crate::clear_last_error();
129        unsafe {
130            ocio_sys::ocio_file_transform_set_direction(self.handle.as_ptr(), direction as i32);
131        }
132        crate::ocio_call_status()
133    }
134
135    /// Create an editable copy that is independent from the original transform.
136    pub fn create_editable_copy(&self) -> Result<Self> {
137        crate::clear_last_error();
138        let handle =
139            unsafe { ocio_sys::ocio_file_transform_create_editable_copy(self.handle.as_ptr()) };
140        crate::handle_result(handle).map(|handle| Self { handle })
141    }
142
143    /// Return format metadata attached to the transform, when available.
144    pub fn format_metadata(&self) -> Option<crate::FormatMetadata> {
145        let handle = unsafe { ocio_sys::ocio_transform_get_format_metadata(self.handle.as_ptr()) };
146        NonNull::new(handle).map(|h| crate::FormatMetadata { handle: h })
147    }
148
149    /// Ask OCIO to validate the transform in place.
150    pub fn validate(&self) -> Result<()> {
151        crate::clear_last_error();
152        unsafe { ocio_sys::ocio_file_transform_validate(self.handle.as_ptr()) };
153        crate::validation_status()
154    }
155
156    /// Return the number of reader formats supported by `FileTransform`.
157    pub fn num_formats() -> i32 {
158        unsafe { ocio_sys::ocio_file_transform_get_num_formats() }
159    }
160
161    /// Return the reader format name at `index`, or `None` for an invalid index.
162    pub fn format_name_by_index(index: i32) -> Option<String> {
163        if index < 0 || index >= Self::num_formats() {
164            return None;
165        }
166        unsafe {
167            cstr_to_opt_string(ocio_sys::ocio_file_transform_get_format_name_by_index(
168                index,
169            ))
170        }
171    }
172
173    /// Return the reader format extension at `index`, without a leading dot.
174    /// Returns `None` for an invalid index.
175    pub fn format_extension_by_index(index: i32) -> Option<String> {
176        if index < 0 || index >= Self::num_formats() {
177            return None;
178        }
179        unsafe {
180            cstr_to_opt_string(ocio_sys::ocio_file_transform_get_format_extension_by_index(
181                index,
182            ))
183        }
184    }
185
186    /// Return whether `extension` is recognized by the upstream file readers.
187    pub fn is_format_extension_supported(extension: impl AsRef<str>) -> bool {
188        let extension = match cstring(extension) {
189            Ok(value) => value,
190            Err(_) => return false,
191        };
192        unsafe {
193            ocio_sys::ocio_file_transform_is_format_extension_supported(extension.as_ptr().cast())
194        }
195    }
196}
197
198impl Drop for FileTransform {
199    fn drop(&mut self) {
200        unsafe { ocio_sys::ocio_file_transform_destroy(self.handle.as_ptr()) };
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    #[test]
209    fn create_file_transform() {
210        let ft = FileTransform::create();
211        assert!(ft.is_ok());
212    }
213
214    #[test]
215    fn set_src_no_crash() {
216        let ft = FileTransform::create().unwrap();
217        assert!(ft.set_src("test.lut").is_ok());
218    }
219
220    #[test]
221    fn interpolation_no_crash() {
222        let ft = FileTransform::create().unwrap();
223        ft.try_set_interpolation(Interpolation::Linear).unwrap();
224        let _ = ft.interpolation();
225    }
226
227    #[test]
228    fn direction_no_crash() {
229        let ft = FileTransform::create().unwrap();
230        ft.try_set_direction(TransformDirection::Inverse).unwrap();
231        let _ = ft.direction();
232    }
233
234    #[test]
235    fn cdl_style_no_crash() {
236        let ft = FileTransform::create().unwrap();
237        let _ = ft.cdl_style();
238        ft.try_set_cdl_style(CDLStyle::NoClamp).unwrap();
239    }
240
241    #[test]
242    fn create_editable_copy_no_crash() {
243        let ft = FileTransform::create().unwrap();
244        let _ = ft.create_editable_copy();
245    }
246
247    #[test]
248    fn format_metadata_no_crash() {
249        let ft = FileTransform::create().unwrap();
250        let _ = ft.format_metadata();
251    }
252
253    #[test]
254    fn validate_no_crash() {
255        let ft = FileTransform::create().unwrap();
256        let _ = ft.validate();
257    }
258
259    #[test]
260    fn static_format_queries_no_crash() {
261        let count = FileTransform::num_formats();
262        assert!(count >= 0);
263        let _ = FileTransform::format_name_by_index(0);
264        let _ = FileTransform::format_extension_by_index(0);
265        let _ = FileTransform::is_format_extension_supported("clf");
266    }
267
268    #[test]
269    #[cfg_attr(ocio_stub, ignore = "requires a real OpenColorIO build")]
270    fn static_format_queries_real_behavior() {
271        if crate::is_stub_build() {
272            return;
273        }
274
275        let count = FileTransform::num_formats();
276        assert!(count > 0);
277        assert!(FileTransform::format_name_by_index(0).is_some());
278        assert!(FileTransform::format_extension_by_index(0).is_some());
279        assert!(FileTransform::is_format_extension_supported("clf"));
280        assert!(FileTransform::is_format_extension_supported(".clf"));
281        assert!(!FileTransform::is_format_extension_supported(
282            "definitely_not_a_lut_ext"
283        ));
284    }
285}