Skip to main content

ocio_rs/
lib.rs

1//! Safe Rust bindings for [OpenColorIO](https://opencolorio.org/) (OCIO 2.4.1 through 2.6.x).
2//!
3//! This crate wraps the OpenColorIO C++ API through a generated FFI layer
4//! ([`ocio_sys`]) and exposes safe Rust types for configuration, color-space
5//! queries, processor creation, CPU/GPU execution, GPU shader extraction, and
6//! transform composition.
7//!
8//! # OCIO version support
9//!
10//! The baseline API works with OpenColorIO >= 2.4.1 and < 2.7. API added in newer
11//! OCIO versions is opt-in through additive `vX_Y` cargo features (e.g.
12//! `v2_5` for hue-curve grading, interchange attributes, and GPU uniform
13//! buffers); enabling one raises the OpenColorIO version requirement checked
14//! at build time.
15//!
16//! # Getting started
17//!
18//! ```rust,no_run
19//! use ocio_rs::Config;
20//!
21//! // Load an OCIO config from a file (real OCIO mode required).
22//! # fn example() -> ocio_rs::Result<()> {
23//! let config = Config::from_file("/path/to/config.ocio")?;
24//!
25//! // Create a processor between two color spaces.
26//! let processor = config.processor("scene_linear", "srgb_texture")?;
27//!
28//! // Apply the default CPU path to a single RGBA pixel.
29//! let mut pixel = [0.5f32, 0.5, 0.5, 1.0];
30//! processor.default_cpu_processor()?.apply_rgba(&mut pixel);
31//! # Ok(())
32//! # }
33//! ```
34//!
35//! # Project status
36//!
37//! This crate targets broad OpenColorIO 2.5 coverage. The low-level FFI and
38//! safe-wrapper layers are available for most of the exposed OCIO 2.5 surface,
39//! while release hardening and long-tail behavioral validation are still in
40//! progress.
41//!
42//! # Build modes
43//!
44//! | Mode | Feature flag | Notes |
45//! |------|-------------|-------|
46//! | **Stub** (default) | `--no-default-features` | APIs return safe defaults; no real color management |
47//! | **System** | `--features system` | Requires installed OpenColorIO and pkg-config |
48//! | **Bundled** | `--features bundled` | Builds vendored OCIO; static linking by default |
49//!
50//! Set `OCIO_RS_LINK=dynamic` for shared linking. With neither backend feature
51//! nor legacy environment override, the backend is stub and performs no color
52//! processing. `OCIO_RS_ENABLE_REAL=0/1` remains a legacy override.
53//!
54//! ```bash
55//! # Stub mode (CI, API-shape testing)
56//! cargo build
57//!
58//! # Bundled real-OCIO build
59//! cargo build --features bundled
60//!
61//! # Use an installed OCIO
62//! OCIO_INSTALL_DIR=/path/to/ocio cargo build --features system
63//! ```
64//!
65//! # Crate-level helpers
66//!
67//! Free functions such as [`current_config`], [`set_current_config`],
68//! [`version`], and [`clear_all_caches`] operate on the process-global OCIO
69//! config. Use them when your application maintains a single shared config
70//! rather than passing `Config` handles through every call site.
71//!
72//! [`ocio_sys`]: crate::ocio_sys
73
74#![cfg_attr(docsrs, feature(doc_cfg))]
75#![allow(
76    unused_imports,
77    clippy::single_component_path_imports,
78    clippy::unnecessary_cast
79)]
80
81mod app_helpers;
82mod spline;
83mod system_monitors;
84#[cfg(feature = "v2_5")]
85pub use spline::BSplineType;
86pub use spline::{
87    ConstGradingBSplineCurve, GradingBSplineCurve, GradingRGBCurve, SharedGradingBSplineCurve,
88    SharedGradingRGBCurve,
89};
90#[cfg(feature = "v2_5")]
91pub use spline::{GradingHueCurve, SharedGradingHueCurve};
92pub use system_monitors::SystemMonitors;
93mod baker;
94pub use app_helpers::{
95    ColorSpaceMenuHelper, ColorSpaceMenuParameters, DisplayViewFromFile, LegacyViewingPipeline,
96    LegacyViewingStage, MixingColorSpaceManager, MixingSlider,
97};
98mod builtin_config_registry;
99mod builtin_transform_registry;
100mod color_space_set;
101mod colorspace;
102mod config;
103#[cfg(feature = "v2_5")]
104mod config_merging;
105#[cfg(feature = "v2_5")]
106pub use config_merging::{ConfigMerger, ConfigMergingParameters, ConstConfigMerger, MergeStrategy};
107mod config_io_proxy;
108mod const_config_item;
109mod const_rules;
110pub mod constants;
111mod context;
112mod enum_text;
113mod file_rules;
114mod format_metadata;
115pub mod grading;
116mod image_desc;
117mod look;
118mod named_transform;
119mod output_writer;
120mod processor;
121mod processor_metadata;
122pub mod transform;
123mod types;
124mod view_transform;
125mod viewing_rules;
126
127pub use baker::Baker;
128pub use builtin_config_registry::BuiltinConfigRegistry;
129pub use builtin_transform_registry::BuiltinTransformRegistry;
130pub use color_space_set::{ColorSpaceSet, ColorSpaceSetRef, ConstColorSpaceSet};
131pub use colorspace::{ColorSpace, ColorSpaceRef, ConstColorSpace};
132pub use config::{Config, ConfigProcessorTarget, ConfigRef, ConstConfig};
133pub use config_io_proxy::{ConfigIOProvider, ConfigIOProxy};
134pub use const_config_item::{ConstLook, ConstNamedTransform, ConstViewTransform};
135pub use const_rules::{ConstFileRules, ConstViewingRules};
136pub use context::{ConstContext, Context};
137pub use enum_text::OcioEnumText;
138pub use file_rules::FileRules;
139pub use format_metadata::{ConstFormatMetadata, FormatMetadata};
140pub use image_desc::{
141    CustomImageLayout, ImageDescChannel, ImageDescProvider, NativeImageDataPointers,
142    NativeImageDesc, NativeImageDescInfo, NativeImageLayout,
143};
144pub use look::Look;
145pub use named_transform::NamedTransform;
146pub use processor::{
147    CPUProcessor, DynamicProperty, GPUProcessor, GpuShaderCreator, GpuShaderDesc,
148    GpuShaderDescView, GpuTexture2D, GpuTexture3D, GpuTextureChannel, GpuTextureDimensions,
149    GpuUniform, GpuUniformCache, GpuUniformCopy, GpuUniformType, GpuUniformValue,
150    PackedConversionLayout, PackedImageLayout, PlanarByteLayout, PlanarBytes, PlanarBytesMut,
151    PlanarF32Layout, Processor, SignedPlanarByteLayout, SignedPlanarBytes, SignedPlanarBytesMut,
152    StaticCPUProcessor, TextureInfo,
153};
154pub use processor::{
155    PersistentPolicyCreator, ShaderCacheIdPolicy, ShaderClonePolicy, ShaderCodeSection,
156    ShaderCreatorOptions, ShaderExtractionHooks, ShaderFinalizeControl, ShaderLifecycle,
157    ShaderSections, ShaderTexture, ShaderTextureAction, ShaderTextureControl, ShaderTexturePolicy,
158    ShaderUniform, ShaderUniformAction, ShaderUniformControl, ShaderUniformGetter,
159    ShaderUniformRegistration,
160};
161pub use processor_metadata::{ConstProcessorMetadata, ProcessorMetadata};
162pub use types::*;
163#[cfg(feature = "v2_6")]
164mod v2_6;
165#[cfg(feature = "v2_6")]
166pub use v2_6::{metadata_id_element, ViewWithAliases};
167pub use view_transform::ViewTransform;
168pub use viewing_rules::ViewingRules;
169
170use std::cell::RefCell;
171use std::ffi::{c_void, CStr, CString};
172use std::ptr::NonNull;
173use std::sync::{Arc, Mutex, OnceLock};
174use thiserror::Error;
175
176pub use ocio_sys;
177
178#[derive(Debug, Error)]
179/// Unified error type for safe `ocio-rs` operations.
180///
181/// Most bridge failures arrive here either as a propagated OpenColorIO runtime
182/// error string or as an input/ownership validation error detected on the Rust
183/// side before the C++ bridge is called.
184pub enum OcioError {
185    #[error("OpenColorIO error: {0}")]
186    Ocio(String),
187    /// Native `ExceptionMissingFile`: an unavailable file or lookup result,
188    /// such as a missing correction in an existing CDL collection.
189    #[error("OpenColorIO file not found: {0}")]
190    MissingFile(String),
191    #[error("Validation failed: {0}")]
192    ValidationFailed(String),
193    #[error("invalid input: {0}")]
194    InvalidInput(String),
195    #[error("path contains interior NUL byte")]
196    InteriorNul,
197    #[error("OpenColorIO handle allocation failed")]
198    AllocationFailed,
199}
200
201/// Crate-local result alias used by the safe wrapper layer.
202pub type Result<T> = std::result::Result<T, OcioError>;
203
204type LoggingCallback = dyn Fn(&str) + Send + Sync + 'static;
205type ComputeHashCallback = dyn Fn(&[u8]) -> Vec<u8> + Send + Sync + 'static;
206
207thread_local! {
208    static COMPUTE_HASH_OUTPUT: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
209    static IN_LOGGING_CALLBACK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
210}
211
212fn check_logging_reentrancy() -> Result<()> {
213    if IN_LOGGING_CALLBACK.with(std::cell::Cell::get) {
214        return Err(OcioError::InvalidInput(
215            "OCIO logging APIs cannot be called from an OCIO logging callback".into(),
216        ));
217    }
218    Ok(())
219}
220
221fn logging_callback_slot() -> &'static Mutex<Option<Arc<LoggingCallback>>> {
222    static SLOT: OnceLock<Mutex<Option<Arc<LoggingCallback>>>> = OnceLock::new();
223    SLOT.get_or_init(|| Mutex::new(None))
224}
225
226fn logging_callback_update_lock() -> &'static Mutex<()> {
227    static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
228    LOCK.get_or_init(|| Mutex::new(()))
229}
230
231fn compute_hash_callback_slot() -> &'static Mutex<Option<Arc<ComputeHashCallback>>> {
232    static SLOT: OnceLock<Mutex<Option<Arc<ComputeHashCallback>>>> = OnceLock::new();
233    SLOT.get_or_init(|| Mutex::new(None))
234}
235
236fn compute_hash_callback_update_lock() -> &'static Mutex<()> {
237    static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
238    LOCK.get_or_init(|| Mutex::new(()))
239}
240
241unsafe extern "C" fn rust_logging_callback(message: *const i8) {
242    if message.is_null() {
243        return;
244    }
245
246    let callback = logging_callback_slot()
247        .lock()
248        .unwrap_or_else(|poisoned| poisoned.into_inner())
249        .clone();
250    if let Some(callback) = callback {
251        let message = unsafe { CStr::from_ptr(message).to_string_lossy() };
252        IN_LOGGING_CALLBACK.with(|active| {
253            struct Reset<'a>(&'a std::cell::Cell<bool>);
254            impl Drop for Reset<'_> {
255                fn drop(&mut self) {
256                    self.0.set(false);
257                }
258            }
259            active.set(true);
260            let _reset = Reset(active);
261            let _ = catch_callback_unwind(std::panic::AssertUnwindSafe(|| callback(&message)));
262        });
263    }
264}
265
266unsafe extern "C" fn rust_compute_hash_callback(
267    input: *const u8,
268    input_len: usize,
269    output: *mut *const u8,
270    output_len: *mut usize,
271) -> bool {
272    if (input.is_null() && input_len != 0) || output.is_null() || output_len.is_null() {
273        return false;
274    }
275    let callback = compute_hash_callback_slot()
276        .lock()
277        .unwrap_or_else(|poisoned| poisoned.into_inner())
278        .clone();
279    let Some(callback) = callback else {
280        return false;
281    };
282    let input = if input_len == 0 {
283        &[]
284    } else {
285        unsafe { std::slice::from_raw_parts(input, input_len) }
286    };
287    let Ok(value) = catch_callback_unwind(std::panic::AssertUnwindSafe(|| callback(input))) else {
288        return false;
289    };
290    COMPUTE_HASH_OUTPUT.with(|slot| {
291        let mut slot = slot.borrow_mut();
292        *slot = value;
293        unsafe {
294            *output = slot.as_ptr();
295            *output_len = slot.len();
296        }
297    });
298    true
299}
300
301/// Returns `true` when the crate was built in stub mode instead of linking a
302/// real OpenColorIO implementation.
303///
304/// Stub mode is useful for API-shape validation and lightweight CI, but it
305/// does not perform real color processing.
306pub fn is_stub_build() -> bool {
307    unsafe { ocio_sys::ocio_runtime_is_stub() }
308}
309
310/// Returns the process-global current OCIO config, if one is installed.
311///
312/// The returned config is an editable snapshot with group-transform children
313/// detached from the installed config. This helper
314/// returns `None` both when no config is installed and when OCIO reports an
315/// error. Use [`try_current_config`] when those cases must be distinguished.
316///
317/// # Safety
318/// The caller must meet the synchronization requirements of [`try_current_config`].
319///
320/// ```compile_fail
321/// let _ = ocio_rs::current_config();
322/// ```
323pub unsafe fn current_config() -> Option<Config> {
324    unsafe { try_current_config() }.ok().flatten()
325}
326
327/// Try to get the process-global current OCIO config.
328///
329/// Returns `Ok(None)` when no config is installed, and surfaces OCIO bridge
330/// errors separately.
331///
332/// # Safety
333/// During this call, the caller must prevent independent native code, including
334/// other libraries, from accessing any config that may be current or mutating
335/// objects retained by it. OCIO const operations such as cache-ID queries can
336/// mutate lazy caches. Concurrent snapshot calls from this crate are permitted
337/// when this condition holds.
338///
339/// OCIO copies can retain external objects, such as a native config IO proxy or
340/// state owned by a custom transform. For as long as the snapshot, any object
341/// derived from it, or a config subsequently installed from it may use such
342/// objects, the caller must ensure those objects support concurrent use or
343/// coordinate all other native access. Rust-managed [`ConfigIOProxy`] providers
344/// are required to be thread-safe.
345///
346/// ```compile_fail
347/// let _ = ocio_rs::try_current_config(); // Requires explicit synchronization.
348/// ```
349pub unsafe fn try_current_config() -> Result<Option<Config>> {
350    clear_last_error();
351    let handle = unsafe { ocio_sys::ocio_get_isolated_current_config() };
352    ocio_call_status()?;
353    Ok(std::ptr::NonNull::new(handle).map(|handle| Config { handle }))
354}
355
356/// Return OCIO's native editable copy of the process-global config.
357///
358/// Unlike [`try_current_config`], this does not detach group-transform
359/// children; OCIO's native copy retains them. It avoids that extra graph copy
360/// when callers can coordinate the resulting shared objects.
361///
362/// # Safety
363/// The caller must meet the synchronization requirements of [`try_current_config`]
364/// while this function copies the global config. For the lifetime of the
365/// returned config and every derived handle, callers must also prevent
366/// conflicting access through all aliases to shared group children. This
367/// includes native aliases and other snapshots derived from the global config.
368/// OCIO may additionally retain external IO proxies and custom-transform state;
369/// the lifetime-wide requirements in [`try_current_config`] apply to them.
370/// Native processor caches are not automatically invalidated by edits through
371/// a shared transform alias.
372///
373/// ```compile_fail
374/// let _ = ocio_rs::try_current_config_native_copy();
375/// ```
376pub unsafe fn try_current_config_native_copy() -> Result<Option<Config>> {
377    clear_last_error();
378    let handle = unsafe { ocio_sys::ocio_get_current_config() };
379    ocio_call_status()?;
380    Ok(std::ptr::NonNull::new(handle).map(|handle| Config { handle }))
381}
382
383/// Return a separate read-only snapshot of the process-global config.
384///
385/// This makes a native config copy: OCIO's copy operation reads mutable lazy
386/// caches, so exposing the global object itself to safe callers on multiple
387/// threads would make concurrent reads and copies unsound. Reuse the snapshot
388/// for repeated operations. Group children are detached from the global config;
389/// further ordinary OCIO copies may share their own group children.
390/// The snapshot remains alive when another config is installed.
391///
392/// # Safety
393/// The caller must meet the synchronization requirements of [`try_current_config`]
394/// for the duration of this call.
395///
396/// ```compile_fail
397/// let _ = ocio_rs::try_const_current_config();
398/// ```
399pub unsafe fn try_const_current_config() -> Result<Option<ConstConfig>> {
400    clear_last_error();
401    let handle = unsafe { ocio_sys::ocio_get_isolated_const_current_config() };
402    ocio_call_status()?;
403    Ok(std::ptr::NonNull::new(handle).map(|handle| ConstConfig { handle }))
404}
405
406/// Retain the native global config without copying it.
407///
408/// # Safety
409/// The caller must serialize all access to the retained native config and its
410/// aliases and to any shared native objects with all other OCIO users, including
411/// global snapshot getters, for the lifetime of this handle and derived handles.
412/// OCIO may mutate lazy caches even for const operations; copying it while a
413/// different thread uses those caches can also race.
414pub unsafe fn try_const_current_config_shared() -> Result<Option<ConstConfig>> {
415    clear_last_error();
416    let handle = unsafe { ocio_sys::ocio_get_const_current_config() };
417    ocio_call_status()?;
418    Ok(std::ptr::NonNull::new(handle).map(|handle| ConstConfig { handle }))
419}
420
421#[deprecated(since = "0.2.0", note = "compat alias; prefer current_config()")]
422/// # Safety
423/// The caller must meet the synchronization requirements of [`try_current_config`].
424///
425/// ```compile_fail
426/// # #[allow(deprecated)]
427/// let _ = ocio_rs::get_current_config();
428/// ```
429pub unsafe fn get_current_config() -> Option<Config> {
430    unsafe { current_config() }
431}
432
433/// Installs `config` as the process-global current OCIO config.
434///
435/// This mutates process-global OCIO state; see [`current_config`] for threading
436/// requirements.
437#[deprecated(
438    since = "0.2.0",
439    note = "discarded OCIO errors; prefer try_set_current_config()"
440)]
441pub fn set_current_config(config: &Config) {
442    let _ = try_set_current_config(config);
443}
444
445/// Try to install `config` as the process-global current OCIO config.
446///
447/// Group-transform graphs are detached from the input before installation so
448/// mutable input children cannot be shared with other threads via the global.
449pub fn try_set_current_config(config: &Config) -> Result<()> {
450    clear_last_error();
451    unsafe { ocio_sys::ocio_set_isolated_current_config(config.handle.as_ptr(), false) };
452    ocio_call_status()
453}
454
455/// Install a shared read-only config as the process-global current config.
456///
457/// Group-transform graphs are detached from the input before installation;
458/// OCIO then makes its own config copy.
459/// See [`current_config`] for the process-global threading considerations.
460pub fn try_set_const_current_config(config: &ConstConfig) -> Result<()> {
461    clear_last_error();
462    unsafe { ocio_sys::ocio_set_isolated_current_config(config.handle.as_ptr(), true) };
463    ocio_call_status()
464}
465
466/// Clears OCIO's process-global caches.
467///
468/// This is mainly useful in tests and tooling that intentionally mutate config
469/// state and want subsequent processor creation to observe the new values.
470/// Serialize this operation with other application threads using OCIO globals.
471#[deprecated(
472    since = "0.2.0",
473    note = "discarded OCIO errors; prefer try_clear_all_caches()"
474)]
475pub fn clear_all_caches() {
476    let _ = try_clear_all_caches();
477}
478
479/// Try to clear OCIO's process-global caches.
480pub fn try_clear_all_caches() -> Result<()> {
481    clear_last_error();
482    unsafe { ocio_sys::ocio_clear_all_caches() };
483    ocio_call_status()
484}
485
486/// Returns the linked OpenColorIO version string, if available.
487pub fn version() -> Option<String> {
488    unsafe { cstr_to_opt_string(ocio_sys::ocio_get_version()) }
489}
490
491/// Returns the linked OpenColorIO version as an integer hex constant.
492pub fn version_hex() -> i32 {
493    unsafe { ocio_sys::ocio_get_version_hex() }
494}
495
496/// Returns the current OCIO global logging level, or `Unknown` when called
497/// reentrantly from a logging callback. Use [`try_logging_level`] to distinguish
498/// that case.
499pub fn logging_level() -> crate::LoggingLevel {
500    try_logging_level().unwrap_or(crate::LoggingLevel::Unknown)
501}
502
503/// Get the global logging level, reporting attempts to reenter from a callback.
504pub fn try_logging_level() -> Result<crate::LoggingLevel> {
505    check_logging_reentrancy()?;
506    let l = unsafe { ocio_sys::ocio_get_logging_level() };
507    Ok(match l {
508        0 => crate::LoggingLevel::None,
509        1 => crate::LoggingLevel::Warning,
510        2 => crate::LoggingLevel::Info,
511        3 => crate::LoggingLevel::Debug,
512        _ => crate::LoggingLevel::Unknown,
513    })
514}
515
516/// Sets the OCIO global logging level.
517///
518/// Serialize this process-global mutation with other application threads using
519/// OCIO globals.
520#[deprecated(
521    since = "0.2.0",
522    note = "discarded OCIO errors; prefer try_set_logging_level()"
523)]
524pub fn set_logging_level(level: crate::LoggingLevel) {
525    let _ = try_set_logging_level(level);
526}
527
528/// Try to set the OCIO global logging level.
529pub fn try_set_logging_level(level: crate::LoggingLevel) -> Result<()> {
530    check_logging_reentrancy()?;
531    if level as i32 == 4 {
532        return Err(OcioError::InvalidInput(
533            "OpenColorIO does not support trace logging".into(),
534        ));
535    }
536    clear_last_error();
537    unsafe { ocio_sys::ocio_set_logging_level(level as i32) };
538    ocio_call_status()
539}
540
541/// Send a message through OCIO's configured logging function.
542///
543/// OCIO's logging mechanism is thread-safe. This only invokes the current
544/// OCIO logger; use `try_set_logging_level` to control filtering.
545pub fn try_log_message(level: crate::LoggingLevel, message: impl AsRef<str>) -> Result<()> {
546    check_logging_reentrancy()?;
547    if level as i32 == 4 {
548        return Err(OcioError::InvalidInput(
549            "OpenColorIO does not support trace logging".into(),
550        ));
551    }
552    let message = cstring(message)?;
553    clear_last_error();
554    unsafe { ocio_sys::ocio_log_message(level as i32, message.as_ptr()) };
555    ocio_call_status()
556}
557
558/// Install a process-global Rust callback for OCIO log messages.
559///
560/// OCIO invokes the callback from any thread that emits a log message. The
561/// callback is retained by the crate until [`reset_logging_callback`] is
562/// called. Panics are caught at the FFI boundary and do not unwind through
563/// OCIO.
564///
565/// Installing or resetting the callback serializes updates made through this
566/// crate. Coordinate with other native code that changes OCIO's global logger.
567///
568/// OCIO invokes the callback while holding a non-recursive global logging lock.
569/// Do not call OCIO from the callback (or wait for another thread that may do
570/// so): even operations unrelated to logging can emit log messages and deadlock.
571/// Direct calls to this crate's logging helpers on the callback thread return an
572/// error; [`logging_level`] returns `Unknown` there for compatibility.
573///
574/// OCIO versions before 2.5.2 do not synchronize logger replacement against
575/// logging. On those versions this safe function returns an error; applications
576/// that can exclude all concurrent OCIO logging may use
577/// [`set_logging_callback_unchecked`] instead.
578pub fn set_logging_callback(callback: impl Fn(&str) + Send + Sync + 'static) -> Result<()> {
579    check_logging_reentrancy()?;
580    if !is_stub_build() && version_hex() < 0x0205_0200 {
581        return Err(OcioError::InvalidInput(
582            "OCIO before 2.5.2 requires externally synchronized logging callback replacement"
583                .into(),
584        ));
585    }
586    // SAFETY: Supported native versions serialize replacement with logging;
587    // stub mode has no native logger.
588    unsafe { set_logging_callback_unchecked(callback) }
589}
590
591/// Install a logger even on versions whose logger replacement is not synchronized.
592///
593/// # Safety
594/// For OCIO before 2.5.2, no other thread or native component may log or replace
595/// the process-global OCIO logger while this function executes. OCIO operations
596/// that appear unrelated may log. This obligation includes native users outside
597/// this crate. The normal callback reentrancy restrictions still apply.
598pub unsafe fn set_logging_callback_unchecked(
599    callback: impl Fn(&str) + Send + Sync + 'static,
600) -> Result<()> {
601    check_logging_reentrancy()?;
602    let update = logging_callback_update_lock()
603        .lock()
604        .unwrap_or_else(|poisoned| poisoned.into_inner());
605    let callback = Arc::new(callback) as Arc<LoggingCallback>;
606    let previous = {
607        let mut slot = logging_callback_slot()
608            .lock()
609            .unwrap_or_else(|poisoned| poisoned.into_inner());
610        (*slot).replace(callback)
611    };
612
613    clear_last_error();
614    unsafe { ocio_sys::ocio_set_logging_callback(Some(rust_logging_callback)) };
615    let result = ocio_call_status();
616    let discarded = if result.is_err() {
617        let mut slot = logging_callback_slot()
618            .lock()
619            .unwrap_or_else(|poisoned| poisoned.into_inner());
620        std::mem::replace(&mut *slot, previous)
621    } else {
622        previous
623    };
624    drop(update);
625    drop(discarded);
626    result
627}
628
629/// Restore OCIO's default process-global logging function.
630///
631/// Any callback previously installed through [`set_logging_callback`] is
632/// dropped after OCIO accepts the reset.
633/// Returns an error before changing state on native versions before 2.5.2;
634/// see [`reset_logging_callback_unchecked`] for externally synchronized use.
635pub fn reset_logging_callback() -> Result<()> {
636    check_logging_reentrancy()?;
637    if !is_stub_build() && version_hex() < 0x0205_0200 {
638        return Err(OcioError::InvalidInput(
639            "OCIO before 2.5.2 requires externally synchronized logging callback replacement"
640                .into(),
641        ));
642    }
643    // SAFETY: Supported native versions serialize replacement with logging;
644    // stub mode has no native logger.
645    unsafe { reset_logging_callback_unchecked() }
646}
647
648/// Reset a logger on versions without synchronized replacement.
649///
650/// # Safety
651/// The same exclusion of concurrent OCIO logging and logger changes required by
652/// [`set_logging_callback_unchecked`] applies for OCIO before 2.5.2.
653pub unsafe fn reset_logging_callback_unchecked() -> Result<()> {
654    check_logging_reentrancy()?;
655    let update = logging_callback_update_lock()
656        .lock()
657        .unwrap_or_else(|poisoned| poisoned.into_inner());
658    clear_last_error();
659    unsafe { ocio_sys::ocio_reset_logging_callback() };
660    ocio_call_status()?;
661    let previous = logging_callback_slot()
662        .lock()
663        .unwrap_or_else(|poisoned| poisoned.into_inner())
664        .take();
665    drop(update);
666    drop(previous);
667    Ok(())
668}
669
670/// Install a process-global OCIO compute-hash callback.
671///
672/// The callback receives OCIO's resolved file path as bytes and returns the
673/// file hash as bytes. OCIO `std::string` values, including embedded NUL bytes,
674/// round-trip without loss. Its output is copied
675/// by the bridge immediately after the callback returns. Panics are caught and never unwind
676/// across the FFI boundary.
677/// OCIO caches file hashes, and replacing this callback does not invalidate
678/// previously cached entries. In particular, a failing callback may leave an
679/// empty cached result. After correcting a failure or changing hash semantics,
680/// coordinate with other OCIO users and call [`try_clear_all_caches`] before
681/// retrying affected files.
682///
683/// # Safety
684///
685/// OCIO does not synchronize replacement of its process-global hash function
686/// with calls to it. The caller must ensure that no thread or reentrant
687/// callback is executing or can start an OCIO operation that may hash a file
688/// until this function returns. Coordinate with other native users of OCIO too;
689/// the crate's internal update lock only serializes updates through this crate.
690///
691/// ```compile_fail
692/// ocio_rs::set_compute_hash_callback(|bytes| bytes.to_vec()).unwrap();
693/// ```
694pub unsafe fn set_compute_hash_callback(
695    callback: impl Fn(&[u8]) -> Vec<u8> + Send + Sync + 'static,
696) -> Result<()> {
697    let update = compute_hash_callback_update_lock()
698        .lock()
699        .unwrap_or_else(|poisoned| poisoned.into_inner());
700    let callback = Arc::new(callback) as Arc<ComputeHashCallback>;
701    let previous = {
702        let mut slot = compute_hash_callback_slot()
703            .lock()
704            .unwrap_or_else(|poisoned| poisoned.into_inner());
705        (*slot).replace(callback)
706    };
707    clear_last_error();
708    unsafe { ocio_sys::ocio_set_compute_hash_callback(Some(rust_compute_hash_callback)) };
709    let result = ocio_call_status();
710    let discarded = if result.is_err() {
711        let mut slot = compute_hash_callback_slot()
712            .lock()
713            .unwrap_or_else(|poisoned| poisoned.into_inner());
714        std::mem::replace(&mut *slot, previous)
715    } else {
716        previous
717    };
718    drop(update);
719    drop(discarded);
720    result
721}
722
723/// Restore OCIO's default process-global compute-hash function.
724///
725/// # Safety
726///
727/// The same process-wide exclusion requirements as
728/// [`set_compute_hash_callback`] apply, including exclusion of a callback
729/// currently executing on the calling thread.
730///
731/// ```compile_fail
732/// ocio_rs::reset_compute_hash_callback().unwrap();
733/// ```
734pub unsafe fn reset_compute_hash_callback() -> Result<()> {
735    let update = compute_hash_callback_update_lock()
736        .lock()
737        .unwrap_or_else(|poisoned| poisoned.into_inner());
738    clear_last_error();
739    unsafe { ocio_sys::ocio_reset_compute_hash_callback() };
740    ocio_call_status()?;
741    let previous = compute_hash_callback_slot()
742        .lock()
743        .unwrap_or_else(|poisoned| poisoned.into_inner())
744        .take();
745    drop(update);
746    drop(previous);
747    Ok(())
748}
749
750/// Resolve an OCIO configuration path to its current persistent form.
751///
752/// In particular, this replaces special built-in config aliases such as
753/// `ocio://default` with the versioned name selected by the linked OCIO build.
754/// The returned string is owned by Rust and may be stored independently of OCIO.
755pub fn resolve_config_path(original_path: impl AsRef<str>) -> Result<String> {
756    let original_path = cstring(original_path)?;
757    clear_last_error();
758    let resolved =
759        unsafe { cstr_to_opt_string(ocio_sys::ocio_resolve_config_path(original_path.as_ptr())) };
760    ocio_call_status()?;
761    resolved
762        .ok_or_else(|| OcioError::Ocio("OpenColorIO returned a null resolved config path".into()))
763}
764
765/// Extract an `.ocioz` archive into a destination directory.
766///
767/// Both paths must be absolute according to OCIO's contract. The destination directory is
768/// created by OCIO along with `config.ocio` and the archive's referenced LUT assets.
769///
770/// This operation requires a real OCIO build. Stub mode returns an [`OcioError`] rather than
771/// pretending that archive extraction succeeded.
772/// OCIO 2.4–2.6 archives created on Unix may contain a `config.ocio` with zero
773/// permission bits, which native extraction preserves. The caller may need to
774/// restore appropriate file permissions before reading it.
775pub fn extract_ocioz_archive(
776    archive_path: impl AsRef<str>,
777    destination_dir: impl AsRef<str>,
778) -> Result<()> {
779    let archive_path = cstring(archive_path)?;
780    let destination_dir = cstring(destination_dir)?;
781    clear_last_error();
782    unsafe {
783        ocio_sys::ocio_extract_ocioz_archive(archive_path.as_ptr(), destination_dir.as_ptr());
784    }
785    ocio_call_status()
786}
787
788/// Read an OCIO process environment variable.
789///
790/// # Safety
791/// OCIO documents its environment-variable helpers as not thread-safe. The
792/// caller must serialize this call with all OCIO environment-variable calls
793/// and other native code that accesses the same process environment.
794pub unsafe fn get_env_variable(name: impl AsRef<str>) -> Result<Option<String>> {
795    let name = cstring(name)?;
796    clear_last_error();
797    let value = unsafe { cstr_to_opt_string(ocio_sys::ocio_get_env_variable(name.as_ptr())) };
798    ocio_call_status()?;
799    Ok(value)
800}
801
802/// Set an OCIO process environment variable.
803///
804/// # Safety
805/// OCIO documents its environment-variable helpers as not thread-safe. The
806/// caller must serialize this call with all OCIO environment-variable calls
807/// and other native code that accesses the same process environment.
808pub unsafe fn set_env_variable(name: impl AsRef<str>, value: impl AsRef<str>) -> Result<()> {
809    let name = cstring(name)?;
810    let value = cstring(value)?;
811    clear_last_error();
812    unsafe { ocio_sys::ocio_set_env_variable(name.as_ptr(), value.as_ptr()) };
813    ocio_call_status()
814}
815
816/// Remove an OCIO process environment variable.
817///
818/// # Safety
819/// OCIO documents its environment-variable helpers as not thread-safe. The
820/// caller must serialize this call with all OCIO environment-variable calls
821/// and other native code that accesses the same process environment.
822pub unsafe fn unset_env_variable(name: impl AsRef<str>) -> Result<()> {
823    let name = cstring(name)?;
824    clear_last_error();
825    unsafe { ocio_sys::ocio_unset_env_variable(name.as_ptr()) };
826    ocio_call_status()
827}
828
829/// Return whether an OCIO process environment variable is present.
830///
831/// # Safety
832/// OCIO documents its environment-variable helpers as not thread-safe. The
833/// caller must serialize this call with all OCIO environment-variable calls
834/// and other native code that accesses the same process environment.
835pub unsafe fn is_env_variable_present(name: impl AsRef<str>) -> Result<bool> {
836    let name = cstring(name)?;
837    clear_last_error();
838    let present = unsafe { ocio_sys::ocio_is_env_variable_present(name.as_ptr()) };
839    ocio_call_status()?;
840    Ok(present)
841}
842
843/// Compatibility alias for overriding the OCIO global logging level.
844#[deprecated(
845    since = "0.2.0",
846    note = "discarded OCIO errors; prefer try_set_logging_level()"
847)]
848pub fn set_logging_level_to_override(level: crate::LoggingLevel) {
849    let _ = try_set_logging_level(level);
850}
851
852/// Returns the processor cache flags from the current global config.
853///
854/// If no current config is installed, this returns an empty flag set.
855///
856/// # Safety
857/// The caller must meet the synchronization requirements of [`try_current_config`].
858///
859/// ```compile_fail
860/// let _ = ocio_rs::processor_cache_flags(); // Reads a native global snapshot.
861/// ```
862pub unsafe fn processor_cache_flags() -> crate::ProcessorCacheFlags {
863    unsafe { try_const_current_config() }
864        .ok()
865        .flatten()
866        .and_then(|config| config.processor_cache_flags().ok())
867        .unwrap_or(crate::ProcessorCacheFlags(0))
868}
869
870/// Updates the processor cache flags on the current global config, if any.
871#[deprecated(
872    since = "0.2.0",
873    note = "discarded OCIO errors; prefer try_set_processor_cache_flags()"
874)]
875/// # Safety
876/// The caller must meet the requirements of [`try_set_processor_cache_flags`].
877///
878/// ```compile_fail
879/// # #[allow(deprecated)]
880/// ocio_rs::set_processor_cache_flags(ocio_rs::ProcessorCacheFlags::DEFAULT);
881/// ```
882pub unsafe fn set_processor_cache_flags(flags: crate::ProcessorCacheFlags) {
883    let _ = unsafe { try_set_processor_cache_flags(flags) };
884}
885
886/// Try to update processor-cache flags on the current global config.
887///
888/// When the policy changes, this installs a new config with fresh caches.
889/// Earlier read-only snapshots and existing processors are unaffected.
890/// Serialize this read/modify/install operation with other global config writes.
891/// This returns `Ok(())` when no global config is installed.
892///
893/// # Safety
894/// The caller must meet the synchronization requirements of [`try_current_config`]
895/// throughout this read/modify/install operation and coordinate global writes.
896///
897/// ```compile_fail
898/// let _ = ocio_rs::try_set_processor_cache_flags(ocio_rs::ProcessorCacheFlags::DEFAULT);
899/// ```
900pub unsafe fn try_set_processor_cache_flags(flags: crate::ProcessorCacheFlags) -> Result<()> {
901    if let Some(current) = unsafe { try_const_current_config()? } {
902        if current.processor_cache_flags()? != flags {
903            let config = current.create_editable_copy()?;
904            config.try_set_processor_cache_flags(flags.0 as i32)?;
905            try_set_current_config(&config)?;
906        }
907    }
908    Ok(())
909}
910
911pub(crate) fn cstring(value: impl AsRef<str>) -> Result<CString> {
912    CString::new(value.as_ref()).map_err(|_| OcioError::InteriorNul)
913}
914
915pub(crate) unsafe fn cstr_to_opt_string(ptr: *const i8) -> Option<String> {
916    if ptr.is_null() {
917        None
918    } else {
919        Some(std::ffi::CStr::from_ptr(ptr).to_string_lossy().into_owned())
920    }
921}
922
923// v2.5.1 compat: accept *mut c_void (new return type for many getter functions)
924pub(crate) unsafe fn cstr_from_mut(ptr: *mut c_void) -> Option<String> {
925    cstr_to_opt_string(ptr as *const i8)
926}
927
928pub(crate) fn clear_last_error() {
929    unsafe { ocio_sys::ocio_error_clear_last() };
930}
931
932// A user-supplied panic payload can itself panic when dropped. Never let a
933// second panic unwind across a C callback boundary.
934pub(crate) fn discard_callback_panic(payload: Box<dyn std::any::Any + Send>) {
935    if let Err(second) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(payload))) {
936        std::mem::forget(second);
937    }
938}
939
940pub(crate) fn catch_callback_unwind<F, T>(callback: F) -> std::result::Result<T, ()>
941where
942    F: FnOnce() -> T + std::panic::UnwindSafe,
943{
944    match std::panic::catch_unwind(callback) {
945        Ok(value) => Ok(value),
946        Err(payload) => {
947            discard_callback_panic(payload);
948            Err(())
949        }
950    }
951}
952
953pub(crate) fn last_error_message() -> Option<String> {
954    unsafe { cstr_to_opt_string(ocio_sys::ocio_error_get_last()) }
955}
956
957/// Read and clear the bridge's thread-local error slot.
958///
959/// Each safe wrapper clears the slot before calling into the bridge. Consuming
960/// an error here prevents a handled failure from being observed by a later FFI
961/// call on the same thread.
962fn take_last_error() -> Option<(String, bool)> {
963    let message = last_error_message();
964    message.map(|message| {
965        let missing_file = unsafe { ocio_sys::ocio_error_get_last_kind() == 1 };
966        clear_last_error();
967        (message, missing_file)
968    })
969}
970
971fn bridge_error(message: String, missing_file: bool) -> OcioError {
972    if missing_file {
973        OcioError::MissingFile(message)
974    } else {
975        OcioError::Ocio(message)
976    }
977}
978
979pub(crate) fn validation_status() -> Result<()> {
980    match take_last_error() {
981        Some((message, _)) => Err(OcioError::ValidationFailed(message)),
982        None => Ok(()),
983    }
984}
985
986pub(crate) fn ocio_call_status() -> Result<()> {
987    match take_last_error() {
988        Some((message, missing_file)) => Err(bridge_error(message, missing_file)),
989        None => Ok(()),
990    }
991}
992
993pub(crate) fn handle_result(handle: *mut c_void) -> Result<NonNull<c_void>> {
994    match NonNull::new(handle) {
995        Some(handle) => Ok(handle),
996        None => match take_last_error() {
997            Some((message, missing_file)) => Err(bridge_error(message, missing_file)),
998            None => Err(OcioError::AllocationFailed),
999        },
1000    }
1001}
1002
1003#[cfg(test)]
1004mod tests {
1005    #[cfg(ocio_stub)]
1006    static CALLBACK_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
1007
1008    #[test]
1009    fn hash_callback_accepts_null_empty_input() {
1010        #[cfg(ocio_stub)]
1011        let _test_guard = CALLBACK_TEST_LOCK.lock().unwrap();
1012        let _guard = super::compute_hash_callback_update_lock().lock().unwrap();
1013        let previous =
1014            super::compute_hash_callback_slot()
1015                .lock()
1016                .unwrap()
1017                .replace(std::sync::Arc::new(|input| {
1018                    assert!(input.is_empty());
1019                    b"hash".to_vec()
1020                }));
1021        let mut output = std::ptr::null();
1022        let mut output_len = 0;
1023        assert!(!unsafe {
1024            super::rust_compute_hash_callback(std::ptr::null(), 1, &mut output, &mut output_len)
1025        });
1026        let succeeded = unsafe {
1027            super::rust_compute_hash_callback(std::ptr::null(), 0, &mut output, &mut output_len)
1028        };
1029        assert!(succeeded);
1030        assert_eq!(
1031            unsafe { std::slice::from_raw_parts(output, output_len) },
1032            b"hash"
1033        );
1034        *super::compute_hash_callback_slot().lock().unwrap() = previous;
1035    }
1036
1037    #[test]
1038    #[cfg(ocio_stub)]
1039    fn callback_captures_are_dropped_without_internal_locks() {
1040        use std::sync::atomic::{AtomicBool, Ordering};
1041        use std::sync::Arc;
1042
1043        struct Probe {
1044            update: &'static std::sync::Mutex<()>,
1045            slot_unlocked: fn() -> bool,
1046            ok: Arc<AtomicBool>,
1047        }
1048        impl Drop for Probe {
1049            fn drop(&mut self) {
1050                self.ok.store(
1051                    self.update.try_lock().is_ok() && (self.slot_unlocked)(),
1052                    Ordering::SeqCst,
1053                );
1054            }
1055        }
1056        let _test_guard = CALLBACK_TEST_LOCK.lock().unwrap();
1057        for reset in [false, true] {
1058            let ok = Arc::new(AtomicBool::new(false));
1059            let probe = Probe {
1060                update: super::logging_callback_update_lock(),
1061                slot_unlocked: || super::logging_callback_slot().try_lock().is_ok(),
1062                ok: Arc::clone(&ok),
1063            };
1064            super::set_logging_callback(move |_| {
1065                let _ = &probe;
1066            })
1067            .unwrap();
1068            if reset {
1069                super::reset_logging_callback().unwrap();
1070            } else {
1071                super::set_logging_callback(|_| {}).unwrap();
1072                super::reset_logging_callback().unwrap();
1073            }
1074            assert!(ok.load(Ordering::SeqCst));
1075
1076            let ok = Arc::new(AtomicBool::new(false));
1077            let probe = Probe {
1078                update: super::compute_hash_callback_update_lock(),
1079                slot_unlocked: || super::compute_hash_callback_slot().try_lock().is_ok(),
1080                ok: Arc::clone(&ok),
1081            };
1082            // Stub mode performs no native hashing; the test lock excludes the
1083            // other test that accesses the callback slot in this process.
1084            unsafe {
1085                super::set_compute_hash_callback(move |_| {
1086                    let _ = &probe;
1087                    Vec::new()
1088                })
1089            }
1090            .unwrap();
1091            if reset {
1092                unsafe { super::reset_compute_hash_callback() }.unwrap();
1093            } else {
1094                unsafe { super::set_compute_hash_callback(|_| Vec::new()) }.unwrap();
1095                unsafe { super::reset_compute_hash_callback() }.unwrap();
1096            }
1097            assert!(ok.load(Ordering::SeqCst));
1098        }
1099    }
1100
1101    #[test]
1102    #[allow(deprecated)]
1103    fn unsupported_trace_logging_is_rejected_before_native_call() {
1104        assert!(matches!(
1105            super::try_set_logging_level(super::LoggingLevel::Trace),
1106            Err(super::OcioError::InvalidInput(_))
1107        ));
1108        assert!(matches!(
1109            super::try_log_message(super::LoggingLevel::Trace, "message"),
1110            Err(super::OcioError::InvalidInput(_))
1111        ));
1112    }
1113
1114    use super::*;
1115
1116    #[test]
1117    fn processor_cache_flags_no_crash() {
1118        // This test process has no foreign native global-config users.
1119        let f = unsafe { processor_cache_flags() };
1120        assert!(unsafe { try_set_processor_cache_flags(f) }.is_ok());
1121    }
1122
1123    #[test]
1124    fn current_config_no_crash() {
1125        let _ = unsafe { current_config() };
1126    }
1127
1128    #[test]
1129    fn try_current_config_no_crash() {
1130        let _ = unsafe { try_current_config() };
1131    }
1132
1133    #[cfg(feature = "bundled")]
1134    #[test]
1135    fn bridge_errors_are_consumed_after_handle_conversion() {
1136        let path = cstring("this-file-does-not-exist.ocio").expect("valid test path");
1137        clear_last_error();
1138        let handle = unsafe { ocio_sys::ocio_config_create_from_file(path.as_ptr().cast()) };
1139
1140        let error = handle_result(handle).expect_err("missing config");
1141        if version_hex() >= 0x02060000 {
1142            assert!(matches!(error, OcioError::MissingFile(_)));
1143        } else {
1144            assert!(matches!(
1145                error,
1146                OcioError::Ocio(_) | OcioError::MissingFile(_)
1147            ));
1148        }
1149        assert!(last_error_message().is_none());
1150        assert_eq!(unsafe { ocio_sys::ocio_error_get_last_kind() }, 0);
1151    }
1152
1153    #[cfg(feature = "bundled")]
1154    #[test]
1155    fn bridge_errors_are_consumed_after_validation() {
1156        let transform = crate::transform::FileTransform::create().expect("file transform create");
1157
1158        assert!(matches!(
1159            transform.validate(),
1160            Err(OcioError::ValidationFailed(_))
1161        ));
1162        assert!(last_error_message().is_none());
1163    }
1164
1165    #[test]
1166    #[allow(deprecated)]
1167    fn current_config_compat_alias_no_crash() {
1168        let _ = unsafe { get_current_config() };
1169    }
1170}