Skip to main content

ocio_rs/
processor.rs

1use std::ffi::c_void;
2use std::ptr::NonNull;
3
4use crate::transform::{transform_from_raw_handle, GroupTransform, Transform};
5#[cfg(feature = "v2_5")]
6use crate::HueCurveType;
7use crate::{
8    cstr_from_mut, cstr_to_opt_string, cstring, BitDepth, ChannelOrdering, DynamicPropertyType,
9    FormatMetadata, GpuLanguage, Interpolation, OcioError, ProcessorMetadata, RGBCurveType, Result,
10};
11use ocio_sys;
12
13fn normalized_stride(api: &str, stride: i64, channels_per_pixel: usize) -> Result<usize> {
14    let stride = if stride == 0 {
15        channels_per_pixel
16    } else {
17        usize::try_from(stride)
18            .map_err(|_| OcioError::InvalidInput(format!("{api}: stride must be non-negative")))?
19    };
20    if stride < channels_per_pixel {
21        return Err(OcioError::InvalidInput(format!(
22            "{api}: stride={stride} is smaller than the {channels_per_pixel} channels per pixel"
23        )));
24    }
25    Ok(stride)
26}
27
28fn required_scalar_len(
29    api: &str,
30    num_pixels: i64,
31    stride: i64,
32    channels_per_pixel: usize,
33) -> Result<usize> {
34    // Native generic scanline loops calculate four samples per pixel in
35    // C++ int arithmetic, which can be narrower than long.
36    if num_pixels > (std::ffi::c_int::MAX / 4) as i64 {
37        return Err(OcioError::InvalidInput(format!(
38            "{api}: pixel count exceeds the native scanline limit"
39        )));
40    }
41    let num_pixels = usize::try_from(num_pixels)
42        .map_err(|_| OcioError::InvalidInput(format!("{api}: num_pixels must be non-negative")))?;
43    let stride = normalized_stride(api, stride, channels_per_pixel)?;
44    if num_pixels == 0 {
45        return Ok(0);
46    }
47    num_pixels
48        .checked_sub(1)
49        .and_then(|pixels_before_last| pixels_before_last.checked_mul(stride))
50        .and_then(|last_pixel_offset| last_pixel_offset.checked_add(channels_per_pixel))
51        .ok_or_else(|| OcioError::InvalidInput(format!("{api}: required buffer size overflowed")))
52}
53
54fn validate_stride_byte_width(
55    api: &str,
56    num_pixels: i64,
57    stride: i64,
58    channels_per_pixel: usize,
59    bytes_per_channel: usize,
60) -> Result<()> {
61    let stride = normalized_stride(api, stride, channels_per_pixel)?;
62    let byte_stride = stride
63        .checked_mul(bytes_per_channel)
64        .ok_or_else(|| OcioError::InvalidInput(format!("{api}: byte stride overflowed")))?;
65    if byte_stride > isize::MAX as usize {
66        return Err(OcioError::InvalidInput(format!(
67            "{api}: byte stride exceeds the C++ ptrdiff_t range"
68        )));
69    }
70    let pixels = usize::try_from(num_pixels)
71        .map_err(|_| OcioError::InvalidInput(format!("{api}: invalid pixel count")))?;
72    if byte_stride
73        .checked_mul(pixels)
74        .is_none_or(|row_stride| row_stride > isize::MAX as usize)
75    {
76        return Err(OcioError::InvalidInput(format!(
77            "{api}: native row stride exceeds the C++ ptrdiff_t range"
78        )));
79    }
80    if channels_per_pixel == 4 && byte_stride > std::ffi::c_int::MAX as usize {
81        return Err(OcioError::InvalidInput(format!(
82            "{api}: RGBA byte stride exceeds the native packed-layout limit"
83        )));
84    }
85    Ok(())
86}
87
88fn rgba_single_pixel_native_stride(
89    api: &str,
90    pixels: i64,
91    stride: i64,
92    sample: usize,
93) -> Result<i64> {
94    if pixels != 1 {
95        return Ok(stride);
96    }
97    let step = normalized_stride(api, stride, 4)?;
98    let bytes = step
99        .checked_mul(sample)
100        .filter(|&n| n <= isize::MAX as usize)
101        .ok_or_else(|| {
102            OcioError::InvalidInput(format!(
103                "{api}: byte stride exceeds the C++ ptrdiff_t range"
104            ))
105        })?;
106    // No second pixel exists; avoid OCIO's lossy int cast without changing
107    // the layout of any accessed channel or weakening stride validation.
108    Ok(if bytes > std::ffi::c_int::MAX as usize {
109        4
110    } else {
111        stride
112    })
113}
114
115pub(crate) fn bit_depth_bytes_per_channel(api: &str, bit_depth: BitDepth) -> Result<usize> {
116    match bit_depth {
117        BitDepth::Uint8 => Ok(1),
118        BitDepth::Uint10
119        | BitDepth::Uint12
120        | BitDepth::Uint14
121        | BitDepth::Uint16
122        | BitDepth::F16 => Ok(2),
123        BitDepth::Uint32 | BitDepth::F32 => Ok(4),
124        BitDepth::Unknown => Err(OcioError::InvalidInput(format!(
125            "{api}: BitDepth::Unknown is not valid for packed pixel IO"
126        ))),
127    }
128}
129
130fn validate_scalar_buffer_len(
131    api: &str,
132    actual_len: usize,
133    num_pixels: i64,
134    stride: i64,
135    channels_per_pixel: usize,
136) -> Result<()> {
137    let required_len = required_scalar_len(api, num_pixels, stride, channels_per_pixel)?;
138    if num_pixels > 0 {
139        validate_stride_byte_width(
140            api,
141            num_pixels,
142            stride,
143            channels_per_pixel,
144            std::mem::size_of::<f32>(),
145        )?;
146    }
147    if actual_len < required_len {
148        return Err(OcioError::InvalidInput(format!(
149            "{api}: buffer too small for num_pixels={num_pixels}, stride={stride}; required at least {required_len} scalars, got {actual_len}"
150        )));
151    }
152    Ok(())
153}
154
155fn validate_packed_buffer_len(
156    api: &str,
157    actual_len: usize,
158    bit_depth: BitDepth,
159    num_pixels: i64,
160    stride: i64,
161    channels_per_pixel: usize,
162) -> Result<()> {
163    let required_scalars = required_scalar_len(api, num_pixels, stride, channels_per_pixel)?;
164    let bytes_per_channel = bit_depth_bytes_per_channel(api, bit_depth)?;
165    if num_pixels > 0 {
166        validate_stride_byte_width(
167            api,
168            num_pixels,
169            stride,
170            channels_per_pixel,
171            bytes_per_channel,
172        )?;
173    }
174    let required_len = required_scalars
175        .checked_mul(bytes_per_channel)
176        .ok_or_else(|| {
177            OcioError::InvalidInput(format!("{api}: required packed buffer size overflowed"))
178        })?;
179    if actual_len < required_len {
180        return Err(OcioError::InvalidInput(format!(
181            "{api}: buffer too small for num_pixels={num_pixels}, stride={stride}, bit_depth={bit_depth:?}; required at least {required_len} bytes, got {actual_len}"
182        )));
183    }
184    Ok(())
185}
186
187fn validate_packed_buffer_alignment(
188    api: &str,
189    buffer: *const u8,
190    bit_depth: BitDepth,
191    num_pixels: i64,
192) -> Result<()> {
193    if num_pixels == 0 {
194        return Ok(());
195    }
196    let alignment = bit_depth_bytes_per_channel(api, bit_depth)?;
197    if !(buffer as usize).is_multiple_of(alignment) {
198        return Err(OcioError::InvalidInput(format!(
199            "{api}: buffer must be aligned to {alignment} bytes for {bit_depth:?} data"
200        )));
201    }
202    Ok(())
203}
204
205/// An immutable color-processing pipeline produced from a [`Config`](crate::Config).
206///
207/// A `Processor` wraps the result of asking a config for a conversion between
208/// two color spaces, a display/view pipeline, a transform, or a named
209/// transform. It is the bridge between configuration and execution.
210///
211/// Use [`default_cpu_processor`] or [`default_gpu_processor`] to obtain an
212/// execution-ready handle. For more control over optimization or bit depth,
213/// see [`optimized_cpu_processor`], [`optimized_gpu_processor`], and
214/// [`optimized_processor_bitdepth`].
215///
216/// The processor is immutable: once created, its pipeline does not change.
217/// Dynamic properties (if any) are accessed through
218/// [`dynamic_property`](Self::dynamic_property) and are scoped to the
219/// processor or its derived CPU/GPU execution handles.
220///
221/// Processor and its execution handles are not `Send` or `Sync`: OCIO dynamic
222/// property handles can outlive their parent and are not internally synchronized.
223/// Create separate processing pipelines on the threads that use them.
224///
225/// ```compile_fail
226/// # use ocio_rs::Processor;
227/// fn require_send<T: Send>() {}
228/// require_send::<Processor>();
229/// ```
230///
231/// [`default_cpu_processor`]: Self::default_cpu_processor
232/// [`default_gpu_processor`]: Self::default_gpu_processor
233/// [`optimized_cpu_processor`]: Self::optimized_cpu_processor
234/// [`optimized_gpu_processor`]: Self::optimized_gpu_processor
235/// [`optimized_processor_bitdepth`]: Self::optimized_processor_bitdepth
236pub struct Processor {
237    pub(crate) handle: NonNull<c_void>,
238}
239
240impl Processor {
241    fn optimization_flags_for_bridge(flags: u64) -> Result<i32> {
242        // The legacy bridge takes a signed C int, but OCIO defines a 32-bit
243        // flag mask. Preserve all its bits (including OPTIMIZATION_ALL).
244        let flags = u32::try_from(flags).map_err(|_| {
245            OcioError::InvalidInput("processor optimization flags exceed 32 bits".into())
246        })?;
247        Ok(flags as i32)
248    }
249
250    /// Share the immutable top-level native format metadata without copying.
251    pub fn try_const_format_metadata(&self) -> Result<Option<crate::ConstFormatMetadata>> {
252        crate::clear_last_error();
253        let handle = unsafe {
254            ocio_sys::ocio_processor_get_const_format_metadata(self.handle.as_ptr(), false, 0)
255        };
256        crate::ocio_call_status()?;
257        Ok(NonNull::new(handle).map(|handle| crate::ConstFormatMetadata { handle }))
258    }
259    /// Share immutable format metadata for an individual processor transform.
260    pub fn try_const_transform_format_metadata(
261        &self,
262        index: i32,
263    ) -> Result<Option<crate::ConstFormatMetadata>> {
264        crate::clear_last_error();
265        let handle = unsafe {
266            ocio_sys::ocio_processor_get_const_format_metadata(self.handle.as_ptr(), true, index)
267        };
268        crate::ocio_call_status()?;
269        Ok(NonNull::new(handle).map(|handle| crate::ConstFormatMetadata { handle }))
270    }
271    /// Build a native CPU processor for explicit input and output bit depths.
272    pub fn optimized_cpu_processor_bit_depth(
273        &self,
274        input: BitDepth,
275        output: BitDepth,
276        flags: u32,
277    ) -> Result<CPUProcessor> {
278        if input == BitDepth::Unknown || output == BitDepth::Unknown {
279            return Err(OcioError::InvalidInput(
280                "CPU processor bit depth cannot be unknown".into(),
281            ));
282        }
283        crate::clear_last_error();
284        let handle = unsafe {
285            ocio_sys::ocio_processor_get_optimized_cpu_processor_bit_depth(
286                self.handle.as_ptr(),
287                input as i32,
288                output as i32,
289                flags,
290            )
291        };
292        Ok(CPUProcessor {
293            handle: crate::handle_result(handle)?,
294            f32_pixel_io: input == BitDepth::F32 && output == BitDepth::F32,
295        })
296    }
297    /// Return whether the processor is an identity/no-op pipeline.
298    pub fn is_no_op(&self) -> bool {
299        self.try_is_no_op().unwrap_or(false)
300    }
301
302    /// Fallible variant of [`Self::is_no_op`].
303    pub fn try_is_no_op(&self) -> Result<bool> {
304        crate::clear_last_error();
305        let value =
306            unsafe { ocio_sys::ocio_processor_is_no_op(self.handle.as_ptr() as *mut c_void) };
307        crate::ocio_call_status()?;
308        Ok(value)
309    }
310
311    /// Return whether the processor mixes channels rather than operating lane-wise.
312    pub fn has_channel_crosstalk(&self) -> bool {
313        self.try_has_channel_crosstalk().unwrap_or(false)
314    }
315
316    /// Fallible variant of [`Self::has_channel_crosstalk`].
317    pub fn try_has_channel_crosstalk(&self) -> Result<bool> {
318        crate::clear_last_error();
319        let value = unsafe {
320            ocio_sys::ocio_processor_has_channel_crosstalk(self.handle.as_ptr() as *mut c_void)
321        };
322        crate::ocio_call_status()?;
323        Ok(value)
324    }
325
326    /// Return OCIO's cache identifier for this processor instance.
327    pub fn cache_id(&self) -> Option<String> {
328        self.try_cache_id().ok().flatten()
329    }
330
331    /// Return OCIO's cache identifier, preserving bridge errors.
332    pub fn try_cache_id(&self) -> Result<Option<String>> {
333        crate::clear_last_error();
334        let value = unsafe {
335            cstr_from_mut(ocio_sys::ocio_processor_get_cache_id(
336                self.handle.as_ptr() as *mut c_void
337            ))
338        };
339        crate::ocio_call_status()?;
340        Ok(value)
341    }
342
343    /// Create the default CPU execution path for this processor.
344    pub fn default_cpu_processor(&self) -> Result<CPUProcessor> {
345        crate::clear_last_error();
346        let handle = unsafe {
347            ocio_sys::ocio_processor_get_default_cpu_processor(self.handle.as_ptr() as *mut c_void)
348        };
349        crate::handle_result(handle).map(|handle| CPUProcessor {
350            handle,
351            f32_pixel_io: true,
352        })
353    }
354
355    /// Create an optimized CPU execution path for this processor.
356    pub fn optimized_cpu_processor(&self, flags: u64) -> Result<CPUProcessor> {
357        let flags = Self::optimization_flags_for_bridge(flags)?;
358        crate::clear_last_error();
359        let handle = unsafe {
360            ocio_sys::ocio_processor_get_optimized_cpu_processor(self.handle.as_ptr(), flags)
361        };
362        crate::handle_result(handle).map(|handle| CPUProcessor {
363            handle,
364            f32_pixel_io: true,
365        })
366    }
367
368    #[doc(hidden)]
369    #[deprecated(since = "0.2.0", note = "compat alias; prefer optimized_processor()")]
370    pub fn optimized_processor_v1(&self, flags: u64) -> Result<Self> {
371        let flags = Self::optimization_flags_for_bridge(flags)?;
372        crate::clear_last_error();
373        let handle = unsafe {
374            ocio_sys::ocio_processor_get_optimized_processor_v1(self.handle.as_ptr(), flags)
375        };
376        crate::handle_result(handle).map(|handle| Self { handle })
377    }
378
379    /// Create an optimized processor variant for explicit input/output bit depths.
380    ///
381    /// This is mainly useful when matching a specific host application's pixel
382    /// format contract before extracting CPU or GPU execution helpers. Pass
383    /// discriminants from [`BitDepth`]; undefined integer values are rejected.
384    pub fn optimized_processor_bitdepth(
385        &self,
386        in_bit_depth: i32,
387        out_bit_depth: i32,
388        flags: u64,
389    ) -> Result<Self> {
390        let flags = Self::optimization_flags_for_bridge(flags)?;
391        crate::clear_last_error();
392        let handle = unsafe {
393            ocio_sys::ocio_processor_get_optimized_processor_v2(
394                self.handle.as_ptr(),
395                in_bit_depth,
396                out_bit_depth,
397                flags,
398            )
399        };
400        crate::handle_result(handle).map(|handle| Self { handle })
401    }
402
403    #[doc(hidden)]
404    #[deprecated(
405        since = "0.2.0",
406        note = "compat alias; prefer optimized_processor_bitdepth()"
407    )]
408    pub fn optimized_processor_v2(
409        &self,
410        in_bit_depth: i32,
411        out_bit_depth: i32,
412        flags: u64,
413    ) -> Result<Self> {
414        self.optimized_processor_bitdepth(in_bit_depth, out_bit_depth, flags)
415    }
416
417    /// Create the default GPU execution path for this processor.
418    pub fn default_gpu_processor(&self) -> Result<GPUProcessor> {
419        crate::clear_last_error();
420        let handle = unsafe {
421            ocio_sys::ocio_processor_get_default_gpu_processor(self.handle.as_ptr() as *mut c_void)
422        };
423        crate::handle_result(handle).map(|handle| GPUProcessor { handle })
424    }
425
426    /// Create an optimized GPU execution path for this processor.
427    pub fn optimized_gpu_processor(&self, flags: u64) -> Result<GPUProcessor> {
428        let flags = Self::optimization_flags_for_bridge(flags)?;
429        crate::clear_last_error();
430        let handle = unsafe {
431            ocio_sys::ocio_processor_get_optimized_gpu_processor(self.handle.as_ptr(), flags)
432        };
433        crate::handle_result(handle).map(|handle| GPUProcessor { handle })
434    }
435
436    #[doc(hidden)]
437    #[deprecated(
438        since = "0.2.0",
439        note = "legacy OCIO GPU optimization path; prefer optimized_gpu_processor or default_gpu_processor"
440    )]
441    pub fn optimized_legacy_gpu_processor(
442        &self,
443        flags: u64,
444        edge_len: u32,
445    ) -> Result<GPUProcessor> {
446        // OCIO v1-style GPU path that bakes some ops into a 3D LUT.
447        let flags = Self::optimization_flags_for_bridge(flags)?;
448        crate::clear_last_error();
449        let handle = unsafe {
450            ocio_sys::ocio_processor_get_optimized_legacy_gpu_processor(
451                self.handle.as_ptr(),
452                flags,
453                edge_len,
454            )
455        };
456        crate::handle_result(handle).map(|handle| GPUProcessor { handle })
457    }
458
459    /// Create an optimized processor without choosing a CPU or GPU execution
460    /// backend. This calls OCIO's flags-only overload, which uses F32 bit depths.
461    pub fn optimized_processor(&self, flags: u64) -> Result<Self> {
462        let flags = Self::optimization_flags_for_bridge(flags)?;
463        crate::clear_last_error();
464        let handle =
465            unsafe { ocio_sys::ocio_processor_optimized_processor(self.handle.as_ptr(), flags) };
466        crate::handle_result(handle).map(|handle| Self { handle })
467    }
468
469    /// Borrow a runtime-adjustable dynamic property from the processor.
470    pub fn dynamic_property(&self, property_type: DynamicPropertyType) -> Result<DynamicProperty> {
471        crate::clear_last_error();
472        let handle = unsafe {
473            ocio_sys::ocio_processor_get_dynamic_property(
474                self.handle.as_ptr(),
475                property_type as i32,
476            )
477        };
478        crate::handle_result(handle).map(|handle| DynamicProperty { handle })
479    }
480
481    /// Return the number of transforms represented by this processor.
482    pub fn num_transforms(&self) -> i32 {
483        unsafe { ocio_sys::ocio_processor_get_num_transforms(self.handle.as_ptr() as *mut c_void) }
484    }
485
486    /// Materialize the processor back into an equivalent group transform, when available.
487    ///
488    /// This compatibility helper discards OCIO error details. Prefer
489    /// [`Self::try_create_group_transform`] in new code.
490    pub fn create_group_transform(&self) -> Option<GroupTransform> {
491        self.try_create_group_transform().ok()
492    }
493
494    /// Materialize the processor back into an equivalent group transform.
495    pub fn try_create_group_transform(&self) -> Result<GroupTransform> {
496        crate::clear_last_error();
497        let handle = unsafe {
498            ocio_sys::ocio_processor_create_group_transform(self.handle.as_ptr() as *mut c_void)
499        };
500        let handle = crate::handle_result(handle)?;
501        match transform_from_raw_handle(handle.as_ptr()) {
502            Some(Transform::Group(transform)) => Ok(transform),
503            Some(_) => Err(crate::OcioError::ValidationFailed(
504                "OCIO returned a non-group transform for Processor::createGroupTransform".into(),
505            )),
506            None => Err(crate::OcioError::AllocationFailed),
507        }
508    }
509
510    // ── v2.5.1 ──
511    /// Return an independent editable copy of the processor's top-level metadata.
512    pub fn format_metadata(&self) -> Option<FormatMetadata> {
513        self.try_format_metadata().ok()
514    }
515
516    /// Copy the processor's top-level metadata, preserving native errors.
517    pub fn try_format_metadata(&self) -> Result<FormatMetadata> {
518        crate::clear_last_error();
519        let h = unsafe {
520            ocio_sys::ocio_processor_get_format_metadata(self.handle.as_ptr() as *mut c_void)
521        };
522        crate::handle_result(h).map(|handle| FormatMetadata { handle })
523    }
524
525    /// Return an editable metadata copy for the transform at `index`.
526    pub fn transform_format_metadata(&self, index: i32) -> Option<FormatMetadata> {
527        self.try_transform_format_metadata(index).ok()
528    }
529
530    /// Copy format metadata for the transform at `index`.
531    pub fn try_transform_format_metadata(&self, index: i32) -> Result<FormatMetadata> {
532        crate::clear_last_error();
533        let h = unsafe {
534            ocio_sys::ocio_processor_get_transform_format_metadata(self.handle.as_ptr(), index)
535        };
536        crate::handle_result(h).map(|handle| FormatMetadata { handle })
537    }
538
539    /// Return an independent editable copy of processor metadata.
540    pub fn processor_metadata(&self) -> Option<ProcessorMetadata> {
541        self.try_processor_metadata().ok()
542    }
543
544    /// Copy technical processor metadata, preserving native errors.
545    pub fn try_processor_metadata(&self) -> Result<ProcessorMetadata> {
546        crate::clear_last_error();
547        let h = unsafe {
548            ocio_sys::ocio_processor_get_processor_metadata(self.handle.as_ptr() as *mut c_void)
549        };
550        crate::handle_result(h).map(|handle| ProcessorMetadata { handle })
551    }
552
553    /// Share immutable native processor metadata without copying its entries.
554    pub fn try_const_processor_metadata(&self) -> Result<Option<crate::ConstProcessorMetadata>> {
555        crate::clear_last_error();
556        let handle = unsafe { ocio_sys::ocio_processor_get_const_metadata(self.handle.as_ptr()) };
557        crate::ocio_call_status()?;
558        Ok(NonNull::new(handle).map(|handle| crate::ConstProcessorMetadata { handle }))
559    }
560
561    /// Return whether the processor exposes a dynamic property of `prop_type`.
562    pub fn has_dynamic_property_kind(&self, prop_type: DynamicPropertyType) -> bool {
563        self.try_has_dynamic_property_kind(prop_type)
564            .unwrap_or(false)
565    }
566
567    /// Fallible variant of [`Self::has_dynamic_property_kind`].
568    pub fn try_has_dynamic_property_kind(&self, prop_type: DynamicPropertyType) -> Result<bool> {
569        crate::clear_last_error();
570        let value = unsafe {
571            ocio_sys::ocio_processor_has_dynamic_property(self.handle.as_ptr(), prop_type as i32)
572        };
573        crate::ocio_call_status()?;
574        Ok(value)
575    }
576
577    #[doc(hidden)]
578    #[deprecated(
579        since = "0.2.0",
580        note = "compat alias; prefer has_dynamic_property_kind with DynamicPropertyType"
581    )]
582    pub fn has_dynamic_property(&self, prop_type: i32) -> bool {
583        crate::clear_last_error();
584        let value = unsafe {
585            ocio_sys::ocio_processor_has_dynamic_property(self.handle.as_ptr(), prop_type)
586        };
587        let _ = crate::ocio_call_status();
588        value
589    }
590
591    /// Return whether this processor contains any runtime-adjustable properties.
592    pub fn is_dynamic(&self) -> bool {
593        self.try_is_dynamic().unwrap_or(false)
594    }
595
596    /// Fallible variant of [`Self::is_dynamic`].
597    pub fn try_is_dynamic(&self) -> Result<bool> {
598        crate::clear_last_error();
599        let value =
600            unsafe { ocio_sys::ocio_processor_is_dynamic(self.handle.as_ptr() as *mut c_void) };
601        crate::ocio_call_status()?;
602        Ok(value)
603    }
604}
605
606impl Drop for Processor {
607    fn drop(&mut self) {
608        unsafe { ocio_sys::ocio_processor_destroy(self.handle.as_ptr() as *mut c_void) };
609    }
610}
611
612// --- CPUProcessor ---
613
614/// CPU implementation of a [`Processor`].
615///
616/// Provides safe in-place pixel processing methods for `f32` RGB/RGBA
617/// buffers and packed byte buffers at various OCIO bit depths. Each method
618/// applies the color transform described by the originating `Processor`.
619///
620/// # Pixel layout
621///
622/// The scalar-stride methods ([`apply_rgba_pixels`](Self::apply_rgba_pixels),
623/// [`apply_rgb_pixels`](Self::apply_rgb_pixels)) accept `&mut [f32]` buffers
624/// and measure stride in `f32` elements, not bytes. Padding elements beyond
625/// the pixel stride are left untouched. A stride of zero uses OCIO's native
626/// three- or four-channel default; smaller strides are rejected.
627///
628/// The packed-byte methods ([`apply_rgba_packed_bit_depth`](Self::apply_rgba_packed_bit_depth),
629/// [`apply_rgb_packed_bit_depth`](Self::apply_rgb_packed_bit_depth)) interpret
630/// the buffer according to the provided [`BitDepth`], with stride measured in
631/// channels (not bytes). A stride of zero uses the native channel count, and
632/// smaller strides are rejected before calling OCIO. Multi-byte packed data
633/// must be aligned to its storage width.
634///
635/// This handle is thread-confined; see [`Processor`] for the dynamic-property
636/// synchronization rationale.
637///
638/// ```compile_fail
639/// # use ocio_rs::CPUProcessor;
640/// fn require_send<T: Send>() {}
641/// require_send::<CPUProcessor>();
642/// ```
643///
644/// [`BitDepth`]: crate::BitDepth
645pub struct CPUProcessor {
646    handle: NonNull<c_void>,
647    // OCIO's single-pixel APIs require F32 input and output but do not check it.
648    // Set once at construction so the pixel hot path avoids two native queries.
649    f32_pixel_io: bool,
650}
651
652/// A CPU processor proven to contain no dynamic properties.
653///
654/// This wrapper can be shared across threads to process independent image
655/// buffers. Its one-time dynamic-property validation adds no lock to pixel
656/// processing. Single-pixel calls still check the processor's cached bit-depth
657/// compatibility. OCIO native interop must not mutate or replace its
658/// underlying processor concurrently.
659///
660/// ```no_run
661/// # use ocio_rs::{CPUProcessor, Result};
662/// # fn example(cpu: CPUProcessor) -> Result<()> {
663/// let cpu = std::sync::Arc::new(cpu.try_into_static()?);
664/// std::thread::scope(|scope| {
665///     let cpu = cpu.clone();
666///     scope.spawn(move || {
667///         let mut rgba = [0.1, 0.2, 0.3, 1.0];
668///         cpu.try_apply_rgba(&mut rgba).unwrap();
669///     });
670/// });
671/// # Ok(())
672/// # }
673/// ```
674#[repr(transparent)]
675pub struct StaticCPUProcessor(CPUProcessor);
676
677// SAFETY: Construction rejects dynamic processors. Native CPU processors are
678// immutable after creation and OCIO supports concurrent processing on them.
679// The only independently mutable CPU state OCIO exposes is dynamic properties,
680// which cannot be obtained from a non-dynamic processor. The shared pointer
681// remains alive until the last Rust owner is dropped. Unsafe external native
682// aliases remain the responsibility of the caller creating them.
683unsafe impl Send for StaticCPUProcessor {}
684// SAFETY: As above, concurrent operations use immutable processor state and the
685// safe processing APIs require exclusive access to each output buffer.
686unsafe impl Sync for StaticCPUProcessor {}
687
688impl StaticCPUProcessor {
689    /// Returns the thread-confined CPU handle when the wrapper is owned.
690    pub fn into_inner(self) -> CPUProcessor {
691        self.0
692    }
693}
694
695impl std::ops::Deref for StaticCPUProcessor {
696    type Target = CPUProcessor;
697
698    fn deref(&self) -> &Self::Target {
699        &self.0
700    }
701}
702
703/// Positive F32 element strides for a planar image.
704#[derive(Debug, Clone, Copy, PartialEq, Eq)]
705pub struct PlanarF32Layout {
706    /// Number of pixels in each row.
707    pub width: usize,
708    /// Number of rows.
709    pub height: usize,
710    /// Distance between adjacent pixels in F32 elements.
711    pub x_stride: usize,
712    /// Distance between adjacent rows in F32 elements.
713    pub y_stride: usize,
714}
715
716/// Positive byte strides and native channel bit depth for a planar image.
717///
718/// Positive-stride in-place and conversion APIs accept planes ending at the
719/// final sample; they split the tail if native pointer stepping requires it.
720#[derive(Debug, Clone, Copy, PartialEq, Eq)]
721pub struct PlanarByteLayout {
722    /// Number of pixels per row.
723    pub width: usize,
724    /// Number of rows.
725    pub height: usize,
726    /// Byte distance between adjacent pixels.
727    pub x_stride: usize,
728    /// Byte distance between adjacent rows; at least `width * x_stride`,
729    /// including when the image has only one row.
730    pub y_stride: usize,
731    /// Native storage and interpretation of each channel.
732    pub bit_depth: BitDepth,
733}
734
735/// Packed source and destination layout for native-depth conversion.
736#[derive(Debug, Clone, Copy, PartialEq, Eq)]
737pub struct PackedConversionLayout {
738    /// Number of RGB or RGBA pixels.
739    pub pixels: i64,
740    /// Three for RGB, four for RGBA.
741    pub channels: u8,
742    /// Input sample bit depth.
743    pub input_depth: BitDepth,
744    /// Output sample bit depth.
745    pub output_depth: BitDepth,
746    /// Distance between input pixels in samples.
747    pub input_stride: i64,
748    /// Distance between output pixels in samples.
749    pub output_stride: i64,
750}
751
752/// Packed image layout with signed pixel and row strides, in bytes.
753///
754/// `origin` points to the first stored channel of the first logical pixel.
755/// Channel stride is positive. In-place, packed-to-packed, and mixed planar
756/// conversions accept unpadded layouts by splitting only when needed. Tight
757/// RGBA uses the native packed fast path.
758/// Strides and origin must be aligned to the sample size. The pixel stride's
759/// magnitude must be at least the channel stride times the channel count, and the row stride's magnitude
760/// must be at least `width * abs(x_stride)`.
761#[derive(Debug, Clone, Copy, PartialEq, Eq)]
762pub struct PackedImageLayout {
763    /// Pixels per row.
764    pub width: usize,
765    /// Number of rows.
766    pub height: usize,
767    /// Byte offset to the first stored channel of the first logical pixel.
768    pub origin: usize,
769    /// Positive byte distance between stored channels of a pixel.
770    pub channel_stride: usize,
771    /// Signed byte distance between adjacent pixels.
772    pub x_stride: isize,
773    /// Signed byte distance between adjacent rows.
774    pub y_stride: isize,
775    /// Native channel storage type, matching the processor bit depth.
776    pub bit_depth: BitDepth,
777    /// Ordering of the stored color and alpha channels.
778    pub channel_order: ChannelOrdering,
779}
780
781#[cfg(test)]
782fn packed_image_descriptor(
783    layout: PackedImageLayout,
784    data: &[u8],
785) -> Result<ocio_sys::OcioPackedBuffer> {
786    let (desc, split) = packed_image_samples(layout, data)?;
787    if split {
788        return Err(OcioError::InvalidInput(
789            "packed pointer-step padding is required".into(),
790        ));
791    }
792    Ok(desc)
793}
794
795pub(crate) fn packed_image_samples(
796    layout: PackedImageLayout,
797    data: &[u8],
798) -> Result<(ocio_sys::OcioPackedBuffer, bool)> {
799    let invalid =
800        || OcioError::InvalidInput("invalid, unaligned or overflowing packed image layout".into());
801    let size = bit_depth_bytes_per_channel("CPUProcessor packed image", layout.bit_depth)?;
802    let channels = match layout.channel_order {
803        ChannelOrdering::Rgb | ChannelOrdering::Bgr => 3,
804        _ => 4,
805    };
806    let pixel_size = (channels - 1usize)
807        .checked_mul(layout.channel_stride)
808        .and_then(|v| v.checked_add(size))
809        .ok_or_else(invalid)?;
810    // OpenColorIO requires a full channel stride for every stored channel,
811    // including the last one, rather than only the occupied sample bytes.
812    let native_pixel_stride = channels
813        .checked_mul(layout.channel_stride)
814        .filter(|&v| v <= isize::MAX as usize)
815        .ok_or_else(invalid)?;
816    let x = layout.x_stride.checked_abs().ok_or_else(invalid)? as usize;
817    let y = layout.y_stride.checked_abs().ok_or_else(invalid)? as usize;
818    if layout.width == 0
819        || layout.height == 0
820        || layout.channel_stride < size
821        || x < native_pixel_stride
822        || y == 0
823        || x > y / layout.width
824        || !layout.channel_stride.is_multiple_of(size)
825        || !x.is_multiple_of(size)
826        || !y.is_multiple_of(size)
827        || !layout.origin.is_multiple_of(size)
828        || !(data.as_ptr() as usize).is_multiple_of(size)
829        || layout.channel_stride > isize::MAX as usize
830        || (layout.channel_order == ChannelOrdering::Rgba
831            && (x > std::ffi::c_int::MAX as usize
832                || layout.channel_stride > std::ffi::c_int::MAX as usize))
833    {
834        return Err(invalid());
835    }
836    let dx = (layout.width - 1).checked_mul(x).ok_or_else(invalid)?;
837    let dy = (layout.height - 1).checked_mul(y).ok_or_else(invalid)?;
838    let backward = (if layout.x_stride < 0 { dx } else { 0 })
839        .checked_add(if layout.y_stride < 0 { dy } else { 0 })
840        .ok_or_else(invalid)?;
841    let forward = (if layout.x_stride > 0 { dx } else { 0 })
842        .checked_add(if layout.y_stride > 0 { dy } else { 0 })
843        .ok_or_else(invalid)?;
844    let low = layout.origin.checked_sub(backward).ok_or_else(invalid)?;
845    let high = layout.origin.checked_add(forward).ok_or_else(invalid)?;
846    // Generic OCIO packing advances every channel pointer after the last
847    // sample. The last stored channel has the furthest positive step.
848    // Tight, forward RGBA uses OCIO's packed path without channel stepping.
849    let packed_fast_path = layout.channel_order == ChannelOrdering::Rgba
850        && layout.channel_stride == size
851        && layout.x_stride > 0
852        && x == 4 * size;
853    let trailing = if layout.x_stride > 0 {
854        x.checked_add(if packed_fast_path {
855            0
856        } else {
857            pixel_size - size
858        })
859        .ok_or_else(invalid)?
860    } else {
861        pixel_size
862    };
863    if high.checked_add(pixel_size).ok_or_else(invalid)? > data.len() {
864        return Err(invalid());
865    }
866    let needs_split = (layout.x_stride < 0 && low < x)
867        || high
868            .checked_add(trailing)
869            .is_none_or(|end| end > data.len());
870    let width = i64::try_from(layout.width).map_err(|_| invalid())?;
871    let height = i64::try_from(layout.height).map_err(|_| invalid())?;
872    Ok((
873        ocio_sys::OcioPackedBuffer {
874            // The native API treats the source descriptor as read-only during conversion.
875            data: unsafe { data.as_ptr().add(layout.origin) }
876                .cast_mut()
877                .cast(),
878            width,
879            height,
880            channel_stride: layout.channel_stride as i64,
881            x_stride: layout.x_stride as i64,
882            y_stride: layout.y_stride as i64,
883            bit_depth: layout.bit_depth as i32,
884            channel_order: layout.channel_order as i32,
885        },
886        needs_split,
887    ))
888}
889
890/// Borrowed source channels for a planar conversion.
891pub struct PlanarBytes<'a> {
892    pub red: &'a [u8],
893    pub green: &'a [u8],
894    pub blue: &'a [u8],
895    pub alpha: Option<&'a [u8]>,
896    pub layout: PlanarByteLayout,
897}
898
899/// Borrowed destination channels for a planar conversion.
900pub struct PlanarBytesMut<'a> {
901    pub red: &'a mut [u8],
902    pub green: &'a mut [u8],
903    pub blue: &'a mut [u8],
904    pub alpha: Option<&'a mut [u8]>,
905    pub layout: PlanarByteLayout,
906}
907
908/// A planar image layout with signed byte strides and an origin in each plane.
909///
910/// The origin is the byte offset of the first pixel to process in every slice.
911/// Strides and origin must be aligned to the sample size. The row stride's
912/// magnitude must be at least `width * abs(x_stride)`.
913#[derive(Debug, Clone, Copy, PartialEq, Eq)]
914pub struct SignedPlanarByteLayout {
915    /// Number of pixels per row.
916    pub width: usize,
917    /// Number of rows.
918    pub height: usize,
919    /// Byte offset of the first logical pixel in each plane.
920    pub origin: usize,
921    /// Signed byte distance between horizontally adjacent pixels.
922    pub x_stride: isize,
923    /// Signed byte distance between adjacent rows.
924    pub y_stride: isize,
925    /// Native storage and interpretation of each channel.
926    pub bit_depth: BitDepth,
927}
928
929/// Immutable planar input with signed byte strides.
930pub struct SignedPlanarBytes<'a> {
931    pub red: &'a [u8],
932    pub green: &'a [u8],
933    pub blue: &'a [u8],
934    pub alpha: Option<&'a [u8]>,
935    pub layout: SignedPlanarByteLayout,
936}
937
938/// Exclusively borrowed planar image with signed byte strides.
939pub struct SignedPlanarBytesMut<'a> {
940    pub red: &'a mut [u8],
941    pub green: &'a mut [u8],
942    pub blue: &'a mut [u8],
943    pub alpha: Option<&'a mut [u8]>,
944    pub layout: SignedPlanarByteLayout,
945}
946
947#[cfg(test)]
948fn validate_signed_planar(layout: SignedPlanarByteLayout, planes: &[&[u8]]) -> Result<[i64; 4]> {
949    let (values, needs_split) = validate_signed_planar_samples(layout, planes)?;
950    if needs_split {
951        return Err(OcioError::InvalidInput(
952            "signed planar pointer-step padding is required".into(),
953        ));
954    }
955    Ok(values)
956}
957
958pub(crate) fn validate_signed_planar_samples(
959    layout: SignedPlanarByteLayout,
960    planes: &[&[u8]],
961) -> Result<([i64; 4], bool)> {
962    let SignedPlanarByteLayout {
963        width,
964        height,
965        origin,
966        x_stride,
967        y_stride,
968        bit_depth,
969    } = layout;
970    let size = bit_depth_bytes_per_channel("CPUProcessor planar image", bit_depth)?;
971    let invalid =
972        || OcioError::InvalidInput("invalid, unaligned or overflowing signed planar layout".into());
973    let x = x_stride.checked_abs().ok_or_else(invalid)? as usize;
974    let y = y_stride.checked_abs().ok_or_else(invalid)? as usize;
975    if width == 0
976        || height == 0
977        || x < size
978        || y == 0
979        || x > y / width
980        || !x.is_multiple_of(size)
981        || !y.is_multiple_of(size)
982        || !origin.is_multiple_of(size)
983    {
984        return Err(invalid());
985    }
986    let dx = (width - 1).checked_mul(x).ok_or_else(invalid)?;
987    let dy = (height - 1).checked_mul(y).ok_or_else(invalid)?;
988    let backward = (if x_stride < 0 { dx } else { 0 })
989        .checked_add(if y_stride < 0 { dy } else { 0 })
990        .ok_or_else(invalid)?;
991    let forward = (if x_stride > 0 { dx } else { 0 })
992        .checked_add(if y_stride > 0 { dy } else { 0 })
993        .ok_or_else(invalid)?;
994    let low = origin.checked_sub(backward).ok_or_else(invalid)?;
995    let high = origin.checked_add(forward).ok_or_else(invalid)?;
996    // OCIO advances each pixel pointer once after processing the last sample.
997    // Keep that pointer within, or one past, the borrowed allocation too.
998    let required = high.checked_add(size).ok_or_else(invalid)?;
999    if planes
1000        .iter()
1001        .any(|p| p.len() < required || !(p.as_ptr() as usize).is_multiple_of(size))
1002    {
1003        return Err(invalid());
1004    }
1005    let [Ok(w), Ok(h)] = [width, height].map(i64::try_from) else {
1006        return Err(invalid());
1007    };
1008    let needs_split = (x_stride < 0 && low < x)
1009        || (x_stride > 0
1010            && high
1011                .checked_add(x)
1012                .is_none_or(|n| planes.iter().any(|p| p.len() < n)));
1013    Ok(([w, h, x_stride as i64, y_stride as i64], needs_split))
1014}
1015
1016fn validate_planar_buffer(layout: PlanarByteLayout, planes: &[&[u8]]) -> Result<[i64; 4]> {
1017    let (values, needs_split) = validate_planar_sample_bounds(layout, planes)?;
1018    if needs_split {
1019        return Err(OcioError::InvalidInput(
1020            "planar pointer-step padding is required".into(),
1021        ));
1022    }
1023    Ok(values)
1024}
1025
1026#[derive(Clone, Copy)]
1027struct PlanarRegion {
1028    source_offset: usize,
1029    destination_offset: usize,
1030    width: i64,
1031    height: i64,
1032    final_pixel: bool,
1033}
1034
1035// For each layout, the tuple is (needs_tail_fallback, extreme_is_first_row).
1036// A single-row image has one edge even when both layouts choose opposite ends.
1037fn tail_row_partition(
1038    height: i64,
1039    a: (bool, bool),
1040    b: (bool, bool),
1041) -> (i64, i64, [Option<i64>; 2]) {
1042    debug_assert!(height > 0);
1043    let mut first = (a.0 && a.1) || (b.0 && b.1);
1044    let mut last = (a.0 && !a.1) || (b.0 && !b.1);
1045    if height == 1 {
1046        first |= last;
1047        last = false;
1048    }
1049    (
1050        i64::from(first),
1051        height - i64::from(last),
1052        [first.then_some(0), last.then_some(height - 1)],
1053    )
1054}
1055
1056// Extents and arithmetic are checked before calling this helper. The first
1057// region ends before the last row, the second before the last pixel, and the
1058// final region uses compact strides. No heap allocation or pixel copy.
1059fn planar_tail_regions(
1060    width: usize,
1061    height: usize,
1062    source: (usize, usize),
1063    destination: (usize, usize),
1064) -> [Option<PlanarRegion>; 3] {
1065    let src_row = (height - 1) * source.1;
1066    let dst_row = (height - 1) * destination.1;
1067    [
1068        (height > 1).then_some(PlanarRegion {
1069            source_offset: 0,
1070            destination_offset: 0,
1071            width: width as i64,
1072            height: height as i64 - 1,
1073            final_pixel: false,
1074        }),
1075        (width > 1).then_some(PlanarRegion {
1076            source_offset: src_row,
1077            destination_offset: dst_row,
1078            width: width as i64 - 1,
1079            height: 1,
1080            final_pixel: false,
1081        }),
1082        Some(PlanarRegion {
1083            source_offset: src_row + (width - 1) * source.0,
1084            destination_offset: dst_row + (width - 1) * destination.0,
1085            width: 1,
1086            height: 1,
1087            final_pixel: true,
1088        }),
1089    ]
1090}
1091
1092fn validate_planar_sample_bounds(
1093    layout: PlanarByteLayout,
1094    planes: &[&[u8]],
1095) -> Result<([i64; 4], bool)> {
1096    let PlanarByteLayout {
1097        width,
1098        height,
1099        x_stride,
1100        y_stride,
1101        bit_depth,
1102    } = layout;
1103    let size = bit_depth_bytes_per_channel("CPUProcessor::try_apply_planar_convert", bit_depth)?;
1104    let invalid =
1105        || OcioError::InvalidInput("invalid, unaligned or overflowing planar layout".into());
1106    if width == 0
1107        || height == 0
1108        || x_stride < size
1109        || y_stride == 0
1110        || !x_stride.is_multiple_of(size)
1111        || !y_stride.is_multiple_of(size)
1112    {
1113        return Err(invalid());
1114    }
1115    // Generic OCIO packing advances the pointer after the final sample.
1116    let row_span = width.checked_mul(x_stride).ok_or_else(invalid)?;
1117    if x_stride > y_stride / width {
1118        return Err(invalid());
1119    }
1120    let row = (height - 1).checked_mul(y_stride).ok_or_else(invalid)?;
1121    let end = (width - 1)
1122        .checked_mul(x_stride)
1123        .and_then(|n| row.checked_add(n))
1124        .and_then(|n| n.checked_add(size))
1125        .ok_or_else(invalid)?;
1126    let required = row.checked_add(row_span);
1127    if planes
1128        .iter()
1129        .any(|p| p.len() < end || !(p.as_ptr() as usize).is_multiple_of(size))
1130    {
1131        return Err(invalid());
1132    }
1133    let [Ok(w), Ok(h), Ok(x), Ok(y)] = [width, height, x_stride, y_stride].map(i64::try_from)
1134    else {
1135        return Err(invalid());
1136    };
1137    let needs_split = required.is_none_or(|n| planes.iter().any(|p| p.len() < n));
1138    Ok(([w, h, x, y], needs_split))
1139}
1140
1141fn signed_planar_source(
1142    image: &SignedPlanarBytes<'_>,
1143) -> Result<(ocio_sys::OcioPlanarBuffer, bool)> {
1144    let ([width, height, x_stride, y_stride], mut split) =
1145        validate_signed_planar_samples(image.layout, &[image.red, image.green, image.blue])?;
1146    if let Some(alpha) = image.alpha {
1147        split |= validate_signed_planar_samples(image.layout, &[alpha])?.1;
1148    }
1149    let origin = image.layout.origin;
1150    Ok((
1151        ocio_sys::OcioPlanarBuffer {
1152            red: image.red.as_ptr().wrapping_add(origin).cast_mut().cast(),
1153            green: image.green.as_ptr().wrapping_add(origin).cast_mut().cast(),
1154            blue: image.blue.as_ptr().wrapping_add(origin).cast_mut().cast(),
1155            alpha: image.alpha.map_or(std::ptr::null_mut(), |p| {
1156                p.as_ptr().wrapping_add(origin).cast_mut().cast()
1157            }),
1158            width,
1159            height,
1160            x_stride,
1161            y_stride,
1162            bit_depth: image.layout.bit_depth as i32,
1163        },
1164        split,
1165    ))
1166}
1167
1168pub(crate) fn signed_planar_destination(
1169    image: &mut SignedPlanarBytesMut<'_>,
1170) -> Result<(ocio_sys::OcioPlanarBuffer, bool)> {
1171    let ([width, height, x_stride, y_stride], mut split) =
1172        validate_signed_planar_samples(image.layout, &[image.red, image.green, image.blue])?;
1173    if let Some(alpha) = image.alpha.as_deref() {
1174        split |= validate_signed_planar_samples(image.layout, &[alpha])?.1;
1175    }
1176    let origin = image.layout.origin;
1177    Ok((
1178        ocio_sys::OcioPlanarBuffer {
1179            red: image.red.as_mut_ptr().wrapping_add(origin).cast(),
1180            green: image.green.as_mut_ptr().wrapping_add(origin).cast(),
1181            blue: image.blue.as_mut_ptr().wrapping_add(origin).cast(),
1182            alpha: image
1183                .alpha
1184                .as_deref_mut()
1185                .map_or(std::ptr::null_mut(), |p| {
1186                    p.as_mut_ptr().wrapping_add(origin).cast()
1187                }),
1188            width,
1189            height,
1190            x_stride,
1191            y_stride,
1192            bit_depth: image.layout.bit_depth as i32,
1193        },
1194        split,
1195    ))
1196}
1197
1198impl CPUProcessor {
1199    // Called only after both layouts and all channel slices have been
1200    // validated and the destination is exclusively borrowed.
1201    fn convert_mixed_regions(
1202        &self,
1203        packed: &ocio_sys::OcioPackedBuffer,
1204        planar: &ocio_sys::OcioPlanarBuffer,
1205        split: (bool, bool),
1206        packed_is_source: bool,
1207        sizes: (usize, usize),
1208    ) -> Result<()> {
1209        let (packed_split, planar_split) = split;
1210        let (packed_size, planar_size) = sizes;
1211        let width = packed.width;
1212        let height = packed.height;
1213        let max = std::ffi::c_long::MAX as i64;
1214        if width > i64::from(std::ffi::c_int::MAX) / 4 || height > max || width > max / height {
1215            return Err(OcioError::InvalidInput(
1216                "mixed image layout exceeds native limits".into(),
1217            ));
1218        }
1219        let channels = if packed.channel_order == ChannelOrdering::Rgb as i32
1220            || packed.channel_order == ChannelOrdering::Bgr as i32
1221        {
1222            3
1223        } else {
1224            4
1225        };
1226        let packed_first = (packed.x_stride < 0) != (packed.y_stride < 0);
1227        let planar_first = (planar.x_stride < 0) != (planar.y_stride < 0);
1228        let (start, end, edges) = tail_row_partition(
1229            height,
1230            (packed_split, packed_first),
1231            (planar_split, planar_first),
1232        );
1233        let shift = |p: *mut c_void, row: i64, col: i64, x: i64, y: i64| -> *mut c_void {
1234            if p.is_null() {
1235                p
1236            } else {
1237                let delta =
1238                    (i128::from(row) * i128::from(y) + i128::from(col) * i128::from(x)) as isize;
1239                p.cast::<u8>().wrapping_offset(delta).cast()
1240            }
1241        };
1242        let packed_region = |row: i64, col: i64, w: i64, h: i64| ocio_sys::OcioPackedBuffer {
1243            data: shift(packed.data, row, col, packed.x_stride, packed.y_stride),
1244            width: w,
1245            height: h,
1246            channel_stride: packed.channel_stride,
1247            x_stride: packed.x_stride,
1248            y_stride: packed.y_stride,
1249            bit_depth: packed.bit_depth,
1250            channel_order: packed.channel_order,
1251        };
1252        let planar_region = |row: i64, col: i64, w: i64, h: i64| ocio_sys::OcioPlanarBuffer {
1253            red: shift(planar.red, row, col, planar.x_stride, planar.y_stride),
1254            green: shift(planar.green, row, col, planar.x_stride, planar.y_stride),
1255            blue: shift(planar.blue, row, col, planar.x_stride, planar.y_stride),
1256            alpha: shift(planar.alpha, row, col, planar.x_stride, planar.y_stride),
1257            width: w,
1258            height: h,
1259            x_stride: planar.x_stride,
1260            y_stride: planar.y_stride,
1261            bit_depth: planar.bit_depth,
1262        };
1263        let apply =
1264            |p: &ocio_sys::OcioPackedBuffer, q: &ocio_sys::OcioPlanarBuffer| -> Result<()> {
1265                crate::clear_last_error();
1266                // SAFETY: callers validate all extents and the partition retains
1267                // source immutability and exclusive destination ownership.
1268                unsafe {
1269                    ocio_sys::ocio_cpu_processor_convert_mixed_image(
1270                        self.handle.as_ptr(),
1271                        p,
1272                        q,
1273                        packed_is_source,
1274                    );
1275                }
1276                crate::ocio_call_status()
1277            };
1278        if end > start {
1279            apply(
1280                &packed_region(start, 0, width, end - start),
1281                &planar_region(start, 0, width, end - start),
1282            )?;
1283        }
1284        #[repr(align(4))]
1285        struct Tail([u8; 32]);
1286        for row in edges.into_iter().flatten() {
1287            if width > 1 {
1288                apply(
1289                    &packed_region(row, 0, width - 1, 1),
1290                    &planar_region(row, 0, width - 1, 1),
1291                )?;
1292            }
1293            let raw_packed = packed_region(row, width - 1, 1, 1);
1294            let raw_planar = planar_region(row, width - 1, 1, 1);
1295            let planes = [
1296                raw_planar.red,
1297                raw_planar.green,
1298                raw_planar.blue,
1299                raw_planar.alpha,
1300            ];
1301            let mut p_tail = Tail([0; 32]);
1302            let mut q_tail = Tail([0; 32]);
1303            if packed_is_source {
1304                for channel in 0..channels {
1305                    // SAFETY: the original packed samples were validated.
1306                    unsafe {
1307                        std::ptr::copy_nonoverlapping(
1308                            raw_packed
1309                                .data
1310                                .cast::<u8>()
1311                                .add(channel * packed.channel_stride as usize),
1312                            p_tail.0.as_mut_ptr().add(channel * packed_size),
1313                            packed_size,
1314                        );
1315                    }
1316                }
1317            } else {
1318                for (channel, source) in planes.iter().enumerate() {
1319                    if !source.is_null() {
1320                        // SAFETY: each original plane contains its final sample.
1321                        unsafe {
1322                            std::ptr::copy_nonoverlapping(
1323                                source.cast::<u8>(),
1324                                q_tail.0.as_mut_ptr().add(channel * planar_size),
1325                                planar_size,
1326                            );
1327                        }
1328                    }
1329                }
1330            }
1331            let stride = (channels * packed_size) as i64;
1332            let p_compact = ocio_sys::OcioPackedBuffer {
1333                data: p_tail.0.as_mut_ptr().cast(),
1334                width: 1,
1335                height: 1,
1336                channel_stride: packed_size as i64,
1337                x_stride: stride,
1338                y_stride: stride,
1339                bit_depth: packed.bit_depth,
1340                channel_order: packed.channel_order,
1341            };
1342            let q_base = q_tail.0.as_mut_ptr();
1343            let q_compact = ocio_sys::OcioPlanarBuffer {
1344                red: q_base.cast(),
1345                green: q_base.wrapping_add(planar_size).cast(),
1346                blue: q_base.wrapping_add(2 * planar_size).cast(),
1347                alpha: if planar.alpha.is_null() {
1348                    std::ptr::null_mut()
1349                } else {
1350                    q_base.wrapping_add(3 * planar_size).cast()
1351                },
1352                width: 1,
1353                height: 1,
1354                x_stride: planar_size as i64,
1355                y_stride: planar_size as i64,
1356                bit_depth: planar.bit_depth,
1357            };
1358            apply(&p_compact, &q_compact)?;
1359            if packed_is_source {
1360                for (channel, destination) in planes.iter().enumerate() {
1361                    if !destination.is_null() {
1362                        // SAFETY: destination samples are validated and exclusive.
1363                        unsafe {
1364                            std::ptr::copy_nonoverlapping(
1365                                q_tail.0.as_ptr().add(channel * planar_size),
1366                                destination.cast::<u8>(),
1367                                planar_size,
1368                            );
1369                        }
1370                    }
1371                }
1372            } else {
1373                for channel in 0..channels {
1374                    // SAFETY: destination packed samples are validated and exclusive.
1375                    unsafe {
1376                        std::ptr::copy_nonoverlapping(
1377                            p_tail.0.as_ptr().add(channel * packed_size),
1378                            raw_packed
1379                                .data
1380                                .cast::<u8>()
1381                                .add(channel * packed.channel_stride as usize),
1382                            packed_size,
1383                        );
1384                    }
1385                }
1386            }
1387        }
1388        Ok(())
1389    }
1390    /// Converts a non-dynamic processor into a thread-shareable processor.
1391    ///
1392    /// Returns an error for a dynamic processor or when the native query fails.
1393    /// This consumes the original handle even on error; query
1394    /// [`Self::try_is_dynamic`] first if it must be retained in that case.
1395    pub fn try_into_static(self) -> Result<StaticCPUProcessor> {
1396        if self.try_is_dynamic()? {
1397            return Err(OcioError::InvalidInput(
1398                "a dynamic CPU processor cannot be shared without synchronization".into(),
1399            ));
1400        }
1401        Ok(StaticCPUProcessor(self))
1402    }
1403
1404    /// Process an exclusively borrowed packed image in place. Unpadded generic
1405    /// layouts may use a small temporary buffer for the final pixel; earlier
1406    /// regions may already be modified if a later native call fails.
1407    pub fn try_apply_packed_image(&self, data: &mut [u8], layout: PackedImageLayout) -> Result<()> {
1408        let (mut desc, split) = packed_image_samples(layout, data)?;
1409        desc.data = unsafe { data.as_mut_ptr().add(layout.origin).cast() };
1410        if split {
1411            let width = desc.width;
1412            let height = desc.height;
1413            let max = std::ffi::c_long::MAX as i64;
1414            if width > i64::from(std::ffi::c_int::MAX) / 4 || height > max || width > max / height {
1415                return Err(OcioError::InvalidInput(
1416                    "packed layout exceeds native limits".into(),
1417                ));
1418            }
1419            let size = bit_depth_bytes_per_channel("packed image", layout.bit_depth)?;
1420            let channels = match layout.channel_order {
1421                ChannelOrdering::Rgb | ChannelOrdering::Bgr => 3,
1422                _ => 4,
1423            };
1424            let first_row_is_extreme = (layout.x_stride < 0) != (layout.y_stride < 0);
1425            let extreme_row = if first_row_is_extreme { 0 } else { height - 1 };
1426            let offset = |row: i64, col: i64| -> usize {
1427                (layout.origin as i128
1428                    + i128::from(row) * i128::from(desc.y_stride)
1429                    + i128::from(col) * i128::from(desc.x_stride)) as usize
1430            };
1431            let data_ptr = data.as_mut_ptr();
1432            let apply_region = |position: usize, w: i64, h: i64| -> Result<()> {
1433                let region = ocio_sys::OcioPackedBuffer {
1434                    data: data_ptr.wrapping_add(position).cast(),
1435                    width: w,
1436                    height: h,
1437                    channel_stride: desc.channel_stride,
1438                    x_stride: desc.x_stride,
1439                    y_stride: desc.y_stride,
1440                    bit_depth: desc.bit_depth,
1441                    channel_order: desc.channel_order,
1442                };
1443                crate::clear_last_error();
1444                // SAFETY: validated corners and partition keep sample access
1445                // and every channel's final step within the borrowed slice.
1446                unsafe {
1447                    ocio_sys::ocio_cpu_processor_apply_packed_image(self.handle.as_ptr(), &region);
1448                }
1449                crate::ocio_call_status()
1450            };
1451            if height > 1 {
1452                apply_region(
1453                    offset(if first_row_is_extreme { 1 } else { 0 }, 0),
1454                    width,
1455                    height - 1,
1456                )?;
1457            }
1458            if width > 1 {
1459                apply_region(offset(extreme_row, 0), width - 1, 1)?;
1460            }
1461            let last = offset(extreme_row, width - 1);
1462            #[repr(align(4))]
1463            struct AlignedPixel([u8; 32]);
1464            let mut tail = AlignedPixel([0; 32]);
1465            for channel in 0..channels {
1466                let source = last + channel * layout.channel_stride;
1467                tail.0[channel * size..(channel + 1) * size]
1468                    .copy_from_slice(&data[source..source + size]);
1469            }
1470            let tight = (channels * size) as i64;
1471            let tail_desc = ocio_sys::OcioPackedBuffer {
1472                data: tail.0.as_mut_ptr().cast(),
1473                width: 1,
1474                height: 1,
1475                channel_stride: size as i64,
1476                x_stride: tight,
1477                y_stride: tight,
1478                bit_depth: desc.bit_depth,
1479                channel_order: desc.channel_order,
1480            };
1481            crate::clear_last_error();
1482            unsafe {
1483                ocio_sys::ocio_cpu_processor_apply_packed_image(self.handle.as_ptr(), &tail_desc);
1484            }
1485            crate::ocio_call_status()?;
1486            for channel in 0..channels {
1487                let destination = last + channel * layout.channel_stride;
1488                data[destination..destination + size]
1489                    .copy_from_slice(&tail.0[channel * size..(channel + 1) * size]);
1490            }
1491            return Ok(());
1492        }
1493        crate::clear_last_error();
1494        unsafe { ocio_sys::ocio_cpu_processor_apply_packed_image(self.handle.as_ptr(), &desc) };
1495        crate::ocio_call_status()
1496    }
1497
1498    /// Convert independently laid-out packed images. Dimensions must match;
1499    /// bit depths and channel ordering may differ. Unpadded tails may use
1500    /// small temporary buffers and multiple calls; later failure may leave
1501    /// earlier destination regions modified.
1502    pub fn try_convert_packed_image(
1503        &self,
1504        source: &[u8],
1505        source_layout: PackedImageLayout,
1506        destination: &mut [u8],
1507        destination_layout: PackedImageLayout,
1508    ) -> Result<()> {
1509        if source_layout.width != destination_layout.width
1510            || source_layout.height != destination_layout.height
1511        {
1512            return Err(OcioError::InvalidInput(
1513                "packed image dimensions differ".into(),
1514            ));
1515        }
1516        let (src, source_split) = packed_image_samples(source_layout, source)?;
1517        let (mut dst, destination_split) = packed_image_samples(destination_layout, destination)?;
1518        dst.data = unsafe {
1519            destination
1520                .as_mut_ptr()
1521                .add(destination_layout.origin)
1522                .cast()
1523        };
1524        if source_split || destination_split {
1525            let width = src.width;
1526            let height = src.height;
1527            let max = std::ffi::c_long::MAX as i64;
1528            if width > i64::from(std::ffi::c_int::MAX) / 4 || height > max || width > max / height {
1529                return Err(OcioError::InvalidInput(
1530                    "packed layout exceeds native limits".into(),
1531                ));
1532            }
1533            let input_size =
1534                bit_depth_bytes_per_channel("packed conversion", source_layout.bit_depth)?;
1535            let output_size =
1536                bit_depth_bytes_per_channel("packed conversion", destination_layout.bit_depth)?;
1537            let count = |order| match order {
1538                ChannelOrdering::Rgb | ChannelOrdering::Bgr => 3usize,
1539                _ => 4usize,
1540            };
1541            let input_channels = count(source_layout.channel_order);
1542            let output_channels = count(destination_layout.channel_order);
1543            let source_first = (src.x_stride < 0) != (src.y_stride < 0);
1544            let destination_first = (dst.x_stride < 0) != (dst.y_stride < 0);
1545            let (start, end, edges) = tail_row_partition(
1546                height,
1547                (source_split, source_first),
1548                (destination_split, destination_first),
1549            );
1550            let region = |base: &ocio_sys::OcioPackedBuffer, row: i64, col: i64, w: i64, h: i64| {
1551                let delta = (i128::from(row) * i128::from(base.y_stride)
1552                    + i128::from(col) * i128::from(base.x_stride))
1553                    as isize;
1554                ocio_sys::OcioPackedBuffer {
1555                    data: base.data.cast::<u8>().wrapping_offset(delta).cast(),
1556                    width: w,
1557                    height: h,
1558                    channel_stride: base.channel_stride,
1559                    x_stride: base.x_stride,
1560                    y_stride: base.y_stride,
1561                    bit_depth: base.bit_depth,
1562                    channel_order: base.channel_order,
1563                }
1564            };
1565            let apply_region = |row, col, w, h| -> Result<()> {
1566                let input = region(&src, row, col, w, h);
1567                let output = region(&dst, row, col, w, h);
1568                crate::clear_last_error();
1569                // SAFETY: validated extents and the extreme-row partition
1570                // keep each native sample and final pointer step in bounds.
1571                unsafe {
1572                    ocio_sys::ocio_cpu_processor_convert_packed_image(
1573                        self.handle.as_ptr(),
1574                        &input,
1575                        &output,
1576                    );
1577                }
1578                crate::ocio_call_status()
1579            };
1580            if end > start {
1581                apply_region(start, 0, width, end - start)?;
1582            }
1583            #[repr(align(4))]
1584            struct AlignedPixel([u8; 32]);
1585            for row in edges.into_iter().flatten() {
1586                if width > 1 {
1587                    apply_region(row, 0, width - 1, 1)?;
1588                }
1589                let offset = |layout: PackedImageLayout| -> usize {
1590                    (layout.origin as i128
1591                        + i128::from(row) * layout.y_stride as i128
1592                        + i128::from(width - 1) * layout.x_stride as i128)
1593                        as usize
1594                };
1595                let source_offset = offset(source_layout);
1596                let destination_offset = offset(destination_layout);
1597                let mut input = AlignedPixel([0; 32]);
1598                let mut output = AlignedPixel([0; 32]);
1599                for channel in 0..input_channels {
1600                    let at = source_offset + channel * source_layout.channel_stride;
1601                    input.0[channel * input_size..(channel + 1) * input_size]
1602                        .copy_from_slice(&source[at..at + input_size]);
1603                }
1604                let tight = |data: *mut u8,
1605                             base: &ocio_sys::OcioPackedBuffer,
1606                             count: usize,
1607                             size: usize| {
1608                    let stride = (count * size) as i64;
1609                    ocio_sys::OcioPackedBuffer {
1610                        data: data.cast(),
1611                        width: 1,
1612                        height: 1,
1613                        channel_stride: size as i64,
1614                        x_stride: stride,
1615                        y_stride: stride,
1616                        bit_depth: base.bit_depth,
1617                        channel_order: base.channel_order,
1618                    }
1619                };
1620                let input_desc = tight(input.0.as_mut_ptr(), &src, input_channels, input_size);
1621                let output_desc = tight(output.0.as_mut_ptr(), &dst, output_channels, output_size);
1622                crate::clear_last_error();
1623                // SAFETY: compact aligned buffers contain each native sample
1624                // and all pointer steps, with original bit depth and ordering.
1625                unsafe {
1626                    ocio_sys::ocio_cpu_processor_convert_packed_image(
1627                        self.handle.as_ptr(),
1628                        &input_desc,
1629                        &output_desc,
1630                    );
1631                }
1632                crate::ocio_call_status()?;
1633                for channel in 0..output_channels {
1634                    let at = destination_offset + channel * destination_layout.channel_stride;
1635                    destination[at..at + output_size].copy_from_slice(
1636                        &output.0[channel * output_size..(channel + 1) * output_size],
1637                    );
1638                }
1639            }
1640            return Ok(());
1641        }
1642        crate::clear_last_error();
1643        unsafe {
1644            ocio_sys::ocio_cpu_processor_convert_packed_image(self.handle.as_ptr(), &src, &dst)
1645        };
1646        crate::ocio_call_status()
1647    }
1648
1649    /// Convert a packed source into separate signed-stride destination planes.
1650    ///
1651    /// The images must have matching dimensions and processor-compatible bit
1652    /// depths. Alpha may be present independently on either side. OCIO fills
1653    /// missing input alpha with zero in 2.4/2.5 and one in 2.6; it discards
1654    /// alpha if the output lacks it.
1655    /// Unpadded tails may use small temporary buffers and multiple native calls;
1656    /// a later error may leave earlier output regions modified.
1657    pub fn try_convert_packed_to_planar(
1658        &self,
1659        source: &[u8],
1660        source_layout: PackedImageLayout,
1661        mut destination: SignedPlanarBytesMut<'_>,
1662    ) -> Result<()> {
1663        if source_layout.width != destination.layout.width
1664            || source_layout.height != destination.layout.height
1665        {
1666            return Err(OcioError::InvalidInput("image dimensions differ".into()));
1667        }
1668        let (packed, packed_split) = packed_image_samples(source_layout, source)?;
1669        let (planar, planar_split) = signed_planar_destination(&mut destination)?;
1670        if packed_split || planar_split {
1671            return self.convert_mixed_regions(
1672                &packed,
1673                &planar,
1674                (packed_split, planar_split),
1675                true,
1676                (
1677                    bit_depth_bytes_per_channel("mixed conversion", source_layout.bit_depth)?,
1678                    bit_depth_bytes_per_channel("mixed conversion", destination.layout.bit_depth)?,
1679                ),
1680            );
1681        }
1682        crate::clear_last_error();
1683        // SAFETY: Both descriptors are validated and destination planes are
1684        // exclusively borrowed for the duration of the synchronous call.
1685        unsafe {
1686            ocio_sys::ocio_cpu_processor_convert_mixed_image(
1687                self.handle.as_ptr(),
1688                &packed,
1689                &planar,
1690                true,
1691            )
1692        };
1693        crate::ocio_call_status()
1694    }
1695
1696    /// Convert signed-stride source planes into a packed destination.
1697    ///
1698    /// See [`Self::try_convert_packed_to_planar`] for dimensions, alpha,
1699    /// bit-depth and borrowed-buffer requirements.
1700    pub fn try_convert_planar_to_packed(
1701        &self,
1702        source: SignedPlanarBytes<'_>,
1703        destination: &mut [u8],
1704        destination_layout: PackedImageLayout,
1705    ) -> Result<()> {
1706        if source.layout.width != destination_layout.width
1707            || source.layout.height != destination_layout.height
1708        {
1709            return Err(OcioError::InvalidInput("image dimensions differ".into()));
1710        }
1711        let (planar, planar_split) = signed_planar_source(&source)?;
1712        let (mut packed, packed_split) = packed_image_samples(destination_layout, destination)?;
1713        packed.data = unsafe {
1714            destination
1715                .as_mut_ptr()
1716                .add(destination_layout.origin)
1717                .cast()
1718        };
1719        if packed_split || planar_split {
1720            return self.convert_mixed_regions(
1721                &packed,
1722                &planar,
1723                (packed_split, planar_split),
1724                false,
1725                (
1726                    bit_depth_bytes_per_channel("mixed conversion", destination_layout.bit_depth)?,
1727                    bit_depth_bytes_per_channel("mixed conversion", source.layout.bit_depth)?,
1728                ),
1729            );
1730        }
1731        crate::clear_last_error();
1732        // SAFETY: Both descriptors are validated, and destination is exclusive.
1733        unsafe {
1734            ocio_sys::ocio_cpu_processor_convert_mixed_image(
1735                self.handle.as_ptr(),
1736                &packed,
1737                &planar,
1738                false,
1739            )
1740        };
1741        crate::ocio_call_status()
1742    }
1743    /// Process a planar image in place with signed byte strides without copying.
1744    ///
1745    /// Unpadded planes are split into up to three native regions so OCIO's
1746    /// final pointer step remains within each slice. Earlier regions may be
1747    /// modified if a later region reports an error.
1748    pub fn try_apply_planar_signed(&self, mut image: SignedPlanarBytesMut<'_>) -> Result<()> {
1749        let ([width, height, x_stride, y_stride], mut split) =
1750            validate_signed_planar_samples(image.layout, &[image.red, image.green, image.blue])?;
1751        if let Some(alpha) = image.alpha.as_deref() {
1752            split |= validate_signed_planar_samples(image.layout, &[alpha])?.1;
1753        }
1754        let origin = image.layout.origin;
1755        if split {
1756            let max = std::ffi::c_long::MAX as i64;
1757            if width > i64::from(std::ffi::c_int::MAX) / 4 || height > max || width > max / height {
1758                return Err(OcioError::InvalidInput(
1759                    "signed planar layout exceeds native limits".into(),
1760                ));
1761            }
1762            let first_row_is_extreme = (x_stride < 0) != (y_stride < 0);
1763            let extreme_row = if first_row_is_extreme { 0 } else { height - 1 };
1764            let offset = |row: i64, column: i64| -> usize {
1765                (origin as i128
1766                    + i128::from(row) * i128::from(y_stride)
1767                    + i128::from(column) * i128::from(x_stride)) as usize
1768            };
1769            let r = image.red.as_mut_ptr();
1770            let g = image.green.as_mut_ptr();
1771            let b = image.blue.as_mut_ptr();
1772            let a = image
1773                .alpha
1774                .as_deref_mut()
1775                .map_or(std::ptr::null_mut(), |p| p.as_mut_ptr());
1776            let size =
1777                bit_depth_bytes_per_channel("CPUProcessor planar image", image.layout.bit_depth)?
1778                    as i64;
1779            let apply = |offset: usize, w: i64, h: i64, x: i64, y: i64| -> Result<()> {
1780                crate::clear_last_error();
1781                // SAFETY: validated corners and the region partition keep all
1782                // samples and final pointer steps within their borrowed planes.
1783                unsafe {
1784                    ocio_sys::ocio_cpu_processor_apply_planar_bytes(
1785                        self.handle.as_ptr(),
1786                        r.add(offset).cast(),
1787                        g.add(offset).cast(),
1788                        b.add(offset).cast(),
1789                        if a.is_null() { a } else { a.add(offset) }.cast(),
1790                        w,
1791                        h,
1792                        x,
1793                        y,
1794                        image.layout.bit_depth as i32,
1795                    );
1796                }
1797                crate::ocio_call_status()
1798            };
1799            if height > 1 {
1800                apply(
1801                    offset(if first_row_is_extreme { 1 } else { 0 }, 0),
1802                    width,
1803                    height - 1,
1804                    x_stride,
1805                    y_stride,
1806                )?;
1807            }
1808            if width > 1 {
1809                apply(offset(extreme_row, 0), width - 1, 1, x_stride, y_stride)?;
1810            }
1811            return apply(offset(extreme_row, width - 1), 1, 1, size, size);
1812        }
1813        crate::clear_last_error();
1814        // SAFETY: The exclusive slices have validated bounds and alignment,
1815        // including the original pointer position and the native strides.
1816        unsafe {
1817            ocio_sys::ocio_cpu_processor_apply_planar_bytes(
1818                self.handle.as_ptr(),
1819                image.red.as_mut_ptr().add(origin).cast(),
1820                image.green.as_mut_ptr().add(origin).cast(),
1821                image.blue.as_mut_ptr().add(origin).cast(),
1822                image
1823                    .alpha
1824                    .as_deref_mut()
1825                    .map_or(std::ptr::null_mut(), |p| p.as_mut_ptr().add(origin).cast()),
1826                width,
1827                height,
1828                x_stride,
1829                y_stride,
1830                image.layout.bit_depth as i32,
1831            )
1832        };
1833        crate::ocio_call_status()
1834    }
1835
1836    /// Convert separate signed-stride planar images without copying pixel data.
1837    ///
1838    /// Source and destination must have equal dimensions. Alpha may be present
1839    /// independently on either side. Missing input alpha follows the native
1840    /// version's behavior, described by [`Self::try_convert_packed_to_planar`].
1841    /// Their layouts and bit depths may differ. Unpadded planes may require
1842    /// multiple native calls; a later failure can leave earlier output modified.
1843    pub fn try_apply_planar_signed_convert(
1844        &self,
1845        source: SignedPlanarBytes<'_>,
1846        mut destination: SignedPlanarBytesMut<'_>,
1847    ) -> Result<()> {
1848        if source.layout.width != destination.layout.width
1849            || source.layout.height != destination.layout.height
1850        {
1851            return Err(OcioError::InvalidInput(
1852                "planar dimensions must match".into(),
1853            ));
1854        }
1855        let ([width, height, ix, iy], mut input_split) = validate_signed_planar_samples(
1856            source.layout,
1857            &[source.red, source.green, source.blue],
1858        )?;
1859        let ([_, _, ox, oy], mut output_split) = validate_signed_planar_samples(
1860            destination.layout,
1861            &[destination.red, destination.green, destination.blue],
1862        )?;
1863        if let Some(alpha) = source.alpha {
1864            input_split |= validate_signed_planar_samples(source.layout, &[alpha])?.1;
1865        }
1866        if let Some(alpha) = destination.alpha.as_deref() {
1867            output_split |= validate_signed_planar_samples(destination.layout, &[alpha])?.1;
1868        }
1869        let input = ocio_sys::OcioPlanarBuffer {
1870            red: source
1871                .red
1872                .as_ptr()
1873                .wrapping_add(source.layout.origin)
1874                .cast_mut()
1875                .cast(),
1876            green: source
1877                .green
1878                .as_ptr()
1879                .wrapping_add(source.layout.origin)
1880                .cast_mut()
1881                .cast(),
1882            blue: source
1883                .blue
1884                .as_ptr()
1885                .wrapping_add(source.layout.origin)
1886                .cast_mut()
1887                .cast(),
1888            alpha: source.alpha.map_or(std::ptr::null_mut(), |p| {
1889                p.as_ptr()
1890                    .wrapping_add(source.layout.origin)
1891                    .cast_mut()
1892                    .cast()
1893            }),
1894            width,
1895            height,
1896            x_stride: ix,
1897            y_stride: iy,
1898            bit_depth: source.layout.bit_depth as i32,
1899        };
1900        let output = ocio_sys::OcioPlanarBuffer {
1901            red: destination
1902                .red
1903                .as_mut_ptr()
1904                .wrapping_add(destination.layout.origin)
1905                .cast(),
1906            green: destination
1907                .green
1908                .as_mut_ptr()
1909                .wrapping_add(destination.layout.origin)
1910                .cast(),
1911            blue: destination
1912                .blue
1913                .as_mut_ptr()
1914                .wrapping_add(destination.layout.origin)
1915                .cast(),
1916            alpha: destination
1917                .alpha
1918                .as_deref_mut()
1919                .map_or(std::ptr::null_mut(), |p| {
1920                    p.as_mut_ptr()
1921                        .wrapping_add(destination.layout.origin)
1922                        .cast()
1923                }),
1924            width,
1925            height,
1926            x_stride: ox,
1927            y_stride: oy,
1928            bit_depth: destination.layout.bit_depth as i32,
1929        };
1930        if input_split || output_split {
1931            let max = std::ffi::c_long::MAX as i64;
1932            if width > i64::from(std::ffi::c_int::MAX) / 4 || height > max || width > max / height {
1933                return Err(OcioError::InvalidInput(
1934                    "signed planar layout exceeds native limits".into(),
1935                ));
1936            }
1937            let input_size =
1938                bit_depth_bytes_per_channel("signed planar conversion", source.layout.bit_depth)?
1939                    as i64;
1940            let output_size = bit_depth_bytes_per_channel(
1941                "signed planar conversion",
1942                destination.layout.bit_depth,
1943            )? as i64;
1944            let input_first = (ix < 0) != (iy < 0);
1945            let output_first = (ox < 0) != (oy < 0);
1946            let (start, end, edges) = tail_row_partition(
1947                height,
1948                (input_split, input_first),
1949                (output_split, output_first),
1950            );
1951            let region = |base: &ocio_sys::OcioPlanarBuffer,
1952                          row: i64,
1953                          col: i64,
1954                          w: i64,
1955                          h: i64,
1956                          sample: i64,
1957                          compact: bool| {
1958                let delta = (i128::from(row) * i128::from(base.y_stride)
1959                    + i128::from(col) * i128::from(base.x_stride))
1960                    as isize;
1961                let advance = |p: *mut c_void| {
1962                    if p.is_null() {
1963                        p
1964                    } else {
1965                        p.cast::<u8>().wrapping_offset(delta).cast()
1966                    }
1967                };
1968                ocio_sys::OcioPlanarBuffer {
1969                    red: advance(base.red),
1970                    green: advance(base.green),
1971                    blue: advance(base.blue),
1972                    alpha: advance(base.alpha),
1973                    width: w,
1974                    height: h,
1975                    x_stride: if compact { sample } else { base.x_stride },
1976                    y_stride: if compact { sample } else { base.y_stride },
1977                    bit_depth: base.bit_depth,
1978                }
1979            };
1980            let apply = |row, col, w, h, compact| -> Result<()> {
1981                let src = region(&input, row, col, w, h, input_size, compact);
1982                let dst = region(&output, row, col, w, h, output_size, compact);
1983                crate::clear_last_error();
1984                // SAFETY: validated source and destination corners and the
1985                // extreme-row partition contain all samples and pointer steps.
1986                unsafe {
1987                    ocio_sys::ocio_cpu_processor_apply_planar_convert(
1988                        self.handle.as_ptr(),
1989                        &src,
1990                        &dst,
1991                    );
1992                }
1993                crate::ocio_call_status()
1994            };
1995            if end > start {
1996                apply(start, 0, width, end - start, false)?;
1997            }
1998            for row in edges.into_iter().flatten() {
1999                if width > 1 {
2000                    apply(row, 0, width - 1, 1, false)?;
2001                }
2002                apply(row, width - 1, 1, 1, true)?;
2003            }
2004            return Ok(());
2005        }
2006        crate::clear_last_error();
2007        // SAFETY: Bounds and alignment have been checked, the source is only
2008        // read, and Rust exclusively borrows all destination planes.
2009        unsafe {
2010            ocio_sys::ocio_cpu_processor_apply_planar_convert(self.handle.as_ptr(), &input, &output)
2011        };
2012        crate::ocio_call_status()
2013    }
2014
2015    /// Convert separate planar buffers using the processor's input and output depths.
2016    ///
2017    /// Layouts may have different strides and bit depths, but must have identical
2018    /// dimensions. Alpha may be present independently on either side; see
2019    /// [`Self::try_convert_packed_to_planar`] for missing-alpha behavior. Buffers are borrowed
2020    /// directly without copying; strides are in bytes and must be positive and aligned.
2021    /// Unpadded tails may require multiple native calls; a later error may leave
2022    /// earlier destination regions modified.
2023    pub fn try_apply_planar_convert(
2024        &self,
2025        source: PlanarBytes<'_>,
2026        mut destination: PlanarBytesMut<'_>,
2027    ) -> Result<()> {
2028        if source.layout.width != destination.layout.width
2029            || source.layout.height != destination.layout.height
2030        {
2031            return Err(OcioError::InvalidInput(
2032                "planar dimensions must match".into(),
2033            ));
2034        }
2035        let ([iw, ih, ix, iy], mut split_input) =
2036            validate_planar_sample_bounds(source.layout, &[source.red, source.green, source.blue])?;
2037        let ([ow, oh, ox, oy], mut split_output) = validate_planar_sample_bounds(
2038            destination.layout,
2039            &[destination.red, destination.green, destination.blue],
2040        )?;
2041        if let Some(input) = source.alpha {
2042            split_input |= validate_planar_sample_bounds(source.layout, &[input])?.1;
2043        }
2044        if let Some(output) = destination.alpha.as_deref() {
2045            split_output |= validate_planar_sample_bounds(destination.layout, &[output])?.1;
2046        }
2047        let input = ocio_sys::OcioPlanarBuffer {
2048            red: source.red.as_ptr().cast_mut().cast(),
2049            green: source.green.as_ptr().cast_mut().cast(),
2050            blue: source.blue.as_ptr().cast_mut().cast(),
2051            alpha: source
2052                .alpha
2053                .map_or(std::ptr::null_mut(), |p| p.as_ptr().cast_mut().cast()),
2054            width: iw,
2055            height: ih,
2056            x_stride: ix,
2057            y_stride: iy,
2058            bit_depth: source.layout.bit_depth as i32,
2059        };
2060        let output = ocio_sys::OcioPlanarBuffer {
2061            red: destination.red.as_mut_ptr().cast(),
2062            green: destination.green.as_mut_ptr().cast(),
2063            blue: destination.blue.as_mut_ptr().cast(),
2064            alpha: destination
2065                .alpha
2066                .as_deref_mut()
2067                .map_or(std::ptr::null_mut(), |p| p.as_mut_ptr().cast()),
2068            width: ow,
2069            height: oh,
2070            x_stride: ox,
2071            y_stride: oy,
2072            bit_depth: destination.layout.bit_depth as i32,
2073        };
2074        if split_input || split_output {
2075            let long_max = std::ffi::c_long::MAX as i64;
2076            if iw > i64::from(std::ffi::c_int::MAX) / 4
2077                || ih > long_max
2078                || iw > long_max / ih
2079                || ix > isize::MAX as i64
2080                || iy > isize::MAX as i64
2081                || ox > isize::MAX as i64
2082                || oy > isize::MAX as i64
2083            {
2084                return Err(OcioError::InvalidInput(
2085                    "planar layout exceeds native limits".into(),
2086                ));
2087            }
2088            let input_size =
2089                bit_depth_bytes_per_channel("planar conversion", source.layout.bit_depth)?;
2090            let output_size =
2091                bit_depth_bytes_per_channel("planar conversion", destination.layout.bit_depth)?;
2092            let region = |base: &ocio_sys::OcioPlanarBuffer,
2093                          offset: usize,
2094                          width: i64,
2095                          height: i64,
2096                          x: i64,
2097                          y: i64| {
2098                let advance = |p: *mut c_void| {
2099                    if p.is_null() {
2100                        p
2101                    } else {
2102                        p.cast::<u8>().wrapping_add(offset).cast()
2103                    }
2104                };
2105                ocio_sys::OcioPlanarBuffer {
2106                    red: advance(base.red),
2107                    green: advance(base.green),
2108                    blue: advance(base.blue),
2109                    alpha: advance(base.alpha),
2110                    width,
2111                    height,
2112                    x_stride: x,
2113                    y_stride: y,
2114                    bit_depth: base.bit_depth,
2115                }
2116            };
2117            let apply_region =
2118                |src_offset, dst_offset, width, height, in_x, in_y, out_x, out_y| -> Result<()> {
2119                    let src = region(&input, src_offset, width, height, in_x, in_y);
2120                    let dst = region(&output, dst_offset, width, height, out_x, out_y);
2121                    crate::clear_last_error();
2122                    // SAFETY: each validated region's samples and final pointer
2123                    // increments fit the corresponding source/destination planes.
2124                    unsafe {
2125                        ocio_sys::ocio_cpu_processor_apply_planar_convert(
2126                            self.handle.as_ptr(),
2127                            &src,
2128                            &dst,
2129                        );
2130                    }
2131                    crate::ocio_call_status()
2132                };
2133            for part in planar_tail_regions(
2134                iw as usize,
2135                ih as usize,
2136                (ix as usize, iy as usize),
2137                (ox as usize, oy as usize),
2138            )
2139            .into_iter()
2140            .flatten()
2141            {
2142                let (in_x, in_y) = if part.final_pixel {
2143                    (input_size as i64, input_size as i64)
2144                } else {
2145                    (ix, iy)
2146                };
2147                let (out_x, out_y) = if part.final_pixel {
2148                    (output_size as i64, output_size as i64)
2149                } else {
2150                    (ox, oy)
2151                };
2152                apply_region(
2153                    part.source_offset,
2154                    part.destination_offset,
2155                    part.width,
2156                    part.height,
2157                    in_x,
2158                    in_y,
2159                    out_x,
2160                    out_y,
2161                )?;
2162            }
2163            return Ok(());
2164        }
2165        crate::clear_last_error();
2166        // SAFETY: Both descriptors have validated extents and alignment. The source
2167        // is read-only during apply, and the destination planes are exclusively borrowed.
2168        unsafe {
2169            ocio_sys::ocio_cpu_processor_apply_planar_convert(self.handle.as_ptr(), &input, &output)
2170        };
2171        crate::ocio_call_status()
2172    }
2173    /// Convert separate packed buffers with the processor's input/output depths.
2174    ///
2175    /// RGB and RGBA are supported. Strides are measured in samples. Input and
2176    /// output slices are checked independently and must meet native alignment.
2177    /// Unpadded tails may require an additional native call; an error in that
2178    /// call can leave the earlier destination pixels modified.
2179    pub fn try_apply_packed_convert(
2180        &self,
2181        input: &[u8],
2182        output: &mut [u8],
2183        layout: PackedConversionLayout,
2184    ) -> Result<()> {
2185        let PackedConversionLayout {
2186            pixels,
2187            channels,
2188            input_depth,
2189            output_depth,
2190            input_stride,
2191            output_stride,
2192        } = layout;
2193        if pixels <= 0
2194            || !matches!(channels, 3 | 4)
2195            || input_stride < i64::from(channels)
2196            || output_stride < i64::from(channels)
2197        {
2198            return Err(OcioError::InvalidInput(
2199                "invalid packed conversion layout".into(),
2200            ));
2201        }
2202        let api = "CPUProcessor::try_apply_packed_convert";
2203        validate_packed_buffer_len(
2204            api,
2205            input.len(),
2206            input_depth,
2207            pixels,
2208            input_stride,
2209            channels as usize,
2210        )?;
2211        validate_packed_buffer_len(
2212            api,
2213            output.len(),
2214            output_depth,
2215            pixels,
2216            output_stride,
2217            channels as usize,
2218        )?;
2219        validate_packed_buffer_alignment(api, input.as_ptr(), input_depth, pixels)?;
2220        validate_packed_buffer_alignment(api, output.as_ptr(), output_depth, pixels)?;
2221        let in_size = bit_depth_bytes_per_channel(api, input_depth)? as i64;
2222        let out_size = bit_depth_bytes_per_channel(api, output_depth)? as i64;
2223        let in_bytes = input_stride
2224            .checked_mul(in_size)
2225            .ok_or_else(|| OcioError::InvalidInput("input stride overflow".into()))?;
2226        let out_bytes = output_stride
2227            .checked_mul(out_size)
2228            .ok_or_else(|| OcioError::InvalidInput("output stride overflow".into()))?;
2229        let count = pixels as usize;
2230        let channel_count = channels as usize;
2231        let needs_tail = |len: usize, stride: i64, size: i64| {
2232            if channels == 4 && stride == i64::from(channels) {
2233                return false; // Native tight RGBA fast path.
2234            }
2235            count
2236                .checked_mul(stride as usize)
2237                .and_then(|n| n.checked_add(channel_count - 1))
2238                .and_then(|n| n.checked_mul(size as usize))
2239                .is_none_or(|required| required > len)
2240        };
2241        if needs_tail(input.len(), input_stride, in_size)
2242            || needs_tail(output.len(), output_stride, out_size)
2243        {
2244            let src_offset = (count - 1) * in_bytes as usize;
2245            let dst_offset = (count - 1) * out_bytes as usize;
2246            if pixels > 1 {
2247                crate::clear_last_error();
2248                // SAFETY: validated layouts contain the prefix plus the next
2249                // pixel, so every native pointer step remains in its slice.
2250                unsafe {
2251                    ocio_sys::ocio_cpu_processor_apply_packed_convert(
2252                        self.handle.as_ptr(),
2253                        input.as_ptr().cast(),
2254                        output.as_mut_ptr().cast(),
2255                        pixels - 1,
2256                        channels.into(),
2257                        input_depth as i32,
2258                        output_depth as i32,
2259                        in_bytes,
2260                        out_bytes,
2261                    );
2262                }
2263                crate::ocio_call_status()?;
2264            }
2265            #[repr(align(4))]
2266            struct AlignedPixel([u8; 28]);
2267            let mut src = AlignedPixel([0; 28]);
2268            let mut dst = AlignedPixel([0; 28]);
2269            let src_len = channel_count * in_size as usize;
2270            let dst_len = channel_count * out_size as usize;
2271            src.0[..src_len].copy_from_slice(&input[src_offset..src_offset + src_len]);
2272            crate::clear_last_error();
2273            // SAFETY: the aligned buffers hold all channels and their final
2274            // native pointer steps; both bit depths are retained unchanged.
2275            unsafe {
2276                ocio_sys::ocio_cpu_processor_apply_packed_convert(
2277                    self.handle.as_ptr(),
2278                    src.0.as_ptr().cast(),
2279                    dst.0.as_mut_ptr().cast(),
2280                    1,
2281                    channels.into(),
2282                    input_depth as i32,
2283                    output_depth as i32,
2284                    channels as i64 * in_size,
2285                    channels as i64 * out_size,
2286                );
2287            }
2288            crate::ocio_call_status()?;
2289            output[dst_offset..dst_offset + dst_len].copy_from_slice(&dst.0[..dst_len]);
2290            return Ok(());
2291        }
2292        crate::clear_last_error();
2293        unsafe {
2294            ocio_sys::ocio_cpu_processor_apply_packed_convert(
2295                self.handle.as_ptr(),
2296                input.as_ptr().cast(),
2297                output.as_mut_ptr().cast(),
2298                pixels,
2299                channels.into(),
2300                input_depth as i32,
2301                output_depth as i32,
2302                in_bytes,
2303                out_bytes,
2304            )
2305        };
2306        crate::ocio_call_status()
2307    }
2308    /// Process planar byte buffers in place at the processor's native bit depth.
2309    ///
2310    /// All pointers and strides must be aligned for the selected storage type.
2311    /// The binding validates the layout and passes the original buffers to OCIO.
2312    /// Unpadded final samples are handled in up to three native regions, with
2313    /// no pixel copy. A later error may leave earlier regions modified.
2314    pub fn try_apply_planar_bytes(
2315        &self,
2316        red: &mut [u8],
2317        green: &mut [u8],
2318        blue: &mut [u8],
2319        alpha: Option<&mut [u8]>,
2320        layout: PlanarByteLayout,
2321    ) -> Result<()> {
2322        let size =
2323            bit_depth_bytes_per_channel("CPUProcessor::try_apply_planar_bytes", layout.bit_depth)?;
2324        let invalid =
2325            || OcioError::InvalidInput("invalid, unaligned or overflowing planar layout".into());
2326        let PlanarByteLayout {
2327            width,
2328            height,
2329            x_stride,
2330            y_stride,
2331            ..
2332        } = layout;
2333        if width == 0
2334            || height == 0
2335            || x_stride < size
2336            || y_stride == 0
2337            || !x_stride.is_multiple_of(size)
2338            || !y_stride.is_multiple_of(size)
2339            || x_stride > y_stride / width
2340        {
2341            return Err(invalid());
2342        }
2343        let row = (height - 1).checked_mul(y_stride).ok_or_else(invalid)?;
2344        let last = (width - 1)
2345            .checked_mul(x_stride)
2346            .and_then(|v| v.checked_add(row))
2347            .ok_or_else(invalid)?;
2348        let end = last.checked_add(size).ok_or_else(invalid)?;
2349        let required = width.checked_mul(x_stride).and_then(|v| row.checked_add(v));
2350        let mut needs_split = false;
2351        for plane in [&*red, &*green, &*blue].into_iter().chain(alpha.as_deref()) {
2352            if plane.len() < end || !(plane.as_ptr() as usize).is_multiple_of(size) {
2353                return Err(invalid());
2354            }
2355            needs_split |= required.is_none_or(|n| plane.len() < n);
2356        }
2357        if needs_split {
2358            let long_max = std::ffi::c_long::MAX as u128;
2359            if width > std::ffi::c_int::MAX as usize / 4
2360                || height as u128 > long_max
2361                || (width as u128) * (height as u128) > long_max
2362                || x_stride > isize::MAX as usize
2363                || y_stride > isize::MAX as usize
2364            {
2365                return Err(invalid());
2366            }
2367            let [Ok(_w), Ok(_h), Ok(x), Ok(y)] =
2368                [width, height, x_stride, y_stride].map(i64::try_from)
2369            else {
2370                return Err(invalid());
2371            };
2372            let r = red.as_mut_ptr();
2373            let g = green.as_mut_ptr();
2374            let b = blue.as_mut_ptr();
2375            let a = alpha.map_or(std::ptr::null_mut(), |plane| plane.as_mut_ptr());
2376            let apply_region =
2377                |offset: usize, width: i64, height: i64, x: i64, y: i64| -> Result<()> {
2378                    crate::clear_last_error();
2379                    // SAFETY: every accessed sample and final pointer step is within
2380                    // its exclusively borrowed, aligned plane or one past it.
2381                    unsafe {
2382                        ocio_sys::ocio_cpu_processor_apply_planar_bytes(
2383                            self.handle.as_ptr(),
2384                            r.add(offset).cast(),
2385                            g.add(offset).cast(),
2386                            b.add(offset).cast(),
2387                            if a.is_null() { a } else { a.add(offset) }.cast(),
2388                            width,
2389                            height,
2390                            x,
2391                            y,
2392                            layout.bit_depth as i32,
2393                        );
2394                    }
2395                    crate::ocio_call_status()
2396                };
2397            for part in
2398                planar_tail_regions(width, height, (x_stride, y_stride), (x_stride, y_stride))
2399                    .into_iter()
2400                    .flatten()
2401            {
2402                let (x, y) = if part.final_pixel {
2403                    (size as i64, size as i64)
2404                } else {
2405                    (x, y)
2406                };
2407                apply_region(part.source_offset, part.width, part.height, x, y)?;
2408            }
2409            return Ok(());
2410        }
2411        let [width, height, x_stride, y_stride] =
2412            validate_planar_buffer(layout, &[red, green, blue])?;
2413        if let Some(alpha) = alpha.as_deref() {
2414            validate_planar_buffer(layout, &[alpha])?;
2415        }
2416        crate::clear_last_error();
2417        unsafe {
2418            ocio_sys::ocio_cpu_processor_apply_planar_bytes(
2419                self.handle.as_ptr(),
2420                red.as_mut_ptr().cast(),
2421                green.as_mut_ptr().cast(),
2422                blue.as_mut_ptr().cast(),
2423                alpha.map_or(std::ptr::null_mut(), |p| p.as_mut_ptr().cast()),
2424                width,
2425                height,
2426                x_stride,
2427                y_stride,
2428                layout.bit_depth as i32,
2429            )
2430        };
2431        crate::ocio_call_status()
2432    }
2433    /// Process strided planar F32 channels in place without copying pixels.
2434    ///
2435    /// Strides are measured in F32 elements and must be positive. As required
2436    /// by OCIO, the row stride must be at least the pixel stride times the
2437    /// width, even for a single row. Alpha may be omitted. If a plane ends
2438    /// immediately after its last sample, the image is processed in up to
2439    /// three regions to keep OCIO's pointer increments within the slices.
2440    /// If a later region fails, earlier regions may already be modified.
2441    pub fn try_apply_planar_strided_f32(
2442        &self,
2443        red: &mut [f32],
2444        green: &mut [f32],
2445        blue: &mut [f32],
2446        alpha: Option<&mut [f32]>,
2447        layout: PlanarF32Layout,
2448    ) -> Result<()> {
2449        let PlanarF32Layout {
2450            width,
2451            height,
2452            x_stride,
2453            y_stride,
2454        } = layout;
2455        let invalid = || OcioError::InvalidInput("invalid or overflowing planar layout".into());
2456        if width == 0 || height == 0 || x_stride == 0 || y_stride == 0 {
2457            return Err(invalid());
2458        }
2459        let row_span = width.checked_mul(x_stride).ok_or_else(invalid)?;
2460        if x_stride > y_stride / width {
2461            return Err(invalid());
2462        }
2463        let last_row = (height - 1).checked_mul(y_stride).ok_or_else(invalid)?;
2464        let last = (width - 1)
2465            .checked_mul(x_stride)
2466            .and_then(|v| v.checked_add(last_row))
2467            .ok_or_else(invalid)?;
2468        let sample_end = last.checked_add(1).ok_or_else(invalid)?;
2469        let required = last_row.checked_add(row_span);
2470        if [red.len(), green.len(), blue.len()]
2471            .iter()
2472            .any(|&n| n < sample_end)
2473            || alpha.as_ref().is_some_and(|plane| plane.len() < sample_end)
2474        {
2475            return Err(invalid());
2476        }
2477        let needs_split = required.is_none_or(|n| {
2478            [red.len(), green.len(), blue.len()]
2479                .iter()
2480                .any(|&len| len < n)
2481                || alpha.as_ref().is_some_and(|plane| plane.len() < n)
2482        });
2483        let values = [width, height, x_stride, y_stride].map(i64::try_from);
2484        let [Ok(native_width), Ok(native_height), Ok(native_x), Ok(native_y)] = values else {
2485            return Err(invalid());
2486        };
2487        if needs_split {
2488            // Apply the same native range checks before any region mutates data.
2489            let long_max = std::ffi::c_long::MAX as u128;
2490            if width > std::ffi::c_int::MAX as usize / 4
2491                || height as u128 > long_max
2492                || (width as u128) * (height as u128) > long_max
2493                || x_stride > isize::MAX as usize / 4
2494                || y_stride > isize::MAX as usize / 4
2495            {
2496                return Err(invalid());
2497            }
2498            let r = red.as_mut_ptr();
2499            let g = green.as_mut_ptr();
2500            let b = blue.as_mut_ptr();
2501            let a = alpha.map_or(std::ptr::null_mut(), |plane| plane.as_mut_ptr());
2502            let apply_region = |offset: usize, w: i64, h: i64, x: i64, y: i64| -> Result<()> {
2503                crate::clear_last_error();
2504                // SAFETY: the validated slices contain every region and its
2505                // final pointer step; all planes remain exclusively borrowed.
2506                unsafe {
2507                    ocio_sys::ocio_cpu_processor_apply_planar_strided_f32(
2508                        self.handle.as_ptr(),
2509                        r.add(offset),
2510                        g.add(offset),
2511                        b.add(offset),
2512                        if a.is_null() { a } else { a.add(offset) },
2513                        w,
2514                        h,
2515                        x,
2516                        y,
2517                    );
2518                }
2519                crate::ocio_call_status()
2520            };
2521            for part in
2522                planar_tail_regions(width, height, (x_stride, y_stride), (x_stride, y_stride))
2523                    .into_iter()
2524                    .flatten()
2525            {
2526                let (x, y) = if part.final_pixel {
2527                    (1, 1)
2528                } else {
2529                    (native_x, native_y)
2530                };
2531                apply_region(part.source_offset, part.width, part.height, x, y)?;
2532            }
2533            return Ok(());
2534        }
2535        crate::clear_last_error();
2536        unsafe {
2537            ocio_sys::ocio_cpu_processor_apply_planar_strided_f32(
2538                self.handle.as_ptr(),
2539                red.as_mut_ptr(),
2540                green.as_mut_ptr(),
2541                blue.as_mut_ptr(),
2542                alpha.map_or(std::ptr::null_mut(), |plane| plane.as_mut_ptr()),
2543                native_width,
2544                native_height,
2545                native_x,
2546                native_y,
2547            )
2548        };
2549        crate::ocio_call_status()
2550    }
2551    /// Process contiguous row-major planar float channels in place.
2552    ///
2553    /// Each channel must contain exactly `width * height` samples. Alpha is
2554    /// optional. The native descriptor borrows these slices for this call and
2555    /// no pixel buffer is allocated or copied by the binding.
2556    pub fn try_apply_planar_f32(
2557        &self,
2558        red: &mut [f32],
2559        green: &mut [f32],
2560        blue: &mut [f32],
2561        alpha: Option<&mut [f32]>,
2562        width: usize,
2563        height: usize,
2564    ) -> Result<()> {
2565        let count = width
2566            .checked_mul(height)
2567            .ok_or_else(|| OcioError::InvalidInput("planar dimensions overflow".into()))?;
2568        if count == 0
2569            || [red.len(), green.len(), blue.len()]
2570                .iter()
2571                .any(|&len| len != count)
2572            || alpha.as_ref().is_some_and(|plane| plane.len() != count)
2573        {
2574            return Err(OcioError::InvalidInput(
2575                "planar channel lengths must match nonzero dimensions".into(),
2576            ));
2577        }
2578        let width = i64::try_from(width)
2579            .map_err(|_| OcioError::InvalidInput("planar width exceeds i64".into()))?;
2580        let height = i64::try_from(height)
2581            .map_err(|_| OcioError::InvalidInput("planar height exceeds i64".into()))?;
2582        crate::clear_last_error();
2583        unsafe {
2584            ocio_sys::ocio_cpu_processor_apply_planar_f32(
2585                self.handle.as_ptr(),
2586                red.as_mut_ptr(),
2587                green.as_mut_ptr(),
2588                blue.as_mut_ptr(),
2589                alpha.map_or(std::ptr::null_mut(), |plane| plane.as_mut_ptr()),
2590                width,
2591                height,
2592            )
2593        };
2594        crate::ocio_call_status()
2595    }
2596    /// # Safety
2597    /// `img_desc` must point to a valid OCIO image descriptor for the active
2598    /// ABI. The pixel buffers referenced by the descriptor must remain
2599    /// allocated, writable, and correctly strided for the full call. The
2600    /// descriptor is borrowed only; this method does not take ownership.
2601    #[deprecated(
2602        since = "0.2.0",
2603        note = "raw OCIO image-descriptor entry point; prefer apply_rgb/apply_rgba/apply_*_pixels for Rust callers"
2604    )]
2605    pub unsafe fn apply(&self, img_desc: *mut c_void) {
2606        let _ = unsafe { self.try_apply_raw(img_desc) };
2607    }
2608
2609    /// Apply in place to a Rust-owned native descriptor.
2610    ///
2611    /// OCIO rejects a descriptor whose bit depth does not match both processor
2612    /// bit depths. The descriptor and its backing buffers are reused.
2613    pub fn try_apply_image_desc(&self, image: &mut crate::NativeImageDesc<'_>) -> Result<()> {
2614        // Fixed-layout constructors check the layout; custom providers uphold
2615        // the same native preconditions through their unsafe trait impl.
2616        unsafe { self.try_apply_raw(image.as_mut_ptr()) }
2617    }
2618
2619    /// Convert between Rust-owned native descriptors of equal size.
2620    ///
2621    /// OCIO checks the dimensions and input/output bit depths before processing.
2622    pub fn try_convert_image_desc(
2623        &self,
2624        source: &mut crate::NativeImageDesc<'_>,
2625        destination: &mut crate::NativeImageDesc<'_>,
2626    ) -> Result<()> {
2627        // Fixed layouts borrow buffers exclusively; custom providers uphold
2628        // non-overlap through their unsafe trait contract.
2629        unsafe { self.try_apply_raw_v2(source.as_mut_ptr(), destination.as_mut_ptr()) }
2630    }
2631
2632    /// Apply a native OCIO image descriptor in place without taking ownership.
2633    ///
2634    /// Prefer the slice-based methods for Rust buffers. This entry point is for
2635    /// interop with C++ code that already owns a descriptor.
2636    ///
2637    /// # Safety
2638    /// `img_desc` must point to a valid OCIO image descriptor for the active
2639    /// ABI (pass a pointer to its `ImageDesc` base). The pixel buffers must
2640    /// remain exclusively accessible, writable, correctly aligned and strided
2641    /// for the processor's bit depths. This bypasses Rust's layout checks and
2642    /// tail handling: the buffers must accommodate native pointer stepping.
2643    pub unsafe fn try_apply_raw(&self, img_desc: *mut c_void) -> Result<()> {
2644        crate::clear_last_error();
2645        unsafe {
2646            ocio_sys::ocio_cpu_processor_apply(self.handle.as_ptr(), img_desc);
2647        }
2648        crate::ocio_call_status()
2649    }
2650
2651    /// # Safety
2652    /// Same invariants as [`apply`](CPUProcessor::apply). This is a
2653    /// compatibility alias for older ABI versions.
2654    #[doc(hidden)]
2655    #[deprecated(
2656        since = "0.2.0",
2657        note = "compat alias; prefer apply() or the typed pixel helpers"
2658    )]
2659    pub unsafe fn apply_v1(&self, img_desc: *mut c_void) {
2660        let _ = unsafe { self.try_apply_raw_v1(img_desc) };
2661    }
2662
2663    /// Fallible raw ABI compatibility entry point for single-descriptor apply.
2664    ///
2665    /// # Safety
2666    /// Same invariants as [`Self::try_apply_raw`].
2667    #[doc(hidden)]
2668    pub unsafe fn try_apply_raw_v1(&self, img_desc: *mut c_void) -> Result<()> {
2669        crate::clear_last_error();
2670        unsafe {
2671            ocio_sys::ocio_cpu_processor_apply_v1(self.handle.as_ptr(), img_desc);
2672        }
2673        crate::ocio_call_status()
2674    }
2675
2676    /// # Safety
2677    /// `src_img_desc` and `dst_img_desc` must point to valid OCIO image
2678    /// descriptors for the active ABI. Their referenced buffers must remain
2679    /// allocated for the call; the destination buffer must be writable. Unless
2680    /// the upstream descriptor contract explicitly permits it, source and
2681    /// destination memory must not overlap. Both descriptors are borrowed only.
2682    #[doc(hidden)]
2683    #[deprecated(
2684        since = "0.2.0",
2685        note = "raw OCIO image-descriptor entry point; prefer apply_rgb/apply_rgba/apply_*_pixels for Rust callers"
2686    )]
2687    pub unsafe fn apply_v2(&self, src_img_desc: *mut c_void, dst_img_desc: *mut c_void) {
2688        let _ = unsafe { self.try_apply_raw_v2(src_img_desc, dst_img_desc) };
2689    }
2690
2691    /// Apply between separate native OCIO image descriptors without taking ownership.
2692    ///
2693    /// # Safety
2694    /// Both pointers must address valid `ImageDesc` bases for the active ABI.
2695    /// Source storage must be readable and destination storage exclusively
2696    /// writable, with no overlap. Both must satisfy the native alignment,
2697    /// bit-depth, stride and pointer-stepping requirements described in
2698    /// [`Self::try_apply_raw`].
2699    pub unsafe fn try_apply_raw_v2(
2700        &self,
2701        src_img_desc: *mut c_void,
2702        dst_img_desc: *mut c_void,
2703    ) -> Result<()> {
2704        crate::clear_last_error();
2705        unsafe {
2706            ocio_sys::ocio_cpu_processor_apply_v2(self.handle.as_ptr(), src_img_desc, dst_img_desc);
2707        }
2708        crate::ocio_call_status()
2709    }
2710
2711    /// Apply the processor in place to one RGBA pixel.
2712    pub fn apply_rgba(&self, rgba: &mut [f32; 4]) {
2713        self.try_apply_rgba(rgba)
2714            .expect("CPUProcessor::apply_rgba failed");
2715    }
2716
2717    /// Apply the processor in place to one RGBA pixel.
2718    ///
2719    /// Both processor bit depths must be F32, as required by OCIO's
2720    /// single-pixel API. A mismatch returns an error without changing `rgba`.
2721    pub fn try_apply_rgba(&self, rgba: &mut [f32; 4]) -> Result<()> {
2722        self.require_f32_pixel_io()?;
2723        let ok = unsafe {
2724            ocio_sys::ocio_cpu_processor_try_apply_rgba(
2725                self.handle.as_ptr(),
2726                rgba.as_mut_ptr() as *mut c_void,
2727            )
2728        };
2729        if ok {
2730            Ok(())
2731        } else {
2732            crate::ocio_call_status()?;
2733            Err(OcioError::Ocio(
2734                "OpenColorIO pixel processing failed without an error message".into(),
2735            ))
2736        }
2737    }
2738
2739    /// Apply the processor in place to one RGB pixel.
2740    pub fn apply_rgb(&self, rgb: &mut [f32; 3]) {
2741        self.try_apply_rgb(rgb)
2742            .expect("CPUProcessor::apply_rgb failed");
2743    }
2744
2745    /// Apply the processor in place to one RGB pixel.
2746    ///
2747    /// Both processor bit depths must be F32, as required by OCIO's
2748    /// single-pixel API. A mismatch returns an error without changing `rgb`.
2749    pub fn try_apply_rgb(&self, rgb: &mut [f32; 3]) -> Result<()> {
2750        self.require_f32_pixel_io()?;
2751        crate::clear_last_error();
2752        unsafe {
2753            ocio_sys::ocio_cpu_processor_apply_rgb(
2754                self.handle.as_ptr(),
2755                rgb.as_mut_ptr() as *mut c_void,
2756            );
2757        }
2758        crate::ocio_call_status()
2759    }
2760
2761    #[inline]
2762    fn require_f32_pixel_io(&self) -> Result<()> {
2763        if self.f32_pixel_io {
2764            Ok(())
2765        } else {
2766            Err(OcioError::InvalidInput(
2767                "single-pixel RGB/RGBA requires F32 input and output bit depths".into(),
2768            ))
2769        }
2770    }
2771
2772    /// Apply the processor to an RGBA float buffer with an explicit scalar stride.
2773    ///
2774    /// `stride` is measured in `f32` elements, not bytes.
2775    pub fn apply_rgba_pixels(&self, rgba: &mut [f32], num_pixels: i64, stride: i64) {
2776        self.try_apply_rgba_pixels(rgba, num_pixels, stride)
2777            .expect("CPUProcessor::apply_rgba_pixels failed");
2778    }
2779
2780    /// Apply the processor to an RGBA float buffer with an explicit scalar stride.
2781    ///
2782    /// `stride` is measured in `f32` elements, not bytes.
2783    pub fn try_apply_rgba_pixels(
2784        &self,
2785        rgba: &mut [f32],
2786        num_pixels: i64,
2787        stride: i64,
2788    ) -> Result<()> {
2789        let stride = rgba_single_pixel_native_stride(
2790            "CPUProcessor::apply_rgba_pixels",
2791            num_pixels,
2792            stride,
2793            std::mem::size_of::<f32>(),
2794        )?;
2795        validate_scalar_buffer_len(
2796            "CPUProcessor::apply_rgba_pixels",
2797            rgba.len(),
2798            num_pixels,
2799            stride,
2800            4,
2801        )?;
2802        if num_pixels > 0 {
2803            let pixels = num_pixels as usize;
2804            let step = normalized_stride("CPUProcessor::apply_rgba_pixels", stride, 4)?;
2805            let enough_for_final_step = pixels
2806                .checked_mul(step)
2807                .and_then(|n| n.checked_add(3))
2808                .is_some_and(|n| n <= rgba.len());
2809            // Tightly packed RGBA uses OCIO's packed fast path, which does not
2810            // advance four individual channel pointers.
2811            if step != 4 && !enough_for_final_step {
2812                let last = (pixels - 1) * step;
2813                if pixels > 1 {
2814                    let ok = unsafe {
2815                        ocio_sys::ocio_cpu_processor_try_apply_rgba_pixels(
2816                            self.handle.as_ptr(),
2817                            rgba.as_mut_ptr(),
2818                            num_pixels - 1,
2819                            stride,
2820                        )
2821                    };
2822                    if !ok {
2823                        crate::ocio_call_status()?;
2824                        return Err(OcioError::Ocio(
2825                            "OpenColorIO pixel processing failed without an error message".into(),
2826                        ));
2827                    }
2828                }
2829                let mut tail = [rgba[last], rgba[last + 1], rgba[last + 2], rgba[last + 3]];
2830                let ok = unsafe {
2831                    ocio_sys::ocio_cpu_processor_try_apply_rgba_pixels(
2832                        self.handle.as_ptr(),
2833                        tail.as_mut_ptr(),
2834                        1,
2835                        4,
2836                    )
2837                };
2838                if !ok {
2839                    crate::ocio_call_status()?;
2840                    return Err(OcioError::Ocio(
2841                        "OpenColorIO pixel processing failed without an error message".into(),
2842                    ));
2843                }
2844                rgba[last..last + 4].copy_from_slice(&tail);
2845                return Ok(());
2846            }
2847        }
2848        let ok = unsafe {
2849            ocio_sys::ocio_cpu_processor_try_apply_rgba_pixels(
2850                self.handle.as_ptr(),
2851                rgba.as_mut_ptr(),
2852                num_pixels,
2853                stride,
2854            )
2855        };
2856        if ok {
2857            Ok(())
2858        } else {
2859            crate::ocio_call_status()?;
2860            Err(OcioError::Ocio(
2861                "OpenColorIO pixel processing failed without an error message".into(),
2862            ))
2863        }
2864    }
2865
2866    /// Apply the processor to an RGB float buffer with an explicit scalar stride.
2867    ///
2868    /// `stride` is measured in `f32` elements, not bytes.
2869    pub fn apply_rgb_pixels(&self, rgb: &mut [f32], num_pixels: i64, stride: i64) {
2870        self.try_apply_rgb_pixels(rgb, num_pixels, stride)
2871            .expect("CPUProcessor::apply_rgb_pixels failed");
2872    }
2873
2874    /// Apply the processor to an RGB float buffer with an explicit scalar stride.
2875    ///
2876    /// `stride` is measured in `f32` elements, not bytes.
2877    pub fn try_apply_rgb_pixels(
2878        &self,
2879        rgb: &mut [f32],
2880        num_pixels: i64,
2881        stride: i64,
2882    ) -> Result<()> {
2883        validate_scalar_buffer_len(
2884            "CPUProcessor::apply_rgb_pixels",
2885            rgb.len(),
2886            num_pixels,
2887            stride,
2888            3,
2889        )?;
2890        if num_pixels > 0 {
2891            let pixels = num_pixels as usize;
2892            let step = normalized_stride("CPUProcessor::apply_rgb_pixels", stride, 3)?;
2893            // OCIO's generic RGB packer advances all three channel pointers
2894            // after the last pixel. The blue pointer advances furthest.
2895            let enough_for_final_step = pixels
2896                .checked_mul(step)
2897                .and_then(|n| n.checked_add(2))
2898                .is_some_and(|n| n <= rgb.len());
2899            if !enough_for_final_step {
2900                let last = (pixels - 1) * step;
2901                if pixels > 1 {
2902                    crate::clear_last_error();
2903                    unsafe {
2904                        ocio_sys::ocio_cpu_processor_apply_rgb_pixels(
2905                            self.handle.as_ptr(),
2906                            rgb.as_mut_ptr(),
2907                            num_pixels - 1,
2908                            stride,
2909                        );
2910                    }
2911                    crate::ocio_call_status()?;
2912                }
2913                // Preserve the native image path (including version-dependent
2914                // missing-alpha semantics); applyRGB has different semantics.
2915                let mut tail = [rgb[last], rgb[last + 1], rgb[last + 2], 0.0, 0.0];
2916                crate::clear_last_error();
2917                unsafe {
2918                    ocio_sys::ocio_cpu_processor_apply_rgb_pixels(
2919                        self.handle.as_ptr(),
2920                        tail.as_mut_ptr(),
2921                        1,
2922                        3,
2923                    );
2924                }
2925                crate::ocio_call_status()?;
2926                rgb[last..last + 3].copy_from_slice(&tail[..3]);
2927                return Ok(());
2928            }
2929        }
2930        crate::clear_last_error();
2931        unsafe {
2932            ocio_sys::ocio_cpu_processor_apply_rgb_pixels(
2933                self.handle.as_ptr(),
2934                rgb.as_mut_ptr(),
2935                num_pixels,
2936                stride,
2937            );
2938        }
2939        crate::ocio_call_status()
2940    }
2941
2942    /// Apply the processor to packed RGBA bytes using an explicit OCIO bit depth.
2943    ///
2944    /// `bit_depth` must match the CPU processor's finalized bit-depth contract.
2945    /// In particular, a default CPU processor commonly expects `BitDepth::F32`.
2946    pub fn apply_rgba_packed_bit_depth(
2947        &self,
2948        rgba: &mut [u8],
2949        bit_depth: BitDepth,
2950        num_pixels: i64,
2951        stride: i64,
2952    ) {
2953        self.try_apply_rgba_packed_bit_depth(rgba, bit_depth, num_pixels, stride)
2954            .expect("CPUProcessor::apply_rgba_packed_bit_depth failed");
2955    }
2956
2957    /// Apply the processor to packed RGBA bytes using an explicit OCIO bit depth.
2958    ///
2959    /// `bit_depth` must match the CPU processor's finalized bit-depth contract.
2960    /// In particular, a default CPU processor commonly expects `BitDepth::F32`.
2961    pub fn try_apply_rgba_packed_bit_depth(
2962        &self,
2963        rgba: &mut [u8],
2964        bit_depth: BitDepth,
2965        num_pixels: i64,
2966        stride: i64,
2967    ) -> Result<()> {
2968        let sample =
2969            bit_depth_bytes_per_channel("CPUProcessor::apply_rgba_packed_bit_depth", bit_depth)?;
2970        let stride = rgba_single_pixel_native_stride(
2971            "CPUProcessor::apply_rgba_packed_bit_depth",
2972            num_pixels,
2973            stride,
2974            sample,
2975        )?;
2976        validate_packed_buffer_len(
2977            "CPUProcessor::apply_rgba_packed_bit_depth",
2978            rgba.len(),
2979            bit_depth,
2980            num_pixels,
2981            stride,
2982            4,
2983        )?;
2984        validate_packed_buffer_alignment(
2985            "CPUProcessor::apply_rgba_packed_bit_depth",
2986            rgba.as_ptr(),
2987            bit_depth,
2988            num_pixels,
2989        )?;
2990        if num_pixels > 0 {
2991            let pixels = num_pixels as usize;
2992            let step = normalized_stride("CPUProcessor::apply_rgba_packed_bit_depth", stride, 4)?;
2993            let sample = bit_depth_bytes_per_channel(
2994                "CPUProcessor::apply_rgba_packed_bit_depth",
2995                bit_depth,
2996            )?;
2997            let enough_for_final_step = pixels
2998                .checked_mul(step)
2999                .and_then(|n| n.checked_add(3))
3000                .and_then(|n| n.checked_mul(sample))
3001                .is_some_and(|n| n <= rgba.len());
3002            if step != 4 && !enough_for_final_step {
3003                let last = (pixels - 1) * step * sample;
3004                if pixels > 1 {
3005                    crate::clear_last_error();
3006                    unsafe {
3007                        ocio_sys::ocio_cpu_processor_apply_rgba_packed(
3008                            self.handle.as_ptr(),
3009                            rgba.as_mut_ptr().cast(),
3010                            bit_depth as i32,
3011                            num_pixels - 1,
3012                            stride,
3013                        );
3014                    }
3015                    crate::ocio_call_status()?;
3016                }
3017                #[repr(align(4))]
3018                struct AlignedTail([u8; 16]);
3019                let mut tail = AlignedTail([0; 16]);
3020                let pixel_bytes = 4 * sample;
3021                tail.0[..pixel_bytes].copy_from_slice(&rgba[last..last + pixel_bytes]);
3022                crate::clear_last_error();
3023                unsafe {
3024                    ocio_sys::ocio_cpu_processor_apply_rgba_packed(
3025                        self.handle.as_ptr(),
3026                        tail.0.as_mut_ptr().cast(),
3027                        bit_depth as i32,
3028                        1,
3029                        4,
3030                    );
3031                }
3032                crate::ocio_call_status()?;
3033                rgba[last..last + pixel_bytes].copy_from_slice(&tail.0[..pixel_bytes]);
3034                return Ok(());
3035            }
3036        }
3037        crate::clear_last_error();
3038        unsafe {
3039            ocio_sys::ocio_cpu_processor_apply_rgba_packed(
3040                self.handle.as_ptr(),
3041                rgba.as_mut_ptr() as *mut std::ffi::c_void,
3042                bit_depth as i32,
3043                num_pixels,
3044                stride,
3045            );
3046        }
3047        crate::ocio_call_status()
3048    }
3049
3050    #[doc(hidden)]
3051    #[deprecated(
3052        since = "0.2.0",
3053        note = "compat alias; prefer apply_rgba_packed_bit_depth with the BitDepth enum"
3054    )]
3055    pub fn apply_rgba_packed(&self, rgba: &mut [u8], bit_depth: i32, num_pixels: i64, stride: i64) {
3056        let bit_depth = match bit_depth {
3057            1 => BitDepth::Uint8,
3058            2 => BitDepth::Uint10,
3059            3 => BitDepth::Uint12,
3060            4 => BitDepth::Uint14,
3061            5 => BitDepth::Uint16,
3062            6 => BitDepth::Uint32,
3063            7 => BitDepth::F16,
3064            8 => BitDepth::F32,
3065            _ => BitDepth::Unknown,
3066        };
3067        self.apply_rgba_packed_bit_depth(rgba, bit_depth, num_pixels, stride);
3068    }
3069
3070    /// Apply the processor to packed RGB bytes using an explicit OCIO bit depth.
3071    ///
3072    /// `bit_depth` must match the CPU processor's finalized bit-depth contract.
3073    /// In particular, a default CPU processor commonly expects `BitDepth::F32`.
3074    pub fn apply_rgb_packed_bit_depth(
3075        &self,
3076        rgb: &mut [u8],
3077        bit_depth: BitDepth,
3078        num_pixels: i64,
3079        stride: i64,
3080    ) {
3081        self.try_apply_rgb_packed_bit_depth(rgb, bit_depth, num_pixels, stride)
3082            .expect("CPUProcessor::apply_rgb_packed_bit_depth failed");
3083    }
3084
3085    /// Apply the processor to packed RGB bytes using an explicit OCIO bit depth.
3086    ///
3087    /// `bit_depth` must match the CPU processor's finalized bit-depth contract.
3088    /// In particular, a default CPU processor commonly expects `BitDepth::F32`.
3089    pub fn try_apply_rgb_packed_bit_depth(
3090        &self,
3091        rgb: &mut [u8],
3092        bit_depth: BitDepth,
3093        num_pixels: i64,
3094        stride: i64,
3095    ) -> Result<()> {
3096        validate_packed_buffer_len(
3097            "CPUProcessor::apply_rgb_packed_bit_depth",
3098            rgb.len(),
3099            bit_depth,
3100            num_pixels,
3101            stride,
3102            3,
3103        )?;
3104        validate_packed_buffer_alignment(
3105            "CPUProcessor::apply_rgb_packed_bit_depth",
3106            rgb.as_ptr(),
3107            bit_depth,
3108            num_pixels,
3109        )?;
3110        if num_pixels > 0 {
3111            let pixels = num_pixels as usize;
3112            let step = normalized_stride("CPUProcessor::apply_rgb_packed_bit_depth", stride, 3)?;
3113            let sample =
3114                bit_depth_bytes_per_channel("CPUProcessor::apply_rgb_packed_bit_depth", bit_depth)?;
3115            let enough_for_final_step = pixels
3116                .checked_mul(step)
3117                .and_then(|n| n.checked_add(2))
3118                .and_then(|n| n.checked_mul(sample))
3119                .is_some_and(|n| n <= rgb.len());
3120            if !enough_for_final_step {
3121                let last = (pixels - 1) * step * sample;
3122                if pixels > 1 {
3123                    crate::clear_last_error();
3124                    unsafe {
3125                        ocio_sys::ocio_cpu_processor_apply_rgb_packed(
3126                            self.handle.as_ptr(),
3127                            rgb.as_mut_ptr().cast(),
3128                            bit_depth as i32,
3129                            num_pixels - 1,
3130                            stride,
3131                        );
3132                    }
3133                    crate::ocio_call_status()?;
3134                }
3135                // The native descriptor performs the same bit-depth conversion
3136                // and missing-alpha handling as for the rest of the image.
3137                #[repr(align(4))]
3138                struct AlignedTail([u8; 20]);
3139                let mut tail = AlignedTail([0; 20]);
3140                let pixel_bytes = 3 * sample;
3141                tail.0[..pixel_bytes].copy_from_slice(&rgb[last..last + pixel_bytes]);
3142                crate::clear_last_error();
3143                unsafe {
3144                    ocio_sys::ocio_cpu_processor_apply_rgb_packed(
3145                        self.handle.as_ptr(),
3146                        tail.0.as_mut_ptr().cast(),
3147                        bit_depth as i32,
3148                        1,
3149                        3,
3150                    );
3151                }
3152                crate::ocio_call_status()?;
3153                rgb[last..last + pixel_bytes].copy_from_slice(&tail.0[..pixel_bytes]);
3154                return Ok(());
3155            }
3156        }
3157        crate::clear_last_error();
3158        unsafe {
3159            ocio_sys::ocio_cpu_processor_apply_rgb_packed(
3160                self.handle.as_ptr(),
3161                rgb.as_mut_ptr() as *mut std::ffi::c_void,
3162                bit_depth as i32,
3163                num_pixels,
3164                stride,
3165            );
3166        }
3167        crate::ocio_call_status()
3168    }
3169
3170    #[doc(hidden)]
3171    #[deprecated(
3172        since = "0.2.0",
3173        note = "compat alias; prefer apply_rgb_packed_bit_depth with the BitDepth enum"
3174    )]
3175    pub fn apply_rgb_packed(&self, rgb: &mut [u8], bit_depth: i32, num_pixels: i64, stride: i64) {
3176        let bit_depth = match bit_depth {
3177            1 => BitDepth::Uint8,
3178            2 => BitDepth::Uint10,
3179            3 => BitDepth::Uint12,
3180            4 => BitDepth::Uint14,
3181            5 => BitDepth::Uint16,
3182            6 => BitDepth::Uint32,
3183            7 => BitDepth::F16,
3184            8 => BitDepth::F32,
3185            _ => BitDepth::Unknown,
3186        };
3187        self.apply_rgb_packed_bit_depth(rgb, bit_depth, num_pixels, stride);
3188    }
3189
3190    /// Return whether the CPU path is an identity/no-op transform.
3191    ///
3192    /// Returns `false` if OCIO reports an error. Use [`Self::try_is_no_op`] to
3193    /// distinguish that case from a non-identity processor.
3194    pub fn is_no_op(&self) -> bool {
3195        self.try_is_no_op().unwrap_or(false)
3196    }
3197
3198    /// Fallible variant of [`Self::is_no_op`].
3199    ///
3200    /// Returns an error when the underlying OCIO query throws.
3201    pub fn try_is_no_op(&self) -> Result<bool> {
3202        crate::clear_last_error();
3203        let value =
3204            unsafe { ocio_sys::ocio_cpu_processor_is_no_op(self.handle.as_ptr() as *mut c_void) };
3205        crate::ocio_call_status()?;
3206        Ok(value)
3207    }
3208
3209    /// Return whether the CPU path mixes color channels.
3210    ///
3211    /// Returns `false` if OCIO reports an error. Use
3212    /// [`Self::try_has_channel_crosstalk`] to distinguish that case from a
3213    /// lane-wise processor.
3214    pub fn has_channel_crosstalk(&self) -> bool {
3215        self.try_has_channel_crosstalk().unwrap_or(false)
3216    }
3217
3218    /// Fallible variant of [`Self::has_channel_crosstalk`].
3219    ///
3220    /// Returns an error when the underlying OCIO query throws.
3221    pub fn try_has_channel_crosstalk(&self) -> Result<bool> {
3222        crate::clear_last_error();
3223        let value = unsafe {
3224            ocio_sys::ocio_cpu_processor_has_channel_crosstalk(self.handle.as_ptr() as *mut c_void)
3225        };
3226        crate::ocio_call_status()?;
3227        Ok(value)
3228    }
3229
3230    /// Return OCIO's cache identifier for this CPU processor instance.
3231    pub fn cache_id(&self) -> Option<String> {
3232        self.try_cache_id().ok().flatten()
3233    }
3234
3235    /// Return OCIO's cache identifier, preserving bridge errors.
3236    pub fn try_cache_id(&self) -> Result<Option<String>> {
3237        crate::clear_last_error();
3238        let value = unsafe {
3239            cstr_from_mut(ocio_sys::ocio_cpu_processor_get_cache_id(
3240                self.handle.as_ptr() as *mut c_void,
3241            ))
3242        };
3243        crate::ocio_call_status()?;
3244        Ok(value)
3245    }
3246
3247    /// Return the declared input bit depth for this CPU path.
3248    pub fn input_bit_depth(&self) -> i32 {
3249        self.try_input_bit_depth().unwrap_or(0)
3250    }
3251
3252    /// Return the declared input bit depth, preserving bridge errors.
3253    pub fn try_input_bit_depth(&self) -> Result<i32> {
3254        crate::clear_last_error();
3255        let value = unsafe {
3256            ocio_sys::ocio_cpu_processor_get_input_bit_depth(self.handle.as_ptr() as *mut c_void)
3257        };
3258        crate::ocio_call_status()?;
3259        Ok(value)
3260    }
3261
3262    /// Return the declared output bit depth for this CPU path.
3263    pub fn output_bit_depth(&self) -> i32 {
3264        self.try_output_bit_depth().unwrap_or(0)
3265    }
3266
3267    /// Return the declared output bit depth, preserving bridge errors.
3268    pub fn try_output_bit_depth(&self) -> Result<i32> {
3269        crate::clear_last_error();
3270        let value = unsafe {
3271            ocio_sys::ocio_cpu_processor_get_output_bit_depth(self.handle.as_ptr() as *mut c_void)
3272        };
3273        crate::ocio_call_status()?;
3274        Ok(value)
3275    }
3276
3277    /// Return whether this CPU path is functionally identity.
3278    ///
3279    /// Returns `false` if OCIO reports an error. Use [`Self::try_is_identity`]
3280    /// to distinguish that case from a non-identity processor.
3281    pub fn is_identity(&self) -> bool {
3282        self.try_is_identity().unwrap_or(false)
3283    }
3284
3285    /// Fallible variant of [`Self::is_identity`].
3286    ///
3287    /// Returns an error when the underlying OCIO query throws.
3288    pub fn try_is_identity(&self) -> Result<bool> {
3289        crate::clear_last_error();
3290        let value = unsafe {
3291            ocio_sys::ocio_cpu_processor_is_identity(self.handle.as_ptr() as *mut c_void)
3292        };
3293        crate::ocio_call_status()?;
3294        Ok(value)
3295    }
3296
3297    // ── v2.5.1 ──
3298    /// Borrow a runtime-adjustable dynamic property from the CPU processor.
3299    ///
3300    /// Returns the OCIO error when the requested property is not available.
3301    pub fn dynamic_property(&self, prop_type: DynamicPropertyType) -> Result<DynamicProperty> {
3302        crate::clear_last_error();
3303        let handle = unsafe {
3304            ocio_sys::ocio_cpu_processor_get_dynamic_property(
3305                self.handle.as_ptr(),
3306                prop_type as i32,
3307            )
3308        };
3309        crate::handle_result(handle).map(|handle| DynamicProperty { handle })
3310    }
3311
3312    #[doc(hidden)]
3313    #[deprecated(
3314        since = "0.2.0",
3315        note = "compat alias; prefer dynamic_property with DynamicPropertyType"
3316    )]
3317    pub fn get_dynamic_property(&self, prop_type: i32) -> Option<DynamicProperty> {
3318        let h = unsafe {
3319            ocio_sys::ocio_cpu_processor_get_dynamic_property(self.handle.as_ptr(), prop_type)
3320        };
3321        NonNull::new(h).map(|h| DynamicProperty { handle: h })
3322    }
3323
3324    /// Return whether the CPU processor exposes a dynamic property of `prop_type`.
3325    pub fn has_dynamic_property_kind(&self, prop_type: DynamicPropertyType) -> bool {
3326        self.try_has_dynamic_property_kind(prop_type)
3327            .unwrap_or(false)
3328    }
3329
3330    /// Fallible variant of [`Self::has_dynamic_property_kind`].
3331    pub fn try_has_dynamic_property_kind(&self, prop_type: DynamicPropertyType) -> Result<bool> {
3332        crate::clear_last_error();
3333        let value = unsafe {
3334            ocio_sys::ocio_cpu_processor_has_dynamic_property(
3335                self.handle.as_ptr(),
3336                prop_type as i32,
3337            )
3338        };
3339        crate::ocio_call_status()?;
3340        Ok(value)
3341    }
3342
3343    #[doc(hidden)]
3344    #[deprecated(
3345        since = "0.2.0",
3346        note = "compat alias; prefer has_dynamic_property_kind with DynamicPropertyType"
3347    )]
3348    pub fn has_dynamic_property(&self, prop_type: i32) -> bool {
3349        crate::clear_last_error();
3350        let value = unsafe {
3351            ocio_sys::ocio_cpu_processor_has_dynamic_property(self.handle.as_ptr(), prop_type)
3352        };
3353        let _ = crate::ocio_call_status();
3354        value
3355    }
3356
3357    /// Return whether this CPU processor contains any runtime-adjustable properties.
3358    pub fn is_dynamic(&self) -> bool {
3359        self.try_is_dynamic().unwrap_or(false)
3360    }
3361
3362    /// Fallible variant of [`Self::is_dynamic`].
3363    pub fn try_is_dynamic(&self) -> Result<bool> {
3364        crate::clear_last_error();
3365        let value =
3366            unsafe { ocio_sys::ocio_cpu_processor_is_dynamic(self.handle.as_ptr() as *mut c_void) };
3367        crate::ocio_call_status()?;
3368        Ok(value)
3369    }
3370}
3371
3372impl Drop for CPUProcessor {
3373    fn drop(&mut self) {
3374        unsafe { ocio_sys::ocio_cpu_processor_destroy(self.handle.as_ptr() as *mut c_void) };
3375    }
3376}
3377
3378// --- GPUProcessor ---
3379
3380/// GPU implementation of a [`Processor`].
3381///
3382/// Wraps a GPU-ready color pipeline and provides [`extract_shader_info`] to
3383/// populate a [`GpuShaderDesc`] with OCIO-generated shader text, textures,
3384/// and uniforms.
3385///
3386/// The typical usage is:
3387///
3388/// ```rust,no_run
3389/// # use ocio_rs::{Config, GpuShaderDesc, GpuLanguage};
3390/// # fn example() -> ocio_rs::Result<()> {
3391/// let config = Config::from_file("config.ocio")?;
3392/// let processor = config.processor("scene_linear", "srgb_texture")?;
3393/// let gpu = processor.default_gpu_processor()?;
3394///
3395/// let mut desc = GpuShaderDesc::create()?;
3396/// desc.set_language(GpuLanguage::Glsl1_2)?;
3397///
3398/// gpu.try_extract_shader_info(&mut desc)?;
3399///
3400/// let shader_text = desc.shader_text().unwrap_or_default();
3401/// // Use shader_text in your rendering pipeline...
3402/// # Ok(())
3403/// # }
3404/// ```
3405///
3406/// This handle is thread-confined; see [`Processor`].
3407///
3408/// ```compile_fail
3409/// # use ocio_rs::GPUProcessor;
3410/// fn require_send<T: Send>() {}
3411/// require_send::<GPUProcessor>();
3412/// ```
3413///
3414/// [`extract_shader_info`]: Self::extract_shader_info
3415/// [`GpuShaderDesc`]: crate::GpuShaderDesc
3416pub struct GPUProcessor {
3417    handle: NonNull<c_void>,
3418}
3419
3420/// A native OCIO shader creator with its real shared-ownership control block.
3421///
3422/// A creator borrowed from a descriptor holds an exclusive Rust borrow until
3423/// dropped. Clones own their independently returned native creator. The type
3424/// is thread-confined and does not yet implement Rust-defined subclasses.
3425///
3426/// ```compile_fail
3427/// # use ocio_rs::GpuShaderDesc;
3428/// # fn example(desc: &mut GpuShaderDesc) -> ocio_rs::Result<()> {
3429/// let creator = desc.try_borrow_creator()?;
3430/// let _text = desc.shader_text(); // descriptor remains exclusively borrowed
3431/// drop(creator);
3432/// # Ok(()) }
3433/// ```
3434///
3435/// ```compile_fail
3436/// # use ocio_rs::GpuShaderCreator;
3437/// fn require_send<T: Send>() {}
3438/// require_send::<GpuShaderCreator<'static>>();
3439/// ```
3440pub struct GpuShaderCreator<'a> {
3441    handle: NonNull<c_void>,
3442    _descriptor: std::marker::PhantomData<&'a mut GpuShaderDesc>,
3443}
3444
3445impl GpuShaderCreator<'_> {
3446    /// Share ownership of a native `OCIO::GpuShaderCreatorRcPtr`.
3447    ///
3448    /// This copies the C++ shared pointer, not the creator or its resources.
3449    /// The pointer object itself need only remain alive during this call.
3450    ///
3451    /// # Safety
3452    /// `shared_ptr` must point to a valid, initialized `OCIO::GpuShaderCreatorRcPtr`
3453    /// compiled with the same OCIO version, C++ standard library, ABI and runtime
3454    /// as this binding. Its object, callbacks, and all external state they use
3455    /// must remain valid for the lifetime of every resulting owner or retained
3456    /// getter. The caller must ensure exclusive access to the creator and its
3457    /// mutable state while any resulting Rust owner, clone that shares state, or
3458    /// retained getter can access it. No native mutation, concurrent access, or
3459    /// callback reentrancy may invalidate Rust borrows or violate OCIO's rules.
3460    /// The creator's virtual methods must obey their C++ exception specifications.
3461    /// They must not retain borrowed string, texture-data, shader-code pointers,
3462    /// or references to passed `std::function` objects beyond the virtual call;
3463    /// copy any data or getter that must survive it.
3464    /// Pointers returned by virtual getters must refer to valid NUL-terminated
3465    /// strings and remain stable until the next mutable access to the creator;
3466    /// they must not be invalidated asynchronously or through another alias.
3467    /// Every native clone must have independent storage for borrowed text,
3468    /// texture data, and uniform snapshots: safe Rust may mutate either clone
3469    /// while holding a borrow from the other. Returning distinct objects that
3470    /// share mutable backing storage is insufficient. This requirement also
3471    /// applies to any descriptor exposed by the creator and its clones.
3472    pub unsafe fn from_native_shared_ptr(
3473        shared_ptr: *const c_void,
3474    ) -> Result<GpuShaderCreator<'static>> {
3475        crate::clear_last_error();
3476        let handle = unsafe { ocio_sys::ocio_gpu_shader_creator_copy_native_shared(shared_ptr) };
3477        Ok(GpuShaderCreator {
3478            handle: crate::handle_result(handle)?,
3479            _descriptor: std::marker::PhantomData,
3480        })
3481    }
3482
3483    fn text(&self, field: i32) -> Result<Option<String>> {
3484        crate::clear_last_error();
3485        let value = unsafe {
3486            cstr_to_opt_string(ocio_sys::ocio_gpu_shader_creator_get_text(
3487                self.handle.as_ptr(),
3488                field,
3489            ))
3490        };
3491        crate::ocio_call_status()?;
3492        Ok(value)
3493    }
3494
3495    fn text_ref(&mut self, field: i32) -> Result<Option<&std::ffi::CStr>> {
3496        crate::clear_last_error();
3497        let ptr =
3498            unsafe { ocio_sys::ocio_gpu_shader_creator_get_text(self.handle.as_ptr(), field) };
3499        crate::ocio_call_status()?;
3500        Ok(if ptr.is_null() {
3501            None
3502        } else {
3503            Some(unsafe { std::ffi::CStr::from_ptr(ptr) })
3504        })
3505    }
3506
3507    /// Borrow the unique ID without allocating; the reference prevents mutation
3508    /// of this creator for its lifetime.
3509    pub fn unique_id_ref(&mut self) -> Result<Option<&std::ffi::CStr>> {
3510        self.text_ref(0)
3511    }
3512    /// Borrow the function name without allocating.
3513    pub fn function_name_ref(&mut self) -> Result<Option<&std::ffi::CStr>> {
3514        self.text_ref(1)
3515    }
3516    /// Borrow the pixel name without allocating.
3517    pub fn pixel_name_ref(&mut self) -> Result<Option<&std::ffi::CStr>> {
3518        self.text_ref(2)
3519    }
3520    /// Borrow the resource prefix without allocating.
3521    pub fn resource_prefix_ref(&mut self) -> Result<Option<&std::ffi::CStr>> {
3522        self.text_ref(3)
3523    }
3524
3525    /// Borrow the virtual native cache ID without allocating. The exclusive
3526    /// borrow prevents safe mutation or another creator query while it is live.
3527    /// Imported native creators must uphold the pointer stability contract of
3528    /// [`Self::from_native_shared_ptr`].
3529    ///
3530    /// ```compile_fail
3531    /// # use ocio_rs::GpuShaderCreator;
3532    /// # fn example(c: &mut GpuShaderCreator<'_>) -> ocio_rs::Result<()> {
3533    /// let id = c.cache_id_ref()?;
3534    /// c.set_function_name("other")?;
3535    /// println!("{id:?}");
3536    /// # Ok(()) }
3537    /// ```
3538    pub fn cache_id_ref(&mut self) -> Result<Option<&std::ffi::CStr>> {
3539        crate::clear_last_error();
3540        let ptr = unsafe { ocio_sys::ocio_gpu_shader_creator_get_cache_id(self.handle.as_ptr()) };
3541        crate::ocio_call_status()?;
3542        Ok(if ptr.is_null() {
3543            None
3544        } else {
3545            Some(unsafe { std::ffi::CStr::from_ptr(ptr) })
3546        })
3547    }
3548
3549    fn set_text(&mut self, field: i32, value: impl AsRef<str>) -> Result<()> {
3550        let value = cstring(value)?;
3551        crate::clear_last_error();
3552        unsafe {
3553            ocio_sys::ocio_gpu_shader_creator_set_text(self.handle.as_ptr(), field, value.as_ptr())
3554        };
3555        crate::ocio_call_status()
3556    }
3557
3558    /// Return the native creator's unique identifier.
3559    pub fn try_unique_id(&self) -> Result<Option<String>> {
3560        self.text(0)
3561    }
3562    /// Set the native creator's unique identifier.
3563    pub fn set_unique_id(&mut self, value: impl AsRef<str>) -> Result<()> {
3564        self.set_text(0, value)
3565    }
3566    /// Return the shader function name.
3567    pub fn try_function_name(&self) -> Result<Option<String>> {
3568        self.text(1)
3569    }
3570    /// Set the shader function name.
3571    pub fn set_function_name(&mut self, value: impl AsRef<str>) -> Result<()> {
3572        self.set_text(1, value)
3573    }
3574    /// Return the shader pixel variable name.
3575    pub fn try_pixel_name(&self) -> Result<Option<String>> {
3576        self.text(2)
3577    }
3578    /// Set the shader pixel variable name.
3579    pub fn set_pixel_name(&mut self, value: impl AsRef<str>) -> Result<()> {
3580        self.set_text(2, value)
3581    }
3582    /// Return the resource name prefix.
3583    pub fn try_resource_prefix(&self) -> Result<Option<String>> {
3584        self.text(3)
3585    }
3586    /// Set the resource name prefix.
3587    pub fn set_resource_prefix(&mut self, value: impl AsRef<str>) -> Result<()> {
3588        self.set_text(3, value)
3589    }
3590
3591    /// Return the native language, rejecting values unavailable in this Rust interface.
3592    pub fn try_language(&self) -> Result<GpuLanguage> {
3593        crate::clear_last_error();
3594        let value = unsafe { ocio_sys::ocio_gpu_shader_creator_get_language(self.handle.as_ptr()) };
3595        crate::ocio_call_status()?;
3596        GpuShaderDesc::gpu_language_from_raw(value)
3597    }
3598
3599    /// Set the shader language.
3600    pub fn set_language(&mut self, language: GpuLanguage) -> Result<()> {
3601        crate::clear_last_error();
3602        unsafe {
3603            ocio_sys::ocio_gpu_shader_creator_set_language(self.handle.as_ptr(), language as i32)
3604        };
3605        crate::ocio_call_status()
3606    }
3607
3608    /// Return and advance the creator's native resource index.
3609    pub fn try_next_resource_index(&mut self) -> Result<u32> {
3610        crate::clear_last_error();
3611        let value =
3612            unsafe { ocio_sys::ocio_gpu_shader_creator_next_resource_index(self.handle.as_ptr()) };
3613        crate::ocio_call_status()?;
3614        Ok(value)
3615    }
3616
3617    /// Register a borrowed 1D/2D texture through the native creator virtual method.
3618    /// Returns the native binding on OCIO 2.5.1+, and `None` on older versions.
3619    #[allow(clippy::too_many_arguments)]
3620    pub fn add_texture_2d(
3621        &mut self,
3622        name: impl AsRef<str>,
3623        sampler: impl AsRef<str>,
3624        width: u32,
3625        height: u32,
3626        channel: GpuTextureChannel,
3627        dimensions: GpuTextureDimensions,
3628        interpolation: Interpolation,
3629        values: &[f32],
3630    ) -> Result<Option<u32>> {
3631        self.add_texture_impl(
3632            name,
3633            sampler,
3634            width,
3635            height,
3636            1,
3637            channel,
3638            dimensions,
3639            interpolation,
3640            values,
3641            false,
3642        )
3643    }
3644
3645    /// Register a borrowed RGB 3D texture through the native creator virtual method.
3646    /// Returns the native binding on OCIO 2.5.1+, and `None` on older versions.
3647    pub fn add_texture_3d(
3648        &mut self,
3649        name: impl AsRef<str>,
3650        sampler: impl AsRef<str>,
3651        edge: u32,
3652        interpolation: Interpolation,
3653        values: &[f32],
3654    ) -> Result<Option<u32>> {
3655        self.add_texture_impl(
3656            name,
3657            sampler,
3658            edge,
3659            edge,
3660            edge,
3661            GpuTextureChannel::Rgb,
3662            GpuTextureDimensions::Texture2D,
3663            interpolation,
3664            values,
3665            true,
3666        )
3667    }
3668
3669    #[allow(clippy::too_many_arguments)]
3670    fn add_texture_impl(
3671        &mut self,
3672        name: impl AsRef<str>,
3673        sampler: impl AsRef<str>,
3674        width: u32,
3675        height: u32,
3676        depth: u32,
3677        channel: GpuTextureChannel,
3678        dimensions: GpuTextureDimensions,
3679        interpolation: Interpolation,
3680        values: &[f32],
3681        is_3d: bool,
3682    ) -> Result<Option<u32>> {
3683        let name = cstring(name)?;
3684        let sampler = cstring(sampler)?;
3685        crate::clear_last_error();
3686        let mut has_binding = false;
3687        let mut binding = 0;
3688        let added = unsafe {
3689            ocio_sys::ocio_gpu_shader_creator_add_texture(
3690                self.handle.as_ptr(),
3691                name.as_ptr(),
3692                sampler.as_ptr(),
3693                width,
3694                height,
3695                depth,
3696                channel as i32,
3697                dimensions as i32,
3698                interpolation as i32,
3699                values.as_ptr(),
3700                values.len(),
3701                is_3d,
3702                &mut has_binding,
3703                &mut binding,
3704            )
3705        };
3706        crate::ocio_call_status()?;
3707        if !added {
3708            return Err(OcioError::ValidationFailed(
3709                "OpenColorIO rejected the texture".into(),
3710            ));
3711        }
3712        Ok(has_binding.then_some(binding))
3713    }
3714
3715    /// Add a shared dynamic property to the native creator. OCIO rejects a
3716    /// second property of the same kind.
3717    pub fn add_dynamic_property(&mut self, property: &DynamicProperty) -> Result<()> {
3718        crate::clear_last_error();
3719        unsafe {
3720            ocio_sys::ocio_gpu_shader_creator_add_dynamic_property(
3721                self.handle.as_ptr(),
3722                property.handle.as_ptr(),
3723            )
3724        };
3725        crate::ocio_call_status()
3726    }
3727
3728    /// Return the number of dynamic properties owned by the creator.
3729    pub fn try_num_dynamic_properties(&self) -> Result<u32> {
3730        crate::clear_last_error();
3731        let value = unsafe {
3732            ocio_sys::ocio_gpu_shader_creator_num_dynamic_properties(self.handle.as_ptr())
3733        };
3734        crate::ocio_call_status()?;
3735        Ok(value)
3736    }
3737
3738    /// Check whether the creator owns a property of the requested kind.
3739    pub fn try_has_dynamic_property_kind(
3740        &self,
3741        property_type: DynamicPropertyType,
3742    ) -> Result<bool> {
3743        crate::clear_last_error();
3744        let value = unsafe {
3745            ocio_sys::ocio_gpu_shader_creator_has_dynamic_property(
3746                self.handle.as_ptr(),
3747                property_type as i32,
3748            )
3749        };
3750        crate::ocio_call_status()?;
3751        Ok(value)
3752    }
3753
3754    fn dynamic_property_query(
3755        &self,
3756        value: u32,
3757        by_index: bool,
3758    ) -> Result<Option<DynamicProperty>> {
3759        crate::clear_last_error();
3760        let handle = unsafe {
3761            ocio_sys::ocio_gpu_shader_creator_dynamic_property(
3762                self.handle.as_ptr(),
3763                value,
3764                by_index,
3765            )
3766        };
3767        crate::ocio_call_status()?;
3768        Ok(NonNull::new(handle).map(|handle| DynamicProperty { handle }))
3769    }
3770
3771    /// Share a property by native ordinal index; invalid indices return an error.
3772    pub fn try_dynamic_property_by_index(&self, index: u32) -> Result<Option<DynamicProperty>> {
3773        self.dynamic_property_query(index, true)
3774    }
3775
3776    /// Share a property by kind; an absent kind is reported as a native error.
3777    pub fn try_dynamic_property(
3778        &self,
3779        property_type: DynamicPropertyType,
3780    ) -> Result<Option<DynamicProperty>> {
3781        self.dynamic_property_query(property_type as u32, false)
3782    }
3783
3784    #[allow(clippy::too_many_arguments)]
3785    fn add_uniform_impl(
3786        &mut self,
3787        name: impl AsRef<str>,
3788        kind: i32,
3789        scalar: f64,
3790        values: *const c_void,
3791        len: usize,
3792        max_size: u32,
3793        property_type: i32,
3794    ) -> Result<bool> {
3795        let name = cstring(name)?;
3796        crate::clear_last_error();
3797        let added = unsafe {
3798            ocio_sys::ocio_gpu_shader_creator_add_uniform(
3799                self.handle.as_ptr(),
3800                name.as_ptr(),
3801                kind,
3802                scalar,
3803                values,
3804                len,
3805                max_size,
3806                property_type,
3807            )
3808        };
3809        crate::ocio_call_status()?;
3810        Ok(added)
3811    }
3812
3813    /// Register a constant double uniform, returning whether it was added.
3814    pub fn add_uniform_f64(&mut self, name: impl AsRef<str>, value: f64) -> Result<bool> {
3815        self.add_uniform_impl(name, 0, value, std::ptr::null(), 0, 0, 0)
3816    }
3817
3818    fn add_scalar_getter<F, T>(
3819        &mut self,
3820        name: impl AsRef<str>,
3821        kind: i32,
3822        getter: F,
3823    ) -> Result<bool>
3824    where
3825        F: Fn() -> T + Send + Sync + 'static,
3826        T: Copy,
3827    {
3828        unsafe extern "C" fn invoke<F: Fn() -> T, T: Copy>(
3829            context: *mut c_void,
3830            out: *mut c_void,
3831        ) -> bool {
3832            crate::catch_callback_unwind(std::panic::AssertUnwindSafe(|| {
3833                let value = unsafe { (&*context.cast::<F>())() };
3834                unsafe { out.cast::<T>().write(value) };
3835            }))
3836            .is_ok()
3837        }
3838        unsafe extern "C" fn release<F>(context: *mut c_void) {
3839            let _ = crate::catch_callback_unwind(std::panic::AssertUnwindSafe(|| unsafe {
3840                drop(Box::from_raw(context.cast::<F>()));
3841            }));
3842        }
3843        let name = cstring(name)?;
3844        let context = Box::into_raw(Box::new(getter)).cast();
3845        crate::clear_last_error();
3846        let added = unsafe {
3847            ocio_sys::ocio_gpu_shader_creator_add_scalar_getter(
3848                self.handle.as_ptr(),
3849                name.as_ptr(),
3850                kind,
3851                context,
3852                invoke::<F, T>,
3853                release::<F>,
3854            )
3855        };
3856        crate::ocio_call_status()?;
3857        Ok(added)
3858    }
3859
3860    /// Register a live thread-safe double getter. Panics are contained and
3861    /// surface as native errors on sampling; duplicate registration drops it.
3862    /// Do not reenter the creator from the getter.
3863    pub fn add_uniform_f64_getter<F>(&mut self, name: impl AsRef<str>, getter: F) -> Result<bool>
3864    where
3865        F: Fn() -> f64 + Send + Sync + 'static,
3866    {
3867        self.add_scalar_getter(name, 0, getter)
3868    }
3869
3870    /// Register a live boolean getter; see [`Self::add_uniform_f64_getter`].
3871    pub fn add_uniform_bool_getter<F>(&mut self, name: impl AsRef<str>, getter: F) -> Result<bool>
3872    where
3873        F: Fn() -> bool + Send + Sync + 'static,
3874    {
3875        self.add_scalar_getter(name, 1, getter)
3876    }
3877
3878    /// Register a live float3 getter. Native code must not sample it
3879    /// concurrently or retain its returned reference across another sample.
3880    pub fn add_uniform_float3_getter<F>(&mut self, name: impl AsRef<str>, getter: F) -> Result<bool>
3881    where
3882        F: Fn() -> [f32; 3] + Send + Sync + 'static,
3883    {
3884        self.add_scalar_getter(name, 2, getter)
3885    }
3886
3887    /// Register a constant boolean uniform, returning whether it was added.
3888    pub fn add_uniform_bool(&mut self, name: impl AsRef<str>, value: bool) -> Result<bool> {
3889        self.add_uniform_impl(name, 1, u8::from(value) as f64, std::ptr::null(), 0, 0, 0)
3890    }
3891
3892    /// Register a constant three-component float uniform.
3893    pub fn add_uniform_float3(&mut self, name: impl AsRef<str>, value: [f32; 3]) -> Result<bool> {
3894        self.add_uniform_impl(name, 2, 0.0, value.as_ptr().cast(), value.len(), 0, 0)
3895    }
3896
3897    /// Register a copied float array with the maximum declared shader length.
3898    pub fn add_uniform_f32_array(
3899        &mut self,
3900        name: impl AsRef<str>,
3901        values: &[f32],
3902        max_size: u32,
3903    ) -> Result<bool> {
3904        self.add_uniform_impl(
3905            name,
3906            3,
3907            0.0,
3908            values.as_ptr().cast(),
3909            values.len(),
3910            max_size,
3911            0,
3912        )
3913    }
3914
3915    /// Register a copied integer array with the maximum declared shader length.
3916    pub fn add_uniform_i32_array(
3917        &mut self,
3918        name: impl AsRef<str>,
3919        values: &[i32],
3920        max_size: u32,
3921    ) -> Result<bool> {
3922        self.add_uniform_impl(
3923            name,
3924            4,
3925            0.0,
3926            values.as_ptr().cast(),
3927            values.len(),
3928            max_size,
3929            0,
3930        )
3931    }
3932
3933    fn add_array_getter<F, T>(
3934        &mut self,
3935        name: impl AsRef<str>,
3936        max_size: u32,
3937        getter: F,
3938        register: unsafe extern "C" fn(
3939            *mut c_void,
3940            *const i8,
3941            u32,
3942            *mut c_void,
3943            unsafe extern "C" fn(*mut c_void, *mut T, usize, *mut usize) -> bool,
3944            unsafe extern "C" fn(*mut c_void),
3945        ) -> bool,
3946    ) -> Result<bool>
3947    where
3948        F: Fn(&mut [T]) -> usize + Send + Sync + 'static,
3949    {
3950        unsafe extern "C" fn invoke<F: Fn(&mut [T]) -> usize, T>(
3951            context: *mut c_void,
3952            data: *mut T,
3953            capacity: usize,
3954            length: *mut usize,
3955        ) -> bool {
3956            crate::catch_callback_unwind(std::panic::AssertUnwindSafe(|| {
3957                let getter = unsafe { &*context.cast::<F>() };
3958                let data = if capacity == 0 {
3959                    NonNull::<T>::dangling().as_ptr()
3960                } else {
3961                    data
3962                };
3963                let buffer = unsafe { std::slice::from_raw_parts_mut(data, capacity) };
3964                unsafe { *length = getter(buffer) };
3965            }))
3966            .is_ok()
3967        }
3968        unsafe extern "C" fn release<F>(context: *mut c_void) {
3969            let _ = crate::catch_callback_unwind(std::panic::AssertUnwindSafe(|| unsafe {
3970                drop(Box::from_raw(context.cast::<F>()));
3971            }));
3972        }
3973        if max_size > i32::MAX as u32
3974            || max_size as usize > isize::MAX as usize / std::mem::size_of::<T>()
3975        {
3976            return Err(OcioError::ValidationFailed(
3977                "uniform max_size exceeds the native integer limit".into(),
3978            ));
3979        }
3980        let name = cstring(name)?;
3981        let context = Box::into_raw(Box::new(getter)).cast();
3982        crate::clear_last_error();
3983        let added = unsafe {
3984            register(
3985                self.handle.as_ptr(),
3986                name.as_ptr(),
3987                max_size,
3988                context,
3989                invoke::<F, T>,
3990                release::<F>,
3991            )
3992        };
3993        crate::ocio_call_status()?;
3994        Ok(added)
3995    }
3996
3997    /// Register a live float array getter. Each size query refreshes one
3998    /// bounded snapshot, and the pointer getter reads that same snapshot.
3999    /// Native callers must serialize access and consume it before the next
4000    /// refresh. Panics and lengths exceeding `max_size` are reported as errors.
4001    pub fn add_uniform_f32_array_getter<F>(
4002        &mut self,
4003        name: impl AsRef<str>,
4004        max_size: u32,
4005        getter: F,
4006    ) -> Result<bool>
4007    where
4008        F: Fn(&mut [f32]) -> usize + Send + Sync + 'static,
4009    {
4010        self.add_array_getter(
4011            name,
4012            max_size,
4013            getter,
4014            ocio_sys::ocio_gpu_shader_creator_add_float_array_getter,
4015        )
4016    }
4017
4018    /// Register a live integer array getter with the same snapshot and
4019    /// lifetime rules as [`Self::add_uniform_f32_array_getter`].
4020    pub fn add_uniform_i32_array_getter<F>(
4021        &mut self,
4022        name: impl AsRef<str>,
4023        max_size: u32,
4024        getter: F,
4025    ) -> Result<bool>
4026    where
4027        F: Fn(&mut [i32]) -> usize + Send + Sync + 'static,
4028    {
4029        self.add_array_getter(
4030            name,
4031            max_size,
4032            getter,
4033            ocio_sys::ocio_gpu_shader_creator_add_int_array_getter,
4034        )
4035    }
4036
4037    /// Register a live double uniform backed by a creator-owned dynamic property.
4038    /// The getter retains the property and does not call back into Rust.
4039    pub fn add_uniform_dynamic_double(
4040        &mut self,
4041        name: impl AsRef<str>,
4042        property_type: DynamicPropertyType,
4043    ) -> Result<bool> {
4044        if !matches!(
4045            property_type,
4046            DynamicPropertyType::Exposure
4047                | DynamicPropertyType::Contrast
4048                | DynamicPropertyType::Gamma
4049        ) {
4050            return Err(OcioError::InvalidInput(
4051                "a double dynamic property is required".into(),
4052            ));
4053        }
4054        self.add_uniform_impl(name, 5, 0.0, std::ptr::null(), 0, 0, property_type as i32)
4055    }
4056
4057    /// Begin native shader collection with the supplied unique identifier.
4058    pub fn begin(&mut self, uid: impl AsRef<str>) -> Result<()> {
4059        let uid = cstring(uid)?;
4060        crate::clear_last_error();
4061        unsafe {
4062            ocio_sys::ocio_gpu_shader_creator_lifecycle(self.handle.as_ptr(), 0, uid.as_ptr())
4063        };
4064        crate::ocio_call_status()
4065    }
4066
4067    /// Invoke the native virtual finalizer.
4068    pub fn finalize(&mut self) -> Result<()> {
4069        crate::clear_last_error();
4070        unsafe {
4071            ocio_sys::ocio_gpu_shader_creator_lifecycle(self.handle.as_ptr(), 1, std::ptr::null())
4072        };
4073        crate::ocio_call_status()
4074    }
4075
4076    /// End native shader collection.
4077    pub fn end(&mut self) -> Result<()> {
4078        crate::clear_last_error();
4079        unsafe {
4080            ocio_sys::ocio_gpu_shader_creator_lifecycle(self.handle.as_ptr(), 2, std::ptr::null())
4081        };
4082        crate::ocio_call_status()
4083    }
4084
4085    fn add_code(&mut self, section: i32, code: impl AsRef<str>) -> Result<()> {
4086        let code = cstring(code)?;
4087        crate::clear_last_error();
4088        unsafe {
4089            ocio_sys::ocio_gpu_shader_creator_add_code(self.handle.as_ptr(), section, code.as_ptr())
4090        };
4091        crate::ocio_call_status()
4092    }
4093
4094    /// Append combined declarations; Vulkan requires the split 2.5+ methods.
4095    pub fn add_to_declare_shader_code(&mut self, code: impl AsRef<str>) -> Result<()> {
4096        self.add_code(0, code)
4097    }
4098    /// Append parameter declarations.
4099    #[cfg(feature = "v2_5")]
4100    #[cfg_attr(docsrs, doc(cfg(feature = "v2_5")))]
4101    pub fn add_to_parameter_declare_shader_code(&mut self, code: impl AsRef<str>) -> Result<()> {
4102        self.add_code(1, code)
4103    }
4104    /// Append texture declarations.
4105    #[cfg(feature = "v2_5")]
4106    #[cfg_attr(docsrs, doc(cfg(feature = "v2_5")))]
4107    pub fn add_to_texture_declare_shader_code(&mut self, code: impl AsRef<str>) -> Result<()> {
4108        self.add_code(2, code)
4109    }
4110    /// Append helper code.
4111    pub fn add_to_helper_shader_code(&mut self, code: impl AsRef<str>) -> Result<()> {
4112        self.add_code(3, code)
4113    }
4114    /// Append function header code.
4115    pub fn add_to_function_header_shader_code(&mut self, code: impl AsRef<str>) -> Result<()> {
4116        self.add_code(4, code)
4117    }
4118    /// Append function body code.
4119    pub fn add_to_function_shader_code(&mut self, code: impl AsRef<str>) -> Result<()> {
4120        self.add_code(5, code)
4121    }
4122    /// Append function footer code.
4123    pub fn add_to_function_footer_shader_code(&mut self, code: impl AsRef<str>) -> Result<()> {
4124        self.add_code(6, code)
4125    }
4126
4127    /// Invoke native shader assembly with six sections. On OCIO 2.4 the two
4128    /// declaration sections are concatenated before invoking its five-argument ABI.
4129    pub fn create_shader_text(
4130        &mut self,
4131        parameters: impl AsRef<str>,
4132        textures: impl AsRef<str>,
4133        helpers: impl AsRef<str>,
4134        header: impl AsRef<str>,
4135        body: impl AsRef<str>,
4136        footer: impl AsRef<str>,
4137    ) -> Result<()> {
4138        let parameters = cstring(parameters)?;
4139        let textures = cstring(textures)?;
4140        let helpers = cstring(helpers)?;
4141        let header = cstring(header)?;
4142        let body = cstring(body)?;
4143        let footer = cstring(footer)?;
4144        crate::clear_last_error();
4145        unsafe {
4146            ocio_sys::ocio_gpu_shader_creator_create_text(
4147                self.handle.as_ptr(),
4148                parameters.as_ptr(),
4149                textures.as_ptr(),
4150                helpers.as_ptr(),
4151                header.as_ptr(),
4152                body.as_ptr(),
4153                footer.as_ptr(),
4154            )
4155        };
4156        crate::ocio_call_status()
4157    }
4158
4159    /// Set native descriptor-set and starting texture binding indices.
4160    ///
4161    /// OCIO reserves binding zero. For non-descriptor creators, resource
4162    /// layout and overflow checks remain the custom implementation's responsibility.
4163    #[cfg(feature = "v2_5")]
4164    #[cfg_attr(docsrs, doc(cfg(feature = "v2_5")))]
4165    pub fn try_set_descriptor_set_index(
4166        &mut self,
4167        index: u32,
4168        texture_binding_start: u32,
4169    ) -> Result<()> {
4170        crate::clear_last_error();
4171        unsafe {
4172            ocio_sys::ocio_gpu_shader_creator_set_descriptor_set_index(
4173                self.handle.as_ptr(),
4174                index,
4175                texture_binding_start,
4176            )
4177        };
4178        crate::ocio_call_status()
4179    }
4180
4181    /// Return the native descriptor-set index.
4182    #[cfg(feature = "v2_5")]
4183    #[cfg_attr(docsrs, doc(cfg(feature = "v2_5")))]
4184    pub fn try_descriptor_set_index(&self) -> Result<u32> {
4185        crate::clear_last_error();
4186        let value = unsafe {
4187            ocio_sys::ocio_gpu_shader_creator_get_descriptor_set_index(self.handle.as_ptr(), false)
4188        };
4189        crate::ocio_call_status()?;
4190        Ok(value)
4191    }
4192
4193    /// Return the native starting texture binding index.
4194    #[cfg(feature = "v2_5")]
4195    #[cfg_attr(docsrs, doc(cfg(feature = "v2_5")))]
4196    pub fn try_texture_binding_start(&self) -> Result<u32> {
4197        crate::clear_last_error();
4198        let value = unsafe {
4199            ocio_sys::ocio_gpu_shader_creator_get_descriptor_set_index(self.handle.as_ptr(), true)
4200        };
4201        crate::ocio_call_status()?;
4202        Ok(value)
4203    }
4204
4205    /// Copy the native virtual cache identifier, preserving bridge errors.
4206    pub fn try_cache_id(&self) -> Result<Option<String>> {
4207        crate::clear_last_error();
4208        let id = unsafe {
4209            cstr_to_opt_string(ocio_sys::ocio_gpu_shader_creator_get_cache_id(
4210                self.handle.as_ptr(),
4211            ))
4212        };
4213        crate::ocio_call_status()?;
4214        Ok(id)
4215    }
4216
4217    /// Query the creator's native virtual maximum texture width.
4218    pub fn try_texture_max_width(&self) -> Result<u32> {
4219        crate::clear_last_error();
4220        let width = unsafe {
4221            ocio_sys::ocio_gpu_shader_creator_get_texture_max_width(self.handle.as_ptr())
4222        };
4223        crate::ocio_call_status()?;
4224        Ok(width)
4225    }
4226
4227    /// Set the creator's native virtual maximum texture width.
4228    /// Widths below two are invalid; other widths still require the native LUT
4229    /// packing precautions documented on [`GpuShaderDesc::validate_lut_texture_layout`].
4230    pub fn try_set_texture_max_width(&mut self, width: u32) -> Result<()> {
4231        if width < 2 {
4232            return Err(OcioError::InvalidInput(
4233                "texture maximum width must be at least 2".into(),
4234            ));
4235        }
4236        crate::clear_last_error();
4237        unsafe {
4238            ocio_sys::ocio_gpu_shader_creator_set_texture_max_width(self.handle.as_ptr(), width)
4239        };
4240        crate::ocio_call_status()
4241    }
4242
4243    /// Query whether the native creator allows 1D textures.
4244    pub fn try_allow_texture_1d(&self) -> Result<bool> {
4245        crate::clear_last_error();
4246        let allow =
4247            unsafe { ocio_sys::ocio_gpu_shader_creator_get_allow_texture_1d(self.handle.as_ptr()) };
4248        crate::ocio_call_status()?;
4249        Ok(allow)
4250    }
4251
4252    /// Set the creator's native virtual 1D texture policy.
4253    pub fn try_set_allow_texture_1d(&mut self, allow: bool) -> Result<()> {
4254        crate::clear_last_error();
4255        unsafe {
4256            ocio_sys::ocio_gpu_shader_creator_set_allow_texture_1d(self.handle.as_ptr(), allow)
4257        };
4258        crate::ocio_call_status()
4259    }
4260
4261    /// Borrow the native descriptor when this creator is a `GpuShaderDesc`.
4262    /// Returns `None` for creators implemented without that descriptor interface.
4263    pub fn try_borrow_desc(&mut self) -> Result<Option<GpuShaderDescView<'_>>> {
4264        crate::clear_last_error();
4265        let handle = unsafe { ocio_sys::ocio_gpu_shader_creator_borrow_desc(self.handle.as_ptr()) };
4266        crate::ocio_call_status()?;
4267        Ok(NonNull::new(handle).map(|handle| GpuShaderDescView {
4268            descriptor: GpuShaderDesc { handle },
4269            _creator: std::marker::PhantomData,
4270        }))
4271    }
4272    /// Invoke the native virtual `clone`. OCIO determines which state is copied;
4273    /// in particular, cloning its descriptor implementation creates a generic
4274    /// descriptor and may not preserve custom subclass resources or behavior.
4275    /// A native clone that returns the same object is rejected. The unsafe
4276    /// import contract additionally requires distinct clones to have independent
4277    /// storage wherever mutation could invalidate a borrowed reference.
4278    pub fn try_clone_creator(&self) -> Result<GpuShaderCreator<'static>> {
4279        crate::clear_last_error();
4280        let handle = unsafe { ocio_sys::ocio_gpu_shader_creator_clone(self.handle.as_ptr()) };
4281        Ok(GpuShaderCreator {
4282            handle: crate::handle_result(handle)?,
4283            _descriptor: std::marker::PhantomData,
4284        })
4285    }
4286}
4287
4288/// Scoped access to a creator's native descriptor. It cannot be moved out or
4289/// used after the creator borrow ends; shared references to its normal
4290/// descriptor methods are available via `Deref`.
4291///
4292/// ```compile_fail
4293/// # use ocio_rs::{GpuShaderCreator, GpuShaderDesc};
4294/// # fn example(creator: &mut GpuShaderCreator<'_>) -> ocio_rs::Result<()> {
4295/// let mut view = creator.try_borrow_desc()?.unwrap();
4296/// let stolen = std::mem::replace(&mut *view, GpuShaderDesc::create()?);
4297/// # Ok(()) }
4298/// ```
4299///
4300/// ```compile_fail
4301/// # use ocio_rs::{GpuShaderCreator, GPUProcessor};
4302/// # fn example(creator: &mut GpuShaderCreator<'_>, gpu: &GPUProcessor) -> ocio_rs::Result<()> {
4303/// let mut view = creator.try_borrow_desc()?.unwrap();
4304/// let values = view.texture_values_ref(0)?;
4305/// gpu.try_extract_to_creator(creator)?;
4306/// println!("{}", values.len());
4307/// # Ok(()) }
4308/// ```
4309pub struct GpuShaderDescView<'a> {
4310    descriptor: GpuShaderDesc,
4311    _creator: std::marker::PhantomData<&'a mut ()>,
4312}
4313
4314impl std::ops::Deref for GpuShaderDescView<'_> {
4315    type Target = GpuShaderDesc;
4316    fn deref(&self) -> &Self::Target {
4317        &self.descriptor
4318    }
4319}
4320
4321impl GpuShaderDescView<'_> {
4322    /// Borrow generated shader text without allocating.
4323    pub fn shader_text_ref(&mut self) -> Result<Option<&std::ffi::CStr>> {
4324        self.descriptor.shader_text_ref()
4325    }
4326    /// Borrow the native 1D/2D texture payload without copying.
4327    pub fn texture_values_ref(&mut self, index: u32) -> Result<&[f32]> {
4328        self.descriptor.texture_values_ref(index)
4329    }
4330    /// Borrow the native 3D texture payload without copying.
4331    pub fn texture_3d_values_ref(&mut self, index: u32) -> Result<&[f32]> {
4332        self.descriptor.texture_3d_values_ref(index)
4333    }
4334    /// Borrow the native shader cache identifier without allocating.
4335    pub fn cache_id_ref(&mut self) -> Result<Option<&std::ffi::CStr>> {
4336        self.descriptor.cache_id_ref()
4337    }
4338    /// Cache native uniform getters while exclusively borrowing this view.
4339    pub fn uniform_cache(&mut self) -> Result<GpuUniformCache<'_>> {
4340        self.descriptor.uniform_cache()
4341    }
4342}
4343
4344impl Drop for GpuShaderCreator<'_> {
4345    fn drop(&mut self) {
4346        unsafe { ocio_sys::ocio_gpu_shader_creator_destroy(self.handle.as_ptr()) }
4347    }
4348}
4349
4350/// Shader sections supplied by OCIO to a custom assembler during extraction.
4351pub struct ShaderSections<'a> {
4352    /// Parameter declarations (or all declarations on OCIO 2.4), without a Vulkan uniform-block wrapper.
4353    pub parameters: &'a str,
4354    /// Texture and sampler declarations; empty on OCIO 2.4 where these are merged into `parameters`.
4355    pub textures: &'a str,
4356    /// Helper function definitions.
4357    pub helpers: &'a str,
4358    /// OCIO function signature and opening code.
4359    pub header: &'a str,
4360    /// OCIO color-processing function body.
4361    pub body: &'a str,
4362    /// OCIO function closing code.
4363    pub footer: &'a str,
4364}
4365
4366/// A texture supplied by OCIO during shader extraction. Data is borrowed only
4367/// for the duration of the callback and may be uploaded without a Rust copy.
4368pub struct ShaderTexture<'a> {
4369    /// Name of the generated texture resource.
4370    pub texture_name: &'a str,
4371    /// Name of its sampler in the generated shader.
4372    pub sampler_name: &'a str,
4373    /// Width in texels.
4374    pub width: u32,
4375    /// Height in texels.
4376    pub height: u32,
4377    /// One for a 1D/2D texture, otherwise the 3D LUT edge length.
4378    pub depth: u32,
4379    /// Channel layout of the native texels.
4380    pub channel: GpuTextureChannel,
4381    /// `None` represents a 3D texture.
4382    pub dimensions: Option<GpuTextureDimensions>,
4383    /// Interpolation requested by OCIO.
4384    pub interpolation: Interpolation,
4385    /// Borrowed texel data, valid only while the callback is running.
4386    pub values: &'a [f32],
4387    /// Proposed binding on OCIO 2.5+, absent on OCIO 2.4. On 2.5.0 this
4388    /// is supplied by the bridge because native indices are per texture kind.
4389    pub suggested_binding: Option<u32>,
4390}
4391
4392/// Storage and optional binding choice for one native texture registration.
4393#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4394pub enum ShaderTextureAction {
4395    /// Copy the texture into the returned native descriptor.
4396    StoreInDescriptor { binding: Option<u32> },
4397    /// The caller copied or uploaded the texture; do not retain it in the descriptor.
4398    External { binding: Option<u32> },
4399}
4400
4401/// Controls storage and binding of each texture registered by a persistent creator.
4402///
4403/// Texel data is borrowed only for the call. External resources already created
4404/// are not rolled back if extraction later fails. Changing the resulting shader
4405/// or binding layout requires updating the creator's cache ID.
4406pub trait ShaderTextureControl {
4407    /// Register or upload the supplied texture and select its storage and binding.
4408    fn register_texture(&mut self, texture: ShaderTexture<'_>) -> Result<ShaderTextureAction>;
4409}
4410
4411// SAFETY: The native event and its name and data pointers remain valid for the
4412// callback, and callers must not let the returned borrows escape that callback.
4413unsafe fn shader_texture_from_event(
4414    event: &ocio_sys::OcioShaderTextureEvent,
4415) -> Result<ShaderTexture<'_>> {
4416    let read = |ptr: *const i8| -> Result<&str> {
4417        if ptr.is_null() {
4418            return Err(OcioError::InvalidInput("null texture name".into()));
4419        }
4420        unsafe { std::ffi::CStr::from_ptr(ptr) }
4421            .to_str()
4422            .map_err(|_| OcioError::InvalidInput("texture name is not UTF-8".into()))
4423    };
4424    if event.values.is_null()
4425        || event.value_count > isize::MAX as usize / std::mem::size_of::<f32>()
4426    {
4427        return Err(OcioError::InvalidInput("invalid texture data".into()));
4428    }
4429    let dimensions = match event.dimensions {
4430        1 => Some(GpuTextureDimensions::Texture1D),
4431        2 => Some(GpuTextureDimensions::Texture2D),
4432        3 => None,
4433        _ => return Err(OcioError::InvalidInput("unknown texture dimensions".into())),
4434    };
4435    let channel = match event.channel {
4436        0 => GpuTextureChannel::Red,
4437        1 => GpuTextureChannel::Rgb,
4438        _ => return Err(OcioError::InvalidInput("unknown texture channel".into())),
4439    };
4440    Ok(ShaderTexture {
4441        texture_name: read(event.texture_name)?,
4442        sampler_name: read(event.sampler_name)?,
4443        width: event.width,
4444        height: event.height,
4445        depth: event.depth,
4446        channel,
4447        dimensions,
4448        interpolation: interpolation_from_raw(event.interpolation),
4449        values: unsafe { std::slice::from_raw_parts(event.values, event.value_count) },
4450        suggested_binding: event.has_binding.then_some(event.binding),
4451    })
4452}
4453
4454/// A uniform registered by OCIO during custom shader extraction.
4455pub struct ShaderUniform<'a> {
4456    /// Name used by the generated shader.
4457    pub name: &'a str,
4458    /// Native uniform value type.
4459    pub uniform_type: GpuUniformType,
4460    /// Index for querying this uniform on the returned descriptor.
4461    pub index: u32,
4462    /// Declared vector capacity on OCIO 2.5+; unavailable on 2.4 and for scalars.
4463    pub max_size: Option<u32>,
4464    /// Byte offset in OCIO's uniform buffer layout on OCIO 2.5+.
4465    pub buffer_offset: Option<usize>,
4466}
4467
4468/// An owned live native uniform getter received during custom registration.
4469///
4470/// The getter keeps its native creator and dynamic properties alive even if
4471/// extraction fails. It is thread-confined and performs no bridge allocation
4472/// while sampling; native getter implementations may themselves allocate.
4473///
4474/// ```compile_fail
4475/// # use ocio_rs::ShaderUniformGetter;
4476/// fn require_send<T: Send>() {}
4477/// require_send::<ShaderUniformGetter>();
4478/// ```
4479pub struct ShaderUniformGetter {
4480    cache: GpuUniformCache<'static>,
4481    uniform_type: GpuUniformType,
4482}
4483
4484impl ShaderUniformGetter {
4485    /// Native value type of this getter.
4486    pub fn uniform_type(&self) -> GpuUniformType {
4487        self.uniform_type
4488    }
4489
4490    /// Read a double without narrowing; `None` indicates another type.
4491    pub fn double(&mut self) -> Result<Option<f64>> {
4492        self.cache.double(0)
4493    }
4494    /// Read a boolean, or `None` for a different uniform type.
4495    pub fn boolean(&mut self) -> Result<Option<bool>> {
4496        if self.uniform_type != GpuUniformType::Bool {
4497            return Ok(None);
4498        }
4499        let mut value = [0.0];
4500        match self.copy_f32_into(&mut value)? {
4501            GpuUniformCopy::Written(1) => Ok(Some(value[0] != 0.0)),
4502            _ => Err(OcioError::Ocio(
4503                "native boolean getter is unavailable".into(),
4504            )),
4505        }
4506    }
4507    /// Read a float3, or `None` for a different uniform type.
4508    pub fn float3(&mut self) -> Result<Option<[f32; 3]>> {
4509        if self.uniform_type != GpuUniformType::Float3 {
4510            return Ok(None);
4511        }
4512        let mut value = [0.0; 3];
4513        match self.copy_f32_into(&mut value)? {
4514            GpuUniformCopy::Written(3) => Ok(Some(value)),
4515            _ => Err(OcioError::Ocio(
4516                "native float3 getter is unavailable".into(),
4517            )),
4518        }
4519    }
4520    /// Copy scalar, float3, or float-array values into caller-owned storage.
4521    pub fn copy_f32_into(&mut self, values: &mut [f32]) -> Result<GpuUniformCopy> {
4522        self.cache.copy_f32_into(0, values)
4523    }
4524    /// Copy integer-array values into caller-owned storage.
4525    pub fn copy_i32_into(&mut self, values: &mut [i32]) -> Result<GpuUniformCopy> {
4526        self.cache.copy_i32_into(0, values)
4527    }
4528}
4529
4530/// A native uniform registration request and its independently owned getter.
4531pub struct ShaderUniformRegistration {
4532    /// Name supplied by OCIO.
4533    pub name: String,
4534    /// Native value type.
4535    pub uniform_type: GpuUniformType,
4536    /// Declared vector capacity on native 2.5+, otherwise unavailable.
4537    pub max_size: Option<u32>,
4538    /// Live getter. Move it out to retain it after the callback.
4539    pub getter: ShaderUniformGetter,
4540}
4541
4542/// How a custom creator handles a native uniform registration request.
4543#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4544pub enum ShaderUniformAction {
4545    /// Let OCIO's descriptor store the getter and determine the return value.
4546    StoreInDescriptor,
4547    /// The caller stored a new uniform; report `true` to OCIO.
4548    ExternalAdded,
4549    /// The caller already had the uniform; report `false` to OCIO.
4550    ExternalDuplicate,
4551}
4552
4553/// Options for extracting with custom creator resource handling.
4554#[derive(Default, Clone, Copy)]
4555pub struct ShaderCreatorOptions<'a> {
4556    /// Replace the creator's native cache ID with this value.
4557    ///
4558    /// OCIO uses this ID when deriving resource keys. The caller must ensure
4559    /// the ID changes whenever creator configuration or output changes,
4560    /// including after mutating the returned descriptor. Update it with
4561    /// [`GpuShaderDesc::set_custom_cache_id`]. The string is copied
4562    /// once into native ownership. `None` retains OCIO's default behavior.
4563    /// Native descriptor cloning creates a generic descriptor and does not
4564    /// preserve this override.
4565    pub cache_id_override: Option<&'a std::ffi::CStr>,
4566    /// Deliver textures to the supplied sink without retaining descriptor copies.
4567    pub stream_textures: bool,
4568}
4569
4570/// Custom control over native uniform registration during shader extraction.
4571///
4572/// ```no_run
4573/// # use ocio_rs::{GPUProcessor, GpuShaderDesc, Result, ShaderExtractionHooks,
4574/// #     ShaderUniformAction, ShaderUniformControl, ShaderUniformGetter,
4575/// #     ShaderUniformRegistration};
4576/// struct Uniforms(Vec<(String, ShaderUniformGetter)>);
4577/// impl ShaderExtractionHooks for Uniforms {}
4578/// impl ShaderUniformControl for Uniforms {
4579///     fn register_uniform(&mut self, uniform: ShaderUniformRegistration) -> Result<ShaderUniformAction> {
4580///         self.0.push((uniform.name, uniform.getter));
4581///         Ok(ShaderUniformAction::ExternalAdded)
4582///     }
4583/// }
4584/// # fn example(gpu: &GPUProcessor, template: &GpuShaderDesc) -> Result<()> {
4585/// let mut uniforms = Uniforms(Vec::new());
4586/// let desc = gpu.try_extract_with_uniform_control(template, &mut uniforms)?;
4587/// // Allocate and populate external GPU storage from the retained getters.
4588/// # let _ = desc;
4589/// # Ok(()) }
4590/// ```
4591pub trait ShaderUniformControl: ShaderExtractionHooks {
4592    /// Decide where to store this uniform and which result to return to OCIO.
4593    fn register_uniform(
4594        &mut self,
4595        uniform: ShaderUniformRegistration,
4596    ) -> Result<ShaderUniformAction>;
4597}
4598
4599/// Optional synchronous replacement for OCIO's native shader finalization stage.
4600///
4601/// Callbacks are detached when extraction returns; later descriptor operations
4602/// use the native implementation and do not call this object.
4603pub trait ShaderFinalizeControl: ShaderUniformControl {
4604    /// Return complete shader text to bypass OCIO's language wrapping and
4605    /// finalization, or `None` to delegate to OCIO. The implementation may
4606    /// collect the raw fragments delivered by [`ShaderExtractionHooks::code`].
4607    fn finalize_shader(&mut self) -> Result<Option<String>>;
4608}
4609
4610/// Synchronous policy for OCIO's native texture-width and 1D-texture getters.
4611///
4612/// These methods can be called repeatedly during extraction. The policy is
4613/// detached before the resulting descriptor is returned. Its maximum width
4614/// must be at least two; supported OCIO versions have a separate LUT padding
4615/// bug for certain width/length pairs, so the caller must ensure its policies
4616/// are safe for every generated LUT. For a conservative probe see
4617/// [`GPUProcessor::try_extract_with_texture_policy_checked`]. No callback runs
4618/// in the GPU pixel loop.
4619/// Setter events update caller-owned policy state and are not rolled back if
4620/// extraction later fails. A checked extraction performs its probe before
4621/// forwarding the template's setter events.
4622///
4623/// ```
4624/// # use ocio_rs::{ShaderTexturePolicy, Result};
4625/// struct Policy;
4626/// impl ShaderTexturePolicy for Policy {
4627///     fn texture_max_width(&mut self) -> Result<u32> { Ok(4096) }
4628///     fn allow_texture_1d(&mut self) -> Result<bool> { Ok(false) }
4629/// }
4630/// ```
4631pub trait ShaderTexturePolicy {
4632    /// Observe or reject a native width setter. The default accepts it.
4633    /// Called with the template's setting before extraction begins.
4634    fn set_texture_max_width(&mut self, _width: u32) -> Result<()> {
4635        Ok(())
4636    }
4637    /// Observe or reject a native 1D setting. The default accepts it.
4638    /// Called with the template's setting before extraction begins.
4639    fn set_allow_texture_1d(&mut self, _allowed: bool) -> Result<()> {
4640        Ok(())
4641    }
4642    /// Maximum native texture width for the current query.
4643    fn texture_max_width(&mut self) -> Result<u32>;
4644    /// Whether OCIO may emit 1D textures for the current query.
4645    fn allow_texture_1d(&mut self) -> Result<bool>;
4646}
4647
4648/// Supplies the native creator's cache ID during an opted-in query or extraction.
4649///
4650/// The ID must be nonempty and identify the current policy and generated
4651/// resources. Do not reenter the creator or GPU processor from this callback.
4652pub trait ShaderCacheIdPolicy {
4653    /// Borrow the ID for the current native cache-key query. OCIO copies it
4654    /// before invoking another policy method; storing it in the policy avoids
4655    /// allocating a new string for each extraction.
4656    fn cache_id(&mut self) -> Result<&std::ffi::CStr>;
4657}
4658
4659/// Supplies the result of the native creator clone operation.
4660pub trait ShaderClonePolicy {
4661    /// Return a distinct owned creator. This transfers the returned handle
4662    /// to OCIO. Do not reenter the source creator from this callback.
4663    fn clone_creator(&mut self) -> Result<GpuShaderCreator<'static>>;
4664}
4665
4666struct PersistentPolicyState<P> {
4667    policy: P,
4668    error: Option<OcioError>,
4669    code_output: Option<std::ffi::CString>,
4670    assembly_output: Option<std::ffi::CString>,
4671    finalizer_output: Option<std::ffi::CString>,
4672}
4673
4674type CacheIdCallback = unsafe extern "C" fn(*mut c_void, *mut *const i8) -> bool;
4675
4676unsafe extern "C" fn persistent_clone_callback<P: ShaderClonePolicy>(
4677    context: *mut c_void,
4678) -> *mut c_void {
4679    let Some(state) = (unsafe { context.cast::<PersistentPolicyState<P>>().as_mut() }) else {
4680        return std::ptr::null_mut();
4681    };
4682    match crate::catch_callback_unwind(std::panic::AssertUnwindSafe(|| {
4683        state.policy.clone_creator()
4684    })) {
4685        Ok(Ok(creator)) => std::mem::ManuallyDrop::new(creator).handle.as_ptr(),
4686        Ok(Err(error)) => {
4687            state.error = Some(error);
4688            std::ptr::null_mut()
4689        }
4690        Err(_) => {
4691            state.error = Some(OcioError::InvalidInput(
4692                "shader creator clone callback panicked".into(),
4693            ));
4694            std::ptr::null_mut()
4695        }
4696    }
4697}
4698
4699unsafe extern "C" fn persistent_cache_id_callback<P: ShaderCacheIdPolicy>(
4700    context: *mut c_void,
4701    output: *mut *const i8,
4702) -> bool {
4703    let state = unsafe { &mut *context.cast::<PersistentPolicyState<P>>() };
4704    if state.error.is_some() {
4705        return false;
4706    }
4707    let result = crate::catch_callback_unwind(std::panic::AssertUnwindSafe(|| -> Result<_> {
4708        if output.is_null() {
4709            return Err(OcioError::InvalidInput("null cache ID output".into()));
4710        }
4711        let id = state.policy.cache_id()?;
4712        if id.to_bytes().is_empty() {
4713            return Err(OcioError::InvalidInput("cache ID must not be empty".into()));
4714        }
4715        Ok(id.as_ptr())
4716    }));
4717    match result {
4718        Ok(Ok(id)) => {
4719            unsafe { *output = id };
4720            true
4721        }
4722        Ok(Err(error)) => {
4723            state.error = Some(error);
4724            false
4725        }
4726        Err(_) => {
4727            state.error = Some(OcioError::InvalidInput("cache ID callback panicked".into()));
4728            false
4729        }
4730    }
4731}
4732
4733unsafe extern "C" fn persistent_policy_callback<P: ShaderTexturePolicy>(
4734    context: *mut c_void,
4735    kind: i32,
4736    value: *mut u32,
4737) -> bool {
4738    let state = unsafe { &mut *context.cast::<PersistentPolicyState<P>>() };
4739    if state.error.is_some() {
4740        return false;
4741    }
4742    let result = crate::catch_callback_unwind(std::panic::AssertUnwindSafe(|| -> Result<u32> {
4743        if value.is_null() {
4744            return Err(OcioError::InvalidInput("null texture policy value".into()));
4745        }
4746        let input = unsafe { *value };
4747        match kind {
4748            0 => {
4749                let width = state.policy.texture_max_width()?;
4750                if width < 2 {
4751                    return Err(OcioError::InvalidInput(
4752                        "texture maximum width must be at least 2".into(),
4753                    ));
4754                }
4755                Ok(width)
4756            }
4757            1 => Ok(u32::from(state.policy.allow_texture_1d()?)),
4758            2 => {
4759                state.policy.set_texture_max_width(input)?;
4760                Ok(input)
4761            }
4762            3 if input <= 1 => {
4763                state.policy.set_allow_texture_1d(input != 0)?;
4764                Ok(input)
4765            }
4766            _ => Err(OcioError::InvalidInput(
4767                "invalid texture policy event".into(),
4768            )),
4769        }
4770    }));
4771    match result {
4772        Ok(Ok(output)) => {
4773            unsafe { *value = output };
4774            true
4775        }
4776        Ok(Err(error)) => {
4777            state.error = Some(error);
4778            false
4779        }
4780        Err(_) => {
4781            state.error = Some(OcioError::InvalidInput(
4782                "texture policy callback panicked".into(),
4783            ));
4784            false
4785        }
4786    }
4787}
4788
4789/// A native creator whose Rust texture policy remains attached between calls.
4790///
4791/// The policy is detached before its Rust state is dropped, even if native
4792/// resources retain the creator. The caller owns cache invalidation: `cache_id`
4793/// must be nonempty and must change whenever the policy or resulting shader
4794/// changes. Native extraction may partially modify the creator on failure and
4795/// repeated extraction may append resources. The policy must avoid OCIO's
4796/// documented LUT-packing bug; this API does not automatically probe layouts.
4797/// Do not reenter the same GPU processor or creator from a policy callback.
4798/// Optional resource controls and hooks also cover texture and uniform
4799/// registration, lifecycle notifications, and shader code fragments. They do
4800/// not provide arbitrary implementations of every creator virtual or clone.
4801///
4802/// ```no_run
4803/// # use ocio_rs::{GPUProcessor, GpuShaderDesc, PersistentPolicyCreator, ShaderTexturePolicy, Result};
4804/// struct Policy;
4805/// impl ShaderTexturePolicy for Policy {
4806///     fn texture_max_width(&mut self) -> Result<u32> { Ok(4096) }
4807///     fn allow_texture_1d(&mut self) -> Result<bool> { Ok(false) }
4808/// }
4809/// # fn example(gpu: &GPUProcessor, template: &GpuShaderDesc) -> Result<()> {
4810/// let mut creator = PersistentPolicyCreator::create(template, Policy, c"policy-v1")?;
4811/// // The application must establish that the policy width is safe for every
4812/// // LUT generated by this processor (see validate_lut_texture_layout).
4813/// creator.try_extract(gpu)?;
4814/// let descriptor = creator.finish()?; // detaches the Rust policy
4815/// # let _ = descriptor;
4816/// # Ok(()) }
4817/// ```
4818///
4819/// ```compile_fail
4820/// # use ocio_rs::{PersistentPolicyCreator, ShaderTexturePolicy};
4821/// # fn example<P: ShaderTexturePolicy>(creator: &mut PersistentPolicyCreator<P>) -> ocio_rs::Result<()> {
4822/// let text = creator.shader_text_ref()?;
4823/// let policy = creator.policy_mut();
4824/// println!("{:?} {:?}", text, std::ptr::from_ref(policy));
4825/// # Ok(()) }
4826/// ```
4827///
4828/// ```compile_fail
4829/// # use ocio_rs::{PersistentPolicyCreator, ShaderTexturePolicy};
4830/// fn require_send<T: Send>() {}
4831/// fn check<P: ShaderTexturePolicy + Send>() { require_send::<PersistentPolicyCreator<P>>(); }
4832/// ```
4833pub struct PersistentPolicyCreator<P: ShaderTexturePolicy> {
4834    creator: GpuShaderCreator<'static>,
4835    descriptor: GpuShaderDesc,
4836    state: Box<PersistentPolicyState<P>>,
4837    extraction_cache_policy: Option<CacheIdCallback>,
4838    recreate: fn(&GpuShaderDesc, P, &std::ffi::CStr) -> Result<Self>,
4839}
4840
4841impl<P: ShaderTexturePolicy> PersistentPolicyCreator<P> {
4842    /// Retain all resource, lifecycle, code, assembly and finalization hooks.
4843    /// Returning `None` from finalization delegates to OCIO, which then calls
4844    /// the assembler. Returning shader text bypasses both native finalization
4845    /// and the assembler; the caller must supply any Vulkan uniform wrapper.
4846    pub fn create_with_finalizer(
4847        template: &GpuShaderDesc,
4848        policy: P,
4849        cache_id: &std::ffi::CStr,
4850    ) -> Result<Self>
4851    where
4852        P: ShaderTextureControl + ShaderFinalizeControl,
4853    {
4854        let mut creator = Self::create_with_assembler(template, policy, cache_id)?;
4855        crate::clear_last_error();
4856        unsafe {
4857            ocio_sys::ocio_gpu_shader_creator_set_persistent_finalizer(
4858                creator.creator.handle.as_ptr(),
4859                persistent_finalizer_callback::<P>,
4860            );
4861        }
4862        crate::ocio_call_status()?;
4863        creator.recreate = Self::create_with_finalizer;
4864        Ok(creator)
4865    }
4866    /// Retain resource controls, hooks, and the optional shader assembler.
4867    /// `assemble` may return `None` to use OCIO's native assembly, including
4868    /// Vulkan uniform wrapping. A replacement must provide any required wrapper.
4869    pub fn create_with_assembler(
4870        template: &GpuShaderDesc,
4871        policy: P,
4872        cache_id: &std::ffi::CStr,
4873    ) -> Result<Self>
4874    where
4875        P: ShaderTextureControl + ShaderUniformControl,
4876    {
4877        let mut creator = Self::create_with_hooks(template, policy, cache_id)?;
4878        crate::clear_last_error();
4879        unsafe {
4880            ocio_sys::ocio_gpu_shader_creator_set_persistent_assembler(
4881                creator.creator.handle.as_ptr(),
4882                persistent_assembler_callback::<P>,
4883            );
4884        }
4885        crate::ocio_call_status()?;
4886        creator.recreate = Self::create_with_assembler;
4887        Ok(creator)
4888    }
4889    /// Retain resource controls and lifecycle/code hooks across extractions.
4890    ///
4891    /// Only `lifecycle` and `code` hooks are installed. Texture and uniform
4892    /// registration use their respective control traits; `assemble` is not
4893    /// installed. Replacement fragments are copied into temporary native-safe
4894    /// storage, while unmodified fragments are forwarded without a copy.
4895    pub fn create_with_hooks(
4896        template: &GpuShaderDesc,
4897        policy: P,
4898        cache_id: &std::ffi::CStr,
4899    ) -> Result<Self>
4900    where
4901        P: ShaderTextureControl + ShaderUniformControl,
4902    {
4903        let mut creator = Self::create_with_resource_control(template, policy, cache_id)?;
4904        crate::clear_last_error();
4905        unsafe {
4906            ocio_sys::ocio_gpu_shader_creator_set_persistent_hooks(
4907                creator.creator.handle.as_ptr(),
4908                persistent_lifecycle_callback::<P>,
4909                persistent_code_callback::<P>,
4910            );
4911        }
4912        crate::ocio_call_status()?;
4913        creator.recreate = Self::create_with_hooks;
4914        Ok(creator)
4915    }
4916    /// Retain both texture and uniform registration controllers between calls.
4917    ///
4918    /// External uniform getters retain the native creator and remain live after
4919    /// this wrapper is dropped. As with textures, external storage is not rolled
4920    /// back if a later callback fails. Do not reenter the creator from callbacks.
4921    /// Only `register_uniform` is used from [`ShaderUniformControl`]; its
4922    /// inherited synchronous shader hooks are not attached by this constructor.
4923    pub fn create_with_resource_control(
4924        template: &GpuShaderDesc,
4925        policy: P,
4926        cache_id: &std::ffi::CStr,
4927    ) -> Result<Self>
4928    where
4929        P: ShaderTextureControl + ShaderUniformControl,
4930    {
4931        let mut creator = Self::create_with_texture_control(template, policy, cache_id)?;
4932        crate::clear_last_error();
4933        unsafe {
4934            ocio_sys::ocio_gpu_shader_creator_set_persistent_uniform_control(
4935                creator.creator.handle.as_ptr(),
4936                persistent_uniform_control_callback::<P>,
4937            );
4938        }
4939        crate::ocio_call_status()?;
4940        creator.recreate = Self::create_with_resource_control;
4941        Ok(creator)
4942    }
4943    /// Create a persistent creator with control over each registered texture.
4944    pub fn create_with_texture_control(
4945        template: &GpuShaderDesc,
4946        policy: P,
4947        cache_id: &std::ffi::CStr,
4948    ) -> Result<Self>
4949    where
4950        P: ShaderTextureControl,
4951    {
4952        let mut creator = Self::create(template, policy, cache_id)?;
4953        crate::clear_last_error();
4954        unsafe {
4955            ocio_sys::ocio_gpu_shader_creator_set_persistent_texture_control(
4956                creator.creator.handle.as_ptr(),
4957                persistent_texture_control_callback::<P>,
4958            );
4959        }
4960        crate::ocio_call_status()?;
4961        creator.recreate = Self::create_with_texture_control;
4962        Ok(creator)
4963    }
4964    /// Create a persistent policy creator using the template's native settings.
4965    /// Existing template shader code and resources are not copied.
4966    pub fn create(template: &GpuShaderDesc, policy: P, cache_id: &std::ffi::CStr) -> Result<Self> {
4967        if cache_id.to_bytes().is_empty() {
4968            return Err(OcioError::InvalidInput(
4969                "texture policy requires a nonempty cache ID".into(),
4970            ));
4971        }
4972        let mut state = Box::new(PersistentPolicyState {
4973            policy,
4974            error: None,
4975            code_output: None,
4976            assembly_output: None,
4977            finalizer_output: None,
4978        });
4979        crate::clear_last_error();
4980        let raw = unsafe {
4981            ocio_sys::ocio_gpu_shader_creator_create_persistent_policy(
4982                template.handle.as_ptr(),
4983                cache_id.as_ptr(),
4984                persistent_policy_callback::<P>,
4985                (&mut *state as *mut PersistentPolicyState<P>).cast(),
4986            )
4987        };
4988        let handle = crate::handle_result(raw);
4989        if let Some(error) = state.error.take() {
4990            return Err(error);
4991        }
4992        let creator = GpuShaderCreator {
4993            handle: handle?,
4994            _descriptor: std::marker::PhantomData,
4995        };
4996        crate::clear_last_error();
4997        let raw_desc =
4998            unsafe { ocio_sys::ocio_gpu_shader_creator_borrow_desc(creator.handle.as_ptr()) };
4999        let descriptor = match crate::handle_result(raw_desc) {
5000            Ok(handle) => GpuShaderDesc { handle },
5001            Err(error) => {
5002                unsafe {
5003                    ocio_sys::ocio_gpu_shader_creator_detach_persistent_policy(
5004                        creator.handle.as_ptr(),
5005                    )
5006                };
5007                return Err(error);
5008            }
5009        };
5010        Ok(Self {
5011            creator,
5012            descriptor,
5013            state,
5014            extraction_cache_policy: None,
5015            recreate: Self::create,
5016        })
5017    }
5018
5019    /// Create an independent creator with the same native settings and enabled
5020    /// hooks, but a new policy and fixed cache ID.
5021    ///
5022    /// This copies stored texture settings, not the old policy's answers.
5023    /// As with the constructors, the new policy receives the initial texture
5024    /// setting notifications. Shader text, registered resources and extraction
5025    /// state are not copied. If enabled, dynamic cache IDs remain enabled and
5026    /// are supplied by the new policy on extraction.
5027    pub fn try_fork_with_policy(&self, policy: P, cache_id: &std::ffi::CStr) -> Result<Self> {
5028        let mut fork = (self.recreate)(&self.descriptor, policy, cache_id)?;
5029        fork.extraction_cache_policy = self.extraction_cache_policy;
5030        Ok(fork)
5031    }
5032
5033    /// Access policy state. Update the cache ID if this changes the shader output.
5034    pub fn policy_mut(&mut self) -> &mut P {
5035        &mut self.state.policy
5036    }
5037
5038    fn policy_result<T>(&mut self, result: Result<T>) -> Result<T> {
5039        match self.state.error.take() {
5040            Some(error) => Err(error),
5041            None => result,
5042        }
5043    }
5044
5045    /// Query the persistent native width policy, preserving Rust callback errors.
5046    pub fn try_texture_max_width(&mut self) -> Result<u32> {
5047        self.state.error = None;
5048        let result = self.creator.try_texture_max_width();
5049        self.policy_result(result)
5050    }
5051
5052    /// Notify the persistent native width setter, preserving callback errors.
5053    pub fn try_set_texture_max_width(&mut self, width: u32) -> Result<()> {
5054        self.state.error = None;
5055        let result = self.creator.try_set_texture_max_width(width);
5056        self.policy_result(result)
5057    }
5058
5059    /// Query the persistent native 1D texture policy.
5060    pub fn try_allow_texture_1d(&mut self) -> Result<bool> {
5061        self.state.error = None;
5062        let result = self.creator.try_allow_texture_1d();
5063        self.policy_result(result)
5064    }
5065
5066    /// Notify the persistent native 1D texture setter.
5067    pub fn try_set_allow_texture_1d(&mut self, allow: bool) -> Result<()> {
5068        self.state.error = None;
5069        let result = self.creator.try_set_allow_texture_1d(allow);
5070        self.policy_result(result)
5071    }
5072
5073    /// Set a nonempty cache ID identifying the current policy and output.
5074    pub fn set_cache_id(&mut self, id: &std::ffi::CStr) -> Result<()> {
5075        if id.to_bytes().is_empty() {
5076            return Err(OcioError::InvalidInput(
5077                "texture policy requires a nonempty cache ID".into(),
5078            ));
5079        }
5080        self.descriptor.set_custom_cache_id(Some(id))
5081    }
5082
5083    /// Copy the current native creator cache ID.
5084    pub fn try_cache_id(&self) -> Result<Option<String>> {
5085        self.creator.try_cache_id()
5086    }
5087
5088    /// Change the shader language. Update the cache ID when output changes;
5089    /// previously generated code and resources are not cleared.
5090    pub fn set_language(&mut self, language: GpuLanguage) -> Result<()> {
5091        self.descriptor.set_language(language)
5092    }
5093
5094    /// Change the generated function name. Update the cache ID when output changes.
5095    pub fn set_function_name(&mut self, name: impl AsRef<str>) -> Result<()> {
5096        self.descriptor.set_function_name(name)
5097    }
5098
5099    /// Change the shader pixel variable name. Update the cache ID when output changes.
5100    pub fn set_pixel_name(&mut self, name: impl AsRef<str>) -> Result<()> {
5101        self.descriptor.set_pixel_name(name)
5102    }
5103
5104    /// Change the resource prefix. Existing resources are not renamed; update
5105    /// the cache ID when subsequent output changes.
5106    pub fn set_resource_prefix(&mut self, prefix: impl AsRef<str>) -> Result<()> {
5107        self.descriptor.set_resource_prefix(prefix)
5108    }
5109
5110    /// Set the native unique ID. Extraction may update this ID; update the
5111    /// cache ID if the change affects generated output.
5112    pub fn set_unique_id(&mut self, id: impl AsRef<str>) -> Result<()> {
5113        self.descriptor.set_unique_id(id)
5114    }
5115
5116    /// Extract into the same native creator, retaining the policy after return.
5117    /// Uses the fixed ID unless [`Self::set_extraction_cache_policy`] enabled
5118    /// dynamic IDs for subsequent extractions.
5119    pub fn try_extract(&mut self, processor: &GPUProcessor) -> Result<()> {
5120        self.extract_with_cache_callback(processor, self.extraction_cache_policy)
5121    }
5122
5123    /// Enable or disable dynamic cache IDs for subsequent [`Self::try_extract`]
5124    /// calls. Outside extraction the fixed ID remains in effect. This does not
5125    /// invalidate or rename existing resources.
5126    pub fn set_extraction_cache_policy(&mut self, enabled: bool)
5127    where
5128        P: ShaderCacheIdPolicy,
5129    {
5130        self.extraction_cache_policy = if enabled {
5131            Some(persistent_cache_id_callback::<P>)
5132        } else {
5133            None
5134        };
5135    }
5136
5137    /// Extract with a Rust-provided native cache-ID getter for this call only.
5138    ///
5139    /// The callback is detached on both success and failure. Its error or panic
5140    /// is returned after native execution; as with other callbacks, resources
5141    /// created before failure are not rolled back. Outside this call the fixed
5142    /// ID set by [`Self::set_cache_id`] remains in effect.
5143    pub fn try_extract_with_cache_policy(&mut self, processor: &GPUProcessor) -> Result<()>
5144    where
5145        P: ShaderCacheIdPolicy,
5146    {
5147        self.extract_with_cache_callback(processor, Some(persistent_cache_id_callback::<P>))
5148    }
5149
5150    fn extract_with_cache_callback(
5151        &mut self,
5152        processor: &GPUProcessor,
5153        callback: Option<CacheIdCallback>,
5154    ) -> Result<()> {
5155        self.state.error = None;
5156        crate::clear_last_error();
5157        unsafe {
5158            if let Some(callback) = callback {
5159                ocio_sys::ocio_gpu_shader_creator_extract_with_cache_policy(
5160                    processor.handle.as_ptr(),
5161                    self.creator.handle.as_ptr(),
5162                    callback,
5163                );
5164            } else {
5165                ocio_sys::ocio_gpu_shader_creator_extract_persistent_policy(
5166                    processor.handle.as_ptr(),
5167                    self.creator.handle.as_ptr(),
5168                );
5169            }
5170        };
5171        let native_result = crate::ocio_call_status();
5172        self.policy_result(native_result)
5173    }
5174
5175    /// Query the native virtual cache ID using the Rust policy without
5176    /// extracting a shader. The fixed cache ID remains in effect afterward.
5177    pub fn try_query_cache_policy(&mut self) -> Result<String>
5178    where
5179        P: ShaderCacheIdPolicy,
5180    {
5181        self.state.error = None;
5182        crate::clear_last_error();
5183        let ptr = unsafe {
5184            ocio_sys::ocio_gpu_shader_creator_query_cache_policy(
5185                self.creator.handle.as_ptr(),
5186                persistent_cache_id_callback::<P>,
5187            )
5188        };
5189        // Copy the policy-owned string before taking another mutable borrow
5190        // of callback state or calling another native creator method.
5191        let result = crate::ocio_call_status().and_then(|()| {
5192            unsafe { crate::cstr_to_opt_string(ptr) }
5193                .ok_or_else(|| OcioError::Ocio("null shader cache ID".into()))
5194        });
5195        self.policy_result(result)
5196    }
5197
5198    /// Invoke the native virtual clone using the configured Rust clone policy.
5199    ///
5200    /// The policy defines what is copied. Its callback is detached on return;
5201    /// the returned creator does not inherit this owner's callback state.
5202    pub fn try_clone_with_policy(&mut self) -> Result<GpuShaderCreator<'static>>
5203    where
5204        P: ShaderClonePolicy,
5205    {
5206        self.state.error = None;
5207        crate::clear_last_error();
5208        let raw = unsafe {
5209            ocio_sys::ocio_gpu_shader_creator_clone_with_policy(
5210                self.creator.handle.as_ptr(),
5211                persistent_clone_callback::<P>,
5212            )
5213        };
5214        let result = crate::handle_result(raw).map(|handle| GpuShaderCreator {
5215            handle,
5216            _descriptor: std::marker::PhantomData,
5217        });
5218        self.policy_result(result)
5219    }
5220
5221    /// Assemble caller-provided shader fragments without a GPU processor.
5222    ///
5223    /// The native lifecycle, code and finalization hooks are invoked as in
5224    /// extraction. After a successful begin, end is attempted even if appending
5225    /// or finalizing fails. The first error wins. Existing native code and
5226    /// resources are not cleared or rolled back.
5227    pub fn try_assemble_fragments(
5228        &mut self,
5229        uid: &std::ffi::CStr,
5230        fragments: &[(ShaderCodeSection, &std::ffi::CStr)],
5231    ) -> Result<()> {
5232        self.state.error = None;
5233        crate::clear_last_error();
5234        unsafe {
5235            ocio_sys::ocio_gpu_shader_creator_begin_manual(
5236                self.creator.handle.as_ptr(),
5237                uid.as_ptr(),
5238            );
5239        }
5240        let begin = crate::ocio_call_status();
5241        self.policy_result(begin)?;
5242
5243        let assembled = (|| {
5244            for &(section, code) in fragments {
5245                let tag = match section {
5246                    ShaderCodeSection::Declarations => 0,
5247                    #[cfg(feature = "v2_5")]
5248                    ShaderCodeSection::Parameters => 1,
5249                    #[cfg(feature = "v2_5")]
5250                    ShaderCodeSection::Textures => 2,
5251                    #[cfg(not(feature = "v2_5"))]
5252                    ShaderCodeSection::Parameters | ShaderCodeSection::Textures => {
5253                        return Err(OcioError::InvalidInput(
5254                            "split declarations require v2_5".into(),
5255                        ));
5256                    }
5257                    ShaderCodeSection::Helpers => 3,
5258                    ShaderCodeSection::Header => 4,
5259                    ShaderCodeSection::Body => 5,
5260                    ShaderCodeSection::Footer => 6,
5261                };
5262                crate::clear_last_error();
5263                unsafe {
5264                    ocio_sys::ocio_gpu_shader_creator_add_code(
5265                        self.creator.handle.as_ptr(),
5266                        tag,
5267                        code.as_ptr(),
5268                    );
5269                }
5270                crate::ocio_call_status()?;
5271            }
5272            self.creator.finalize()
5273        })();
5274        let assembled = self.policy_result(assembled);
5275        let ended = self.creator.end();
5276        assembled.and(self.policy_result(ended))
5277    }
5278
5279    /// Return an owned copy of the generated shader text.
5280    pub fn try_shader_text(&self) -> Result<Option<String>> {
5281        self.descriptor.try_shader_text()
5282    }
5283    /// Copy metadata for a descriptor-owned 1D/2D texture.
5284    pub fn try_texture_2d(&self, index: u32) -> Result<Option<GpuTexture2D>> {
5285        self.descriptor.try_texture_2d(index)
5286    }
5287    /// Copy metadata for a descriptor-owned 3D texture.
5288    pub fn try_texture_3d(&self, index: u32) -> Result<Option<GpuTexture3D>> {
5289        self.descriptor.try_texture_3d(index)
5290    }
5291    /// Return the number of descriptor-owned uniforms.
5292    pub fn try_num_uniforms(&self) -> Result<u32> {
5293        self.descriptor.try_num_uniforms()
5294    }
5295    /// Read a descriptor-owned uniform and its current value.
5296    pub fn try_uniform(&self, index: u32) -> Result<Option<GpuUniform>> {
5297        self.descriptor.try_uniform(index)
5298    }
5299    /// Share a native dynamic property, if present, without copying it.
5300    pub fn try_dynamic_property(
5301        &self,
5302        property_type: DynamicPropertyType,
5303    ) -> Result<Option<DynamicProperty>> {
5304        self.descriptor.try_dynamic_property(property_type)
5305    }
5306
5307    /// Borrow generated shader text until the creator is mutated.
5308    pub fn shader_text_ref(&mut self) -> Result<Option<&std::ffi::CStr>> {
5309        self.descriptor.shader_text_ref()
5310    }
5311    /// Return the number of descriptor-owned 1D/2D textures.
5312    pub fn try_num_textures(&self) -> Result<u32> {
5313        self.descriptor.try_num_textures()
5314    }
5315    /// Borrow a descriptor-owned 1D/2D texture payload without copying.
5316    pub fn texture_values_ref(&mut self, index: u32) -> Result<&[f32]> {
5317        self.descriptor.texture_values_ref(index)
5318    }
5319    /// Return the number of descriptor-owned 3D textures.
5320    pub fn try_num_3d_textures(&self) -> Result<u32> {
5321        self.descriptor.try_num_3d_textures()
5322    }
5323    /// Borrow a descriptor-owned 3D texture payload without copying.
5324    pub fn texture_3d_values_ref(&mut self, index: u32) -> Result<&[f32]> {
5325        self.descriptor.texture_3d_values_ref(index)
5326    }
5327    /// Retain a scoped cache of the descriptor's native uniform getters.
5328    pub fn uniform_cache(&mut self) -> Result<GpuUniformCache<'_>> {
5329        self.descriptor.uniform_cache()
5330    }
5331}
5332
5333unsafe extern "C" fn persistent_texture_control_callback<
5334    P: ShaderTexturePolicy + ShaderTextureControl,
5335>(
5336    context: *mut c_void,
5337    event: *const ocio_sys::OcioShaderTextureEvent,
5338    store: *mut bool,
5339    replace: *mut bool,
5340    binding: *mut u32,
5341) -> bool {
5342    if context.is_null() {
5343        return false;
5344    }
5345    let state = unsafe { &mut *context.cast::<PersistentPolicyState<P>>() };
5346    if state.error.is_some() {
5347        return false;
5348    }
5349    let result = crate::catch_callback_unwind(std::panic::AssertUnwindSafe(
5350        || -> Result<ShaderTextureAction> {
5351            let event = unsafe { event.as_ref() }
5352                .ok_or_else(|| OcioError::InvalidInput("null texture event".into()))?;
5353            if store.is_null() || replace.is_null() || binding.is_null() {
5354                return Err(OcioError::InvalidInput(
5355                    "null texture control output".into(),
5356                ));
5357            }
5358            state
5359                .policy
5360                .register_texture(unsafe { shader_texture_from_event(event)? })
5361        },
5362    ));
5363    match result {
5364        Ok(Ok(action)) => {
5365            let (stored, requested) = match action {
5366                ShaderTextureAction::StoreInDescriptor { binding } => (true, binding),
5367                ShaderTextureAction::External { binding } => (false, binding),
5368            };
5369            unsafe {
5370                *store = stored;
5371                *replace = requested.is_some();
5372                if let Some(value) = requested {
5373                    *binding = value;
5374                }
5375            }
5376            true
5377        }
5378        Ok(Err(error)) => {
5379            state.error = Some(error);
5380            false
5381        }
5382        Err(_) => {
5383            state.error = Some(OcioError::InvalidInput(
5384                "shader texture callback panicked".into(),
5385            ));
5386            false
5387        }
5388    }
5389}
5390
5391unsafe extern "C" fn persistent_uniform_control_callback<
5392    P: ShaderTexturePolicy + ShaderUniformControl,
5393>(
5394    context: *mut c_void,
5395    name: *const i8,
5396    uniform_type: i32,
5397    has_max_size: bool,
5398    max_size: u32,
5399    getter: *mut c_void,
5400    action: *mut i32,
5401) -> bool {
5402    // Ownership transfers on every path, including an invalid context or error.
5403    let Some(handle) = NonNull::new(getter) else {
5404        return false;
5405    };
5406    let getter = ShaderUniformGetter {
5407        cache: GpuUniformCache {
5408            handle,
5409            _desc: std::marker::PhantomData,
5410        },
5411        uniform_type: GpuUniformType::from_raw(uniform_type),
5412    };
5413    if context.is_null() {
5414        return false;
5415    }
5416    let state = unsafe { &mut *context.cast::<PersistentPolicyState<P>>() };
5417    if state.error.is_some() {
5418        return false;
5419    }
5420    let result = crate::catch_callback_unwind(std::panic::AssertUnwindSafe(
5421        || -> Result<ShaderUniformAction> {
5422            if name.is_null() || action.is_null() || !(0..=4).contains(&uniform_type) {
5423                return Err(OcioError::InvalidInput(
5424                    "invalid uniform registration".into(),
5425                ));
5426            }
5427            let name = unsafe { std::ffi::CStr::from_ptr(name) }
5428                .to_str()
5429                .map_err(|_| OcioError::InvalidInput("uniform name is not UTF-8".into()))?;
5430            state.policy.register_uniform(ShaderUniformRegistration {
5431                name: name.to_owned(),
5432                uniform_type: GpuUniformType::from_raw(uniform_type),
5433                max_size: has_max_size.then_some(max_size),
5434                getter,
5435            })
5436        },
5437    ));
5438    match result {
5439        Ok(Ok(choice)) => {
5440            unsafe {
5441                *action = match choice {
5442                    ShaderUniformAction::StoreInDescriptor => 0,
5443                    ShaderUniformAction::ExternalAdded => 1,
5444                    ShaderUniformAction::ExternalDuplicate => 2,
5445                };
5446            }
5447            true
5448        }
5449        Ok(Err(error)) => {
5450            state.error = Some(error);
5451            false
5452        }
5453        Err(_) => {
5454            state.error = Some(OcioError::InvalidInput(
5455                "uniform registration callback panicked".into(),
5456            ));
5457            false
5458        }
5459    }
5460}
5461
5462impl<P: ShaderTexturePolicy> PersistentPolicyCreator<P> {
5463    /// Detach and release the Rust policy, returning the generated native descriptor.
5464    /// Subsequent descriptor operations use its native stored texture settings.
5465    pub fn finish(self) -> Result<GpuShaderDesc> {
5466        crate::clear_last_error();
5467        let raw =
5468            unsafe { ocio_sys::ocio_gpu_shader_creator_borrow_desc(self.creator.handle.as_ptr()) };
5469        Ok(GpuShaderDesc {
5470            handle: crate::handle_result(raw)?,
5471        })
5472    }
5473}
5474
5475unsafe extern "C" fn persistent_lifecycle_callback<
5476    P: ShaderTexturePolicy + ShaderExtractionHooks,
5477>(
5478    context: *mut c_void,
5479    event: i32,
5480    uid: *const i8,
5481) -> bool {
5482    if context.is_null() {
5483        return false;
5484    }
5485    let state = unsafe { &mut *context.cast::<PersistentPolicyState<P>>() };
5486    // End is still delivered after a failed callback; preserve the first error.
5487    if state.error.is_some() && event != 2 {
5488        return false;
5489    }
5490    let result = crate::catch_callback_unwind(std::panic::AssertUnwindSafe(|| -> Result<()> {
5491        let event = match event {
5492            0 if !uid.is_null() => ShaderLifecycle::Begin {
5493                unique_id: unsafe { std::ffi::CStr::from_ptr(uid) }
5494                    .to_str()
5495                    .map_err(|_| {
5496                        OcioError::InvalidInput("shader identifier is not UTF-8".into())
5497                    })?,
5498            },
5499            1 => ShaderLifecycle::Finalized,
5500            2 => ShaderLifecycle::End,
5501            _ => {
5502                return Err(OcioError::InvalidInput(
5503                    "invalid shader lifecycle event".into(),
5504                ))
5505            }
5506        };
5507        state.policy.lifecycle(event)
5508    }));
5509    match result {
5510        Ok(Ok(())) => true,
5511        Ok(Err(error)) => {
5512            state.error.get_or_insert(error);
5513            false
5514        }
5515        Err(_) => {
5516            state.error.get_or_insert(OcioError::InvalidInput(
5517                "shader lifecycle callback panicked".into(),
5518            ));
5519            false
5520        }
5521    }
5522}
5523
5524unsafe extern "C" fn persistent_code_callback<P: ShaderTexturePolicy + ShaderExtractionHooks>(
5525    context: *mut c_void,
5526    section: i32,
5527    code: *const i8,
5528    replacement: *mut *const i8,
5529) -> bool {
5530    if context.is_null() {
5531        return false;
5532    }
5533    let state = unsafe { &mut *context.cast::<PersistentPolicyState<P>>() };
5534    if state.error.is_some() {
5535        return false;
5536    }
5537    let result = crate::catch_callback_unwind(std::panic::AssertUnwindSafe(
5538        || -> Result<Option<std::ffi::CString>> {
5539            let section = match section {
5540                0 => ShaderCodeSection::Declarations,
5541                1 => ShaderCodeSection::Parameters,
5542                2 => ShaderCodeSection::Textures,
5543                3 => ShaderCodeSection::Helpers,
5544                4 => ShaderCodeSection::Header,
5545                5 => ShaderCodeSection::Body,
5546                6 => ShaderCodeSection::Footer,
5547                _ => {
5548                    return Err(OcioError::InvalidInput(
5549                        "invalid shader code section".into(),
5550                    ))
5551                }
5552            };
5553            if code.is_null() || replacement.is_null() {
5554                return Err(OcioError::InvalidInput("null shader code event".into()));
5555            }
5556            let code = unsafe { std::ffi::CStr::from_ptr(code) }
5557                .to_str()
5558                .map_err(|_| OcioError::InvalidInput("shader code is not UTF-8".into()))?;
5559            state
5560                .policy
5561                .code(section, code)?
5562                .map(std::ffi::CString::new)
5563                .transpose()
5564                .map_err(|_| OcioError::InteriorNul)
5565        },
5566    ));
5567    match result {
5568        Ok(Ok(output)) => {
5569            state.code_output = output;
5570            unsafe {
5571                *replacement = state
5572                    .code_output
5573                    .as_ref()
5574                    .map_or(std::ptr::null(), |s| s.as_ptr())
5575            };
5576            true
5577        }
5578        Ok(Err(error)) => {
5579            state.error.get_or_insert(error);
5580            false
5581        }
5582        Err(_) => {
5583            state.error.get_or_insert(OcioError::InvalidInput(
5584                "shader code callback panicked".into(),
5585            ));
5586            false
5587        }
5588    }
5589}
5590
5591unsafe extern "C" fn persistent_assembler_callback<
5592    P: ShaderTexturePolicy + ShaderExtractionHooks,
5593>(
5594    context: *mut c_void,
5595    parameters: *const i8,
5596    textures: *const i8,
5597    helpers: *const i8,
5598    header: *const i8,
5599    body: *const i8,
5600    footer: *const i8,
5601    output: *mut *const i8,
5602) -> bool {
5603    if context.is_null() {
5604        return false;
5605    }
5606    let state = unsafe { &mut *context.cast::<PersistentPolicyState<P>>() };
5607    if state.error.is_some() {
5608        return false;
5609    }
5610    let result = crate::catch_callback_unwind(std::panic::AssertUnwindSafe(
5611        || -> Result<Option<std::ffi::CString>> {
5612            if output.is_null() {
5613                return Err(OcioError::InvalidInput("null shader output".into()));
5614            }
5615            let read = |ptr: *const i8| -> Result<&str> {
5616                if ptr.is_null() {
5617                    return Err(OcioError::InvalidInput("null shader section".into()));
5618                }
5619                unsafe { std::ffi::CStr::from_ptr(ptr) }
5620                    .to_str()
5621                    .map_err(|_| OcioError::InvalidInput("shader section is not UTF-8".into()))
5622            };
5623            state
5624                .policy
5625                .assemble(ShaderSections {
5626                    parameters: read(parameters)?,
5627                    textures: read(textures)?,
5628                    helpers: read(helpers)?,
5629                    header: read(header)?,
5630                    body: read(body)?,
5631                    footer: read(footer)?,
5632                })?
5633                .map(|s| {
5634                    std::ffi::CString::new(s).map_err(|_| {
5635                        OcioError::InvalidInput("assembled shader contains a NUL byte".into())
5636                    })
5637                })
5638                .transpose()
5639        },
5640    ));
5641    match result {
5642        Ok(Ok(text)) => {
5643            state.assembly_output = text;
5644            unsafe {
5645                *output = state
5646                    .assembly_output
5647                    .as_ref()
5648                    .map_or(std::ptr::null(), |s| s.as_ptr())
5649            };
5650            true
5651        }
5652        Ok(Err(error)) => {
5653            state.error.get_or_insert(error);
5654            false
5655        }
5656        Err(_) => {
5657            state
5658                .error
5659                .get_or_insert(OcioError::InvalidInput("shader assembler panicked".into()));
5660            false
5661        }
5662    }
5663}
5664
5665unsafe extern "C" fn persistent_finalizer_callback<
5666    P: ShaderTexturePolicy + ShaderFinalizeControl,
5667>(
5668    context: *mut c_void,
5669    output: *mut *const i8,
5670) -> bool {
5671    if context.is_null() {
5672        return false;
5673    }
5674    let state = unsafe { &mut *context.cast::<PersistentPolicyState<P>>() };
5675    if state.error.is_some() {
5676        return false;
5677    }
5678    let result = crate::catch_callback_unwind(std::panic::AssertUnwindSafe(
5679        || -> Result<Option<std::ffi::CString>> {
5680            if output.is_null() {
5681                return Err(OcioError::InvalidInput(
5682                    "null shader finalizer output".into(),
5683                ));
5684            }
5685            state
5686                .policy
5687                .finalize_shader()?
5688                .map(std::ffi::CString::new)
5689                .transpose()
5690                .map_err(|_| OcioError::InteriorNul)
5691        },
5692    ));
5693    match result {
5694        Ok(Ok(text)) => {
5695            state.finalizer_output = text;
5696            unsafe {
5697                *output = state
5698                    .finalizer_output
5699                    .as_ref()
5700                    .map_or(std::ptr::null(), |s| s.as_ptr())
5701            };
5702            true
5703        }
5704        Ok(Err(error)) => {
5705            state.error.get_or_insert(error);
5706            false
5707        }
5708        Err(_) => {
5709            state
5710                .error
5711                .get_or_insert(OcioError::InvalidInput("shader finalizer panicked".into()));
5712            false
5713        }
5714    }
5715}
5716
5717impl<P: ShaderTexturePolicy> Drop for PersistentPolicyCreator<P> {
5718    fn drop(&mut self) {
5719        unsafe {
5720            ocio_sys::ocio_gpu_shader_creator_detach_persistent_policy(self.creator.handle.as_ptr())
5721        }
5722    }
5723}
5724
5725/// Lifecycle stages of a native shader-creator extraction.
5726#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5727pub enum ShaderLifecycle<'a> {
5728    /// OCIO has started collection with this generated resource identifier.
5729    Begin { unique_id: &'a str },
5730    /// OCIO has finalized and assembled the shader.
5731    Finalized,
5732    /// OCIO has ended collection, including after an extraction error once
5733    /// `Begin` returned successfully. A failed `Begin` has no `End` event.
5734    End,
5735}
5736
5737/// Native shader code section currently being appended.
5738#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5739pub enum ShaderCodeSection {
5740    /// Combined parameter and texture declarations on OCIO 2.4.
5741    Declarations,
5742    /// Parameter declarations on OCIO 2.5 and newer.
5743    Parameters,
5744    /// Texture declarations on OCIO 2.5 and newer.
5745    Textures,
5746    /// Helper function definitions.
5747    Helpers,
5748    /// Function opening code.
5749    Header,
5750    /// Function body code.
5751    Body,
5752    /// Function closing code.
5753    Footer,
5754}
5755
5756/// Synchronous customization hooks for OCIO shader extraction.
5757///
5758/// Defaults retain OCIO's resource handling, forward individual code
5759/// fragments, and use OCIO's native shader assembly.
5760/// Implementations may override selected callbacks; they must not reenter
5761/// extraction on the same processor. Callbacks must not retain borrowed inputs.
5762///
5763/// ```no_run
5764/// # use ocio_rs::{GPUProcessor, GpuShaderDesc, Result, ShaderCodeSection, ShaderExtractionHooks};
5765/// struct MarkBody;
5766/// impl ShaderExtractionHooks for MarkBody {
5767///     fn code(&mut self, section: ShaderCodeSection, code: &str) -> Result<Option<String>> {
5768///         if section == ShaderCodeSection::Body {
5769///             Ok(Some(format!("// application hook\n{code}")))
5770///         } else {
5771///             Ok(None)
5772///         }
5773///     }
5774/// }
5775/// # fn extract(gpu: &GPUProcessor, template: &GpuShaderDesc) -> Result<()> {
5776/// let desc = gpu.try_extract_with_hooks(template, &mut MarkBody)?;
5777/// # let _ = desc;
5778/// # Ok(()) }
5779/// ```
5780pub trait ShaderExtractionHooks {
5781    /// Inspect a lifecycle event.
5782    fn lifecycle(&mut self, _event: ShaderLifecycle<'_>) -> Result<()> {
5783        Ok(())
5784    }
5785    /// Inspect a texture and optionally override its binding on OCIO 2.5+.
5786    fn texture(&mut self, _texture: ShaderTexture<'_>) -> Result<Option<u32>> {
5787        Ok(None)
5788    }
5789    /// Inspect a registered uniform.
5790    fn uniform(&mut self, _uniform: ShaderUniform<'_>) -> Result<()> {
5791        Ok(())
5792    }
5793    /// Return replacement code, or `None` to forward the original without copying.
5794    fn code(&mut self, _section: ShaderCodeSection, _code: &str) -> Result<Option<String>> {
5795        Ok(None)
5796    }
5797    /// Return replacement shader text, or `None` to use OCIO's native assembly.
5798    /// A replacement must include any required language-specific uniform block.
5799    fn assemble(&mut self, _parts: ShaderSections<'_>) -> Result<Option<String>> {
5800        Ok(None)
5801    }
5802}
5803
5804impl GPUProcessor {
5805    /// Extract through the native creator overload using shared ownership.
5806    /// OCIO may leave partially generated state on failure.
5807    pub fn try_extract_to_creator(&self, creator: &mut GpuShaderCreator<'_>) -> Result<()> {
5808        crate::clear_last_error();
5809        unsafe {
5810            ocio_sys::ocio_gpu_processor_extract_owned_creator(
5811                self.handle.as_ptr(),
5812                creator.handle.as_ptr(),
5813            )
5814        };
5815        crate::ocio_call_status()
5816    }
5817    /// Extract a fresh descriptor while assembling its shader text in Rust.
5818    ///
5819    /// The template supplies language, resource names, binding settings and
5820    /// texture preferences; existing template resources are not copied. OCIO
5821    /// retains ownership of resources and live dynamic properties in the result.
5822    /// The callback runs synchronously and must return the complete shader text.
5823    /// Callback errors and panics are returned as errors without crossing FFI.
5824    /// OCIO holds its GPU processor lock during the callback; do not reenter
5825    /// extraction on the same processor. For Vulkan, the callback must include
5826    /// any desired uniform-buffer wrapper around `parameters` itself.
5827    ///
5828    /// ```no_run
5829    /// # use ocio_rs::{GPUProcessor, GpuShaderDesc, Result};
5830    /// # fn example(gpu: &GPUProcessor, template: &GpuShaderDesc) -> Result<()> {
5831    /// let desc = gpu.try_extract_with_assembler(template, |parts| {
5832    ///     Ok(format!("// custom\n{}{}{}{}{}{}", parts.parameters, parts.textures,
5833    ///         parts.helpers, parts.header, parts.body, parts.footer))
5834    /// })?;
5835    /// assert!(desc.shader_text().unwrap().starts_with("// custom"));
5836    /// # Ok(())
5837    /// # }
5838    /// ```
5839    pub fn try_extract_with_assembler<F>(
5840        &self,
5841        template: &GpuShaderDesc,
5842        mut assemble: F,
5843    ) -> Result<GpuShaderDesc>
5844    where
5845        F: FnMut(ShaderSections<'_>) -> Result<String>,
5846    {
5847        self.try_extract_with_callbacks(
5848            template,
5849            false,
5850            None,
5851            None,
5852            &mut |_| Ok(ShaderUniformAction::StoreInDescriptor),
5853            false,
5854            |parts| assemble(parts).map(Some),
5855            |_| Ok(None),
5856            false,
5857            &mut |_| Ok(()),
5858            false,
5859            &mut |_| Ok(()),
5860            false,
5861            &mut |_, _| Ok(None),
5862            false,
5863            None,
5864        )
5865    }
5866
5867    /// Extract a shader with synchronous Rust assembly and texture callbacks.
5868    ///
5869    /// The texture callback receives a temporary borrow of each native LUT and
5870    /// may return `Some(binding)` to override OCIO's proposed binding on 2.5+.
5871    /// Return `None` to keep the native binding; OCIO 2.4 requires `None`.
5872    /// Binding zero and duplicate bindings are rejected. Callback errors and
5873    /// panics abort extraction, but external uploads already performed by the
5874    /// callback remain the caller's responsibility. Do not reenter extraction
5875    /// on this GPU processor from either callback.
5876    ///
5877    /// Borrowed texture values cannot escape the callback:
5878    ///
5879    /// ```compile_fail
5880    /// # use ocio_rs::{GPUProcessor, GpuShaderDesc};
5881    /// # fn example(gpu: &GPUProcessor, template: &GpuShaderDesc) {
5882    /// let mut saved = None;
5883    /// let _ = gpu.try_extract_with_texture_callback(template,
5884    ///     |_| Ok(String::new()), |texture| { saved = Some(texture.values); Ok(None) });
5885    /// println!("{:?}", saved);
5886    /// # }
5887    /// ```
5888    pub fn try_extract_with_texture_callback<F, G>(
5889        &self,
5890        template: &GpuShaderDesc,
5891        mut assemble: F,
5892        texture: G,
5893    ) -> Result<GpuShaderDesc>
5894    where
5895        F: FnMut(ShaderSections<'_>) -> Result<String>,
5896        G: FnMut(ShaderTexture<'_>) -> Result<Option<u32>>,
5897    {
5898        self.try_extract_with_callbacks(
5899            template,
5900            false,
5901            None,
5902            None,
5903            &mut |_| Ok(ShaderUniformAction::StoreInDescriptor),
5904            false,
5905            |parts| assemble(parts).map(Some),
5906            texture,
5907            true,
5908            &mut |_| Ok(()),
5909            false,
5910            &mut |_| Ok(()),
5911            false,
5912            &mut |_, _| Ok(None),
5913            false,
5914            None,
5915        )
5916    }
5917
5918    /// Extract with synchronous shader assembly, texture, and uniform callbacks.
5919    ///
5920    /// Uniform events are sent only for newly registered uniforms, before shader
5921    /// assembly. Use the reported index to query current dynamic values from the
5922    /// returned descriptor; OCIO retains the getters. Names are borrowed only
5923    /// for the callback. OCIO 2.4 does not expose vector maximum sizes or
5924    /// uniform-buffer offsets.
5925    /// Callback errors and panics abort extraction; already performed external
5926    /// resource allocations remain the caller's responsibility. Do not reenter
5927    /// extraction on this GPU processor from any callback.
5928    ///
5929    /// ```compile_fail
5930    /// # use ocio_rs::{GPUProcessor, GpuShaderDesc};
5931    /// # fn example(gpu: &GPUProcessor, desc: &GpuShaderDesc) {
5932    /// let mut saved = None;
5933    /// let _ = gpu.try_extract_with_resource_callbacks(desc, |_| Ok(String::new()),
5934    ///     |_| Ok(None), |uniform| { saved = Some(uniform.name); Ok(()) });
5935    /// println!("{:?}", saved);
5936    /// # }
5937    /// ```
5938    pub fn try_extract_with_resource_callbacks<F, G, H>(
5939        &self,
5940        template: &GpuShaderDesc,
5941        mut assemble: F,
5942        texture: G,
5943        mut uniform: H,
5944    ) -> Result<GpuShaderDesc>
5945    where
5946        F: FnMut(ShaderSections<'_>) -> Result<String>,
5947        G: FnMut(ShaderTexture<'_>) -> Result<Option<u32>>,
5948        H: FnMut(ShaderUniform<'_>) -> Result<()>,
5949    {
5950        self.try_extract_with_callbacks(
5951            template,
5952            false,
5953            None,
5954            None,
5955            &mut |_| Ok(ShaderUniformAction::StoreInDescriptor),
5956            false,
5957            |parts| assemble(parts).map(Some),
5958            texture,
5959            true,
5960            &mut uniform,
5961            true,
5962            &mut |_| Ok(()),
5963            false,
5964            &mut |_, _| Ok(None),
5965            false,
5966            None,
5967        )
5968    }
5969
5970    /// Extract with shader, texture, uniform, and creator-lifecycle callbacks.
5971    ///
5972    /// Events occur synchronously in OCIO order: `Begin`, zero or more
5973    /// resource callbacks, shader assembly, `Finalized`, then `End`. If an
5974    /// extraction callback fails after `Begin`, OCIO still calls `End`;
5975    /// an error from `Begin` itself does not trigger `End`. The first callback
5976    /// error is preserved if cleanup also fails. IDs are borrowed for the
5977    /// callback only. Do not reenter extraction on this processor.
5978    ///
5979    /// ```compile_fail
5980    /// # use ocio_rs::{GPUProcessor, GpuShaderDesc, ShaderLifecycle};
5981    /// # fn example(gpu: &GPUProcessor, desc: &GpuShaderDesc) {
5982    /// let mut saved = None;
5983    /// let _ = gpu.try_extract_with_lifecycle_callbacks(desc, |_| Ok(String::new()),
5984    ///     |_| Ok(None), |_| Ok(()), |event| {
5985    ///         if let ShaderLifecycle::Begin { unique_id } = event { saved = Some(unique_id); }
5986    ///         Ok(())
5987    ///     });
5988    /// println!("{:?}", saved);
5989    /// # }
5990    /// ```
5991    pub fn try_extract_with_lifecycle_callbacks<F, G, H, L>(
5992        &self,
5993        template: &GpuShaderDesc,
5994        mut assemble: F,
5995        texture: G,
5996        mut uniform: H,
5997        mut lifecycle: L,
5998    ) -> Result<GpuShaderDesc>
5999    where
6000        F: FnMut(ShaderSections<'_>) -> Result<String>,
6001        G: FnMut(ShaderTexture<'_>) -> Result<Option<u32>>,
6002        H: FnMut(ShaderUniform<'_>) -> Result<()>,
6003        L: FnMut(ShaderLifecycle<'_>) -> Result<()>,
6004    {
6005        self.try_extract_with_callbacks(
6006            template,
6007            false,
6008            None,
6009            None,
6010            &mut |_| Ok(ShaderUniformAction::StoreInDescriptor),
6011            false,
6012            |parts| assemble(parts).map(Some),
6013            texture,
6014            true,
6015            &mut uniform,
6016            true,
6017            &mut lifecycle,
6018            true,
6019            &mut |_, _| Ok(None),
6020            false,
6021            None,
6022        )
6023    }
6024
6025    /// Extract using a single hooks object for code, resources, and lifecycle.
6026    ///
6027    /// Events are synchronous; callback errors and panics abort extraction and
6028    /// any already-created external resources remain the caller's responsibility.
6029    /// On OCIO 2.4 declaration events are combined into `Declarations`.
6030    pub fn try_extract_with_hooks<H: ShaderExtractionHooks>(
6031        &self,
6032        template: &GpuShaderDesc,
6033        hooks: &mut H,
6034    ) -> Result<GpuShaderDesc> {
6035        let hooks = std::cell::RefCell::new(hooks);
6036        self.try_extract_with_callbacks(
6037            template,
6038            false,
6039            None,
6040            None,
6041            &mut |_| Ok(ShaderUniformAction::StoreInDescriptor),
6042            false,
6043            |parts| hooks.borrow_mut().assemble(parts),
6044            |texture| hooks.borrow_mut().texture(texture),
6045            true,
6046            &mut |uniform| hooks.borrow_mut().uniform(uniform),
6047            true,
6048            &mut |event| hooks.borrow_mut().lifecycle(event),
6049            true,
6050            &mut |section, code| hooks.borrow_mut().code(section, code),
6051            true,
6052            None,
6053        )
6054    }
6055
6056    /// Extract using hooks while streaming texture data directly to the caller.
6057    ///
6058    /// The required texture sink must upload or copy the borrowed data before it
6059    /// returns; the returned descriptor does not retain or report these
6060    /// textures. Uniforms and shader text remain available on the descriptor.
6061    /// On failure, cleanup of any resources created by hooks is the caller's
6062    /// responsibility. The hooks object's `texture` method is not called;
6063    /// binding overrides come from the supplied sink.
6064    ///
6065    /// ```compile_fail
6066    /// # use ocio_rs::{GPUProcessor, GpuShaderDesc, ShaderExtractionHooks};
6067    /// # struct Hooks;
6068    /// # impl ShaderExtractionHooks for Hooks {}
6069    /// # fn example(gpu: &GPUProcessor, desc: &GpuShaderDesc) {
6070    /// let mut saved = None;
6071    /// let _ = gpu.try_extract_with_streamed_textures(desc, &mut Hooks, |texture| {
6072    ///     saved = Some(texture.values);
6073    ///     Ok(None)
6074    /// });
6075    /// println!("{saved:?}");
6076    /// # }
6077    /// ```
6078    pub fn try_extract_with_streamed_textures<H, T>(
6079        &self,
6080        template: &GpuShaderDesc,
6081        hooks: &mut H,
6082        texture: T,
6083    ) -> Result<GpuShaderDesc>
6084    where
6085        H: ShaderExtractionHooks,
6086        T: FnMut(ShaderTexture<'_>) -> Result<Option<u32>>,
6087    {
6088        let hooks = std::cell::RefCell::new(hooks);
6089        self.try_extract_with_callbacks(
6090            template,
6091            true,
6092            None,
6093            None,
6094            &mut |_| Ok(ShaderUniformAction::StoreInDescriptor),
6095            false,
6096            |parts| hooks.borrow_mut().assemble(parts),
6097            texture,
6098            true,
6099            &mut |uniform| hooks.borrow_mut().uniform(uniform),
6100            true,
6101            &mut |event| hooks.borrow_mut().lifecycle(event),
6102            true,
6103            &mut |section, code| hooks.borrow_mut().code(section, code),
6104            true,
6105            None,
6106        )
6107    }
6108
6109    /// Extract using hooks that control native uniform registration.
6110    ///
6111    /// External uniforms are not included in the descriptor's uniform list or
6112    /// buffer offsets. The caller must retain their getters and manage storage,
6113    /// layout and cleanup. Callback errors and panics abort extraction; owned
6114    /// getters already transferred to the caller remain usable. Do not reenter
6115    /// extraction on the same GPU processor from a callback.
6116    pub fn try_extract_with_uniform_control<H: ShaderUniformControl>(
6117        &self,
6118        template: &GpuShaderDesc,
6119        hooks: &mut H,
6120    ) -> Result<GpuShaderDesc> {
6121        let hooks = std::cell::RefCell::new(hooks);
6122        let mut registration = |uniform| hooks.borrow_mut().register_uniform(uniform);
6123        self.try_extract_with_callbacks(
6124            template,
6125            false,
6126            None,
6127            None,
6128            &mut registration,
6129            true,
6130            |parts| hooks.borrow_mut().assemble(parts),
6131            |texture| hooks.borrow_mut().texture(texture),
6132            true,
6133            &mut |uniform| hooks.borrow_mut().uniform(uniform),
6134            true,
6135            &mut |event| hooks.borrow_mut().lifecycle(event),
6136            true,
6137            &mut |section, code| hooks.borrow_mut().code(section, code),
6138            true,
6139            None,
6140        )
6141    }
6142
6143    /// Control uniform registration and stream textures in the same extraction.
6144    ///
6145    /// External uniforms and streamed textures are not enumerated by the
6146    /// returned descriptor. The sink must copy or upload each texture before
6147    /// returning, and retained uniform getters keep their native owner alive.
6148    /// As with [`Self::try_extract_with_streamed_textures`], the hooks object's
6149    /// texture method is not called. Callers own cleanup on failure.
6150    pub fn try_extract_with_uniform_control_and_streamed_textures<H, T>(
6151        &self,
6152        template: &GpuShaderDesc,
6153        hooks: &mut H,
6154        texture: T,
6155    ) -> Result<GpuShaderDesc>
6156    where
6157        H: ShaderUniformControl,
6158        T: FnMut(ShaderTexture<'_>) -> Result<Option<u32>>,
6159    {
6160        let hooks = std::cell::RefCell::new(hooks);
6161        let mut registration = |uniform| hooks.borrow_mut().register_uniform(uniform);
6162        self.try_extract_with_callbacks(
6163            template,
6164            true,
6165            None,
6166            None,
6167            &mut registration,
6168            true,
6169            |parts| hooks.borrow_mut().assemble(parts),
6170            texture,
6171            true,
6172            &mut |uniform| hooks.borrow_mut().uniform(uniform),
6173            true,
6174            &mut |event| hooks.borrow_mut().lifecycle(event),
6175            true,
6176            &mut |section, code| hooks.borrow_mut().code(section, code),
6177            true,
6178            None,
6179        )
6180    }
6181
6182    /// Extract with custom registration, texture handling and creator options.
6183    ///
6184    /// The texture callback receives each LUT synchronously whether or not
6185    /// streaming is selected. In streaming mode it must copy or upload the
6186    /// borrowed data before returning. A custom cache ID remains in effect on
6187    /// the returned descriptor; see [`ShaderCreatorOptions`] for invalidation
6188    /// responsibility. Callback and external resource cleanup rules are the same
6189    /// as [`Self::try_extract_with_uniform_control_and_streamed_textures`].
6190    pub fn try_extract_with_creator_options<H, T>(
6191        &self,
6192        template: &GpuShaderDesc,
6193        hooks: &mut H,
6194        options: ShaderCreatorOptions<'_>,
6195        texture: T,
6196    ) -> Result<GpuShaderDesc>
6197    where
6198        H: ShaderUniformControl,
6199        T: FnMut(ShaderTexture<'_>) -> Result<Option<u32>>,
6200    {
6201        let hooks = std::cell::RefCell::new(hooks);
6202        let mut registration = |uniform| hooks.borrow_mut().register_uniform(uniform);
6203        self.try_extract_with_callbacks(
6204            template,
6205            options.stream_textures,
6206            None,
6207            options.cache_id_override,
6208            &mut registration,
6209            true,
6210            |parts| hooks.borrow_mut().assemble(parts),
6211            texture,
6212            true,
6213            &mut |uniform| hooks.borrow_mut().uniform(uniform),
6214            true,
6215            &mut |event| hooks.borrow_mut().lifecycle(event),
6216            true,
6217            &mut |section, code| hooks.borrow_mut().code(section, code),
6218            true,
6219            None,
6220        )
6221    }
6222
6223    /// Choose storage separately for each texture and control uniform registration.
6224    ///
6225    /// External textures are not returned by the descriptor; their data must be
6226    /// copied or uploaded before the callback returns. On 2.5+, bindings are
6227    /// shared across all texture types, including external textures. A binding
6228    /// override is not supported on 2.4. Callback errors and panics abort
6229    /// extraction; external resources already created remain the caller's responsibility.
6230    /// The hooks object's `texture` method is not called. Do not reenter extraction.
6231    pub fn try_extract_with_texture_control<H, T>(
6232        &self,
6233        template: &GpuShaderDesc,
6234        hooks: &mut H,
6235        cache_id_override: Option<&std::ffi::CStr>,
6236        mut texture: T,
6237    ) -> Result<GpuShaderDesc>
6238    where
6239        H: ShaderUniformControl,
6240        T: FnMut(ShaderTexture<'_>) -> Result<ShaderTextureAction>,
6241    {
6242        let hooks = std::cell::RefCell::new(hooks);
6243        let storage = std::cell::Cell::new(true);
6244        let mut registration = |uniform| hooks.borrow_mut().register_uniform(uniform);
6245        self.try_extract_with_callbacks(
6246            template,
6247            false,
6248            Some(&storage),
6249            cache_id_override,
6250            &mut registration,
6251            true,
6252            |parts| hooks.borrow_mut().assemble(parts),
6253            |event| match texture(event)? {
6254                ShaderTextureAction::StoreInDescriptor { binding } => {
6255                    storage.set(true);
6256                    Ok(binding)
6257                }
6258                ShaderTextureAction::External { binding } => {
6259                    storage.set(false);
6260                    Ok(binding)
6261                }
6262            },
6263            true,
6264            &mut |uniform| hooks.borrow_mut().uniform(uniform),
6265            true,
6266            &mut |event| hooks.borrow_mut().lifecycle(event),
6267            true,
6268            &mut |section, code| hooks.borrow_mut().code(section, code),
6269            true,
6270            None,
6271        )
6272    }
6273
6274    /// Extract with independent texture/uniform storage and optional custom finalization.
6275    ///
6276    /// A custom finalizer receives control before OCIO performs its language
6277    /// wrapping. It must return a complete shader, including any required
6278    /// declarations and language-specific wrappers. Returning `None` delegates
6279    /// finalization and assembly to the ordinary native path. This control is
6280    /// scoped to the extraction and is not retained by the returned descriptor.
6281    /// Finalizer errors
6282    /// and panics abort extraction; already-created external resources remain
6283    /// the caller's responsibility. Do not reenter extraction from callbacks.
6284    pub fn try_extract_with_finalize_control<H, T>(
6285        &self,
6286        template: &GpuShaderDesc,
6287        hooks: &mut H,
6288        cache_id_override: Option<&std::ffi::CStr>,
6289        mut texture: T,
6290    ) -> Result<GpuShaderDesc>
6291    where
6292        H: ShaderFinalizeControl,
6293        T: FnMut(ShaderTexture<'_>) -> Result<ShaderTextureAction>,
6294    {
6295        let hooks = std::cell::RefCell::new(hooks);
6296        let storage = std::cell::Cell::new(true);
6297        let mut registration = |uniform| hooks.borrow_mut().register_uniform(uniform);
6298        let mut finalizer = || hooks.borrow_mut().finalize_shader();
6299        self.try_extract_with_callbacks(
6300            template,
6301            false,
6302            Some(&storage),
6303            cache_id_override,
6304            &mut registration,
6305            true,
6306            |parts| hooks.borrow_mut().assemble(parts),
6307            |event| match texture(event)? {
6308                ShaderTextureAction::StoreInDescriptor { binding } => {
6309                    storage.set(true);
6310                    Ok(binding)
6311                }
6312                ShaderTextureAction::External { binding } => {
6313                    storage.set(false);
6314                    Ok(binding)
6315                }
6316            },
6317            true,
6318            &mut |uniform| hooks.borrow_mut().uniform(uniform),
6319            true,
6320            &mut |event| hooks.borrow_mut().lifecycle(event),
6321            true,
6322            &mut |section, code| hooks.borrow_mut().code(section, code),
6323            true,
6324            Some(&mut finalizer),
6325        )
6326    }
6327
6328    /// Extract with independently controlled texture policy, resource storage,
6329    /// uniforms and finalization. Policy callbacks are synchronous and detached
6330    /// on every return path. Do not reenter the same processor from callbacks.
6331    ///
6332    /// The native width getter is `noexcept`: on a callback failure or panic,
6333    /// extraction uses a conservative temporary fallback and then returns the
6334    /// original error. Other callbacks and external uploads may have occurred
6335    /// before failure and their cleanup remains the caller's responsibility.
6336    /// Policy values may vary during extraction, so a template-only layout probe
6337    /// cannot prove them safe; consider [`Self::try_extract_with_texture_policy_checked`].
6338    /// `cache_id` must be nonempty and uniquely represent the policy and output;
6339    /// update it whenever they change to avoid native resource-key collisions.
6340    pub fn try_extract_with_texture_policy<H, P, T>(
6341        &self,
6342        template: &GpuShaderDesc,
6343        hooks: &mut H,
6344        policy: &mut P,
6345        cache_id: &std::ffi::CStr,
6346        mut texture: T,
6347    ) -> Result<GpuShaderDesc>
6348    where
6349        H: ShaderFinalizeControl + ?Sized,
6350        P: ShaderTexturePolicy + ?Sized,
6351        T: FnMut(ShaderTexture<'_>) -> Result<ShaderTextureAction>,
6352    {
6353        if cache_id.to_bytes().is_empty() {
6354            return Err(OcioError::InvalidInput(
6355                "texture policy requires a nonempty cache ID".into(),
6356            ));
6357        }
6358        let hooks = std::cell::RefCell::new(hooks);
6359        let storage = std::cell::Cell::new(true);
6360        let mut registration = |uniform| hooks.borrow_mut().register_uniform(uniform);
6361        let mut finalizer = || hooks.borrow_mut().finalize_shader();
6362        let mut query = |kind, input| match kind {
6363            0 => policy.texture_max_width(),
6364            1 => policy.allow_texture_1d().map(u32::from),
6365            2 => policy.set_texture_max_width(input).map(|()| input),
6366            3 => policy.set_allow_texture_1d(input != 0).map(|()| input),
6367            _ => Err(OcioError::InvalidInput(
6368                "invalid texture policy query".into(),
6369            )),
6370        };
6371        self.try_extract_with_callbacks_and_policy(
6372            template,
6373            false,
6374            Some(&storage),
6375            Some(cache_id),
6376            &mut registration,
6377            true,
6378            |parts| hooks.borrow_mut().assemble(parts),
6379            |event| match texture(event)? {
6380                ShaderTextureAction::StoreInDescriptor { binding } => {
6381                    storage.set(true);
6382                    Ok(binding)
6383                }
6384                ShaderTextureAction::External { binding } => {
6385                    storage.set(false);
6386                    Ok(binding)
6387                }
6388            },
6389            true,
6390            &mut |uniform| hooks.borrow_mut().uniform(uniform),
6391            true,
6392            &mut |event| hooks.borrow_mut().lifecycle(event),
6393            true,
6394            &mut |section, code| hooks.borrow_mut().code(section, code),
6395            true,
6396            Some(&mut finalizer),
6397            Some(&mut query),
6398        )
6399    }
6400
6401    /// Conservatively probe optimized texture lengths, then validate every
6402    /// width returned by `policy` against every probed length before OCIO uses it.
6403    ///
6404    /// This generates the shader twice and may reject non-LUT 1D/2D resources.
6405    /// It relies on the native 2.4–2.6 LUT length limit and does not validate
6406    /// newer versions or arbitrary native creators. The processor and any state
6407    /// capable of changing generated resources must remain unchanged across the
6408    /// probe and actual extraction, including inside user callbacks. External
6409    /// resources created before a later policy error remain caller-owned.
6410    /// `cache_id` has the same requirements as on
6411    /// [`Self::try_extract_with_texture_policy`].
6412    pub fn try_extract_with_texture_policy_checked<H, P, T>(
6413        &self,
6414        template: &GpuShaderDesc,
6415        hooks: &mut H,
6416        policy: &mut P,
6417        cache_id: &std::ffi::CStr,
6418        texture: T,
6419    ) -> Result<GpuShaderDesc>
6420    where
6421        H: ShaderFinalizeControl + ?Sized,
6422        P: ShaderTexturePolicy + ?Sized,
6423        T: FnMut(ShaderTexture<'_>) -> Result<ShaderTextureAction>,
6424    {
6425        struct CheckedPolicy<'a, P: ?Sized> {
6426            policy: &'a mut P,
6427            lengths: &'a [usize],
6428        }
6429        impl<P: ShaderTexturePolicy + ?Sized> ShaderTexturePolicy for CheckedPolicy<'_, P> {
6430            fn set_texture_max_width(&mut self, width: u32) -> Result<()> {
6431                self.policy.set_texture_max_width(width)
6432            }
6433            fn set_allow_texture_1d(&mut self, allowed: bool) -> Result<()> {
6434                self.policy.set_allow_texture_1d(allowed)
6435            }
6436            fn texture_max_width(&mut self) -> Result<u32> {
6437                let width = self.policy.texture_max_width()?;
6438                if width < 2 {
6439                    return Err(OcioError::InvalidInput(
6440                        "texture maximum width must be at least 2".into(),
6441                    ));
6442                }
6443                for &length in self.lengths {
6444                    GpuShaderDesc::validate_lut_texture_width(width, length)?;
6445                }
6446                Ok(width)
6447            }
6448            fn allow_texture_1d(&mut self) -> Result<bool> {
6449                self.policy.allow_texture_1d()
6450            }
6451        }
6452        if cache_id.to_bytes().is_empty() {
6453            return Err(OcioError::InvalidInput(
6454                "texture policy requires a nonempty cache ID".into(),
6455            ));
6456        }
6457        let (lengths, _) = self.probe_shader_texture_lengths(template)?;
6458        let mut checked = CheckedPolicy {
6459            policy,
6460            lengths: &lengths,
6461        };
6462        self.try_extract_with_texture_policy(template, hooks, &mut checked, cache_id, texture)
6463    }
6464
6465    #[allow(clippy::too_many_arguments)]
6466    fn try_extract_with_callbacks<F, G>(
6467        &self,
6468        template: &GpuShaderDesc,
6469        stream_textures: bool,
6470        texture_storage: Option<&std::cell::Cell<bool>>,
6471        cache_id_override: Option<&std::ffi::CStr>,
6472        registration: &mut dyn FnMut(ShaderUniformRegistration) -> Result<ShaderUniformAction>,
6473        has_registration: bool,
6474        assemble: F,
6475        texture: G,
6476        notify_texture: bool,
6477        uniform: &mut dyn FnMut(ShaderUniform<'_>) -> Result<()>,
6478        notify_uniform: bool,
6479        lifecycle: &mut dyn FnMut(ShaderLifecycle<'_>) -> Result<()>,
6480        notify_lifecycle: bool,
6481        code: &mut dyn FnMut(ShaderCodeSection, &str) -> Result<Option<String>>,
6482        notify_code: bool,
6483        finalizer: Option<&mut dyn FnMut() -> Result<Option<String>>>,
6484    ) -> Result<GpuShaderDesc>
6485    where
6486        F: FnMut(ShaderSections<'_>) -> Result<Option<String>>,
6487        G: FnMut(ShaderTexture<'_>) -> Result<Option<u32>>,
6488    {
6489        self.try_extract_with_callbacks_and_policy(
6490            template,
6491            stream_textures,
6492            texture_storage,
6493            cache_id_override,
6494            registration,
6495            has_registration,
6496            assemble,
6497            texture,
6498            notify_texture,
6499            uniform,
6500            notify_uniform,
6501            lifecycle,
6502            notify_lifecycle,
6503            code,
6504            notify_code,
6505            finalizer,
6506            None,
6507        )
6508    }
6509
6510    #[allow(clippy::too_many_arguments)]
6511    fn try_extract_with_callbacks_and_policy<F, G>(
6512        &self,
6513        template: &GpuShaderDesc,
6514        stream_textures: bool,
6515        texture_storage: Option<&std::cell::Cell<bool>>,
6516        cache_id_override: Option<&std::ffi::CStr>,
6517        registration: &mut dyn FnMut(ShaderUniformRegistration) -> Result<ShaderUniformAction>,
6518        has_registration: bool,
6519        mut assemble: F,
6520        mut texture: G,
6521        notify_texture: bool,
6522        uniform: &mut dyn FnMut(ShaderUniform<'_>) -> Result<()>,
6523        notify_uniform: bool,
6524        lifecycle: &mut dyn FnMut(ShaderLifecycle<'_>) -> Result<()>,
6525        notify_lifecycle: bool,
6526        code: &mut dyn FnMut(ShaderCodeSection, &str) -> Result<Option<String>>,
6527        notify_code: bool,
6528        mut finalizer: Option<&mut dyn FnMut() -> Result<Option<String>>>,
6529        mut policy: Option<&mut dyn FnMut(i32, u32) -> Result<u32>>,
6530    ) -> Result<GpuShaderDesc>
6531    where
6532        F: FnMut(ShaderSections<'_>) -> Result<Option<String>>,
6533        G: FnMut(ShaderTexture<'_>) -> Result<Option<u32>>,
6534    {
6535        struct State<'a, F, G> {
6536            function: &'a mut F,
6537            texture: &'a mut G,
6538            texture_storage: Option<&'a std::cell::Cell<bool>>,
6539            uniform: &'a mut dyn FnMut(ShaderUniform<'_>) -> Result<()>,
6540            lifecycle: &'a mut dyn FnMut(ShaderLifecycle<'_>) -> Result<()>,
6541            code: &'a mut dyn FnMut(ShaderCodeSection, &str) -> Result<Option<String>>,
6542            registration:
6543                &'a mut dyn FnMut(ShaderUniformRegistration) -> Result<ShaderUniformAction>,
6544            finalizer: Option<&'a mut dyn FnMut() -> Result<Option<String>>>,
6545            policy: Option<&'a mut dyn FnMut(i32, u32) -> Result<u32>>,
6546            output: Option<std::ffi::CString>,
6547            code_output: Option<std::ffi::CString>,
6548            finalizer_output: Option<std::ffi::CString>,
6549            error: Option<OcioError>,
6550        }
6551        unsafe extern "C" fn policy_callback<F, G>(
6552            context: *mut c_void,
6553            kind: i32,
6554            value: *mut u32,
6555        ) -> bool
6556        where
6557            F: FnMut(ShaderSections<'_>) -> Result<Option<String>>,
6558            G: FnMut(ShaderTexture<'_>) -> Result<Option<u32>>,
6559        {
6560            let state = unsafe { &mut *context.cast::<State<'_, F, G>>() };
6561            if state.error.is_some() {
6562                return false;
6563            }
6564            let result =
6565                crate::catch_callback_unwind(std::panic::AssertUnwindSafe(|| -> Result<u32> {
6566                    if value.is_null() || !(0..=3).contains(&kind) {
6567                        return Err(OcioError::InvalidInput(
6568                            "invalid texture policy event".into(),
6569                        ));
6570                    }
6571                    let policy = state
6572                        .policy
6573                        .as_mut()
6574                        .ok_or_else(|| OcioError::InvalidInput("missing texture policy".into()))?;
6575                    let input = unsafe { *value };
6576                    if kind == 3 && input > 1 {
6577                        return Err(OcioError::InvalidInput(
6578                            "invalid texture policy setter value".into(),
6579                        ));
6580                    }
6581                    let result = policy(kind, input)?;
6582                    if (kind == 0 && result < 2) || (kind == 1 && result > 1) {
6583                        return Err(OcioError::InvalidInput(
6584                            "invalid texture policy value".into(),
6585                        ));
6586                    }
6587                    Ok(result)
6588                }));
6589            match result {
6590                Ok(Ok(result)) => {
6591                    unsafe { *value = result };
6592                    true
6593                }
6594                Ok(Err(error)) => {
6595                    state.error.get_or_insert(error);
6596                    false
6597                }
6598                Err(_) => {
6599                    state.error.get_or_insert_with(|| {
6600                        OcioError::InvalidInput("texture policy callback panicked".into())
6601                    });
6602                    false
6603                }
6604            }
6605        }
6606        unsafe extern "C" fn finalize_callback<F, G>(
6607            context: *mut c_void,
6608            output: *mut *const i8,
6609        ) -> bool
6610        where
6611            F: FnMut(ShaderSections<'_>) -> Result<Option<String>>,
6612            G: FnMut(ShaderTexture<'_>) -> Result<Option<u32>>,
6613        {
6614            let state = unsafe { &mut *context.cast::<State<'_, F, G>>() };
6615            let result = crate::catch_callback_unwind(std::panic::AssertUnwindSafe(
6616                || -> Result<Option<std::ffi::CString>> {
6617                    if output.is_null() {
6618                        return Err(OcioError::InvalidInput(
6619                            "null shader finalizer output".into(),
6620                        ));
6621                    }
6622                    state.finalizer.as_mut().ok_or_else(|| {
6623                        OcioError::InvalidInput("missing shader finalizer".into())
6624                    })?()?
6625                    .map(std::ffi::CString::new)
6626                    .transpose()
6627                    .map_err(|_| OcioError::InteriorNul)
6628                },
6629            ));
6630            match result {
6631                Ok(Ok(value)) => {
6632                    state.finalizer_output = value;
6633                    unsafe {
6634                        *output = state
6635                            .finalizer_output
6636                            .as_ref()
6637                            .map_or(std::ptr::null(), |s| s.as_ptr());
6638                    }
6639                    true
6640                }
6641                Ok(Err(error)) => {
6642                    state.error.get_or_insert(error);
6643                    false
6644                }
6645                Err(_) => {
6646                    state.error.get_or_insert_with(|| {
6647                        OcioError::InvalidInput("shader finalizer panicked".into())
6648                    });
6649                    false
6650                }
6651            }
6652        }
6653        unsafe extern "C" fn code_callback<F, G>(
6654            context: *mut c_void,
6655            section: i32,
6656            code: *const i8,
6657            replacement: *mut *const i8,
6658        ) -> bool
6659        where
6660            F: FnMut(ShaderSections<'_>) -> Result<Option<String>>,
6661            G: FnMut(ShaderTexture<'_>) -> Result<Option<u32>>,
6662        {
6663            let state = unsafe { &mut *context.cast::<State<'_, F, G>>() };
6664            let result = crate::catch_callback_unwind(std::panic::AssertUnwindSafe(
6665                || -> Result<Option<std::ffi::CString>> {
6666                    let section = match section {
6667                        0 => ShaderCodeSection::Declarations,
6668                        1 => ShaderCodeSection::Parameters,
6669                        2 => ShaderCodeSection::Textures,
6670                        3 => ShaderCodeSection::Helpers,
6671                        4 => ShaderCodeSection::Header,
6672                        5 => ShaderCodeSection::Body,
6673                        6 => ShaderCodeSection::Footer,
6674                        _ => {
6675                            return Err(OcioError::InvalidInput(
6676                                "invalid shader code section".into(),
6677                            ))
6678                        }
6679                    };
6680                    if code.is_null() || replacement.is_null() {
6681                        return Err(OcioError::InvalidInput("null shader code event".into()));
6682                    }
6683                    let code = unsafe { std::ffi::CStr::from_ptr(code) }
6684                        .to_str()
6685                        .map_err(|_| OcioError::InvalidInput("shader code is not UTF-8".into()))?;
6686                    (state.code)(section, code)?
6687                        .map(std::ffi::CString::new)
6688                        .transpose()
6689                        .map_err(|_| OcioError::InteriorNul)
6690                },
6691            ));
6692            match result {
6693                Ok(Ok(value)) => {
6694                    state.code_output = value;
6695                    unsafe {
6696                        *replacement = state
6697                            .code_output
6698                            .as_ref()
6699                            .map_or(std::ptr::null(), |s| s.as_ptr());
6700                    }
6701                    true
6702                }
6703                Ok(Err(error)) => {
6704                    state.error.get_or_insert(error);
6705                    false
6706                }
6707                Err(_) => {
6708                    state.error.get_or_insert_with(|| {
6709                        OcioError::InvalidInput("shader code callback panicked".into())
6710                    });
6711                    false
6712                }
6713            }
6714        }
6715        unsafe extern "C" fn lifecycle_callback<F, G>(
6716            context: *mut c_void,
6717            event: i32,
6718            uid: *const i8,
6719        ) -> bool
6720        where
6721            F: FnMut(ShaderSections<'_>) -> Result<Option<String>>,
6722            G: FnMut(ShaderTexture<'_>) -> Result<Option<u32>>,
6723        {
6724            let state = unsafe { &mut *context.cast::<State<'_, F, G>>() };
6725            let result =
6726                crate::catch_callback_unwind(std::panic::AssertUnwindSafe(|| -> Result<()> {
6727                    let event = match event {
6728                        0 if !uid.is_null() => ShaderLifecycle::Begin {
6729                            unique_id: unsafe { std::ffi::CStr::from_ptr(uid) }.to_str().map_err(
6730                                |_| {
6731                                    OcioError::InvalidInput("shader identifier is not UTF-8".into())
6732                                },
6733                            )?,
6734                        },
6735                        1 => ShaderLifecycle::Finalized,
6736                        2 => ShaderLifecycle::End,
6737                        _ => {
6738                            return Err(OcioError::InvalidInput(
6739                                "invalid shader lifecycle event".into(),
6740                            ))
6741                        }
6742                    };
6743                    (state.lifecycle)(event)
6744                }));
6745            match result {
6746                Ok(Ok(())) => true,
6747                Ok(Err(error)) => {
6748                    state.error.get_or_insert(error);
6749                    false
6750                }
6751                Err(_) => {
6752                    state.error.get_or_insert_with(|| {
6753                        OcioError::InvalidInput("shader lifecycle callback panicked".into())
6754                    });
6755                    false
6756                }
6757            }
6758        }
6759        unsafe extern "C" fn uniform_callback<F, G>(
6760            context: *mut c_void,
6761            name: *const i8,
6762            uniform_type: i32,
6763            index: u32,
6764            has_max_size: bool,
6765            max_size: u32,
6766            has_buffer_offset: bool,
6767            buffer_offset: usize,
6768        ) -> bool
6769        where
6770            F: FnMut(ShaderSections<'_>) -> Result<Option<String>>,
6771            G: FnMut(ShaderTexture<'_>) -> Result<Option<u32>>,
6772        {
6773            let state = unsafe { &mut *context.cast::<State<'_, F, G>>() };
6774            let result =
6775                crate::catch_callback_unwind(std::panic::AssertUnwindSafe(|| -> Result<()> {
6776                    if name.is_null() || !(0..=4).contains(&uniform_type) {
6777                        return Err(OcioError::InvalidInput("invalid uniform event".into()));
6778                    }
6779                    let name = unsafe { std::ffi::CStr::from_ptr(name) }
6780                        .to_str()
6781                        .map_err(|_| OcioError::InvalidInput("uniform name is not UTF-8".into()))?;
6782                    (state.uniform)(ShaderUniform {
6783                        name,
6784                        uniform_type: GpuUniformType::from_raw(uniform_type),
6785                        index,
6786                        max_size: has_max_size.then_some(max_size),
6787                        buffer_offset: has_buffer_offset.then_some(buffer_offset),
6788                    })
6789                }));
6790            match result {
6791                Ok(Ok(())) => true,
6792                Ok(Err(error)) => {
6793                    state.error.get_or_insert(error);
6794                    false
6795                }
6796                Err(_) => {
6797                    state.error.get_or_insert(OcioError::InvalidInput(
6798                        "shader uniform callback panicked".into(),
6799                    ));
6800                    false
6801                }
6802            }
6803        }
6804        unsafe extern "C" fn callback<F, G>(
6805            context: *mut c_void,
6806            p: *const i8,
6807            t: *const i8,
6808            h: *const i8,
6809            head: *const i8,
6810            body: *const i8,
6811            foot: *const i8,
6812            output_ptr: *mut *const i8,
6813        ) -> bool
6814        where
6815            F: FnMut(ShaderSections<'_>) -> Result<Option<String>>,
6816            G: FnMut(ShaderTexture<'_>) -> Result<Option<u32>>,
6817        {
6818            let state = unsafe { &mut *context.cast::<State<'_, F, G>>() };
6819            let result = crate::catch_callback_unwind(std::panic::AssertUnwindSafe(
6820                || -> Result<Option<std::ffi::CString>> {
6821                    let read = |ptr: *const i8| -> Result<&str> {
6822                        if ptr.is_null() {
6823                            return Err(OcioError::InvalidInput("null shader section".into()));
6824                        }
6825                        unsafe { std::ffi::CStr::from_ptr(ptr) }
6826                            .to_str()
6827                            .map_err(|_| {
6828                                OcioError::InvalidInput("shader section is not UTF-8".into())
6829                            })
6830                    };
6831                    let text = (state.function)(ShaderSections {
6832                        parameters: read(p)?,
6833                        textures: read(t)?,
6834                        helpers: read(h)?,
6835                        header: read(head)?,
6836                        body: read(body)?,
6837                        footer: read(foot)?,
6838                    })?;
6839                    text.map(|text| {
6840                        std::ffi::CString::new(text).map_err(|_| {
6841                            OcioError::InvalidInput("assembled shader contains a NUL byte".into())
6842                        })
6843                    })
6844                    .transpose()
6845                },
6846            ));
6847            match result {
6848                Ok(Ok(output)) => {
6849                    state.output = output;
6850                    unsafe {
6851                        *output_ptr = state
6852                            .output
6853                            .as_ref()
6854                            .map_or(std::ptr::null(), |text| text.as_ptr())
6855                    };
6856                    true
6857                }
6858                Ok(Err(error)) => {
6859                    state.error.get_or_insert(error);
6860                    false
6861                }
6862                Err(_) => {
6863                    state
6864                        .error
6865                        .get_or_insert(OcioError::InvalidInput("shader assembler panicked".into()));
6866                    false
6867                }
6868            }
6869        }
6870        unsafe extern "C" fn texture_callback<F, G>(
6871            context: *mut c_void,
6872            event: *const ocio_sys::OcioShaderTextureEvent,
6873            replace: *mut bool,
6874            binding: *mut u32,
6875        ) -> bool
6876        where
6877            F: FnMut(ShaderSections<'_>) -> Result<Option<String>>,
6878            G: FnMut(ShaderTexture<'_>) -> Result<Option<u32>>,
6879        {
6880            let state = unsafe { &mut *context.cast::<State<'_, F, G>>() };
6881            let result = crate::catch_callback_unwind(std::panic::AssertUnwindSafe(
6882                || -> Result<Option<u32>> {
6883                    let event = unsafe { event.as_ref() }
6884                        .ok_or_else(|| OcioError::InvalidInput("null texture event".into()))?;
6885                    (state.texture)(unsafe { shader_texture_from_event(event)? })
6886                },
6887            ));
6888            match result {
6889                Ok(Ok(value)) => {
6890                    if let Some(value) = value {
6891                        unsafe {
6892                            *replace = true;
6893                            *binding = value;
6894                        }
6895                    }
6896                    true
6897                }
6898                Ok(Err(error)) => {
6899                    state.error.get_or_insert(error);
6900                    false
6901                }
6902                Err(_) => {
6903                    state.error.get_or_insert(OcioError::InvalidInput(
6904                        "shader texture callback panicked".into(),
6905                    ));
6906                    false
6907                }
6908            }
6909        }
6910        unsafe extern "C" fn texture_control_callback<F, G>(
6911            context: *mut c_void,
6912            event: *const ocio_sys::OcioShaderTextureEvent,
6913            store: *mut bool,
6914            replace: *mut bool,
6915            binding: *mut u32,
6916        ) -> bool
6917        where
6918            F: FnMut(ShaderSections<'_>) -> Result<Option<String>>,
6919            G: FnMut(ShaderTexture<'_>) -> Result<Option<u32>>,
6920        {
6921            if store.is_null() {
6922                return false;
6923            }
6924            if !unsafe { texture_callback::<F, G>(context, event, replace, binding) } {
6925                return false;
6926            }
6927            let state = unsafe { &*context.cast::<State<'_, F, G>>() };
6928            if let Some(storage) = state.texture_storage {
6929                unsafe { *store = storage.get() };
6930                true
6931            } else {
6932                false
6933            }
6934        }
6935        unsafe extern "C" fn registration_callback<F, G>(
6936            context: *mut c_void,
6937            name: *const i8,
6938            uniform_type: i32,
6939            has_max_size: bool,
6940            max_size: u32,
6941            getter: *mut c_void,
6942            action: *mut i32,
6943        ) -> bool
6944        where
6945            F: FnMut(ShaderSections<'_>) -> Result<Option<String>>,
6946            G: FnMut(ShaderTexture<'_>) -> Result<Option<u32>>,
6947        {
6948            let state = unsafe { &mut *context.cast::<State<'_, F, G>>() };
6949            let Some(handle) = NonNull::new(getter) else {
6950                state
6951                    .error
6952                    .get_or_insert_with(|| OcioError::InvalidInput("null uniform getter".into()));
6953                return false;
6954            };
6955            // SAFETY: Ownership of this native cache is transferred by the
6956            // bridge, which retained the native creator and its properties.
6957            let getter = ShaderUniformGetter {
6958                cache: GpuUniformCache {
6959                    handle,
6960                    _desc: std::marker::PhantomData,
6961                },
6962                uniform_type: GpuUniformType::from_raw(uniform_type),
6963            };
6964            let result = crate::catch_callback_unwind(std::panic::AssertUnwindSafe(
6965                || -> Result<ShaderUniformAction> {
6966                    if name.is_null() || action.is_null() || !(0..=4).contains(&uniform_type) {
6967                        return Err(OcioError::InvalidInput(
6968                            "invalid uniform registration".into(),
6969                        ));
6970                    }
6971                    let name = unsafe { std::ffi::CStr::from_ptr(name) }
6972                        .to_str()
6973                        .map_err(|_| OcioError::InvalidInput("uniform name is not UTF-8".into()))?;
6974                    (state.registration)(ShaderUniformRegistration {
6975                        name: name.to_owned(),
6976                        uniform_type: GpuUniformType::from_raw(uniform_type),
6977                        max_size: has_max_size.then_some(max_size),
6978                        getter,
6979                    })
6980                },
6981            ));
6982            match result {
6983                Ok(Ok(choice)) => {
6984                    unsafe {
6985                        *action = match choice {
6986                            ShaderUniformAction::StoreInDescriptor => 0,
6987                            ShaderUniformAction::ExternalAdded => 1,
6988                            ShaderUniformAction::ExternalDuplicate => 2,
6989                        }
6990                    };
6991                    true
6992                }
6993                Ok(Err(error)) => {
6994                    state.error.get_or_insert(error);
6995                    false
6996                }
6997                Err(_) => {
6998                    state.error.get_or_insert_with(|| {
6999                        OcioError::InvalidInput("uniform registration callback panicked".into())
7000                    });
7001                    false
7002                }
7003            }
7004        }
7005        let has_finalizer = finalizer.is_some();
7006        let has_policy = policy.is_some();
7007        let mut state = State {
7008            function: &mut assemble,
7009            texture: &mut texture,
7010            texture_storage,
7011            uniform,
7012            lifecycle,
7013            code,
7014            registration,
7015            finalizer: finalizer
7016                .as_mut()
7017                .map(|f| &mut **f as &mut dyn FnMut() -> Result<Option<String>>),
7018            policy: policy
7019                .as_mut()
7020                .map(|p| &mut **p as &mut dyn FnMut(i32, u32) -> Result<u32>),
7021            output: None,
7022            code_output: None,
7023            finalizer_output: None,
7024            error: None,
7025        };
7026        crate::clear_last_error();
7027        let ptr = unsafe {
7028            let context = (&mut state as *mut State<'_, F, G>).cast();
7029            let extract = if stream_textures {
7030                ocio_sys::ocio_gpu_processor_extract_with_streamed_texture_hooks
7031                    as unsafe extern "C" fn(_, _, _, _, _, _, _, _) -> _
7032            } else {
7033                ocio_sys::ocio_gpu_processor_extract_with_hooks
7034            };
7035            if has_policy {
7036                debug_assert!(has_finalizer && texture_storage.is_some());
7037                ocio_sys::ocio_gpu_processor_extract_with_texture_policy(
7038                    self.handle.as_ptr(),
7039                    template.handle.as_ptr(),
7040                    callback::<F, G>,
7041                    texture_control_callback::<F, G>,
7042                    notify_uniform.then_some(uniform_callback::<F, G>),
7043                    notify_lifecycle.then_some(lifecycle_callback::<F, G>),
7044                    notify_code.then_some(code_callback::<F, G>),
7045                    has_registration.then_some(registration_callback::<F, G>),
7046                    finalize_callback::<F, G>,
7047                    policy_callback::<F, G>,
7048                    cache_id_override.map_or(std::ptr::null(), |id| id.as_ptr()),
7049                    context,
7050                )
7051            } else if has_finalizer {
7052                ocio_sys::ocio_gpu_processor_extract_with_finalize_control(
7053                    self.handle.as_ptr(),
7054                    template.handle.as_ptr(),
7055                    callback::<F, G>,
7056                    texture_control_callback::<F, G>,
7057                    notify_uniform.then_some(uniform_callback::<F, G>),
7058                    notify_lifecycle.then_some(lifecycle_callback::<F, G>),
7059                    notify_code.then_some(code_callback::<F, G>),
7060                    has_registration.then_some(registration_callback::<F, G>),
7061                    finalize_callback::<F, G>,
7062                    cache_id_override.map_or(std::ptr::null(), |id| id.as_ptr()),
7063                    context,
7064                )
7065            } else if texture_storage.is_some() {
7066                ocio_sys::ocio_gpu_processor_extract_with_texture_control(
7067                    self.handle.as_ptr(),
7068                    template.handle.as_ptr(),
7069                    callback::<F, G>,
7070                    texture_control_callback::<F, G>,
7071                    notify_uniform.then_some(uniform_callback::<F, G>),
7072                    notify_lifecycle.then_some(lifecycle_callback::<F, G>),
7073                    notify_code.then_some(code_callback::<F, G>),
7074                    has_registration.then_some(registration_callback::<F, G>),
7075                    cache_id_override.map_or(std::ptr::null(), |id| id.as_ptr()),
7076                    context,
7077                )
7078            } else if let Some(cache_id) = cache_id_override {
7079                debug_assert!(has_registration);
7080                ocio_sys::ocio_gpu_processor_extract_with_creator_options(
7081                    self.handle.as_ptr(),
7082                    template.handle.as_ptr(),
7083                    callback::<F, G>,
7084                    notify_texture.then_some(texture_callback::<F, G>),
7085                    notify_uniform.then_some(uniform_callback::<F, G>),
7086                    notify_lifecycle.then_some(lifecycle_callback::<F, G>),
7087                    notify_code.then_some(code_callback::<F, G>),
7088                    Some(registration_callback::<F, G>),
7089                    stream_textures,
7090                    cache_id.as_ptr(),
7091                    context,
7092                )
7093            } else if has_registration {
7094                ocio_sys::ocio_gpu_processor_extract_with_uniform_control(
7095                    self.handle.as_ptr(),
7096                    template.handle.as_ptr(),
7097                    callback::<F, G>,
7098                    notify_texture.then_some(texture_callback::<F, G>),
7099                    notify_uniform.then_some(uniform_callback::<F, G>),
7100                    notify_lifecycle.then_some(lifecycle_callback::<F, G>),
7101                    notify_code.then_some(code_callback::<F, G>),
7102                    Some(registration_callback::<F, G>),
7103                    stream_textures,
7104                    context,
7105                )
7106            } else {
7107                extract(
7108                    self.handle.as_ptr(),
7109                    template.handle.as_ptr(),
7110                    callback::<F, G>,
7111                    notify_texture.then_some(texture_callback::<F, G>),
7112                    notify_uniform.then_some(uniform_callback::<F, G>),
7113                    notify_lifecycle.then_some(lifecycle_callback::<F, G>),
7114                    notify_code.then_some(code_callback::<F, G>),
7115                    context,
7116                )
7117            }
7118        };
7119        let result = crate::handle_result(ptr);
7120        if let Some(error) = state.error {
7121            if let Ok(handle) = result {
7122                unsafe { ocio_sys::ocio_gpu_shader_desc_destroy(handle.as_ptr()) };
7123            }
7124            return Err(error);
7125        }
7126        Ok(GpuShaderDesc { handle: result? })
7127    }
7128    /// Return whether the GPU path is an identity/no-op transform.
7129    ///
7130    /// Returns `false` if OCIO reports an error. Use [`Self::try_is_no_op`] to
7131    /// distinguish that case from a non-identity processor.
7132    pub fn is_no_op(&self) -> bool {
7133        self.try_is_no_op().unwrap_or(false)
7134    }
7135
7136    /// Fallible variant of [`Self::is_no_op`].
7137    ///
7138    /// Returns an error when the underlying OCIO query throws.
7139    pub fn try_is_no_op(&self) -> Result<bool> {
7140        crate::clear_last_error();
7141        let value =
7142            unsafe { ocio_sys::ocio_gpu_processor_is_no_op(self.handle.as_ptr() as *mut c_void) };
7143        crate::ocio_call_status()?;
7144        Ok(value)
7145    }
7146
7147    /// Return whether the GPU path mixes color channels.
7148    ///
7149    /// Returns `false` if OCIO reports an error. Use
7150    /// [`Self::try_has_channel_crosstalk`] to distinguish that case from a
7151    /// lane-wise processor.
7152    pub fn has_channel_crosstalk(&self) -> bool {
7153        self.try_has_channel_crosstalk().unwrap_or(false)
7154    }
7155
7156    /// Fallible variant of [`Self::has_channel_crosstalk`].
7157    ///
7158    /// Returns an error when the underlying OCIO query throws.
7159    pub fn try_has_channel_crosstalk(&self) -> Result<bool> {
7160        crate::clear_last_error();
7161        let value = unsafe {
7162            ocio_sys::ocio_gpu_processor_has_channel_crosstalk(self.handle.as_ptr() as *mut c_void)
7163        };
7164        crate::ocio_call_status()?;
7165        Ok(value)
7166    }
7167
7168    /// Return OCIO's cache identifier for this GPU processor instance.
7169    pub fn cache_id(&self) -> Option<String> {
7170        self.try_cache_id().ok().flatten()
7171    }
7172
7173    /// Return OCIO's cache identifier, preserving bridge errors.
7174    pub fn try_cache_id(&self) -> Result<Option<String>> {
7175        crate::clear_last_error();
7176        let value = unsafe {
7177            cstr_from_mut(ocio_sys::ocio_gpu_processor_get_cache_id(
7178                self.handle.as_ptr() as *mut c_void,
7179            ))
7180        };
7181        crate::ocio_call_status()?;
7182        Ok(value)
7183    }
7184
7185    /// Fill `shader_desc` with OCIO-generated shader text, uniforms, and textures.
7186    ///
7187    /// Panics when OCIO rejects extraction. Use [`Self::try_extract_shader_info`]
7188    /// when extraction failures should be handled by the caller.
7189    #[deprecated(
7190        since = "0.2.0",
7191        note = "panics on OCIO errors; prefer try_extract_shader_info()"
7192    )]
7193    pub fn extract_shader_info(&self, shader_desc: &mut GpuShaderDesc) {
7194        self.try_extract_shader_info(shader_desc)
7195            .expect("GPUProcessor::extract_shader_info failed");
7196    }
7197
7198    /// Try to fill `shader_desc` with OCIO-generated shader text, uniforms, and textures.
7199    ///
7200    /// This calls the native generator directly. The repository's vendored
7201    /// source fixes the multi-row LUT allocation. When linking an unpatched
7202    /// system library or building from unpatched external source, use
7203    /// [Self::try_extract_shader_info_checked] for untrusted or unknown LUT lengths.
7204    pub fn try_extract_shader_info(&self, shader_desc: &mut GpuShaderDesc) -> Result<()> {
7205        crate::clear_last_error();
7206        unsafe {
7207            ocio_sys::ocio_gpu_processor_extract_gpu_shader_info_v1(
7208                self.handle.as_ptr(),
7209                shader_desc.handle.as_ptr(),
7210            );
7211        }
7212        crate::ocio_call_status()
7213    }
7214
7215    /// Probe optimized texture resources before extracting into `shader_desc`.
7216    ///
7217    /// Unpatched OCIO 2.4–2.6 can underflow while packing some 1D LUT lengths
7218    /// into 2D textures. This check remains conservative with the patched
7219    /// vendored source. The probe uses a temporary descriptor wide enough for every
7220    /// 1D LUT accepted by these versions, streams its textures without storing
7221    /// them, and checks their lengths against the requested width before the
7222    /// real extraction. The target descriptor is untouched if probing fails.
7223    ///
7224    /// On OCIO 2.5+, it also checks the binding range needed by the probed
7225    /// textures and the target's existing textures before modifying the target.
7226    /// This assumes resource generation does not change between the probe and
7227    /// extraction; custom descriptors with noncontiguous bindings may be rejected
7228    /// conservatively. It does not validate arbitrary native creators.
7229    ///
7230    /// This performs shader generation twice and allocates OCIO's temporary
7231    /// texture data. It conservatively checks all 1D/2D resources with height
7232    /// one, including non-LUT resources, so it can reject a safe processor.
7233    /// It relies on the 1,048,576-entry limit of supported OCIO 2.4–2.6 and
7234    /// must be re-audited before supporting a newer native version.
7235    pub fn try_extract_shader_info_checked(&self, shader_desc: &mut GpuShaderDesc) -> Result<()> {
7236        let (lengths, texture_count) = self.probe_shader_texture_lengths(shader_desc)?;
7237        for length in lengths {
7238            shader_desc.validate_lut_texture_layout(length)?;
7239        }
7240        #[cfg(feature = "v2_5")]
7241        {
7242            let start = u64::from(shader_desc.try_texture_binding_start()?);
7243            let count = u64::from(shader_desc.try_num_textures()?)
7244                + u64::from(shader_desc.try_num_3d_textures()?)
7245                + texture_count;
7246            if count > 0 && start + count - 1 > u64::from(u32::MAX) {
7247                return Err(OcioError::InvalidInput(
7248                    "texture binding index overflow".into(),
7249                ));
7250            }
7251        }
7252        #[cfg(not(feature = "v2_5"))]
7253        let _ = texture_count;
7254        self.try_extract_shader_info(shader_desc)
7255    }
7256
7257    /// Conservatively check the optimized processor's texture layouts before
7258    /// extraction with `template`. This performs a probe extraction, but does
7259    /// not invoke the caller's shader hooks or retain probe textures.
7260    ///
7261    /// The probe has the cost and version/false-positive limitations documented
7262    /// on [`Self::try_extract_shader_info_checked`]. It may be followed by any
7263    /// of this library's synchronous custom extraction APIs using the same
7264    /// processor and unchanged template settings. It does not validate arbitrary
7265    /// native creators with independently implemented texture-policy methods.
7266    ///
7267    /// ```no_run
7268    /// # use ocio_rs::{GPUProcessor, GpuShaderDesc, ShaderExtractionHooks, Result};
7269    /// # fn extract<H: ShaderExtractionHooks>(gpu: &GPUProcessor, template: &GpuShaderDesc, hooks: &mut H) -> Result<()> {
7270    /// gpu.validate_shader_texture_layout(template)?;
7271    /// let shader = gpu.try_extract_with_hooks(template, hooks)?;
7272    /// # let _ = shader;
7273    /// # Ok(()) }
7274    /// ```
7275    pub fn validate_shader_texture_layout(&self, shader_desc: &GpuShaderDesc) -> Result<()> {
7276        let (lengths, _) = self.probe_shader_texture_lengths(shader_desc)?;
7277        for length in lengths {
7278            shader_desc.validate_lut_texture_layout(length)?;
7279        }
7280        Ok(())
7281    }
7282
7283    fn probe_shader_texture_lengths(
7284        &self,
7285        shader_desc: &GpuShaderDesc,
7286    ) -> Result<(Vec<usize>, u64)> {
7287        struct ProbeHooks;
7288        impl ShaderExtractionHooks for ProbeHooks {}
7289        let probe = shader_desc.try_clone_desc()?;
7290        probe.set_texture_max_width(1_048_577)?;
7291        probe.set_allow_texture_1d(shader_desc.try_allow_texture_1d()?)?;
7292        let mut lengths = Vec::new();
7293        let mut texture_count = 0u64;
7294        self.try_extract_with_streamed_textures(&probe, &mut ProbeHooks, |texture| {
7295            texture_count += 1;
7296            if texture.dimensions.is_some() && texture.height == 1 && texture.width >= 2 {
7297                lengths.push(texture.width as usize);
7298            }
7299            Ok(None)
7300        })?;
7301        Ok((lengths, texture_count))
7302    }
7303
7304    #[doc(hidden)]
7305    #[deprecated(
7306        since = "0.2.0",
7307        note = "compat alias; prefer try_extract_shader_info()"
7308    )]
7309    pub fn extract_gpu_shader_info(&self, shader_desc: &mut GpuShaderDesc) {
7310        self.try_extract_shader_info(shader_desc)
7311            .expect("GPUProcessor::extract_gpu_shader_info failed");
7312    }
7313
7314    #[doc(hidden)]
7315    #[deprecated(
7316        since = "0.2.0",
7317        note = "compat alias; prefer try_extract_shader_info()"
7318    )]
7319    pub fn extract_gpu_shader_info_v1(&self, shader_desc: &mut GpuShaderDesc) {
7320        self.try_extract_shader_info(shader_desc)
7321            .expect("GPUProcessor::extract_gpu_shader_info_v1 failed");
7322    }
7323
7324    /// # Safety
7325    /// `shader_creator` must point to a valid mutable OCIO shader creator object
7326    /// for the active ABI and remain alive and exclusively accessible for the
7327    /// duration of the call. OCIO receives a temporary non-owning shared pointer;
7328    /// the object and its callbacks must not retain that shared pointer or depend
7329    /// on it sharing ownership with another control block. Neither this method
7330    /// nor the Rust binding destroys the object. Prefer
7331    /// [`Self::try_extract_shader_info`] with [`GpuShaderDesc`] for a typed,
7332    /// Rust-owned descriptor.
7333    #[doc(hidden)]
7334    #[deprecated(
7335        since = "0.2.0",
7336        note = "raw OCIO shader-creator entry point; prefer extract_shader_info with GpuShaderDesc for Rust callers"
7337    )]
7338    pub unsafe fn extract_gpu_shader_info_v2(&self, shader_creator: *mut c_void) {
7339        let _ = unsafe { self.try_extract_shader_info_raw(shader_creator) };
7340    }
7341
7342    /// Extract shader information through a raw `OCIO::GpuShaderCreator*`.
7343    ///
7344    /// # Safety
7345    /// `shader_creator` must meet the same ABI, exclusivity, lifetime, and ownership
7346    /// requirements as [`Self::extract_gpu_shader_info_v2`].
7347    #[doc(hidden)]
7348    pub unsafe fn try_extract_shader_info_raw(&self, shader_creator: *mut c_void) -> Result<()> {
7349        if shader_creator.is_null() {
7350            return Err(OcioError::InvalidInput(
7351                "native shader creator cannot be null".into(),
7352            ));
7353        }
7354        crate::clear_last_error();
7355        unsafe {
7356            ocio_sys::ocio_gpu_processor_extract_gpu_shader_info_v2(
7357                self.handle.as_ptr(),
7358                shader_creator,
7359            );
7360        }
7361        crate::ocio_call_status()
7362    }
7363}
7364
7365impl Drop for GPUProcessor {
7366    fn drop(&mut self) {
7367        unsafe { ocio_sys::ocio_gpu_processor_destroy(self.handle.as_ptr() as *mut c_void) };
7368    }
7369}
7370
7371// --- GpuShaderDesc ---
7372
7373/// Collects parameters and emitted source for GPU shader extraction.
7374///
7375/// A `GpuShaderDesc` describes how OCIO should emit shader code for a given
7376/// target language. Before extraction, configure the descriptor with a
7377/// [`GpuLanguage`], entry-point name, pixel variable name, resource prefix,
7378/// and optional descriptor-set binding offsets.
7379///
7380/// After calling [`GPUProcessor::extract_shader_info`], the descriptor
7381/// contains the generated shader text (via [`shader_text`](Self::shader_text))
7382/// and any textures ([`textures_2d`](Self::textures_2d)) or uniforms
7383/// ([`uniforms`](Self::uniforms)) needed by the shader.
7384///
7385/// For manual shader assembly, the section-based helpers
7386/// ([`add_to_function_shader_code`](Self::add_to_function_shader_code),
7387/// `add_to_parameter_declare_shader_code` (`v2_5` feature), etc.) and
7388/// [`create_shader_text`](Self::create_shader_text) let you build the final
7389/// shader string from OCIO-provided fragments.
7390///
7391/// This handle is thread-confined; its dynamic property handles may outlive it.
7392///
7393/// ```compile_fail
7394/// # use ocio_rs::GpuShaderDesc;
7395/// fn require_send<T: Send>() {}
7396/// require_send::<GpuShaderDesc>();
7397/// ```
7398///
7399/// [`GpuLanguage`]: crate::GpuLanguage
7400/// [`GPUProcessor::extract_shader_info`]: crate::GPUProcessor::extract_shader_info
7401pub struct GpuShaderDesc {
7402    handle: NonNull<c_void>,
7403}
7404
7405/// Result of copying a cached live uniform into caller-owned storage.
7406#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7407pub enum GpuUniformCopy {
7408    Written(usize),
7409    BufferTooSmall { required: usize },
7410    WrongType,
7411}
7412
7413/// Cached OCIO uniform getters for repeated sampling without bridge allocations.
7414///
7415/// The descriptor remains exclusively borrowed because native getters may
7416/// reference properties owned by it. Values remain live; only the getters,
7417/// not their results, are cached. This type cannot be sent to another thread.
7418/// Getter implementations may themselves allocate or perform other work.
7419pub struct GpuUniformCache<'a> {
7420    handle: NonNull<c_void>,
7421    _desc: std::marker::PhantomData<&'a mut GpuShaderDesc>,
7422}
7423
7424impl GpuUniformCache<'_> {
7425    fn copy_result(status: i32, actual: usize) -> Result<GpuUniformCopy> {
7426        crate::ocio_call_status()?;
7427        match status {
7428            0 => Ok(GpuUniformCopy::WrongType),
7429            1 => Ok(GpuUniformCopy::Written(actual)),
7430            2 => Ok(GpuUniformCopy::BufferTooSmall { required: actual }),
7431            _ => Err(OcioError::Ocio("uniform cache operation failed".into())),
7432        }
7433    }
7434
7435    /// Copies a double, boolean, float3, or float array as `f32` values.
7436    /// An undersized buffer is left untouched.
7437    pub fn copy_f32_into(&mut self, index: u32, values: &mut [f32]) -> Result<GpuUniformCopy> {
7438        let mut actual = 0;
7439        crate::clear_last_error();
7440        let status = unsafe {
7441            ocio_sys::ocio_gpu_uniform_cache_copy_f32(
7442                self.handle.as_ptr(),
7443                index,
7444                values.as_mut_ptr(),
7445                values.len(),
7446                &mut actual,
7447            )
7448        };
7449        Self::copy_result(status, actual)
7450    }
7451
7452    /// Copies an integer array. An undersized buffer is left untouched.
7453    pub fn copy_i32_into(&mut self, index: u32, values: &mut [i32]) -> Result<GpuUniformCopy> {
7454        let mut actual = 0;
7455        crate::clear_last_error();
7456        let status = unsafe {
7457            ocio_sys::ocio_gpu_uniform_cache_copy_i32(
7458                self.handle.as_ptr(),
7459                index,
7460                values.as_mut_ptr(),
7461                values.len(),
7462                &mut actual,
7463            )
7464        };
7465        Self::copy_result(status, actual)
7466    }
7467
7468    /// Reads a double without narrowing to `f32`; returns `None` for other types.
7469    pub fn double(&mut self, index: u32) -> Result<Option<f64>> {
7470        let mut value = 0.0;
7471        crate::clear_last_error();
7472        let status = unsafe {
7473            ocio_sys::ocio_gpu_uniform_cache_double(self.handle.as_ptr(), index, &mut value)
7474        };
7475        crate::ocio_call_status()?;
7476        match status {
7477            0 => Ok(None),
7478            1 => Ok(Some(value)),
7479            _ => Err(OcioError::Ocio("uniform cache operation failed".into())),
7480        }
7481    }
7482}
7483
7484impl Drop for GpuUniformCache<'_> {
7485    fn drop(&mut self) {
7486        unsafe { ocio_sys::ocio_gpu_uniform_cache_destroy(self.handle.as_ptr()) }
7487    }
7488}
7489
7490#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7491#[repr(i32)]
7492/// Channel layout used by extracted 1D/2D GPU texture payloads.
7493pub enum GpuTextureChannel {
7494    Red = 0,
7495    Rgb = 1,
7496}
7497
7498impl GpuTextureChannel {
7499    fn from_raw(value: i32) -> Result<Self> {
7500        match value {
7501            0 => Ok(Self::Red),
7502            1 => Ok(Self::Rgb),
7503            _ => Err(OcioError::ValidationFailed(format!(
7504                "unknown GPU texture channel {value}"
7505            ))),
7506        }
7507    }
7508
7509    fn channel_count(self) -> usize {
7510        match self {
7511            Self::Red => 1,
7512            Self::Rgb => 3,
7513        }
7514    }
7515}
7516
7517#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7518#[repr(i32)]
7519/// Dimensionality metadata for extracted 1D/2D GPU texture payloads.
7520pub enum GpuTextureDimensions {
7521    Texture1D = 1,
7522    Texture2D = 2,
7523}
7524
7525impl GpuTextureDimensions {
7526    fn from_raw(value: i32) -> Result<Self> {
7527        match value {
7528            1 => Ok(Self::Texture1D),
7529            2 => Ok(Self::Texture2D),
7530            _ => Err(OcioError::ValidationFailed(format!(
7531                "unknown GPU texture dimensions {value}"
7532            ))),
7533        }
7534    }
7535}
7536
7537fn required_ocio_string(ptr: *const i8) -> Option<String> {
7538    let value = unsafe { cstr_to_opt_string(ptr) }?;
7539    if value.is_empty() {
7540        None
7541    } else {
7542        Some(value)
7543    }
7544}
7545
7546fn try_resize_gpu_values<T: Copy + Default>(values: &mut Vec<T>, len: usize) -> Result<()> {
7547    if len > values.len() {
7548        values.try_reserve_exact(len - values.len()).map_err(|_| {
7549            OcioError::ValidationFailed(
7550                "GPU resource payload allocation failed or overflowed".into(),
7551            )
7552        })?;
7553    }
7554    values.resize(len, T::default());
7555    Ok(())
7556}
7557
7558#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7559#[repr(i32)]
7560/// Uniform value encoding reported by OCIO GPU shader extraction.
7561pub enum GpuUniformType {
7562    Double = 0,
7563    Bool = 1,
7564    Float3 = 2,
7565    VectorFloat = 3,
7566    VectorInt = 4,
7567    Unknown = 5,
7568}
7569
7570impl GpuUniformType {
7571    fn from_raw(value: i32) -> Self {
7572        match value {
7573            0 => Self::Double,
7574            1 => Self::Bool,
7575            2 => Self::Float3,
7576            3 => Self::VectorFloat,
7577            4 => Self::VectorInt,
7578            _ => Self::Unknown,
7579        }
7580    }
7581}
7582
7583#[derive(Debug, Clone)]
7584/// Texture payload and metadata for a 1D/2D GPU LUT resource.
7585pub struct GpuTexture2D {
7586    /// OCIO-generated texture symbol name used in emitted shader code.
7587    pub texture_name: String,
7588    /// Sampler symbol name paired with `texture_name` in the emitted shader.
7589    pub sampler_name: String,
7590    /// Logical texture width in texels.
7591    pub width: u32,
7592    /// Logical texture height in texels.
7593    pub height: u32,
7594    /// Channel packing used by the texture values.
7595    pub channel: GpuTextureChannel,
7596    /// Whether the resource is logically treated as 1D or 2D.
7597    pub dimensions: GpuTextureDimensions,
7598    /// Interpolation mode OCIO expects the texture to use.
7599    pub interpolation: Interpolation,
7600    /// API-facing binding slot reported by OCIO 2.5.1 and newer.
7601    ///
7602    /// OpenColorIO 2.4 does not expose binding indexes.
7603    pub binding_index: Option<u32>,
7604    /// Flattened texel payload in row-major order.
7605    pub values: Vec<f32>,
7606}
7607
7608impl GpuTexture2D {
7609    /// Returns the number of `f32` values, saturating at `usize::MAX` on overflow.
7610    pub fn expected_value_count(&self) -> usize {
7611        self.checked_expected_value_count().unwrap_or(usize::MAX)
7612    }
7613
7614    /// Returns the number of `f32` values, or `None` if it overflows.
7615    pub fn checked_expected_value_count(&self) -> Option<usize> {
7616        (self.width as usize)
7617            .checked_mul(self.height as usize)?
7618            .checked_mul(self.channel.channel_count())
7619    }
7620}
7621
7622#[derive(Debug, Clone)]
7623/// Texture payload and metadata for a 3D GPU LUT resource.
7624pub struct GpuTexture3D {
7625    /// OCIO-generated texture symbol name used in emitted shader code.
7626    pub texture_name: String,
7627    /// Sampler symbol name paired with `texture_name` in the emitted shader.
7628    pub sampler_name: String,
7629    /// Cube edge length in texels.
7630    pub edge_len: u32,
7631    /// Interpolation mode OCIO expects the 3D LUT to use.
7632    pub interpolation: Interpolation,
7633    /// API-facing binding slot reported by OCIO 2.5.1 and newer.
7634    ///
7635    /// OpenColorIO 2.4 does not expose binding indexes.
7636    pub binding_index: Option<u32>,
7637    /// Flattened texel payload in OCIO's native 3D LUT ordering.
7638    pub values: Vec<f32>,
7639}
7640
7641impl GpuTexture3D {
7642    /// Returns the number of `f32` values, saturating at `usize::MAX` on overflow.
7643    pub fn expected_value_count(&self) -> usize {
7644        self.checked_expected_value_count().unwrap_or(usize::MAX)
7645    }
7646
7647    /// Returns the number of `f32` values, or `None` if it overflows.
7648    pub fn checked_expected_value_count(&self) -> Option<usize> {
7649        let edge = self.edge_len as usize;
7650        edge.checked_mul(edge)?.checked_mul(edge)?.checked_mul(3)
7651    }
7652}
7653
7654#[derive(Debug, Clone)]
7655/// Typed value payload for a GPU uniform extracted from OCIO.
7656pub enum GpuUniformValue {
7657    /// Floating-point uniform payload.
7658    F32(Vec<f32>),
7659    /// Integer uniform payload.
7660    I32(Vec<i32>),
7661    /// Uniform payload could not be represented through the current Rust helper.
7662    Unsupported,
7663}
7664
7665#[derive(Debug, Clone)]
7666/// GPU uniform metadata and current value payload extracted from OCIO.
7667pub struct GpuUniform {
7668    /// Uniform symbol name used in the emitted shader.
7669    pub name: String,
7670    /// OCIO-reported uniform value encoding.
7671    pub uniform_type: GpuUniformType,
7672    /// Byte offset into the packed uniform buffer layout on OpenColorIO 2.5.1
7673    /// and newer.
7674    pub buffer_offset: Option<usize>,
7675    /// Logical scalar count for the current uniform payload.
7676    pub value_count: usize,
7677    /// Typed uniform payload copied into Rust-owned memory.
7678    pub value: GpuUniformValue,
7679}
7680
7681impl GpuShaderDesc {
7682    /// Borrow this descriptor as a native shader creator using OCIO shared ownership.
7683    /// The descriptor cannot be accessed until the returned creator is dropped.
7684    pub fn try_borrow_creator(&mut self) -> Result<GpuShaderCreator<'_>> {
7685        crate::clear_last_error();
7686        let handle = unsafe { ocio_sys::ocio_gpu_shader_creator_from_desc(self.handle.as_ptr()) };
7687        Ok(GpuShaderCreator {
7688            handle: crate::handle_result(handle)?,
7689            _descriptor: std::marker::PhantomData,
7690        })
7691    }
7692    /// Captures the current uniform getters for repeated reads without bridge allocations.
7693    ///
7694    /// Extract shader information before calling this method. Drop the cache
7695    /// before changing the descriptor or extracting shader information again.
7696    ///
7697    /// ```compile_fail
7698    /// # use ocio_rs::GpuShaderDesc;
7699    /// # fn example(mut desc: GpuShaderDesc) -> ocio_rs::Result<()> {
7700    /// let mut cache = desc.uniform_cache()?;
7701    /// desc.set_function_name("other")?;
7702    /// let _ = cache.double(0)?;
7703    /// # Ok(())
7704    /// # }
7705    /// ```
7706    pub fn uniform_cache(&mut self) -> Result<GpuUniformCache<'_>> {
7707        crate::clear_last_error();
7708        let ptr = unsafe { ocio_sys::ocio_gpu_uniform_cache_create(self.handle.as_ptr()) };
7709        crate::handle_result(ptr).map(|handle| GpuUniformCache {
7710            handle,
7711            _desc: std::marker::PhantomData,
7712        })
7713    }
7714    /// Borrow this descriptor as a native `OCIO::GpuShaderCreator*` for C++ interop.
7715    ///
7716    /// The pointer is invalid after this descriptor is dropped. Native code
7717    /// must not delete it, retain it beyond that lifetime, or access the object
7718    /// concurrently or reentrantly with Rust operations on this descriptor.
7719    /// The returned raw pointer is only usable with a compatible OCIO ABI.
7720    pub fn borrow_native_creator(&mut self) -> Result<NonNull<c_void>> {
7721        crate::clear_last_error();
7722        let ptr =
7723            unsafe { ocio_sys::ocio_gpu_shader_desc_borrow_native_creator(self.handle.as_ptr()) };
7724        crate::handle_result(ptr)
7725    }
7726
7727    /// Creates an empty OCIO GPU shader descriptor that can be configured and
7728    /// passed to `GPUProcessor::extract_shader_info`.
7729    pub fn create() -> Result<Self> {
7730        crate::clear_last_error();
7731        let handle = unsafe { ocio_sys::ocio_gpu_shader_desc_create() };
7732        crate::handle_result(handle).map(|handle| Self { handle })
7733    }
7734
7735    fn bool_call_result(ok: bool) -> Result<bool> {
7736        if ok {
7737            Ok(true)
7738        } else {
7739            match crate::ocio_call_status() {
7740                Ok(()) => Ok(false),
7741                Err(err) => Err(err),
7742            }
7743        }
7744    }
7745
7746    /// Returns the extracted shader source text, if any.
7747    pub fn shader_text(&self) -> Option<String> {
7748        self.try_shader_text().ok().flatten()
7749    }
7750
7751    /// Return the extracted shader source text, if any.
7752    ///
7753    /// Unlike [`Self::shader_text`], this preserves OCIO query failures as
7754    /// [`OcioError`].
7755    pub fn try_shader_text(&self) -> Result<Option<String>> {
7756        crate::clear_last_error();
7757        let shader_text = unsafe {
7758            cstr_from_mut(ocio_sys::ocio_gpu_shader_desc_get_shader_text(
7759                self.handle.as_ptr() as *mut c_void,
7760            ))
7761        };
7762        crate::ocio_call_status()?;
7763        Ok(shader_text)
7764    }
7765
7766    /// Borrow OCIO's shader text without allocating or converting its bytes.
7767    ///
7768    /// The exclusive borrow prevents mutation or re-extraction into this
7769    /// descriptor while the returned native string is in use. Raw native users
7770    /// must also avoid concurrent or reentrant mutation of the descriptor.
7771    /// The empty string is returned as `Some`; stub builds return `None`.
7772    ///
7773    /// ```compile_fail
7774    /// # use ocio_rs::GpuShaderDesc;
7775    /// # fn example(desc: &mut GpuShaderDesc) {
7776    /// let text = desc.shader_text_ref().unwrap().unwrap();
7777    /// desc.set_function_name("changed").unwrap();
7778    /// println!("{:?}", text);
7779    /// # }
7780    /// ```
7781    pub fn shader_text_ref(&mut self) -> Result<Option<&std::ffi::CStr>> {
7782        crate::clear_last_error();
7783        let ptr = unsafe { ocio_sys::ocio_gpu_shader_desc_get_shader_text(self.handle.as_ptr()) };
7784        crate::ocio_call_status()?;
7785        if ptr.is_null() {
7786            Ok(None)
7787        } else {
7788            // SAFETY: OCIO owns a NUL-terminated string until the descriptor is
7789            // mutated or dropped; the exclusive borrow prevents both in safe Rust.
7790            Ok(Some(unsafe { std::ffi::CStr::from_ptr(ptr.cast()) }))
7791        }
7792    }
7793
7794    /// Returns the number of reported 1D/2D texture resources.
7795    pub fn num_textures(&self) -> u32 {
7796        self.try_num_textures().unwrap_or(0)
7797    }
7798
7799    /// Return the number of reported 1D/2D texture resources.
7800    pub fn try_num_textures(&self) -> Result<u32> {
7801        crate::clear_last_error();
7802        let value =
7803            unsafe { ocio_sys::ocio_gpu_shader_desc_get_num_textures_u32(self.handle.as_ptr()) };
7804        crate::ocio_call_status()?;
7805        Ok(value)
7806    }
7807
7808    /// Returns lightweight legacy metadata for a 1D/2D texture resource.
7809    pub fn texture_info(&self, index: u32) -> Option<TextureInfo> {
7810        let info = self.texture_info_raw(index)?;
7811        let channel = GpuTextureChannel::from_raw(info.channel).ok()?;
7812        let dimensions = GpuTextureDimensions::from_raw(info.dimensions).ok()?;
7813        Some(TextureInfo {
7814            texture_name: required_ocio_string(info.texture_name)?,
7815            sampler_name: required_ocio_string(info.sampler_name)?,
7816            width: info.width,
7817            height: info.height,
7818            channel: channel as i32,
7819            dimensions: dimensions as i32,
7820            interpolation: interpolation_from_raw(info.interpolation) as i32,
7821        })
7822    }
7823
7824    // The returned pointers borrow descriptor storage. Callers must consume
7825    // them before mutating the descriptor or returning from the safe method.
7826    fn texture_info_raw(&self, index: u32) -> Option<ocio_sys::OcioGpuTexture2DInfo> {
7827        let mut info = ocio_sys::OcioGpuTexture2DInfo {
7828            texture_name: std::ptr::null(),
7829            sampler_name: std::ptr::null(),
7830            width: 0,
7831            height: 0,
7832            channel: 0,
7833            dimensions: 0,
7834            interpolation: 0,
7835            has_binding_index: false,
7836            binding_index: 0,
7837        };
7838        crate::clear_last_error();
7839        let ok = unsafe {
7840            ocio_sys::ocio_gpu_shader_desc_get_texture_info(self.handle.as_ptr(), index, &mut info)
7841        };
7842        crate::ocio_call_status().ok()?;
7843        ok.then_some(info)
7844    }
7845
7846    fn texture_3d_info_raw(&self, index: u32) -> Option<ocio_sys::OcioGpuTexture3DInfo> {
7847        let mut info = ocio_sys::OcioGpuTexture3DInfo {
7848            texture_name: std::ptr::null(),
7849            sampler_name: std::ptr::null(),
7850            edge_len: 0,
7851            interpolation: 0,
7852            has_binding_index: false,
7853            binding_index: 0,
7854        };
7855        crate::clear_last_error();
7856        let ok = unsafe {
7857            ocio_sys::ocio_gpu_shader_desc_get3d_texture_info(
7858                self.handle.as_ptr(),
7859                index,
7860                &mut info,
7861            )
7862        };
7863        crate::ocio_call_status().ok()?;
7864        ok.then_some(info)
7865    }
7866
7867    /// Returns a structured 1D/2D texture resource and copied texel payload.
7868    pub fn texture_2d(&self, index: u32) -> Option<GpuTexture2D> {
7869        self.try_texture_2d(index).ok().flatten()
7870    }
7871
7872    /// Return a structured 1D/2D texture resource, preserving bridge failures.
7873    ///
7874    /// An out-of-range `index` is returned as an OCIO error. `Ok(None)` means
7875    /// OCIO did not report a usable texture resource without raising an error.
7876    pub fn try_texture_2d(&self, index: u32) -> Result<Option<GpuTexture2D>> {
7877        let mut info = ocio_sys::OcioGpuTexture2DInfo {
7878            texture_name: std::ptr::null(),
7879            sampler_name: std::ptr::null(),
7880            width: 0,
7881            height: 0,
7882            channel: 0,
7883            dimensions: 0,
7884            interpolation: 0,
7885            has_binding_index: false,
7886            binding_index: 0,
7887        };
7888        crate::clear_last_error();
7889        let ok = unsafe {
7890            ocio_sys::ocio_gpu_shader_desc_get_texture_info(self.handle.as_ptr(), index, &mut info)
7891        };
7892        crate::ocio_call_status()?;
7893        if !ok {
7894            return Ok(None);
7895        }
7896        let channel = GpuTextureChannel::from_raw(info.channel)?;
7897        let dimensions = GpuTextureDimensions::from_raw(info.dimensions)?;
7898        let value_count = (info.width as usize)
7899            .checked_mul(info.height as usize)
7900            .and_then(|count| count.checked_mul(channel.channel_count()))
7901            .ok_or_else(|| {
7902                OcioError::ValidationFailed("GPU texture payload size overflowed usize".into())
7903            })?;
7904        let mut values = Vec::<f32>::new();
7905        try_resize_gpu_values(&mut values, value_count)?;
7906        crate::clear_last_error();
7907        let values_ok = unsafe {
7908            ocio_sys::ocio_gpu_shader_desc_copy_texture_values(
7909                self.handle.as_ptr(),
7910                index,
7911                values.as_mut_ptr(),
7912                values.len(),
7913            )
7914        };
7915        crate::ocio_call_status()?;
7916        if !values_ok {
7917            return Err(OcioError::ValidationFailed(
7918                "OCIO could not copy the reported GPU texture payload".into(),
7919            ));
7920        }
7921        let Some(texture_name) = required_ocio_string(info.texture_name) else {
7922            return Ok(None);
7923        };
7924        let Some(sampler_name) = required_ocio_string(info.sampler_name) else {
7925            return Ok(None);
7926        };
7927        Ok(Some(GpuTexture2D {
7928            texture_name,
7929            sampler_name,
7930            width: info.width,
7931            height: info.height,
7932            channel,
7933            dimensions,
7934            interpolation: interpolation_from_raw(info.interpolation),
7935            binding_index: info.has_binding_index.then_some(info.binding_index),
7936            values,
7937        }))
7938    }
7939
7940    /// Returns all structured 1D/2D texture resources currently reported by OCIO.
7941    pub fn textures_2d(&self) -> Vec<GpuTexture2D> {
7942        (0..self.num_textures())
7943            .filter_map(|index| self.texture_2d(index))
7944            .collect()
7945    }
7946
7947    fn gpu_language_from_raw(l: i32) -> Result<GpuLanguage> {
7948        Ok(match l {
7949            0 => GpuLanguage::Cg,
7950            1 => GpuLanguage::Glsl1_2,
7951            2 => GpuLanguage::Glsl1_3,
7952            3 => GpuLanguage::Glsl4_0,
7953            #[cfg(feature = "v2_5")]
7954            4 => GpuLanguage::GlslVk4_6,
7955            5 => GpuLanguage::HlslSm5_0,
7956            6 => GpuLanguage::Osl1,
7957            7 => GpuLanguage::GlslEs1_0,
7958            8 => GpuLanguage::GlslEs3_0,
7959            9 => GpuLanguage::Msl2_0,
7960            _ => {
7961                return Err(OcioError::ValidationFailed(format!(
7962                    "GPU language {l} is unavailable at the enabled interface level"
7963                )))
7964            }
7965        })
7966    }
7967
7968    /// Returns the shader language currently configured on the descriptor.
7969    /// Unknown languages or native errors fall back to GLSL 1.2; use
7970    /// [`Self::try_language`] to detect them.
7971    pub fn language(&self) -> GpuLanguage {
7972        self.try_language().unwrap_or(GpuLanguage::Glsl1_2)
7973    }
7974
7975    /// Return the configured shader language, preserving bridge failures and
7976    /// reporting native languages unavailable at this interface level.
7977    pub fn try_language(&self) -> Result<GpuLanguage> {
7978        crate::clear_last_error();
7979        let language = unsafe {
7980            ocio_sys::ocio_gpu_shader_desc_get_language(self.handle.as_ptr() as *mut c_void)
7981        };
7982        crate::ocio_call_status()?;
7983        Self::gpu_language_from_raw(language)
7984    }
7985
7986    /// Sets the shader language OCIO should target during extraction.
7987    pub fn set_language(&self, language: GpuLanguage) -> Result<()> {
7988        crate::clear_last_error();
7989        unsafe {
7990            ocio_sys::ocio_gpu_shader_desc_set_language(self.handle.as_ptr(), language as i32);
7991        }
7992        crate::ocio_call_status()
7993    }
7994
7995    /// Returns the configured shader entry-point name, if any.
7996    pub fn function_name(&self) -> Option<String> {
7997        self.try_function_name().ok().flatten()
7998    }
7999
8000    /// Return the configured shader entry-point name, preserving bridge errors.
8001    pub fn try_function_name(&self) -> Result<Option<String>> {
8002        crate::clear_last_error();
8003        let value = unsafe {
8004            cstr_to_opt_string(ocio_sys::ocio_gpu_shader_desc_get_function_name(
8005                self.handle.as_ptr() as *mut c_void,
8006            ))
8007        };
8008        crate::ocio_call_status()?;
8009        Ok(value)
8010    }
8011
8012    /// Sets the shader entry-point name used during extraction.
8013    pub fn set_function_name(&self, name: impl AsRef<str>) -> Result<()> {
8014        let n = cstring(name)?;
8015        crate::clear_last_error();
8016        unsafe {
8017            ocio_sys::ocio_gpu_shader_desc_set_function_name(
8018                self.handle.as_ptr(),
8019                n.as_ptr().cast(),
8020            );
8021        }
8022        crate::ocio_call_status()
8023    }
8024
8025    /// Returns the configured pixel variable name, if any.
8026    pub fn pixel_name(&self) -> Option<String> {
8027        self.try_pixel_name().ok().flatten()
8028    }
8029
8030    /// Return the configured pixel variable name, preserving bridge errors.
8031    pub fn try_pixel_name(&self) -> Result<Option<String>> {
8032        crate::clear_last_error();
8033        let value = unsafe {
8034            cstr_to_opt_string(ocio_sys::ocio_gpu_shader_desc_get_pixel_name(
8035                self.handle.as_ptr() as *mut c_void,
8036            ))
8037        };
8038        crate::ocio_call_status()?;
8039        Ok(value)
8040    }
8041
8042    /// Sets the pixel variable name used in emitted shader code.
8043    pub fn set_pixel_name(&self, name: impl AsRef<str>) -> Result<()> {
8044        let n = cstring(name)?;
8045        crate::clear_last_error();
8046        unsafe {
8047            ocio_sys::ocio_gpu_shader_desc_set_pixel_name(self.handle.as_ptr(), n.as_ptr().cast());
8048        }
8049        crate::ocio_call_status()
8050    }
8051
8052    /// Returns the explicit unique identifier configured for shader extraction, if any.
8053    pub fn unique_id(&self) -> Option<String> {
8054        self.try_unique_id().ok().flatten()
8055    }
8056
8057    /// Return the explicit unique identifier, preserving bridge errors.
8058    pub fn try_unique_id(&self) -> Result<Option<String>> {
8059        crate::clear_last_error();
8060        let value = unsafe {
8061            cstr_to_opt_string(ocio_sys::ocio_gpu_shader_desc_get_unique_id(
8062                self.handle.as_ptr() as *mut c_void,
8063            ))
8064        };
8065        crate::ocio_call_status()?;
8066        Ok(value)
8067    }
8068
8069    /// Sets the unique identifier OCIO should use for generated shader resources.
8070    pub fn set_unique_id(&self, uid: impl AsRef<str>) -> Result<()> {
8071        let uid = cstring(uid)?;
8072        crate::clear_last_error();
8073        unsafe {
8074            ocio_sys::ocio_gpu_shader_desc_set_unique_id(self.handle.as_ptr(), uid.as_ptr().cast());
8075        }
8076        crate::ocio_call_status()
8077    }
8078
8079    /// Returns the configured resource-name prefix, if any.
8080    pub fn resource_prefix(&self) -> Option<String> {
8081        self.try_resource_prefix().ok().flatten()
8082    }
8083
8084    /// Return the configured resource-name prefix, preserving bridge errors.
8085    pub fn try_resource_prefix(&self) -> Result<Option<String>> {
8086        crate::clear_last_error();
8087        let value = unsafe {
8088            cstr_to_opt_string(ocio_sys::ocio_gpu_shader_desc_get_resource_prefix(
8089                self.handle.as_ptr() as *mut c_void,
8090            ))
8091        };
8092        crate::ocio_call_status()?;
8093        Ok(value)
8094    }
8095
8096    /// Sets the prefix OCIO uses for generated resource names.
8097    pub fn set_resource_prefix(&self, prefix: impl AsRef<str>) -> Result<()> {
8098        let p = cstring(prefix)?;
8099        crate::clear_last_error();
8100        unsafe {
8101            ocio_sys::ocio_gpu_shader_desc_set_resource_prefix(
8102                self.handle.as_ptr(),
8103                p.as_ptr().cast(),
8104            );
8105        }
8106        crate::ocio_call_status()
8107    }
8108
8109    /// Configures the descriptor-set index and starting texture-binding slot used by OCIO.
8110    #[deprecated(
8111        since = "0.2.0",
8112        note = "panics on OCIO errors; prefer try_set_descriptor_set_index()"
8113    )]
8114    #[cfg(feature = "v2_5")]
8115    #[cfg_attr(docsrs, doc(cfg(feature = "v2_5")))]
8116    pub fn set_descriptor_set_index(&self, index: u32, texture_binding_start: u32) {
8117        self.try_set_descriptor_set_index(index, texture_binding_start)
8118            .expect("GpuShaderDesc::set_descriptor_set_index failed");
8119    }
8120
8121    /// Configures the descriptor-set index and starting texture-binding slot used by OCIO.
8122    #[cfg(feature = "v2_5")]
8123    #[cfg_attr(docsrs, doc(cfg(feature = "v2_5")))]
8124    pub fn try_set_descriptor_set_index(
8125        &self,
8126        index: u32,
8127        texture_binding_start: u32,
8128    ) -> Result<()> {
8129        crate::clear_last_error();
8130        unsafe {
8131            ocio_sys::ocio_gpu_shader_desc_set_descriptor_set_index(
8132                self.handle.as_ptr(),
8133                index,
8134                texture_binding_start,
8135            );
8136        }
8137        crate::ocio_call_status()
8138    }
8139
8140    /// Returns the configured descriptor-set index.
8141    #[cfg(feature = "v2_5")]
8142    #[cfg_attr(docsrs, doc(cfg(feature = "v2_5")))]
8143    pub fn descriptor_set_index(&self) -> u32 {
8144        self.try_descriptor_set_index().unwrap_or(0)
8145    }
8146
8147    /// Return the configured descriptor-set index, preserving bridge failures.
8148    #[cfg(feature = "v2_5")]
8149    #[cfg_attr(docsrs, doc(cfg(feature = "v2_5")))]
8150    pub fn try_descriptor_set_index(&self) -> Result<u32> {
8151        crate::clear_last_error();
8152        let index = unsafe {
8153            ocio_sys::ocio_gpu_shader_desc_get_descriptor_set_index(self.handle.as_ptr())
8154        };
8155        crate::ocio_call_status()?;
8156        Ok(index)
8157    }
8158
8159    /// Returns the configured starting binding slot for extracted textures.
8160    #[cfg(feature = "v2_5")]
8161    #[cfg_attr(docsrs, doc(cfg(feature = "v2_5")))]
8162    pub fn texture_binding_start(&self) -> u32 {
8163        self.try_texture_binding_start().unwrap_or(0)
8164    }
8165
8166    /// Return the starting texture binding slot, preserving bridge failures.
8167    #[cfg(feature = "v2_5")]
8168    #[cfg_attr(docsrs, doc(cfg(feature = "v2_5")))]
8169    pub fn try_texture_binding_start(&self) -> Result<u32> {
8170        crate::clear_last_error();
8171        let index = unsafe {
8172            ocio_sys::ocio_gpu_shader_desc_get_texture_binding_start(self.handle.as_ptr())
8173        };
8174        crate::ocio_call_status()?;
8175        Ok(index)
8176    }
8177
8178    /// Sets the maximum width OCIO may use when laying out extracted 1D textures.
8179    ///
8180    /// Values below 2 are rejected: native OCIO uses the width as a divisor,
8181    /// and uses width minus one as a loop increment. For widths of 2 or more,
8182    /// affected OCIO versions can still miscalculate padding for some LUT
8183    /// lengths; choose a width at least as large as the LUT when possible.
8184    pub fn set_texture_max_width(&self, max_width: u32) -> Result<()> {
8185        if max_width < 2 {
8186            return Err(OcioError::InvalidInput(
8187                "texture maximum width must be at least 2".into(),
8188            ));
8189        }
8190        crate::clear_last_error();
8191        unsafe {
8192            ocio_sys::ocio_gpu_shader_desc_set_texture_max_width_u32(
8193                self.handle.as_ptr(),
8194                max_width,
8195            );
8196        }
8197        crate::ocio_call_status()
8198    }
8199
8200    /// Check whether a known 1D LUT length fits OCIO's packed texture layout.
8201    ///
8202    /// Unpatched OCIO 2.4–2.6 may underflow its padding count for some combinations of
8203    /// LUT length and maximum width. This portable check detects those combinations
8204    /// even with the patched vendored source. It only checks the supplied length: optimization or
8205    /// other operations can introduce LUTs with different lengths, so success
8206    /// does not establish that an arbitrary GPU processor is safe to extract.
8207    /// A caller must validate every LUT length that reaches native extraction.
8208    pub fn validate_lut_texture_layout(&self, length: usize) -> Result<()> {
8209        Self::validate_lut_texture_width(self.try_texture_max_width()?, length)
8210    }
8211
8212    fn validate_lut_texture_width(max_width: u32, length: usize) -> Result<()> {
8213        if length < 2 {
8214            return Err(OcioError::InvalidInput(
8215                "LUT length must be at least 2".into(),
8216            ));
8217        }
8218        let maximum = u128::from(max_width);
8219        if maximum < 2 {
8220            return Err(OcioError::InvalidInput(
8221                "texture maximum width must be at least 2".into(),
8222            ));
8223        }
8224        let length = length as u128;
8225        let width = length.min(maximum);
8226        let height = length / maximum + 1;
8227        // OCIO uses unsigned long for dimensions and RGB indexing, which is
8228        // only 32 bits on Windows even in a 64-bit process.
8229        let native_limit = std::os::raw::c_ulong::MAX as u128;
8230        if length > native_limit / 3 || width * height > native_limit / 3 {
8231            return Err(OcioError::InvalidInput(
8232                "LUT texture layout exceeds native arithmetic limits".into(),
8233            ));
8234        }
8235        let padded = if height > 1 {
8236            length + (length - 1) / (width - 1)
8237        } else {
8238            length
8239        };
8240        if padded > width * height {
8241            return Err(OcioError::InvalidInput(
8242                "OpenColorIO LUT texture padding exceeds its allocated layout".into(),
8243            ));
8244        }
8245        Ok(())
8246    }
8247
8248    /// Controls whether OCIO may use native 1D textures instead of always promoting to 2D.
8249    pub fn set_allow_texture_1d(&self, allowed: bool) -> Result<()> {
8250        crate::clear_last_error();
8251        unsafe {
8252            ocio_sys::ocio_gpu_shader_desc_set_allow_texture_1d(self.handle.as_ptr(), allowed);
8253        }
8254        crate::ocio_call_status()
8255    }
8256
8257    /// Returns whether OCIO may use native 1D textures during extraction.
8258    pub fn allow_texture_1d(&self) -> bool {
8259        self.try_allow_texture_1d().unwrap_or(false)
8260    }
8261
8262    /// Return whether OCIO may use native 1D textures, preserving bridge failures.
8263    pub fn try_allow_texture_1d(&self) -> Result<bool> {
8264        crate::clear_last_error();
8265        let allowed =
8266            unsafe { ocio_sys::ocio_gpu_shader_desc_get_allow_texture_1d(self.handle.as_ptr()) };
8267        crate::ocio_call_status()?;
8268        Ok(allowed)
8269    }
8270
8271    /// Marks the beginning of shader-data collection with the provided OCIO resource UID.
8272    pub fn begin(&self, uid: impl AsRef<str>) -> Result<()> {
8273        let uid = cstring(uid)?;
8274        crate::clear_last_error();
8275        unsafe { ocio_sys::ocio_gpu_shader_desc_begin(self.handle.as_ptr(), uid.as_ptr()) };
8276        crate::ocio_call_status()
8277    }
8278
8279    /// Marks the end of shader-data collection.
8280    pub fn end(&self) -> Result<()> {
8281        crate::clear_last_error();
8282        unsafe { ocio_sys::ocio_gpu_shader_desc_end(self.handle.as_ptr()) };
8283        crate::ocio_call_status()
8284    }
8285
8286    /// Returns the next OCIO-managed resource index and advances the internal counter.
8287    pub fn next_resource_index(&self) -> u32 {
8288        self.try_next_resource_index().unwrap_or(0)
8289    }
8290
8291    /// Return and advance the OCIO-managed resource index, preserving bridge failures.
8292    pub fn try_next_resource_index(&self) -> Result<u32> {
8293        crate::clear_last_error();
8294        let index =
8295            unsafe { ocio_sys::ocio_gpu_shader_desc_get_next_resource_index(self.handle.as_ptr()) };
8296        crate::ocio_call_status()?;
8297        Ok(index)
8298    }
8299
8300    /// Append to OCIO 2.4's combined declaration section.
8301    ///
8302    /// On native OCIO 2.5 and later this uses the parameter declaration
8303    /// section for compatibility with non-Vulkan languages. Do not mix this
8304    /// method with the separate parameter/texture append methods, since the
8305    /// two native sections are assembled separately. Vulkan requires those
8306    /// separate methods and is rejected here.
8307    pub fn add_to_declare_shader_code(&self, shader_code: impl AsRef<str>) -> Result<()> {
8308        let shader_code = cstring(shader_code)?;
8309        crate::clear_last_error();
8310        unsafe {
8311            ocio_sys::ocio_gpu_shader_desc_add_to_declare_shader_code(
8312                self.handle.as_ptr(),
8313                shader_code.as_ptr(),
8314            )
8315        };
8316        crate::ocio_call_status()
8317    }
8318
8319    /// Appends text to the shader's parameter-declaration section.
8320    #[cfg(feature = "v2_5")]
8321    #[cfg_attr(docsrs, doc(cfg(feature = "v2_5")))]
8322    pub fn add_to_parameter_declare_shader_code(&self, shader_code: impl AsRef<str>) -> Result<()> {
8323        let shader_code = cstring(shader_code)?;
8324        crate::clear_last_error();
8325        unsafe {
8326            ocio_sys::ocio_gpu_shader_desc_add_to_parameter_declare_shader_code(
8327                self.handle.as_ptr(),
8328                shader_code.as_ptr(),
8329            );
8330        }
8331        crate::ocio_call_status()
8332    }
8333
8334    /// Appends text to the shader's texture-declaration section.
8335    #[cfg(feature = "v2_5")]
8336    #[cfg_attr(docsrs, doc(cfg(feature = "v2_5")))]
8337    pub fn add_to_texture_declare_shader_code(&self, shader_code: impl AsRef<str>) -> Result<()> {
8338        let shader_code = cstring(shader_code)?;
8339        crate::clear_last_error();
8340        unsafe {
8341            ocio_sys::ocio_gpu_shader_desc_add_to_texture_declare_shader_code(
8342                self.handle.as_ptr(),
8343                shader_code.as_ptr(),
8344            );
8345        }
8346        crate::ocio_call_status()
8347    }
8348
8349    /// Appends text to the shader's helper-method section.
8350    pub fn add_to_helper_shader_code(&self, shader_code: impl AsRef<str>) -> Result<()> {
8351        let shader_code = cstring(shader_code)?;
8352        crate::clear_last_error();
8353        unsafe {
8354            ocio_sys::ocio_gpu_shader_desc_add_to_helper_shader_code(
8355                self.handle.as_ptr(),
8356                shader_code.as_ptr(),
8357            );
8358        }
8359        crate::ocio_call_status()
8360    }
8361
8362    /// Appends text to the shader function's header section.
8363    pub fn add_to_function_header_shader_code(&self, shader_code: impl AsRef<str>) -> Result<()> {
8364        let shader_code = cstring(shader_code)?;
8365        crate::clear_last_error();
8366        unsafe {
8367            ocio_sys::ocio_gpu_shader_desc_add_to_function_header_shader_code(
8368                self.handle.as_ptr(),
8369                shader_code.as_ptr(),
8370            );
8371        }
8372        crate::ocio_call_status()
8373    }
8374
8375    /// Appends text to the shader function's body section.
8376    pub fn add_to_function_shader_code(&self, shader_code: impl AsRef<str>) -> Result<()> {
8377        let shader_code = cstring(shader_code)?;
8378        crate::clear_last_error();
8379        unsafe {
8380            ocio_sys::ocio_gpu_shader_desc_add_to_function_shader_code(
8381                self.handle.as_ptr(),
8382                shader_code.as_ptr(),
8383            );
8384        }
8385        crate::ocio_call_status()
8386    }
8387
8388    /// Appends text to the shader function's footer section.
8389    pub fn add_to_function_footer_shader_code(&self, shader_code: impl AsRef<str>) -> Result<()> {
8390        let shader_code = cstring(shader_code)?;
8391        crate::clear_last_error();
8392        unsafe {
8393            ocio_sys::ocio_gpu_shader_desc_add_to_function_footer_shader_code(
8394                self.handle.as_ptr(),
8395                shader_code.as_ptr(),
8396            );
8397        }
8398        crate::ocio_call_status()
8399    }
8400
8401    /// Returns the copied texel payload for a 1D/2D texture resource.
8402    pub fn texture_values(&self, index: u32) -> Vec<f32> {
8403        self.texture_2d(index)
8404            .map(|texture| texture.values)
8405            .unwrap_or_default()
8406    }
8407
8408    /// Borrow 1D/2D LUT values directly from OCIO without copying.
8409    ///
8410    /// The exclusive descriptor borrow prevents safe Rust code from mutating
8411    /// the descriptor while the returned slice is live. Native code using raw
8412    /// pointers must likewise avoid concurrent or reentrant mutation.
8413    ///
8414    /// ```compile_fail
8415    /// # use ocio_rs::GpuShaderDesc;
8416    /// # fn example(desc: &mut GpuShaderDesc) {
8417    /// let values = desc.texture_values_ref(0).unwrap();
8418    /// desc.set_function_name("changed").unwrap();
8419    /// println!("{}", values[0]);
8420    /// # }
8421    /// ```
8422    pub fn texture_values_ref(&mut self, index: u32) -> Result<&[f32]> {
8423        self.borrow_texture_values(index, false)
8424    }
8425
8426    fn borrow_texture_values(&mut self, index: u32, is_3d: bool) -> Result<&[f32]> {
8427        let mut len = 0usize;
8428        crate::clear_last_error();
8429        let ptr = unsafe {
8430            ocio_sys::ocio_gpu_shader_desc_borrow_texture_values(
8431                self.handle.as_ptr(),
8432                index,
8433                is_3d,
8434                &mut len,
8435            )
8436        };
8437        crate::ocio_call_status()?;
8438        if ptr.is_null() || len == 0 {
8439            return Err(OcioError::ValidationFailed(
8440                "OCIO returned no GPU texture values".into(),
8441            ));
8442        }
8443        // SAFETY: The bridge validates the count and returns OCIO-owned f32
8444        // storage. The exclusive descriptor borrow keeps it alive and prevents
8445        // safe mutations for the lifetime of the returned slice.
8446        Ok(unsafe { std::slice::from_raw_parts(ptr, len) })
8447    }
8448
8449    /// Adds a manual 1D/2D texture resource to the descriptor.
8450    ///
8451    /// The result contains the OCIO shader binding index on OpenColorIO 2.5.1
8452    /// and newer. OpenColorIO 2.4 performs the insertion but returns `None`
8453    /// because that release does not expose binding indexes.
8454    #[allow(clippy::too_many_arguments)]
8455    pub fn add_texture_2d(
8456        &self,
8457        texture_name: impl AsRef<str>,
8458        sampler_name: impl AsRef<str>,
8459        width: u32,
8460        height: u32,
8461        channel: GpuTextureChannel,
8462        dimensions: GpuTextureDimensions,
8463        interpolation: Interpolation,
8464        values: &[f32],
8465    ) -> Result<Option<u32>> {
8466        let expected = (width as usize)
8467            .checked_mul(height as usize)
8468            .and_then(|count| count.checked_mul(channel.channel_count()))
8469            .ok_or_else(|| {
8470                OcioError::ValidationFailed("GPU texture payload size overflowed usize".into())
8471            })?;
8472        if values.len() != expected {
8473            return Err(OcioError::ValidationFailed(format!(
8474                "gpu texture value count mismatch: expected {expected}, got {}",
8475                values.len()
8476            )));
8477        }
8478        let texture_name = cstring(texture_name)?;
8479        let sampler_name = cstring(sampler_name)?;
8480        crate::clear_last_error();
8481        let mut has_binding_index = false;
8482        let mut binding_index = 0;
8483        let inserted = unsafe {
8484            ocio_sys::ocio_gpu_shader_desc_add_texture(
8485                self.handle.as_ptr(),
8486                texture_name.as_ptr(),
8487                sampler_name.as_ptr(),
8488                width,
8489                height,
8490                channel as i32,
8491                dimensions as i32,
8492                interpolation as i32,
8493                values.as_ptr(),
8494                values.len(),
8495                &mut has_binding_index,
8496                &mut binding_index,
8497            )
8498        };
8499        crate::ocio_call_status()?;
8500        if !inserted {
8501            return Err(OcioError::ValidationFailed(
8502                "OpenColorIO rejected the 1D/2D texture".to_owned(),
8503            ));
8504        }
8505        Ok(has_binding_index.then_some(binding_index))
8506    }
8507
8508    /// Rebuilds the full shader text from the provided OCIO shader sections.
8509    pub fn create_shader_text(
8510        &self,
8511        shader_parameter_declarations: impl AsRef<str>,
8512        shader_texture_declarations: impl AsRef<str>,
8513        shader_helper_methods: impl AsRef<str>,
8514        shader_function_header: impl AsRef<str>,
8515        shader_function_body: impl AsRef<str>,
8516        shader_function_footer: impl AsRef<str>,
8517    ) -> Result<()> {
8518        let shader_parameter_declarations = cstring(shader_parameter_declarations)?;
8519        let shader_texture_declarations = cstring(shader_texture_declarations)?;
8520        let shader_helper_methods = cstring(shader_helper_methods)?;
8521        let shader_function_header = cstring(shader_function_header)?;
8522        let shader_function_body = cstring(shader_function_body)?;
8523        let shader_function_footer = cstring(shader_function_footer)?;
8524        crate::clear_last_error();
8525        unsafe {
8526            ocio_sys::ocio_gpu_shader_desc_create_shader_text(
8527                self.handle.as_ptr(),
8528                shader_parameter_declarations.as_ptr(),
8529                shader_texture_declarations.as_ptr(),
8530                shader_helper_methods.as_ptr(),
8531                shader_function_header.as_ptr(),
8532                shader_function_body.as_ptr(),
8533                shader_function_footer.as_ptr(),
8534            );
8535        }
8536        crate::ocio_call_status()
8537    }
8538
8539    /// Finalizes descriptor configuration before extraction when OCIO requires it.
8540    pub fn finalize(&self) -> Result<()> {
8541        crate::clear_last_error();
8542        unsafe {
8543            ocio_sys::ocio_gpu_shader_desc_finalize(self.handle.as_ptr() as *mut c_void);
8544        }
8545        crate::ocio_call_status()
8546    }
8547
8548    /// Returns the maximum width OCIO would like to use for GPU textures.
8549    pub fn texture_max_width(&self) -> u32 {
8550        self.try_texture_max_width().unwrap_or(0)
8551    }
8552
8553    /// Return the maximum OCIO GPU texture width, preserving bridge failures.
8554    pub fn try_texture_max_width(&self) -> Result<u32> {
8555        crate::clear_last_error();
8556        let width =
8557            unsafe { ocio_sys::ocio_gpu_shader_desc_get_texture_max_width(self.handle.as_ptr()) };
8558        crate::ocio_call_status()?;
8559        Ok(width)
8560    }
8561
8562    /// Returns OCIO's cache identifier for the current descriptor configuration.
8563    pub fn cache_id(&self) -> Option<String> {
8564        self.try_cache_id().ok().flatten()
8565    }
8566
8567    /// Return OCIO's descriptor cache identifier, preserving bridge errors.
8568    pub fn try_cache_id(&self) -> Result<Option<String>> {
8569        crate::clear_last_error();
8570        let value = unsafe {
8571            cstr_to_opt_string(ocio_sys::ocio_gpu_shader_desc_get_cache_id(
8572                self.handle.as_ptr() as *mut c_void,
8573            ))
8574        };
8575        crate::ocio_call_status()?;
8576        Ok(value)
8577    }
8578
8579    /// Borrow the native cache identifier without copying or UTF-8 conversion.
8580    ///
8581    /// OCIO invalidates this string when descriptor settings change. The
8582    /// exclusive borrow prevents safe Rust from mutating the descriptor or
8583    /// replacing its custom ID while the returned string is in use. Native
8584    /// aliases must not mutate it concurrently. Stub builds return `None`.
8585    ///
8586    /// ```compile_fail
8587    /// # use ocio_rs::GpuShaderDesc;
8588    /// # fn example(desc: &mut GpuShaderDesc) {
8589    /// let id = desc.cache_id_ref().unwrap().unwrap();
8590    /// desc.set_custom_cache_id(Some(c"new-id")).unwrap();
8591    /// println!("{:?}", id);
8592    /// # }
8593    /// ```
8594    pub fn cache_id_ref(&mut self) -> Result<Option<&std::ffi::CStr>> {
8595        crate::clear_last_error();
8596        let ptr = unsafe { ocio_sys::ocio_gpu_shader_desc_get_cache_id(self.handle.as_ptr()) };
8597        crate::ocio_call_status()?;
8598        if ptr.is_null() {
8599            Ok(None)
8600        } else {
8601            // SAFETY: the descriptor owns this NUL-terminated string and the
8602            // exclusive borrow prevents mutation or destruction in safe Rust.
8603            Ok(Some(unsafe { std::ffi::CStr::from_ptr(ptr) }))
8604        }
8605    }
8606
8607    /// Change or clear the cache ID override on a descriptor created by a
8608    /// custom extraction method. Clearing restores OCIO's native cache ID.
8609    ///
8610    /// This does not rename resources already generated during extraction;
8611    /// applications must manage any resource keys and external caches as well.
8612    /// Generic descriptors, including native clones, do not support this override.
8613    pub fn set_custom_cache_id(&mut self, id: Option<&std::ffi::CStr>) -> Result<()> {
8614        crate::clear_last_error();
8615        let ok = unsafe {
8616            ocio_sys::ocio_gpu_shader_desc_set_custom_cache_id(
8617                self.handle.as_ptr(),
8618                id.map_or(std::ptr::null(), std::ffi::CStr::as_ptr),
8619            )
8620        };
8621        crate::ocio_call_status()?;
8622        if !ok {
8623            return Err(OcioError::Ocio(
8624                "Could not set custom shader cache ID".into(),
8625            ));
8626        }
8627        Ok(())
8628    }
8629
8630    /// Returns the OCIO texture UID associated with a 1D/2D resource, if any.
8631    pub fn texture_uid(&self, index: i32) -> Option<String> {
8632        self.try_texture_uid(index).ok().flatten()
8633    }
8634
8635    /// Return a texture UID, preserving bridge errors.
8636    ///
8637    /// `Ok(None)` means no texture exists at `index`.
8638    pub fn try_texture_uid(&self, index: i32) -> Result<Option<String>> {
8639        crate::clear_last_error();
8640        let value = unsafe {
8641            cstr_to_opt_string(ocio_sys::ocio_gpu_shader_desc_get_texture_uid(
8642                self.handle.as_ptr(),
8643                index,
8644            ))
8645        };
8646        crate::ocio_call_status()?;
8647        Ok(value)
8648    }
8649
8650    // ── v2.5.1 ──
8651    /// Clone the descriptor configuration.
8652    ///
8653    /// In real OCIO builds this preserves descriptor settings such as language,
8654    /// function name, pixel name, resource prefix, and descriptor-set settings.
8655    /// Lower-level creator implementation knobs such as 1D texture width and
8656    /// `allow_texture_1d` may fall back to OCIO defaults on clone, and
8657    /// extracted shader payloads are not guaranteed to be copied into the clone.
8658    /// A custom cache ID from [`ShaderCreatorOptions`] is not preserved.
8659    pub fn clone_desc(&self) -> Option<GpuShaderDesc> {
8660        self.try_clone_desc().ok()
8661    }
8662
8663    /// Clone descriptor configuration and preserve native errors.
8664    /// See [`Self::clone_desc`] for which native settings are copied.
8665    pub fn try_clone_desc(&self) -> Result<GpuShaderDesc> {
8666        crate::clear_last_error();
8667        let h =
8668            unsafe { ocio_sys::ocio_gpu_shader_desc_clone(self.handle.as_ptr() as *mut c_void) };
8669        Ok(GpuShaderDesc {
8670            handle: crate::handle_result(h)?,
8671        })
8672    }
8673
8674    #[doc(hidden)]
8675    #[deprecated(since = "0.2.0", note = "compat alias; prefer clone_desc()")]
8676    #[allow(clippy::should_implement_trait)]
8677    pub fn clone(&self) -> Option<GpuShaderDesc> {
8678        self.clone_desc()
8679    }
8680
8681    /// Adds an existing dynamic property to this shader creator's native store.
8682    ///
8683    /// OCIO retains shared ownership; changes through either handle affect the
8684    /// same property, even after the original owner is dropped. Only one
8685    /// property of a given type can be added; duplicates return an OCIO error.
8686    /// This does not itself add a uniform or shader code. Like the descriptor,
8687    /// the property is thread-confined; native aliases must not be accessed
8688    /// concurrently or reentrantly.
8689    pub fn add_dynamic_property(&mut self, property: &DynamicProperty) -> Result<()> {
8690        crate::clear_last_error();
8691        unsafe {
8692            ocio_sys::ocio_gpu_shader_desc_add_dynamic_property(
8693                self.handle.as_ptr(),
8694                property.handle.as_ptr(),
8695            )
8696        };
8697        crate::ocio_call_status()
8698    }
8699
8700    /// Registers a live double uniform backed by a property already in this
8701    /// descriptor. Supports exposure, contrast, and gamma properties.
8702    ///
8703    /// The getter owns the native property reference and does not invoke Rust
8704    /// when sampled. Returns `false` if the uniform name already exists.
8705    /// This does not emit a shader declaration; custom creators must emit it.
8706    pub fn add_uniform_dynamic_double(
8707        &mut self,
8708        name: impl AsRef<str>,
8709        property_type: DynamicPropertyType,
8710    ) -> Result<bool> {
8711        if !matches!(
8712            property_type,
8713            DynamicPropertyType::Exposure
8714                | DynamicPropertyType::Contrast
8715                | DynamicPropertyType::Gamma
8716        ) {
8717            return Err(OcioError::InvalidInput(
8718                "a double dynamic property is required".into(),
8719            ));
8720        }
8721        let name = cstring(name)?;
8722        crate::clear_last_error();
8723        let added = unsafe {
8724            ocio_sys::ocio_gpu_shader_desc_add_uniform_dynamic_double(
8725                self.handle.as_ptr(),
8726                name.as_ptr(),
8727                property_type as i32,
8728            )
8729        };
8730        Self::bool_call_result(added)
8731    }
8732
8733    /// Returns the number of reported uniforms.
8734    pub fn num_uniforms(&self) -> u32 {
8735        self.try_num_uniforms().unwrap_or(0)
8736    }
8737
8738    /// Return the number of reported uniforms.
8739    pub fn try_num_uniforms(&self) -> Result<u32> {
8740        crate::clear_last_error();
8741        let value =
8742            unsafe { ocio_sys::ocio_gpu_shader_desc_get_num_uniforms_u32(self.handle.as_ptr()) };
8743        crate::ocio_call_status()?;
8744        Ok(value)
8745    }
8746
8747    #[doc(hidden)]
8748    #[deprecated(since = "0.2.0", note = "compat alias; prefer num_uniforms()")]
8749    pub fn get_num_uniforms_u32(&self) -> u32 {
8750        self.num_uniforms()
8751    }
8752
8753    /// Returns the size in bytes of OCIO's packed uniform buffer layout.
8754    #[cfg(feature = "v2_5")]
8755    #[cfg_attr(docsrs, doc(cfg(feature = "v2_5")))]
8756    pub fn uniform_buffer_size(&self) -> usize {
8757        self.try_uniform_buffer_size().unwrap_or(0)
8758    }
8759
8760    /// Return the packed uniform-buffer size, preserving bridge errors.
8761    #[cfg(feature = "v2_5")]
8762    #[cfg_attr(docsrs, doc(cfg(feature = "v2_5")))]
8763    pub fn try_uniform_buffer_size(&self) -> Result<usize> {
8764        crate::clear_last_error();
8765        let value = unsafe {
8766            ocio_sys::ocio_gpu_shader_desc_get_uniform_buffer_size_bytes(self.handle.as_ptr())
8767        };
8768        crate::ocio_call_status()?;
8769        Ok(value)
8770    }
8771
8772    #[doc(hidden)]
8773    #[deprecated(since = "0.2.0", note = "compat alias; prefer uniform_buffer_size()")]
8774    #[cfg(feature = "v2_5")]
8775    #[cfg_attr(docsrs, doc(cfg(feature = "v2_5")))]
8776    pub fn get_uniform_buffer_size_bytes(&self) -> usize {
8777        self.uniform_buffer_size()
8778    }
8779
8780    /// Adds a scalar floating-point uniform and returns `false` when the name already exists.
8781    pub fn add_uniform_f64(&self, name: impl AsRef<str>, value: f64) -> Result<bool> {
8782        let name = cstring(name)?;
8783        crate::clear_last_error();
8784        let ok = unsafe {
8785            ocio_sys::ocio_gpu_shader_desc_add_uniform_double(
8786                self.handle.as_ptr(),
8787                name.as_ptr(),
8788                value,
8789            )
8790        };
8791        Self::bool_call_result(ok)
8792    }
8793
8794    /// Adds a live double uniform backed by a thread-safe Rust getter.
8795    ///
8796    /// OCIO owns the getter until it no longer needs the uniform. It may invoke
8797    /// the getter multiple times and from native code; do not reenter the same
8798    /// descriptor from the getter. A panic is contained and reported as an
8799    /// OCIO error when the uniform is sampled. Returns `false` for a duplicate
8800    /// uniform name, in which case the supplied getter is dropped immediately.
8801    pub fn add_uniform_f64_getter<F>(&self, name: impl AsRef<str>, getter: F) -> Result<bool>
8802    where
8803        F: Fn() -> f64 + Send + Sync + 'static,
8804    {
8805        unsafe extern "C" fn invoke<F: Fn() -> f64>(context: *mut c_void, out: *mut f64) -> bool {
8806            match crate::catch_callback_unwind(std::panic::AssertUnwindSafe(|| {
8807                let getter = unsafe { &*context.cast::<F>() };
8808                unsafe { *out = getter() };
8809            })) {
8810                Ok(()) => true,
8811                Err(_) => false,
8812            }
8813        }
8814        unsafe extern "C" fn release<F>(context: *mut c_void) {
8815            let _ = crate::catch_callback_unwind(std::panic::AssertUnwindSafe(|| unsafe {
8816                drop(Box::from_raw(context.cast::<F>()));
8817            }));
8818        }
8819        let name = cstring(name)?;
8820        let context = Box::into_raw(Box::new(getter)).cast();
8821        crate::clear_last_error();
8822        let ok = unsafe {
8823            ocio_sys::ocio_gpu_shader_desc_add_uniform_double_getter(
8824                self.handle.as_ptr(),
8825                name.as_ptr(),
8826                context,
8827                invoke::<F>,
8828                release::<F>,
8829            )
8830        };
8831        Self::bool_call_result(ok)
8832    }
8833
8834    /// Adds a boolean uniform and returns `false` when the name already exists.
8835    pub fn add_uniform_bool(&self, name: impl AsRef<str>, value: bool) -> Result<bool> {
8836        let name = cstring(name)?;
8837        crate::clear_last_error();
8838        let ok = unsafe {
8839            ocio_sys::ocio_gpu_shader_desc_add_uniform_bool(
8840                self.handle.as_ptr(),
8841                name.as_ptr(),
8842                value,
8843            )
8844        };
8845        Self::bool_call_result(ok)
8846    }
8847
8848    /// Adds a live boolean uniform; see [`Self::add_uniform_f64_getter`] for
8849    /// callback ownership, thread-safety, and panic behavior.
8850    pub fn add_uniform_bool_getter<F>(&self, name: impl AsRef<str>, getter: F) -> Result<bool>
8851    where
8852        F: Fn() -> bool + Send + Sync + 'static,
8853    {
8854        unsafe extern "C" fn invoke<F: Fn() -> bool>(context: *mut c_void, out: *mut bool) -> bool {
8855            crate::catch_callback_unwind(std::panic::AssertUnwindSafe(|| {
8856                let getter = unsafe { &*context.cast::<F>() };
8857                unsafe { *out = getter() };
8858            }))
8859            .is_ok()
8860        }
8861        unsafe extern "C" fn release<F>(context: *mut c_void) {
8862            let _ = crate::catch_callback_unwind(std::panic::AssertUnwindSafe(|| unsafe {
8863                drop(Box::from_raw(context.cast::<F>()));
8864            }));
8865        }
8866        let name = cstring(name)?;
8867        let context = Box::into_raw(Box::new(getter)).cast();
8868        crate::clear_last_error();
8869        let ok = unsafe {
8870            ocio_sys::ocio_gpu_shader_desc_add_uniform_bool_getter(
8871                self.handle.as_ptr(),
8872                name.as_ptr(),
8873                context,
8874                invoke::<F>,
8875                release::<F>,
8876            )
8877        };
8878        Self::bool_call_result(ok)
8879    }
8880
8881    /// Adds a three-component floating-point uniform and returns `false` when the name already exists.
8882    pub fn add_uniform_float3(&self, name: impl AsRef<str>, value: [f32; 3]) -> Result<bool> {
8883        let name = cstring(name)?;
8884        crate::clear_last_error();
8885        let ok = unsafe {
8886            ocio_sys::ocio_gpu_shader_desc_add_uniform_float3(
8887                self.handle.as_ptr(),
8888                name.as_ptr(),
8889                value[0],
8890                value[1],
8891                value[2],
8892            )
8893        };
8894        Self::bool_call_result(ok)
8895    }
8896
8897    /// Adds a live three-component uniform; see [`Self::add_uniform_f64_getter`]
8898    /// for callback ownership and panic behavior. Native callers must not sample
8899    /// the same descriptor concurrently or retain a returned native reference
8900    /// across another sample of this uniform.
8901    pub fn add_uniform_float3_getter<F>(&self, name: impl AsRef<str>, getter: F) -> Result<bool>
8902    where
8903        F: Fn() -> [f32; 3] + Send + Sync + 'static,
8904    {
8905        unsafe extern "C" fn invoke<F: Fn() -> [f32; 3]>(
8906            context: *mut c_void,
8907            out: *mut f32,
8908        ) -> bool {
8909            crate::catch_callback_unwind(std::panic::AssertUnwindSafe(|| {
8910                let getter = unsafe { &*context.cast::<F>() };
8911                let value = getter();
8912                unsafe { std::ptr::copy_nonoverlapping(value.as_ptr(), out, 3) };
8913            }))
8914            .is_ok()
8915        }
8916        unsafe extern "C" fn release<F>(context: *mut c_void) {
8917            let _ = crate::catch_callback_unwind(std::panic::AssertUnwindSafe(|| unsafe {
8918                drop(Box::from_raw(context.cast::<F>()));
8919            }));
8920        }
8921        let name = cstring(name)?;
8922        let context = Box::into_raw(Box::new(getter)).cast();
8923        crate::clear_last_error();
8924        let ok = unsafe {
8925            ocio_sys::ocio_gpu_shader_desc_add_uniform_float3_getter(
8926                self.handle.as_ptr(),
8927                name.as_ptr(),
8928                context,
8929                invoke::<F>,
8930                release::<F>,
8931            )
8932        };
8933        Self::bool_call_result(ok)
8934    }
8935
8936    /// Adds a floating-point array uniform and returns `false` when the name already exists.
8937    pub fn add_uniform_f32_array(
8938        &self,
8939        name: impl AsRef<str>,
8940        values: &[f32],
8941        max_size: u32,
8942    ) -> Result<bool> {
8943        if values.len() > i32::MAX as usize || values.len() > max_size as usize {
8944            return Err(OcioError::ValidationFailed(format!(
8945                "gpu uniform value count {} exceeds max_size {} or the native integer limit",
8946                values.len(),
8947                max_size
8948            )));
8949        }
8950        let name = cstring(name)?;
8951        crate::clear_last_error();
8952        let ok = unsafe {
8953            ocio_sys::ocio_gpu_shader_desc_add_uniform_vector_float(
8954                self.handle.as_ptr(),
8955                name.as_ptr(),
8956                values.as_ptr(),
8957                values.len(),
8958                max_size,
8959            )
8960        };
8961        Self::bool_call_result(ok)
8962    }
8963
8964    /// Adds a live float array uniform. The getter fills the provided buffer and
8965    /// returns the initialized length, which must not exceed `max_size`.
8966    ///
8967    /// Storage is allocated once at registration. Each native size query
8968    /// refreshes the snapshot; its pointer getter reads that same snapshot.
8969    /// Native callers must serialize descriptor access and consume the pointer
8970    /// before the next size query. Panics and excessive lengths are errors.
8971    pub fn add_uniform_f32_array_getter<F>(
8972        &self,
8973        name: impl AsRef<str>,
8974        max_size: u32,
8975        getter: F,
8976    ) -> Result<bool>
8977    where
8978        F: Fn(&mut [f32]) -> usize + Send + Sync + 'static,
8979    {
8980        unsafe extern "C" fn invoke<F: Fn(&mut [f32]) -> usize>(
8981            context: *mut c_void,
8982            data: *mut f32,
8983            capacity: usize,
8984            length: *mut usize,
8985        ) -> bool {
8986            crate::catch_callback_unwind(std::panic::AssertUnwindSafe(|| {
8987                let getter = unsafe { &*context.cast::<F>() };
8988                let data = if capacity == 0 {
8989                    std::ptr::NonNull::<f32>::dangling().as_ptr()
8990                } else {
8991                    data
8992                };
8993                let buffer = unsafe { std::slice::from_raw_parts_mut(data, capacity) };
8994                unsafe { *length = getter(buffer) };
8995            }))
8996            .is_ok()
8997        }
8998        unsafe extern "C" fn release<F>(context: *mut c_void) {
8999            let _ = crate::catch_callback_unwind(std::panic::AssertUnwindSafe(|| unsafe {
9000                drop(Box::from_raw(context.cast::<F>()));
9001            }));
9002        }
9003        if max_size > i32::MAX as u32
9004            || max_size as usize > isize::MAX as usize / std::mem::size_of::<f32>()
9005        {
9006            return Err(OcioError::ValidationFailed(
9007                "uniform max_size exceeds the native integer limit".into(),
9008            ));
9009        }
9010        let name = cstring(name)?;
9011        let context = Box::into_raw(Box::new(getter)).cast();
9012        crate::clear_last_error();
9013        let ok = unsafe {
9014            ocio_sys::ocio_gpu_shader_desc_add_uniform_vector_float_getter(
9015                self.handle.as_ptr(),
9016                name.as_ptr(),
9017                max_size,
9018                context,
9019                invoke::<F>,
9020                release::<F>,
9021            )
9022        };
9023        Self::bool_call_result(ok)
9024    }
9025
9026    /// Adds an integer array uniform and returns `false` when the name already exists.
9027    pub fn add_uniform_i32_array(
9028        &self,
9029        name: impl AsRef<str>,
9030        values: &[i32],
9031        max_size: u32,
9032    ) -> Result<bool> {
9033        if values.len() > i32::MAX as usize || values.len() > max_size as usize {
9034            return Err(OcioError::ValidationFailed(format!(
9035                "gpu uniform value count {} exceeds max_size {} or the native integer limit",
9036                values.len(),
9037                max_size
9038            )));
9039        }
9040        let name = cstring(name)?;
9041        crate::clear_last_error();
9042        let ok = unsafe {
9043            ocio_sys::ocio_gpu_shader_desc_add_uniform_vector_int(
9044                self.handle.as_ptr(),
9045                name.as_ptr(),
9046                values.as_ptr(),
9047                values.len(),
9048                max_size,
9049            )
9050        };
9051        Self::bool_call_result(ok)
9052    }
9053
9054    /// Adds a live integer array uniform with the same snapshot and lifetime
9055    /// rules as [`Self::add_uniform_f32_array_getter`].
9056    pub fn add_uniform_i32_array_getter<F>(
9057        &self,
9058        name: impl AsRef<str>,
9059        max_size: u32,
9060        getter: F,
9061    ) -> Result<bool>
9062    where
9063        F: Fn(&mut [i32]) -> usize + Send + Sync + 'static,
9064    {
9065        unsafe extern "C" fn invoke<F: Fn(&mut [i32]) -> usize>(
9066            context: *mut c_void,
9067            data: *mut i32,
9068            capacity: usize,
9069            length: *mut usize,
9070        ) -> bool {
9071            crate::catch_callback_unwind(std::panic::AssertUnwindSafe(|| {
9072                let getter = unsafe { &*context.cast::<F>() };
9073                let data = if capacity == 0 {
9074                    std::ptr::NonNull::<i32>::dangling().as_ptr()
9075                } else {
9076                    data
9077                };
9078                let buffer = unsafe { std::slice::from_raw_parts_mut(data, capacity) };
9079                unsafe { *length = getter(buffer) };
9080            }))
9081            .is_ok()
9082        }
9083        unsafe extern "C" fn release<F>(context: *mut c_void) {
9084            let _ = crate::catch_callback_unwind(std::panic::AssertUnwindSafe(|| unsafe {
9085                drop(Box::from_raw(context.cast::<F>()));
9086            }));
9087        }
9088        if max_size > i32::MAX as u32
9089            || max_size as usize > isize::MAX as usize / std::mem::size_of::<i32>()
9090        {
9091            return Err(OcioError::ValidationFailed(
9092                "uniform max_size exceeds the native integer limit".into(),
9093            ));
9094        }
9095        let name = cstring(name)?;
9096        let context = Box::into_raw(Box::new(getter)).cast();
9097        crate::clear_last_error();
9098        let ok = unsafe {
9099            ocio_sys::ocio_gpu_shader_desc_add_uniform_vector_int_getter(
9100                self.handle.as_ptr(),
9101                name.as_ptr(),
9102                max_size,
9103                context,
9104                invoke::<F>,
9105                release::<F>,
9106            )
9107        };
9108        Self::bool_call_result(ok)
9109    }
9110
9111    /// Returns the number of dynamic properties attached to the descriptor.
9112    pub fn num_dynamic_properties(&self) -> u32 {
9113        self.try_num_dynamic_properties().unwrap_or(0)
9114    }
9115
9116    /// Return the number of dynamic properties attached to the descriptor.
9117    pub fn try_num_dynamic_properties(&self) -> Result<u32> {
9118        crate::clear_last_error();
9119        let value = unsafe {
9120            ocio_sys::ocio_gpu_shader_desc_get_num_dynamic_properties_u32(self.handle.as_ptr())
9121        };
9122        crate::ocio_call_status()?;
9123        Ok(value)
9124    }
9125
9126    /// Returns a dynamic property by ordinal index, if present.
9127    pub fn dynamic_property_by_index(&self, index: u32) -> Option<DynamicProperty> {
9128        self.try_dynamic_property_by_index(index).ok().flatten()
9129    }
9130
9131    /// Return a dynamic property by ordinal index, preserving bridge failures.
9132    ///
9133    /// An out-of-range `index` is reported as an OCIO error. The legacy
9134    /// [`Self::dynamic_property_by_index`] helper maps that error to `None`.
9135    pub fn try_dynamic_property_by_index(&self, index: u32) -> Result<Option<DynamicProperty>> {
9136        crate::clear_last_error();
9137        let handle = unsafe {
9138            ocio_sys::ocio_gpu_shader_desc_get_dynamic_property_by_index(
9139                self.handle.as_ptr(),
9140                index,
9141            )
9142        };
9143        crate::ocio_call_status()?;
9144        Ok(NonNull::new(handle).map(|handle| DynamicProperty { handle }))
9145    }
9146
9147    /// Returns the dynamic property associated with the given OCIO property kind, if present.
9148    pub fn dynamic_property(&self, property_type: DynamicPropertyType) -> Option<DynamicProperty> {
9149        self.try_dynamic_property(property_type).ok().flatten()
9150    }
9151
9152    /// Return the dynamic property for an OCIO property kind, preserving bridge failures.
9153    ///
9154    /// An absent property is reported as a native error. The legacy
9155    /// [`Self::dynamic_property`] helper maps that error to `None`.
9156    pub fn try_dynamic_property(
9157        &self,
9158        property_type: DynamicPropertyType,
9159    ) -> Result<Option<DynamicProperty>> {
9160        crate::clear_last_error();
9161        let handle = unsafe {
9162            ocio_sys::ocio_gpu_shader_desc_get_dynamic_property(
9163                self.handle.as_ptr(),
9164                property_type as i32,
9165            )
9166        };
9167        crate::ocio_call_status()?;
9168        Ok(NonNull::new(handle).map(|handle| DynamicProperty { handle }))
9169    }
9170
9171    /// Returns whether the descriptor exposes the given OCIO dynamic property kind.
9172    pub fn has_dynamic_property_kind(&self, prop_type: DynamicPropertyType) -> bool {
9173        self.try_has_dynamic_property_kind(prop_type)
9174            .unwrap_or(false)
9175    }
9176
9177    /// Fallible variant of [`Self::has_dynamic_property_kind`].
9178    pub fn try_has_dynamic_property_kind(&self, prop_type: DynamicPropertyType) -> Result<bool> {
9179        crate::clear_last_error();
9180        let value = unsafe {
9181            ocio_sys::ocio_gpu_shader_desc_has_dynamic_property(
9182                self.handle.as_ptr(),
9183                prop_type as i32,
9184            )
9185        };
9186        crate::ocio_call_status()?;
9187        Ok(value)
9188    }
9189
9190    /// Returns a structured uniform record with Rust-owned payload values.
9191    pub fn uniform(&self, index: u32) -> Option<GpuUniform> {
9192        self.try_uniform(index).ok().flatten()
9193    }
9194
9195    /// Return a structured uniform record, preserving bridge failures.
9196    ///
9197    /// An out-of-range `index` is returned as an OCIO error. `Ok(None)` means
9198    /// OCIO did not report a usable uniform without raising an error. A uniform
9199    /// with a payload that OCIO cannot expose through this ABI is returned with
9200    /// [`GpuUniformValue::Unsupported`].
9201    /// Dynamic arrays are sampled with their actual copied length. If an array
9202    /// repeatedly outgrows the buffer during sampling, an error is returned.
9203    pub fn try_uniform(&self, index: u32) -> Result<Option<GpuUniform>> {
9204        let mut info = ocio_sys::OcioGpuUniformInfo {
9205            name: std::ptr::null(),
9206            type_: 5,
9207            has_buffer_offset: false,
9208            buffer_offset: 0,
9209            value_count: 0,
9210        };
9211        crate::clear_last_error();
9212        let ok = unsafe {
9213            ocio_sys::ocio_gpu_shader_desc_get_uniform_info(self.handle.as_ptr(), index, &mut info)
9214        };
9215        crate::ocio_call_status()?;
9216        if !ok {
9217            return Ok(None);
9218        }
9219        let uniform_type = GpuUniformType::from_raw(info.type_);
9220        let value = match uniform_type {
9221            GpuUniformType::VectorInt => {
9222                let mut values = Vec::<i32>::new();
9223                try_resize_gpu_values(&mut values, info.value_count)?;
9224                let mut copied = false;
9225                for attempt in 0..3 {
9226                    let mut actual = 0;
9227                    crate::clear_last_error();
9228                    let ok = unsafe {
9229                        ocio_sys::ocio_gpu_shader_desc_copy_uniform_i32_values_with_count(
9230                            self.handle.as_ptr(),
9231                            index,
9232                            values.as_mut_ptr(),
9233                            values.len(),
9234                            &mut actual,
9235                        )
9236                    };
9237                    crate::ocio_call_status()?;
9238                    if ok {
9239                        values.truncate(actual);
9240                        info.value_count = actual;
9241                        copied = true;
9242                        break;
9243                    }
9244                    if actual <= values.len() {
9245                        break;
9246                    }
9247                    if attempt == 2 {
9248                        return Err(OcioError::ValidationFailed(
9249                            "uniform array kept growing while sampled".into(),
9250                        ));
9251                    }
9252                    try_resize_gpu_values(&mut values, actual)?;
9253                }
9254                if copied {
9255                    GpuUniformValue::I32(values)
9256                } else {
9257                    GpuUniformValue::Unsupported
9258                }
9259            }
9260            GpuUniformType::Unknown => GpuUniformValue::Unsupported,
9261            _ => {
9262                let mut values = Vec::<f32>::new();
9263                try_resize_gpu_values(&mut values, info.value_count)?;
9264                let mut copied = false;
9265                for attempt in 0..3 {
9266                    let mut actual = 0;
9267                    crate::clear_last_error();
9268                    let ok = unsafe {
9269                        ocio_sys::ocio_gpu_shader_desc_copy_uniform_f32_values_with_count(
9270                            self.handle.as_ptr(),
9271                            index,
9272                            values.as_mut_ptr(),
9273                            values.len(),
9274                            &mut actual,
9275                        )
9276                    };
9277                    crate::ocio_call_status()?;
9278                    if ok {
9279                        values.truncate(actual);
9280                        info.value_count = actual;
9281                        copied = true;
9282                        break;
9283                    }
9284                    if actual <= values.len() {
9285                        break;
9286                    }
9287                    if attempt == 2 {
9288                        return Err(OcioError::ValidationFailed(
9289                            "uniform array kept growing while sampled".into(),
9290                        ));
9291                    }
9292                    try_resize_gpu_values(&mut values, actual)?;
9293                }
9294                if copied {
9295                    GpuUniformValue::F32(values)
9296                } else {
9297                    GpuUniformValue::Unsupported
9298                }
9299            }
9300        };
9301        let Some(name) = required_ocio_string(info.name) else {
9302            return Ok(None);
9303        };
9304        Ok(Some(GpuUniform {
9305            name,
9306            uniform_type,
9307            buffer_offset: info.has_buffer_offset.then_some(info.buffer_offset),
9308            value_count: info.value_count,
9309            value,
9310        }))
9311    }
9312
9313    #[doc(hidden)]
9314    #[deprecated(since = "0.2.0", note = "compat alias; prefer uniform()")]
9315    pub fn get_uniform_info(&self, index: u32) -> Option<GpuUniform> {
9316        self.uniform(index)
9317    }
9318
9319    /// Returns the scalar value count for a uniform, or `0` when absent.
9320    pub fn uniform_value_count(&self, index: u32) -> usize {
9321        self.try_uniform_value_count(index).unwrap_or(0)
9322    }
9323
9324    /// Return the current scalar count without a Rust-owned payload copy.
9325    ///
9326    /// For a live array OCIO invokes its size getter. A registered Rust array
9327    /// getter may fill its preallocated native snapshot and execute user code;
9328    /// external getters may do their own work or allocation. An invalid index
9329    /// or a native error is returned as an error.
9330    pub fn try_uniform_value_count(&self, index: u32) -> Result<usize> {
9331        crate::clear_last_error();
9332        let count = unsafe {
9333            ocio_sys::ocio_gpu_shader_desc_get_uniform_value_count(self.handle.as_ptr(), index)
9334        };
9335        crate::ocio_call_status()?;
9336        Ok(count)
9337    }
9338
9339    #[doc(hidden)]
9340    #[deprecated(since = "0.2.0", note = "compat alias; prefer uniform_value_count()")]
9341    pub fn get_uniform_value_count(&self, index: u32) -> usize {
9342        self.uniform_value_count(index)
9343    }
9344
9345    /// Returns copied floating-point uniform values when the uniform uses an `f32` payload.
9346    pub fn uniform_values_f32(&self, index: u32) -> Vec<f32> {
9347        match self.uniform(index).map(|uniform| uniform.value) {
9348            Some(GpuUniformValue::F32(values)) => values,
9349            _ => Vec::new(),
9350        }
9351    }
9352
9353    /// Reads the current native double uniform value without narrowing to `f32`.
9354    /// Returns `Ok(None)` for a uniform of another type; invalid indices and
9355    /// failures from the native or Rust getter are returned as errors.
9356    pub fn try_uniform_f64_value(&self, index: u32) -> Result<Option<f64>> {
9357        let mut value = 0.0;
9358        crate::clear_last_error();
9359        let found = unsafe {
9360            ocio_sys::ocio_gpu_shader_desc_get_uniform_double_value(
9361                self.handle.as_ptr(),
9362                index,
9363                &mut value,
9364            )
9365        };
9366        crate::ocio_call_status()?;
9367        Ok(found.then_some(value))
9368    }
9369
9370    /// Read a native boolean uniform without converting it to a float.
9371    /// Returns `Ok(None)` for another uniform type; invalid indices and getter
9372    /// failures are returned as errors. `Some(false)` is a valid value.
9373    pub fn try_uniform_bool_value(&self, index: u32) -> Result<Option<bool>> {
9374        let mut value = false;
9375        crate::clear_last_error();
9376        let found = unsafe {
9377            ocio_sys::ocio_gpu_shader_desc_get_uniform_bool_value(
9378                self.handle.as_ptr(),
9379                index,
9380                &mut value,
9381            )
9382        };
9383        crate::ocio_call_status()?;
9384        Ok(found.then_some(value))
9385    }
9386
9387    /// Read the current floating-point uniform payload into caller-owned storage.
9388    ///
9389    /// Returns `Ok(false)` if the uniform is not representable as floats or
9390    /// `values` is too short. Double uniforms are converted to `f32`, and bool
9391    /// uniforms are represented as 0.0 or 1.0, matching OCIO GPU conventions.
9392    /// An invalid index or native failure is returned as an error. The binding
9393    /// does not allocate a Rust output buffer. The native getter is called on
9394    /// every invocation and may itself allocate or execute a Rust callback.
9395    pub fn try_copy_uniform_f32_into(&self, index: u32, values: &mut [f32]) -> Result<bool> {
9396        crate::clear_last_error();
9397        // SAFETY: The bridge writes at most values.len() floats into the slice.
9398        let copied = unsafe {
9399            ocio_sys::ocio_gpu_shader_desc_copy_uniform_f32_values(
9400                self.handle.as_ptr(),
9401                index,
9402                values.as_mut_ptr(),
9403                values.len(),
9404            )
9405        };
9406        crate::ocio_call_status()?;
9407        Ok(copied)
9408    }
9409
9410    #[doc(hidden)]
9411    #[deprecated(
9412        since = "0.2.0",
9413        note = "compat alias; prefer uniform_values_f32() or uniform()"
9414    )]
9415    pub fn copy_uniform_f32_values(&self, index: u32) -> Vec<f32> {
9416        self.uniform_values_f32(index)
9417    }
9418
9419    /// Returns copied integer uniform values when the uniform uses an `i32` payload.
9420    pub fn uniform_values_i32(&self, index: u32) -> Vec<i32> {
9421        match self.uniform(index).map(|uniform| uniform.value) {
9422            Some(GpuUniformValue::I32(values)) => values,
9423            _ => Vec::new(),
9424        }
9425    }
9426
9427    /// Read an integer-vector uniform into caller-owned storage without a
9428    /// binding-side Rust output allocation. Native getters or user callbacks
9429    /// may allocate. Returns `Ok(false)` for a different type or a short
9430    /// buffer; invalid indices and native failures are returned as errors.
9431    pub fn try_copy_uniform_i32_into(&self, index: u32, values: &mut [i32]) -> Result<bool> {
9432        crate::clear_last_error();
9433        // SAFETY: The bridge writes at most values.len() integers into the slice.
9434        let copied = unsafe {
9435            ocio_sys::ocio_gpu_shader_desc_copy_uniform_i32_values(
9436                self.handle.as_ptr(),
9437                index,
9438                values.as_mut_ptr(),
9439                values.len(),
9440            )
9441        };
9442        crate::ocio_call_status()?;
9443        Ok(copied)
9444    }
9445
9446    #[doc(hidden)]
9447    #[deprecated(
9448        since = "0.2.0",
9449        note = "compat alias; prefer uniform_values_i32() or uniform()"
9450    )]
9451    pub fn copy_uniform_i32_values(&self, index: u32) -> Vec<i32> {
9452        self.uniform_values_i32(index)
9453    }
9454
9455    /// Returns all structured uniform records currently reported by OCIO.
9456    pub fn uniforms(&self) -> Vec<GpuUniform> {
9457        (0..self.num_uniforms())
9458            .filter_map(|index| self.uniform(index))
9459            .collect()
9460    }
9461
9462    /// Returns the number of reported 3D texture resources.
9463    pub fn num_3d_textures(&self) -> u32 {
9464        self.try_num_3d_textures().unwrap_or(0)
9465    }
9466
9467    /// Return the number of reported 3D texture resources.
9468    pub fn try_num_3d_textures(&self) -> Result<u32> {
9469        crate::clear_last_error();
9470        let value =
9471            unsafe { ocio_sys::ocio_gpu_shader_desc_get_num3d_textures_u32(self.handle.as_ptr()) };
9472        crate::ocio_call_status()?;
9473        Ok(value)
9474    }
9475
9476    #[doc(hidden)]
9477    #[deprecated(since = "0.2.0", note = "compat alias; prefer num_textures()")]
9478    pub fn get_num_textures_u32(&self) -> u32 {
9479        self.num_textures()
9480    }
9481
9482    /// Returns the scalar count for a 1D/2D texture resource without copying it.
9483    /// Returns zero on an invalid index or native error; use
9484    /// [`Self::try_texture_value_count`] to distinguish errors.
9485    pub fn texture_value_count(&self, index: u32) -> usize {
9486        self.try_texture_value_count(index).unwrap_or(0)
9487    }
9488
9489    /// Return the scalar count for a 1D/2D texture without allocating.
9490    pub fn try_texture_value_count(&self, index: u32) -> Result<usize> {
9491        crate::clear_last_error();
9492        let count = unsafe {
9493            ocio_sys::ocio_gpu_shader_desc_get_texture_value_count(self.handle.as_ptr(), index)
9494        };
9495        crate::ocio_call_status()?;
9496        Ok(count)
9497    }
9498
9499    #[doc(hidden)]
9500    #[deprecated(since = "0.2.0", note = "compat alias; prefer texture_value_count()")]
9501    pub fn get_texture_value_count(&self, index: u32) -> usize {
9502        self.texture_value_count(index)
9503    }
9504
9505    #[doc(hidden)]
9506    #[deprecated(
9507        since = "0.2.0",
9508        note = "compat alias; prefer texture_2d() or textures_2d()"
9509    )]
9510    pub fn copy_texture_values(&self, index: u32) -> Vec<f32> {
9511        self.texture_values(index)
9512    }
9513
9514    #[doc(hidden)]
9515    #[deprecated(since = "0.2.0", note = "compat alias; prefer num_3d_textures()")]
9516    pub fn get_num3d_textures_u32(&self) -> u32 {
9517        self.num_3d_textures()
9518    }
9519
9520    /// Returns a structured 3D texture resource and copied texel payload.
9521    pub fn texture_3d(&self, index: u32) -> Option<GpuTexture3D> {
9522        self.try_texture_3d(index).ok().flatten()
9523    }
9524
9525    /// Return a structured 3D texture resource, preserving bridge failures.
9526    ///
9527    /// An out-of-range `index` is returned as an OCIO error. `Ok(None)` means
9528    /// OCIO did not report a usable texture resource without raising an error.
9529    pub fn try_texture_3d(&self, index: u32) -> Result<Option<GpuTexture3D>> {
9530        let mut info = ocio_sys::OcioGpuTexture3DInfo {
9531            texture_name: std::ptr::null(),
9532            sampler_name: std::ptr::null(),
9533            edge_len: 0,
9534            interpolation: 0,
9535            has_binding_index: false,
9536            binding_index: 0,
9537        };
9538        crate::clear_last_error();
9539        let ok = unsafe {
9540            ocio_sys::ocio_gpu_shader_desc_get3d_texture_info(
9541                self.handle.as_ptr(),
9542                index,
9543                &mut info,
9544            )
9545        };
9546        crate::ocio_call_status()?;
9547        if !ok {
9548            return Ok(None);
9549        }
9550        let edge = info.edge_len as usize;
9551        let value_count = edge
9552            .checked_mul(edge)
9553            .and_then(|count| count.checked_mul(edge))
9554            .and_then(|count| count.checked_mul(3))
9555            .ok_or_else(|| {
9556                OcioError::ValidationFailed("GPU 3D texture payload size overflowed usize".into())
9557            })?;
9558        let mut values = Vec::<f32>::new();
9559        try_resize_gpu_values(&mut values, value_count)?;
9560        crate::clear_last_error();
9561        let values_ok = unsafe {
9562            ocio_sys::ocio_gpu_shader_desc_copy3d_texture_values(
9563                self.handle.as_ptr(),
9564                index,
9565                values.as_mut_ptr(),
9566                values.len(),
9567            )
9568        };
9569        crate::ocio_call_status()?;
9570        if !values_ok {
9571            return Err(OcioError::ValidationFailed(
9572                "OCIO could not copy the reported GPU 3D texture payload".into(),
9573            ));
9574        }
9575        let Some(texture_name) = required_ocio_string(info.texture_name) else {
9576            return Ok(None);
9577        };
9578        let Some(sampler_name) = required_ocio_string(info.sampler_name) else {
9579            return Ok(None);
9580        };
9581        Ok(Some(GpuTexture3D {
9582            texture_name,
9583            sampler_name,
9584            edge_len: info.edge_len,
9585            interpolation: interpolation_from_raw(info.interpolation),
9586            binding_index: info.has_binding_index.then_some(info.binding_index),
9587            values,
9588        }))
9589    }
9590
9591    #[doc(hidden)]
9592    #[deprecated(since = "0.2.0", note = "compat alias; prefer texture_3d()")]
9593    pub fn get3d_texture_info(&self, index: u32) -> Option<GpuTexture3D> {
9594        self.texture_3d(index)
9595    }
9596
9597    /// Returns the scalar count for a 3D texture resource without copying it.
9598    /// Returns zero on an invalid index or native error; use
9599    /// [`Self::try_texture_3d_value_count`] to distinguish errors.
9600    pub fn texture_3d_value_count(&self, index: u32) -> usize {
9601        self.try_texture_3d_value_count(index).unwrap_or(0)
9602    }
9603
9604    /// Return the scalar count for a 3D texture without allocating.
9605    pub fn try_texture_3d_value_count(&self, index: u32) -> Result<usize> {
9606        crate::clear_last_error();
9607        let count = unsafe {
9608            ocio_sys::ocio_gpu_shader_desc_get3d_texture_value_count(self.handle.as_ptr(), index)
9609        };
9610        crate::ocio_call_status()?;
9611        Ok(count)
9612    }
9613
9614    #[doc(hidden)]
9615    #[deprecated(
9616        since = "0.2.0",
9617        note = "compat alias; prefer texture_3d_value_count()"
9618    )]
9619    pub fn get3d_texture_value_count(&self, index: u32) -> usize {
9620        self.texture_3d_value_count(index)
9621    }
9622
9623    /// Returns the copied texel payload for a 3D texture resource.
9624    pub fn texture_3d_values(&self, index: u32) -> Vec<f32> {
9625        self.texture_3d(index)
9626            .map(|texture| texture.values)
9627            .unwrap_or_default()
9628    }
9629
9630    /// Borrow the native 3D LUT values without allocating or copying.
9631    /// The returned slice is tied to the exclusive descriptor borrow.
9632    pub fn texture_3d_values_ref(&mut self, index: u32) -> Result<&[f32]> {
9633        self.borrow_texture_values(index, true)
9634    }
9635
9636    /// Adds a manual 3D texture resource to the descriptor.
9637    ///
9638    /// The result contains the OCIO shader binding index on OpenColorIO 2.5.1
9639    /// and newer. OpenColorIO 2.4 performs the insertion but returns `None`
9640    /// because that release does not expose binding indexes.
9641    pub fn add_texture_3d(
9642        &self,
9643        texture_name: impl AsRef<str>,
9644        sampler_name: impl AsRef<str>,
9645        edge_len: u32,
9646        interpolation: Interpolation,
9647        values: &[f32],
9648    ) -> Result<Option<u32>> {
9649        let edge = edge_len as usize;
9650        let expected = edge
9651            .checked_mul(edge)
9652            .and_then(|count| count.checked_mul(edge))
9653            .and_then(|count| count.checked_mul(3))
9654            .ok_or_else(|| {
9655                OcioError::ValidationFailed("GPU 3D texture payload size overflowed usize".into())
9656            })?;
9657        if values.len() != expected {
9658            return Err(OcioError::ValidationFailed(format!(
9659                "gpu 3d texture value count mismatch: expected {expected}, got {}",
9660                values.len()
9661            )));
9662        }
9663        let texture_name = cstring(texture_name)?;
9664        let sampler_name = cstring(sampler_name)?;
9665        crate::clear_last_error();
9666        let mut has_binding_index = false;
9667        let mut binding_index = 0;
9668        let inserted = unsafe {
9669            ocio_sys::ocio_gpu_shader_desc_add3d_texture(
9670                self.handle.as_ptr(),
9671                texture_name.as_ptr(),
9672                sampler_name.as_ptr(),
9673                edge_len,
9674                interpolation as i32,
9675                values.as_ptr(),
9676                values.len(),
9677                &mut has_binding_index,
9678                &mut binding_index,
9679            )
9680        };
9681        crate::ocio_call_status()?;
9682        if !inserted {
9683            return Err(OcioError::ValidationFailed(
9684                "OpenColorIO rejected the 3D texture".to_owned(),
9685            ));
9686        }
9687        Ok(has_binding_index.then_some(binding_index))
9688    }
9689
9690    #[doc(hidden)]
9691    #[deprecated(since = "0.2.0", note = "compat alias; prefer texture_3d_values()")]
9692    pub fn copy3d_texture_values(&self, index: u32) -> Vec<f32> {
9693        self.texture_3d_values(index)
9694    }
9695
9696    /// Returns all structured 3D texture resources currently reported by OCIO.
9697    pub fn textures_3d(&self) -> Vec<GpuTexture3D> {
9698        (0..self.num_3d_textures())
9699            .filter_map(|index| self.texture_3d(index))
9700            .collect()
9701    }
9702
9703    #[doc(hidden)]
9704    #[deprecated(since = "0.2.0", note = "compat alias; prefer num_3d_textures()")]
9705    pub fn get_num3d_textures(&self) -> u32 {
9706        self.num_3d_textures()
9707    }
9708
9709    #[doc(hidden)]
9710    #[deprecated(since = "0.2.0", note = "compat alias; prefer texture_3d()")]
9711    pub fn get3d_texture(&self, index: u32) -> Option<GpuTexture3D> {
9712        self.texture_3d(index)
9713    }
9714
9715    #[doc(hidden)]
9716    #[deprecated(since = "0.2.0", note = "compat alias; prefer texture_3d_values()")]
9717    pub fn get3d_texture_values(&self, index: u32) -> Vec<f32> {
9718        self.texture_3d_values(index)
9719    }
9720
9721    /// Returns the binding index for a 3D texture resource, if present.
9722    pub fn texture_3d_shader_binding_index(&self, index: u32) -> Option<u32> {
9723        let info = self.texture_3d_info_raw(index)?;
9724        info.has_binding_index.then_some(info.binding_index)
9725    }
9726
9727    #[doc(hidden)]
9728    #[deprecated(
9729        since = "0.2.0",
9730        note = "compat alias; prefer texture_3d_shader_binding_index()"
9731    )]
9732    pub fn get3d_texture_shader_binding_index(&self, index: u32) -> Option<u32> {
9733        self.texture_3d_shader_binding_index(index)
9734    }
9735
9736    /// Returns the binding index for a 1D/2D texture resource, if present.
9737    pub fn texture_shader_binding_index(&self, index: u32) -> Option<u32> {
9738        let info = self.texture_info_raw(index)?;
9739        info.has_binding_index.then_some(info.binding_index)
9740    }
9741
9742    /// Returns the uniform symbol name for the given index, if present.
9743    pub fn uniform_name(&self, index: u32) -> Option<String> {
9744        crate::clear_last_error();
9745        let name =
9746            unsafe { ocio_sys::ocio_gpu_shader_desc_get_uniform_name(self.handle.as_ptr(), index) };
9747        crate::ocio_call_status().ok()?;
9748        required_ocio_string(name)
9749    }
9750}
9751
9752impl Drop for GpuShaderDesc {
9753    fn drop(&mut self) {
9754        unsafe { ocio_sys::ocio_gpu_shader_desc_destroy(self.handle.as_ptr() as *mut c_void) };
9755    }
9756}
9757
9758#[doc(hidden)]
9759/// Lightweight texture metadata used by legacy GPU descriptor accessors.
9760pub struct TextureInfo {
9761    pub texture_name: String,
9762    pub sampler_name: String,
9763    pub width: u32,
9764    pub height: u32,
9765    pub channel: i32,
9766    pub dimensions: i32,
9767    pub interpolation: i32,
9768}
9769
9770fn interpolation_from_raw(value: i32) -> Interpolation {
9771    match value {
9772        1 => Interpolation::Nearest,
9773        2 => Interpolation::Linear,
9774        3 => Interpolation::Tetrahedral,
9775        4 => Interpolation::Cubic,
9776        254 => Interpolation::Default,
9777        255 => Interpolation::Best,
9778        _ => Interpolation::Unknown,
9779    }
9780}
9781
9782// --- DynamicProperty ---
9783
9784fn dynamic_property_type_from_raw(value: i32) -> Result<DynamicPropertyType> {
9785    Ok(match value {
9786        0 => DynamicPropertyType::Exposure,
9787        1 => DynamicPropertyType::Contrast,
9788        2 => DynamicPropertyType::Gamma,
9789        3 => DynamicPropertyType::GradingPrimary,
9790        4 => DynamicPropertyType::GradingRgbCurve,
9791        5 => DynamicPropertyType::GradingTone,
9792        #[cfg(feature = "v2_5")]
9793        6 => DynamicPropertyType::GradingHueCurve,
9794        _ => {
9795            return Err(OcioError::Ocio(format!(
9796                "unknown dynamic property type {value}"
9797            )))
9798        }
9799    })
9800}
9801
9802/// References a processor property that may be adjusted dynamically at runtime.
9803pub struct DynamicProperty {
9804    handle: NonNull<c_void>,
9805}
9806
9807impl DynamicProperty {
9808    /// Retain the current RGB curve value without a deep copy.
9809    pub fn grading_rgb_curve_shared(&self) -> Result<crate::SharedGradingRGBCurve> {
9810        self.require_property_type(
9811            DynamicPropertyType::GradingRgbCurve,
9812            "DynamicProperty::grading_rgb_curve_shared",
9813        )?;
9814        crate::SharedGradingRGBCurve::from_source(self.handle.as_ptr(), 1)
9815    }
9816    /// Retain the current hue curve value without a deep copy.
9817    #[cfg(feature = "v2_5")]
9818    pub fn grading_hue_curve_shared(&self) -> Result<crate::SharedGradingHueCurve> {
9819        self.require_property_type(
9820            DynamicPropertyType::GradingHueCurve,
9821            "DynamicProperty::grading_hue_curve_shared",
9822        )?;
9823        crate::SharedGradingHueCurve::from_source(self.handle.as_ptr(), 3)
9824    }
9825    /// Return an independent native RGB curve value, including its non-point state.
9826    pub fn grading_rgb_curve_object(&self) -> Result<crate::GradingRGBCurve> {
9827        self.require_property_type(
9828            DynamicPropertyType::GradingRgbCurve,
9829            "DynamicProperty::grading_rgb_curve_object",
9830        )?;
9831        crate::clear_last_error();
9832        let value = unsafe {
9833            ocio_sys::ocio_dynamic_property_grading_rgb_curve_object_get(self.handle.as_ptr())
9834        };
9835        Ok(crate::GradingRGBCurve {
9836            handle: crate::handle_result(value)?,
9837        })
9838    }
9839
9840    /// Replace the native RGB curve value in one update.
9841    pub fn set_grading_rgb_curve_object(&self, value: &crate::GradingRGBCurve) -> Result<()> {
9842        self.require_property_type(
9843            DynamicPropertyType::GradingRgbCurve,
9844            "DynamicProperty::set_grading_rgb_curve_object",
9845        )?;
9846        crate::clear_last_error();
9847        unsafe {
9848            ocio_sys::ocio_dynamic_property_grading_rgb_curve_object_set(
9849                self.handle.as_ptr(),
9850                value.handle.as_ptr(),
9851            )
9852        };
9853        crate::ocio_call_status()
9854    }
9855
9856    /// Forward a shared RGB curve directly to OCIO's native setter, without
9857    /// making an editable copy in the binding.
9858    pub fn set_grading_rgb_curve_shared(&self, value: &crate::SharedGradingRGBCurve) -> Result<()> {
9859        self.set_shared_grading_curve(value.handle, false)
9860    }
9861
9862    #[cfg(feature = "v2_5")]
9863    /// Return an independent native HUE curve value, including its non-point state.
9864    pub fn grading_hue_curve_object(&self) -> Result<crate::GradingHueCurve> {
9865        self.require_property_type(
9866            DynamicPropertyType::GradingHueCurve,
9867            "DynamicProperty::grading_hue_curve_object",
9868        )?;
9869        crate::clear_last_error();
9870        let value = unsafe {
9871            ocio_sys::ocio_dynamic_property_grading_hue_curve_object_get(self.handle.as_ptr())
9872        };
9873        Ok(crate::GradingHueCurve {
9874            handle: crate::handle_result(value)?,
9875        })
9876    }
9877
9878    #[cfg(feature = "v2_5")]
9879    /// Replace the native HUE curve value in one update.
9880    pub fn set_grading_hue_curve_object(&self, value: &crate::GradingHueCurve) -> Result<()> {
9881        self.require_property_type(
9882            DynamicPropertyType::GradingHueCurve,
9883            "DynamicProperty::set_grading_hue_curve_object",
9884        )?;
9885        crate::clear_last_error();
9886        unsafe {
9887            ocio_sys::ocio_dynamic_property_grading_hue_curve_object_set(
9888                self.handle.as_ptr(),
9889                value.handle.as_ptr(),
9890            )
9891        };
9892        crate::ocio_call_status()
9893    }
9894
9895    /// Forward a shared hue curve directly to OCIO's native setter, without
9896    /// making an editable copy in the binding.
9897    #[cfg(feature = "v2_5")]
9898    pub fn set_grading_hue_curve_shared(&self, value: &crate::SharedGradingHueCurve) -> Result<()> {
9899        self.set_shared_grading_curve(value.handle, true)
9900    }
9901
9902    fn set_shared_grading_curve(&self, value: NonNull<c_void>, hue: bool) -> Result<()> {
9903        crate::clear_last_error();
9904        unsafe {
9905            ocio_sys::ocio_grading_curve_value_shared_set_dynamic_property(
9906                value.as_ptr(),
9907                hue,
9908                self.handle.as_ptr(),
9909            )
9910        };
9911        crate::ocio_call_status()
9912    }
9913
9914    fn require_property_type(
9915        &self,
9916        expected: DynamicPropertyType,
9917        operation: &'static str,
9918    ) -> Result<()> {
9919        let actual = self.try_property_type()?;
9920        if actual == expected {
9921            Ok(())
9922        } else {
9923            Err(OcioError::InvalidInput(format!(
9924                "{operation} requires {:?}, got {:?}",
9925                expected, actual
9926            )))
9927        }
9928    }
9929
9930    fn require_double_property(&self, operation: &'static str) -> Result<()> {
9931        let actual = self.try_property_type()?;
9932        match actual {
9933            DynamicPropertyType::Exposure
9934            | DynamicPropertyType::Contrast
9935            | DynamicPropertyType::Gamma => Ok(()),
9936            _ => Err(OcioError::InvalidInput(format!(
9937                "{operation} requires Exposure, Contrast, or Gamma, got {:?}",
9938                actual
9939            ))),
9940        }
9941    }
9942
9943    fn require_grading_rgb_curve_property(&self, operation: &'static str) -> Result<()> {
9944        self.require_property_type(DynamicPropertyType::GradingRgbCurve, operation)
9945    }
9946
9947    #[cfg(feature = "v2_5")]
9948    fn require_grading_hue_curve_property(&self, operation: &'static str) -> Result<()> {
9949        self.require_property_type(DynamicPropertyType::GradingHueCurve, operation)
9950    }
9951
9952    /// Return the property type, or `Exposure` if the native type is unknown
9953    /// or the bridge reports an error. Use [`Self::try_property_type`] when a
9954    /// fallback would be ambiguous. Typed property operations use that fallible
9955    /// query and do not treat an unknown type as exposure.
9956    pub fn property_type(&self) -> DynamicPropertyType {
9957        self.try_property_type()
9958            .unwrap_or(DynamicPropertyType::Exposure)
9959    }
9960
9961    /// Query the property type without treating unknown native values as exposure.
9962    pub fn try_property_type(&self) -> Result<DynamicPropertyType> {
9963        crate::clear_last_error();
9964        let t = unsafe {
9965            ocio_sys::ocio_dynamic_property_get_type(self.handle.as_ptr() as *mut c_void)
9966        };
9967        crate::ocio_call_status()?;
9968        dynamic_property_type_from_raw(t)
9969    }
9970
9971    pub fn double_value(&self) -> Result<f64> {
9972        self.require_double_property("DynamicProperty::double_value")?;
9973        crate::clear_last_error();
9974        let value = unsafe {
9975            ocio_sys::ocio_dynamic_property_double_get_value(self.handle.as_ptr() as *mut c_void)
9976        };
9977        crate::ocio_call_status()?;
9978        Ok(value)
9979    }
9980    pub fn set_double_value(&self, value: f64) -> Result<()> {
9981        self.require_double_property("DynamicProperty::set_double_value")?;
9982        crate::clear_last_error();
9983        unsafe { ocio_sys::ocio_dynamic_property_double_set_value(self.handle.as_ptr(), value) };
9984        crate::ocio_call_status()
9985    }
9986
9987    pub fn grading_primary_value(&self) -> Result<crate::grading::GradingPrimary> {
9988        self.require_property_type(
9989            DynamicPropertyType::GradingPrimary,
9990            "DynamicProperty::grading_primary_value",
9991        )?;
9992        let mut values = [0.0f64; 34];
9993        crate::clear_last_error();
9994        unsafe {
9995            ocio_sys::ocio_dynamic_property_grading_primary_get_value(
9996                self.handle.as_ptr(),
9997                values.as_mut_ptr(),
9998            );
9999        }
10000        crate::ocio_call_status()?;
10001        Ok(crate::grading::GradingPrimary::from_flat_array(&values))
10002    }
10003
10004    pub fn set_grading_primary_value(&self, value: &crate::grading::GradingPrimary) -> Result<()> {
10005        self.require_property_type(
10006            DynamicPropertyType::GradingPrimary,
10007            "DynamicProperty::set_grading_primary_value",
10008        )?;
10009        let values = value.to_flat_array();
10010        crate::clear_last_error();
10011        unsafe {
10012            ocio_sys::ocio_dynamic_property_grading_primary_set_value(
10013                self.handle.as_ptr(),
10014                values.as_ptr(),
10015            );
10016        }
10017        crate::ocio_call_status()
10018    }
10019
10020    pub fn grading_tone_value(&self) -> Result<crate::grading::GradingTone> {
10021        self.require_property_type(
10022            DynamicPropertyType::GradingTone,
10023            "DynamicProperty::grading_tone_value",
10024        )?;
10025        let mut values = [0.0f64; 31];
10026        crate::clear_last_error();
10027        unsafe {
10028            ocio_sys::ocio_dynamic_property_grading_tone_get_value(
10029                self.handle.as_ptr(),
10030                values.as_mut_ptr(),
10031            );
10032        }
10033        crate::ocio_call_status()?;
10034        Ok(crate::grading::GradingTone::from_flat_array(&values))
10035    }
10036
10037    pub fn set_grading_tone_value(&self, value: &crate::grading::GradingTone) -> Result<()> {
10038        self.require_property_type(
10039            DynamicPropertyType::GradingTone,
10040            "DynamicProperty::set_grading_tone_value",
10041        )?;
10042        let values = value.to_flat_array();
10043        crate::clear_last_error();
10044        unsafe {
10045            ocio_sys::ocio_dynamic_property_grading_tone_set_value(
10046                self.handle.as_ptr(),
10047                values.as_ptr(),
10048            );
10049        }
10050        crate::ocio_call_status()
10051    }
10052
10053    pub fn grading_rgb_curve_num_control_points(&self, curve_type: RGBCurveType) -> Result<i32> {
10054        self.require_grading_rgb_curve_property(
10055            "DynamicProperty::grading_rgb_curve_num_control_points",
10056        )?;
10057        crate::clear_last_error();
10058        let value = unsafe {
10059            ocio_sys::ocio_dynamic_property_grading_rgb_curve_get_num_control_points(
10060                self.handle.as_ptr(),
10061                curve_type as i32,
10062            )
10063        };
10064        crate::ocio_call_status()?;
10065        Ok(value)
10066    }
10067
10068    pub fn grading_rgb_curve_set_num_control_points(
10069        &self,
10070        curve_type: RGBCurveType,
10071        num: i32,
10072    ) -> Result<()> {
10073        self.require_grading_rgb_curve_property(
10074            "DynamicProperty::grading_rgb_curve_set_num_control_points",
10075        )?;
10076        if num < 0 {
10077            return Err(OcioError::InvalidInput(
10078                "DynamicProperty::grading_rgb_curve_set_num_control_points: num must be non-negative"
10079                    .to_string(),
10080            ));
10081        }
10082        crate::clear_last_error();
10083        unsafe {
10084            ocio_sys::ocio_dynamic_property_grading_rgb_curve_set_num_control_points(
10085                self.handle.as_ptr(),
10086                curve_type as i32,
10087                num,
10088            );
10089        }
10090        crate::ocio_call_status()
10091    }
10092
10093    pub fn grading_rgb_curve_control_point(
10094        &self,
10095        curve_type: RGBCurveType,
10096        index: i32,
10097    ) -> Result<(f32, f32)> {
10098        self.require_grading_rgb_curve_property(
10099            "DynamicProperty::grading_rgb_curve_control_point",
10100        )?;
10101        if index < 0 {
10102            return Err(OcioError::InvalidInput(
10103                "DynamicProperty::grading_rgb_curve_control_point: index must be non-negative"
10104                    .to_string(),
10105            ));
10106        }
10107        let mut x = 0.0f32;
10108        let mut y = 0.0f32;
10109        crate::clear_last_error();
10110        unsafe {
10111            ocio_sys::ocio_dynamic_property_grading_rgb_curve_get_control_point(
10112                self.handle.as_ptr(),
10113                curve_type as i32,
10114                index,
10115                &mut x,
10116                &mut y,
10117            );
10118        }
10119        crate::ocio_call_status()?;
10120        Ok((x, y))
10121    }
10122
10123    pub fn grading_rgb_curve_set_control_point(
10124        &self,
10125        curve_type: RGBCurveType,
10126        index: i32,
10127        x: f32,
10128        y: f32,
10129    ) -> Result<()> {
10130        self.require_grading_rgb_curve_property(
10131            "DynamicProperty::grading_rgb_curve_set_control_point",
10132        )?;
10133        if index < 0 {
10134            return Err(OcioError::InvalidInput(
10135                "DynamicProperty::grading_rgb_curve_set_control_point: index must be non-negative"
10136                    .to_string(),
10137            ));
10138        }
10139        crate::clear_last_error();
10140        unsafe {
10141            ocio_sys::ocio_dynamic_property_grading_rgb_curve_set_control_point(
10142                self.handle.as_ptr(),
10143                curve_type as i32,
10144                index,
10145                x,
10146                y,
10147            );
10148        }
10149        crate::ocio_call_status()
10150    }
10151
10152    pub fn grading_rgb_curve_slope(&self, curve_type: RGBCurveType, index: i32) -> Result<f32> {
10153        self.require_grading_rgb_curve_property("DynamicProperty::grading_rgb_curve_slope")?;
10154        if index < 0 {
10155            return Err(OcioError::InvalidInput(
10156                "DynamicProperty::grading_rgb_curve_slope: index must be non-negative".to_string(),
10157            ));
10158        }
10159        crate::clear_last_error();
10160        let value = unsafe {
10161            ocio_sys::ocio_dynamic_property_grading_rgb_curve_get_slope(
10162                self.handle.as_ptr(),
10163                curve_type as i32,
10164                index,
10165            )
10166        };
10167        crate::ocio_call_status()?;
10168        Ok(value)
10169    }
10170
10171    pub fn grading_rgb_curve_set_slope(
10172        &self,
10173        curve_type: RGBCurveType,
10174        index: i32,
10175        slope: f32,
10176    ) -> Result<()> {
10177        self.require_grading_rgb_curve_property("DynamicProperty::grading_rgb_curve_set_slope")?;
10178        if index < 0 {
10179            return Err(OcioError::InvalidInput(
10180                "DynamicProperty::grading_rgb_curve_set_slope: index must be non-negative"
10181                    .to_string(),
10182            ));
10183        }
10184        crate::clear_last_error();
10185        unsafe {
10186            ocio_sys::ocio_dynamic_property_grading_rgb_curve_set_slope(
10187                self.handle.as_ptr(),
10188                curve_type as i32,
10189                index,
10190                slope,
10191            );
10192        }
10193        crate::ocio_call_status()
10194    }
10195
10196    pub fn grading_rgb_curve_slopes_are_default(&self, curve_type: RGBCurveType) -> Result<bool> {
10197        self.require_grading_rgb_curve_property(
10198            "DynamicProperty::grading_rgb_curve_slopes_are_default",
10199        )?;
10200        crate::clear_last_error();
10201        let value = unsafe {
10202            ocio_sys::ocio_dynamic_property_grading_rgb_curve_slopes_are_default(
10203                self.handle.as_ptr(),
10204                curve_type as i32,
10205            )
10206        };
10207        crate::ocio_call_status()?;
10208        Ok(value)
10209    }
10210
10211    #[cfg(feature = "v2_5")]
10212    #[cfg_attr(docsrs, doc(cfg(feature = "v2_5")))]
10213    pub fn grading_hue_curve_num_control_points(&self, curve_type: HueCurveType) -> Result<i32> {
10214        self.require_grading_hue_curve_property(
10215            "DynamicProperty::grading_hue_curve_num_control_points",
10216        )?;
10217        crate::clear_last_error();
10218        let value = unsafe {
10219            ocio_sys::ocio_dynamic_property_grading_hue_curve_get_num_control_points(
10220                self.handle.as_ptr(),
10221                curve_type as i32,
10222            )
10223        };
10224        crate::ocio_call_status()?;
10225        Ok(value)
10226    }
10227
10228    /// Snapshot all eight curves of a dynamic hue-curve property.
10229    ///
10230    /// This is a control-plane operation: it copies the native curve data.
10231    #[cfg(feature = "v2_5")]
10232    pub fn complete_grading_hue_curve_value(
10233        &self,
10234    ) -> Result<crate::grading::CompleteGradingHueCurveValue> {
10235        use crate::grading::{
10236            CompleteGradingHueCurveValue, GradingCurvePoint, GradingHueCurveValue,
10237        };
10238        let read = |kind| -> Result<Vec<GradingCurvePoint>> {
10239            let count = crate::transform::checked_native_count(
10240                self.grading_hue_curve_num_control_points(kind)?,
10241                "DynamicProperty::complete_grading_hue_curve_value",
10242            )?;
10243            let mut points = crate::transform::reserve_native_items(
10244                count,
10245                "DynamicProperty::complete_grading_hue_curve_value",
10246            )?;
10247            for index in 0..count {
10248                let (x, y) = self.grading_hue_curve_control_point(kind, index as i32)?;
10249                let slope = self.grading_hue_curve_slope(kind, index as i32)?;
10250                points.push(GradingCurvePoint { x, y, slope });
10251            }
10252            Ok(points)
10253        };
10254        Ok(CompleteGradingHueCurveValue {
10255            base: GradingHueCurveValue {
10256                hue_hue: read(HueCurveType::HueHue)?,
10257                hue_sat: read(HueCurveType::HueSat)?,
10258                hue_lum: read(HueCurveType::HueLum)?,
10259                lum_sat: read(HueCurveType::LumSat)?,
10260            },
10261            sat_sat: read(HueCurveType::SatSat)?,
10262            lum_lum: read(HueCurveType::LumLum)?,
10263            sat_lum: read(HueCurveType::SatLum)?,
10264            hue_fx: read(HueCurveType::HueFx)?,
10265        })
10266    }
10267
10268    /// Validate and replace all eight curves in one native update.
10269    ///
10270    /// If curve validation fails, the original property is left unchanged. The curve data is
10271    /// borrowed across the FFI boundary; no Rust-side point copy is made.
10272    #[cfg(feature = "v2_5")]
10273    pub fn set_complete_grading_hue_curve_value(
10274        &self,
10275        value: &crate::grading::CompleteGradingHueCurveValue,
10276    ) -> Result<()> {
10277        self.require_grading_hue_curve_property(
10278            "DynamicProperty::set_complete_grading_hue_curve_value",
10279        )?;
10280        let curves = [
10281            &value.base.hue_hue,
10282            &value.base.hue_sat,
10283            &value.base.hue_lum,
10284            &value.base.lum_sat,
10285            &value.sat_sat,
10286            &value.lum_lum,
10287            &value.sat_lum,
10288            &value.hue_fx,
10289        ];
10290        let pointers = curves.map(|points| points.as_ptr().cast::<std::ffi::c_void>());
10291        let counts = curves.map(|points| points.len());
10292        crate::clear_last_error();
10293        unsafe {
10294            ocio_sys::ocio_dynamic_property_grading_hue_curve_set_complete(
10295                self.handle.as_ptr(),
10296                pointers.as_ptr(),
10297                counts.as_ptr(),
10298            )
10299        };
10300        crate::ocio_call_status()
10301    }
10302
10303    #[cfg(feature = "v2_5")]
10304    #[cfg_attr(docsrs, doc(cfg(feature = "v2_5")))]
10305    pub fn grading_hue_curve_set_num_control_points(
10306        &self,
10307        curve_type: HueCurveType,
10308        num: i32,
10309    ) -> Result<()> {
10310        self.require_grading_hue_curve_property(
10311            "DynamicProperty::grading_hue_curve_set_num_control_points",
10312        )?;
10313        if num < 0 {
10314            return Err(OcioError::InvalidInput(
10315                "DynamicProperty::grading_hue_curve_set_num_control_points: num must be non-negative"
10316                    .to_string(),
10317            ));
10318        }
10319        crate::clear_last_error();
10320        unsafe {
10321            ocio_sys::ocio_dynamic_property_grading_hue_curve_set_num_control_points(
10322                self.handle.as_ptr(),
10323                curve_type as i32,
10324                num,
10325            );
10326        }
10327        crate::ocio_call_status()
10328    }
10329
10330    #[cfg(feature = "v2_5")]
10331    #[cfg_attr(docsrs, doc(cfg(feature = "v2_5")))]
10332    pub fn grading_hue_curve_control_point(
10333        &self,
10334        curve_type: HueCurveType,
10335        index: i32,
10336    ) -> Result<(f32, f32)> {
10337        self.require_grading_hue_curve_property(
10338            "DynamicProperty::grading_hue_curve_control_point",
10339        )?;
10340        if index < 0 {
10341            return Err(OcioError::InvalidInput(
10342                "DynamicProperty::grading_hue_curve_control_point: index must be non-negative"
10343                    .to_string(),
10344            ));
10345        }
10346        let mut x = 0.0f32;
10347        let mut y = 0.0f32;
10348        crate::clear_last_error();
10349        unsafe {
10350            ocio_sys::ocio_dynamic_property_grading_hue_curve_get_control_point(
10351                self.handle.as_ptr(),
10352                curve_type as i32,
10353                index,
10354                &mut x,
10355                &mut y,
10356            );
10357        }
10358        crate::ocio_call_status()?;
10359        Ok((x, y))
10360    }
10361
10362    #[cfg(feature = "v2_5")]
10363    #[cfg_attr(docsrs, doc(cfg(feature = "v2_5")))]
10364    pub fn grading_hue_curve_set_control_point(
10365        &self,
10366        curve_type: HueCurveType,
10367        index: i32,
10368        x: f32,
10369        y: f32,
10370    ) -> Result<()> {
10371        self.require_grading_hue_curve_property(
10372            "DynamicProperty::grading_hue_curve_set_control_point",
10373        )?;
10374        if index < 0 {
10375            return Err(OcioError::InvalidInput(
10376                "DynamicProperty::grading_hue_curve_set_control_point: index must be non-negative"
10377                    .to_string(),
10378            ));
10379        }
10380        crate::clear_last_error();
10381        unsafe {
10382            ocio_sys::ocio_dynamic_property_grading_hue_curve_set_control_point(
10383                self.handle.as_ptr(),
10384                curve_type as i32,
10385                index,
10386                x,
10387                y,
10388            );
10389        }
10390        crate::ocio_call_status()
10391    }
10392
10393    #[cfg(feature = "v2_5")]
10394    #[cfg_attr(docsrs, doc(cfg(feature = "v2_5")))]
10395    pub fn grading_hue_curve_slope(&self, curve_type: HueCurveType, index: i32) -> Result<f32> {
10396        self.require_grading_hue_curve_property("DynamicProperty::grading_hue_curve_slope")?;
10397        if index < 0 {
10398            return Err(OcioError::InvalidInput(
10399                "DynamicProperty::grading_hue_curve_slope: index must be non-negative".to_string(),
10400            ));
10401        }
10402        crate::clear_last_error();
10403        let value = unsafe {
10404            ocio_sys::ocio_dynamic_property_grading_hue_curve_get_slope(
10405                self.handle.as_ptr(),
10406                curve_type as i32,
10407                index,
10408            )
10409        };
10410        crate::ocio_call_status()?;
10411        Ok(value)
10412    }
10413
10414    #[cfg(feature = "v2_5")]
10415    #[cfg_attr(docsrs, doc(cfg(feature = "v2_5")))]
10416    pub fn grading_hue_curve_set_slope(
10417        &self,
10418        curve_type: HueCurveType,
10419        index: i32,
10420        slope: f32,
10421    ) -> Result<()> {
10422        self.require_grading_hue_curve_property("DynamicProperty::grading_hue_curve_set_slope")?;
10423        if index < 0 {
10424            return Err(OcioError::InvalidInput(
10425                "DynamicProperty::grading_hue_curve_set_slope: index must be non-negative"
10426                    .to_string(),
10427            ));
10428        }
10429        crate::clear_last_error();
10430        unsafe {
10431            ocio_sys::ocio_dynamic_property_grading_hue_curve_set_slope(
10432                self.handle.as_ptr(),
10433                curve_type as i32,
10434                index,
10435                slope,
10436            );
10437        }
10438        crate::ocio_call_status()
10439    }
10440
10441    #[cfg(feature = "v2_5")]
10442    #[cfg_attr(docsrs, doc(cfg(feature = "v2_5")))]
10443    pub fn grading_hue_curve_slopes_are_default(&self, curve_type: HueCurveType) -> Result<bool> {
10444        self.require_grading_hue_curve_property(
10445            "DynamicProperty::grading_hue_curve_slopes_are_default",
10446        )?;
10447        crate::clear_last_error();
10448        let value = unsafe {
10449            ocio_sys::ocio_dynamic_property_grading_hue_curve_slopes_are_default(
10450                self.handle.as_ptr(),
10451                curve_type as i32,
10452            )
10453        };
10454        crate::ocio_call_status()?;
10455        Ok(value)
10456    }
10457}
10458
10459impl Drop for DynamicProperty {
10460    fn drop(&mut self) {
10461        unsafe { ocio_sys::ocio_dynamic_property_destroy(self.handle.as_ptr() as *mut c_void) };
10462    }
10463}
10464
10465#[cfg(test)]
10466mod tests {
10467    use super::*;
10468
10469    #[test]
10470    fn dynamic_property_type_rejects_unknown_values() {
10471        assert_eq!(
10472            dynamic_property_type_from_raw(0).unwrap(),
10473            DynamicPropertyType::Exposure
10474        );
10475        assert_eq!(
10476            dynamic_property_type_from_raw(5).unwrap(),
10477            DynamicPropertyType::GradingTone
10478        );
10479        assert!(dynamic_property_type_from_raw(-1).is_err());
10480        assert!(dynamic_property_type_from_raw(i32::MAX).is_err());
10481        #[cfg(feature = "v2_5")]
10482        assert_eq!(
10483            dynamic_property_type_from_raw(6).unwrap(),
10484            DynamicPropertyType::GradingHueCurve
10485        );
10486        #[cfg(not(feature = "v2_5"))]
10487        assert!(dynamic_property_type_from_raw(6).is_err());
10488    }
10489
10490    #[test]
10491    fn tail_row_partition_covers_each_row_once() {
10492        for height in 1..=5 {
10493            for a_split in [false, true] {
10494                for a_first in [false, true] {
10495                    for b_split in [false, true] {
10496                        for b_first in [false, true] {
10497                            let (start, end, edges) =
10498                                tail_row_partition(height, (a_split, a_first), (b_split, b_first));
10499                            let mut visits = vec![0u8; height as usize];
10500                            for row in start..end {
10501                                visits[row as usize] += 1;
10502                            }
10503                            for row in edges.into_iter().flatten() {
10504                                visits[row as usize] += 1;
10505                            }
10506                            assert!(
10507                                visits.iter().all(|&v| v == 1),
10508                                "height={height}, a={a_split}/{a_first}, b={b_split}/{b_first}"
10509                            );
10510                            if a_split {
10511                                assert!(edges.contains(&Some(if a_first {
10512                                    0
10513                                } else {
10514                                    height - 1
10515                                })));
10516                            }
10517                            if b_split {
10518                                assert!(edges.contains(&Some(if b_first {
10519                                    0
10520                                } else {
10521                                    height - 1
10522                                })));
10523                            }
10524                        }
10525                    }
10526                }
10527            }
10528        }
10529    }
10530
10531    #[test]
10532    fn planar_tail_regions_cover_every_pixel_with_independent_offsets() {
10533        for (width, height) in [(1, 1), (3, 1), (1, 3), (3, 2)] {
10534            let source = (2, width * 2 + 1);
10535            let destination = (4, width * 4 + 2);
10536            let regions = planar_tail_regions(width, height, source, destination);
10537            let mut pixels = Vec::new();
10538            for part in regions.into_iter().flatten() {
10539                for y in 0..part.height as usize {
10540                    for x in 0..part.width as usize {
10541                        let in_offset = part.source_offset + y * source.1 + x * source.0;
10542                        let out_offset =
10543                            part.destination_offset + y * destination.1 + x * destination.0;
10544                        pixels.push((in_offset, out_offset));
10545                    }
10546                }
10547            }
10548            let expected: Vec<_> = (0..height)
10549                .flat_map(|y| {
10550                    (0..width).map(move |x| {
10551                        (
10552                            y * source.1 + x * source.0,
10553                            y * destination.1 + x * destination.0,
10554                        )
10555                    })
10556                })
10557                .collect();
10558            assert_eq!(pixels, expected);
10559        }
10560    }
10561
10562    #[cfg(all(target_os = "windows", not(ocio_stub)))]
10563    #[test]
10564    fn planar_float_native_entrypoints_reject_pixel_count_overflow() {
10565        let width = 2;
10566        let height = i64::from(i32::MAX) / 2 + 1;
10567        let mut channel = 0.0_f32;
10568        let ptr = std::ptr::addr_of_mut!(channel);
10569        // The rejected dimensions must be checked before either entry point
10570        // dereferences the processor or the deliberately tiny channel buffer.
10571        unsafe {
10572            crate::clear_last_error();
10573            ocio_sys::ocio_cpu_processor_apply_planar_f32(
10574                std::ptr::null_mut(),
10575                ptr,
10576                ptr,
10577                ptr,
10578                std::ptr::null_mut(),
10579                width,
10580                height,
10581            );
10582            assert!(crate::last_error_message()
10583                .unwrap()
10584                .contains("invalid planar"));
10585            crate::clear_last_error();
10586            ocio_sys::ocio_cpu_processor_apply_planar_strided_f32(
10587                std::ptr::null_mut(),
10588                ptr,
10589                ptr,
10590                ptr,
10591                std::ptr::null_mut(),
10592                width,
10593                height,
10594                1,
10595                width,
10596            );
10597            assert!(crate::last_error_message()
10598                .unwrap()
10599                .contains("invalid planar"));
10600            crate::clear_last_error();
10601        }
10602    }
10603
10604    #[test]
10605    fn packed_scalar_validation_enforces_native_scanline_limit() {
10606        let limit = (std::ffi::c_int::MAX / 4) as i64;
10607        assert!(required_scalar_len("test", limit, 0, 3).is_ok());
10608        assert!(required_scalar_len("test", limit + 1, 0, 3).is_err());
10609    }
10610
10611    #[test]
10612    fn gpu_payload_allocation_overflow_returns_error_without_mutation() {
10613        let mut values = vec![1.0_f32, 2.0];
10614        assert!(try_resize_gpu_values(&mut values, usize::MAX).is_err());
10615        assert_eq!(values, [1.0, 2.0]);
10616        try_resize_gpu_values(&mut values, 3).unwrap();
10617        assert_eq!(values, [1.0, 2.0, 0.0]);
10618        try_resize_gpu_values(&mut values, 1).unwrap();
10619        assert_eq!(values, [1.0]);
10620    }
10621
10622    #[test]
10623    #[cfg(not(feature = "v2_5"))]
10624    #[cfg_attr(ocio_stub, ignore = "requires native OpenColorIO 2.5.1 or later")]
10625    fn newer_native_gpu_language_is_not_misreported_by_fallible_query() {
10626        if crate::version_hex() < 0x0205_0100 {
10627            return;
10628        }
10629        let desc = GpuShaderDesc::create().unwrap();
10630        crate::clear_last_error();
10631        unsafe { ocio_sys::ocio_gpu_shader_desc_set_language(desc.handle.as_ptr(), 4) };
10632        crate::ocio_call_status().unwrap();
10633        assert!(matches!(
10634            desc.try_language(),
10635            Err(OcioError::ValidationFailed(_))
10636        ));
10637        assert_eq!(desc.language(), GpuLanguage::Glsl1_2);
10638        desc.set_language(GpuLanguage::Glsl4_0).unwrap();
10639        assert_eq!(desc.try_language().unwrap(), GpuLanguage::Glsl4_0);
10640    }
10641
10642    #[test]
10643    fn scalar_validation_rejects_overflowing_native_row_stride() {
10644        // The last RGB sample is addressable in principle, but OCIO's
10645        // descriptor also requires stride * pixel count to fit ptrdiff_t.
10646        let stride = (isize::MAX as i64 / 8) + 1;
10647        assert!(required_scalar_len("test", 2, stride, 3).is_ok());
10648        let error = validate_stride_byte_width("test", 2, stride, 3, 4).unwrap_err();
10649        assert!(error.to_string().contains("row stride"));
10650        assert!(validate_stride_byte_width("test", 1, stride, 3, 4).is_ok());
10651    }
10652
10653    #[cfg(target_pointer_width = "64")]
10654    #[test]
10655    fn rgba_stride_validation_rejects_native_int_truncation() {
10656        let stride = i64::from(i32::MAX) / 4 + 1;
10657        assert!(validate_stride_byte_width("test", 1, stride, 4, 4).is_err());
10658        assert!(validate_stride_byte_width("test", 1, stride, 3, 4).is_ok());
10659        assert!(validate_stride_byte_width("test", 1, 4, 4, 4).is_ok());
10660    }
10661
10662    #[cfg(all(target_pointer_width = "64", not(ocio_stub)))]
10663    #[test]
10664    fn native_packed_entrypoints_reject_truncated_rgba_stride() {
10665        let mut channel = 0.0_f32;
10666        let ptr = std::ptr::addr_of_mut!(channel);
10667        // The low 32 bits resemble a tightly packed float RGBA stride.
10668        let bytes = (1_i64 << 32) + 16;
10669        let desc = ocio_sys::OcioPackedBuffer {
10670            data: ptr.cast(),
10671            width: 1,
10672            height: 1,
10673            channel_stride: 4,
10674            x_stride: bytes,
10675            y_stride: bytes,
10676            bit_depth: BitDepth::F32 as i32,
10677            channel_order: ChannelOrdering::Rgba as i32,
10678        };
10679        unsafe {
10680            crate::clear_last_error();
10681            ocio_sys::ocio_cpu_processor_apply_packed_image(std::ptr::null_mut(), &desc);
10682            assert!(crate::last_error_message()
10683                .unwrap()
10684                .contains("invalid packed"));
10685            crate::clear_last_error();
10686            assert!(!ocio_sys::ocio_cpu_processor_try_apply_rgba_pixels(
10687                std::ptr::null_mut(),
10688                ptr,
10689                1,
10690                bytes / 4,
10691            ));
10692            assert!(crate::last_error_message().unwrap().contains("stride"));
10693            crate::clear_last_error();
10694            ocio_sys::ocio_cpu_processor_apply_packed_convert(
10695                std::ptr::null_mut(),
10696                ptr.cast(),
10697                ptr.cast(),
10698                1,
10699                4,
10700                BitDepth::F32 as i32,
10701                BitDepth::F32 as i32,
10702                bytes,
10703                16,
10704            );
10705            assert!(crate::last_error_message()
10706                .unwrap()
10707                .contains("invalid packed"));
10708            crate::clear_last_error();
10709        }
10710    }
10711
10712    #[cfg(not(ocio_stub))]
10713    #[test]
10714    fn native_image_entrypoints_reject_scanline_overflow() {
10715        let width = (std::ffi::c_int::MAX / 4) as i64 + 1;
10716        let mut channel = 0.0_f32;
10717        let ptr = std::ptr::addr_of_mut!(channel);
10718        let desc = ocio_sys::OcioPackedBuffer {
10719            data: ptr.cast(),
10720            width,
10721            height: 1,
10722            channel_stride: 4,
10723            x_stride: 12,
10724            y_stride: 12 * width,
10725            bit_depth: BitDepth::F32 as i32,
10726            channel_order: ChannelOrdering::Rgb as i32,
10727        };
10728        // All calls must reject the width before accessing the null processor
10729        // or the undersized buffers.
10730        unsafe {
10731            crate::clear_last_error();
10732            ocio_sys::ocio_cpu_processor_apply_planar_f32(
10733                std::ptr::null_mut(),
10734                ptr,
10735                ptr,
10736                ptr,
10737                std::ptr::null_mut(),
10738                width,
10739                1,
10740            );
10741            assert!(crate::last_error_message()
10742                .unwrap()
10743                .contains("invalid planar"));
10744            crate::clear_last_error();
10745            ocio_sys::ocio_cpu_processor_apply_packed_image(std::ptr::null_mut(), &desc);
10746            assert!(crate::last_error_message()
10747                .unwrap()
10748                .contains("invalid packed"));
10749            crate::clear_last_error();
10750            ocio_sys::ocio_cpu_processor_apply_rgb_pixels(std::ptr::null_mut(), ptr, width, 3);
10751            assert!(crate::last_error_message()
10752                .unwrap()
10753                .contains("scanline limit"));
10754            crate::clear_last_error();
10755        }
10756    }
10757
10758    #[test]
10759    fn packed_layout_rejects_out_of_bounds_and_overflow() {
10760        let bytes = [0u8; 24];
10761        let layout = PackedImageLayout {
10762            width: 2,
10763            height: 2,
10764            origin: 0,
10765            channel_stride: 1,
10766            x_stride: 4,
10767            y_stride: 8,
10768            bit_depth: BitDepth::Uint8,
10769            channel_order: ChannelOrdering::Rgba,
10770        };
10771        assert!(packed_image_descriptor(layout, &bytes[..16]).is_ok());
10772        assert!(packed_image_descriptor(layout, &bytes[..15]).is_err());
10773        assert!(packed_image_descriptor(
10774            PackedImageLayout {
10775                x_stride: isize::MIN,
10776                ..layout
10777            },
10778            &bytes
10779        )
10780        .is_err());
10781        assert!(packed_image_descriptor(
10782            PackedImageLayout {
10783                channel_stride: usize::MAX,
10784                ..layout
10785            },
10786            &bytes
10787        )
10788        .is_err());
10789        assert!(packed_image_descriptor(
10790            PackedImageLayout {
10791                x_stride: -4,
10792                origin: 4,
10793                ..layout
10794            },
10795            &bytes
10796        )
10797        .is_err());
10798        assert!(packed_image_descriptor(
10799            PackedImageLayout {
10800                x_stride: -4,
10801                origin: 8,
10802                ..layout
10803            },
10804            &bytes
10805        )
10806        .is_ok());
10807    }
10808
10809    #[test]
10810    fn packed_layout_requires_full_final_channel_stride() {
10811        let bytes = [0u8; 16];
10812        let layout = PackedImageLayout {
10813            width: 1,
10814            height: 1,
10815            origin: 0,
10816            channel_stride: 2,
10817            x_stride: 5,
10818            y_stride: 5,
10819            bit_depth: BitDepth::Uint8,
10820            channel_order: ChannelOrdering::Rgb,
10821        };
10822        assert!(packed_image_descriptor(layout, &bytes).is_err());
10823        assert!(packed_image_descriptor(
10824            PackedImageLayout {
10825                x_stride: 6,
10826                y_stride: 6,
10827                ..layout
10828            },
10829            &bytes
10830        )
10831        .is_ok());
10832    }
10833
10834    #[test]
10835    fn generic_packed_layout_requires_all_channel_pointer_steps() {
10836        let bytes = [0u8; 8];
10837        let rgb = PackedImageLayout {
10838            width: 2,
10839            height: 1,
10840            origin: 0,
10841            channel_stride: 1,
10842            x_stride: 3,
10843            y_stride: 6,
10844            bit_depth: BitDepth::Uint8,
10845            channel_order: ChannelOrdering::Rgb,
10846        };
10847        assert!(packed_image_descriptor(rgb, &bytes[..6]).is_err());
10848        assert!(packed_image_descriptor(rgb, &bytes).is_ok());
10849        let rgba = PackedImageLayout {
10850            x_stride: 4,
10851            y_stride: 8,
10852            channel_order: ChannelOrdering::Rgba,
10853            ..rgb
10854        };
10855        assert!(packed_image_descriptor(rgba, &bytes).is_ok());
10856    }
10857    use crate::Config;
10858
10859    #[test]
10860    fn gpu_texture_dimension_discriminants_match_native_headers() {
10861        assert_eq!(GpuTextureDimensions::Texture1D as i32, 1);
10862        assert_eq!(GpuTextureDimensions::Texture2D as i32, 2);
10863        assert_eq!(
10864            GpuTextureDimensions::from_raw(1).unwrap(),
10865            GpuTextureDimensions::Texture1D
10866        );
10867        assert_eq!(
10868            GpuTextureDimensions::from_raw(2).unwrap(),
10869            GpuTextureDimensions::Texture2D
10870        );
10871        assert!(GpuTextureDimensions::from_raw(0).is_err());
10872        assert!(GpuTextureDimensions::from_raw(3).is_err());
10873        assert_eq!(
10874            GpuTextureChannel::from_raw(0).unwrap(),
10875            GpuTextureChannel::Red
10876        );
10877        assert_eq!(
10878            GpuTextureChannel::from_raw(1).unwrap(),
10879            GpuTextureChannel::Rgb
10880        );
10881        assert!(GpuTextureChannel::from_raw(2).is_err());
10882    }
10883
10884    #[test]
10885    fn gpu_texture_dimensions_reject_overflow_without_panicking() {
10886        let desc = GpuShaderDesc::create().unwrap();
10887        assert!(desc
10888            .add_texture_3d("texture", "sampler", 1 << 22, Interpolation::Linear, &[])
10889            .is_err());
10890        assert!(desc
10891            .add_texture_2d(
10892                "texture",
10893                "sampler",
10894                u32::MAX,
10895                u32::MAX,
10896                GpuTextureChannel::Rgb,
10897                GpuTextureDimensions::Texture2D,
10898                Interpolation::Linear,
10899                &[]
10900            )
10901            .is_err());
10902    }
10903
10904    #[test]
10905    fn signed_planar_layout_checks_all_corners_and_pointer_steps() {
10906        let plane = [0u8; 8];
10907        for x in [-1isize, 1] {
10908            for y in [-3isize, 3] {
10909                let layout = SignedPlanarByteLayout {
10910                    width: 2,
10911                    height: 2,
10912                    origin: 1 + if x < 0 { 1 } else { 0 } + if y < 0 { 3 } else { 0 },
10913                    x_stride: x,
10914                    y_stride: y,
10915                    bit_depth: BitDepth::Uint8,
10916                };
10917                assert!(validate_signed_planar(layout, &[&plane]).is_ok());
10918                assert!(validate_signed_planar(layout, &[&plane[..4]]).is_err());
10919            }
10920        }
10921        let underflow = SignedPlanarByteLayout {
10922            width: 2,
10923            height: 1,
10924            origin: 1,
10925            x_stride: -1,
10926            y_stride: 2,
10927            bit_depth: BitDepth::Uint8,
10928        };
10929        assert!(validate_signed_planar(underflow, &[&plane]).is_err());
10930        assert!(validate_signed_planar(
10931            SignedPlanarByteLayout {
10932                x_stride: isize::MIN,
10933                ..underflow
10934            },
10935            &[&plane]
10936        )
10937        .is_err());
10938    }
10939
10940    #[test]
10941    fn planar_layout_requires_native_row_stride_even_for_one_row() {
10942        let plane = [0u8; 4];
10943        let layout = PlanarByteLayout {
10944            width: 2,
10945            height: 1,
10946            x_stride: 2,
10947            y_stride: 3,
10948            bit_depth: BitDepth::Uint8,
10949        };
10950        assert!(validate_planar_buffer(layout, &[&plane]).is_err());
10951        assert!(validate_planar_buffer(
10952            PlanarByteLayout {
10953                y_stride: 4,
10954                ..layout
10955            },
10956            &[&plane]
10957        )
10958        .is_ok());
10959        assert!(validate_planar_buffer(
10960            PlanarByteLayout {
10961                y_stride: 4,
10962                ..layout
10963            },
10964            &[&plane[..3]]
10965        )
10966        .is_err());
10967        assert!(validate_planar_buffer(
10968            PlanarByteLayout {
10969                width: 2,
10970                x_stride: usize::MAX,
10971                y_stride: usize::MAX,
10972                ..layout
10973            },
10974            &[&plane]
10975        )
10976        .is_err());
10977    }
10978
10979    #[test]
10980    fn processor_metadata() {
10981        let config = Config::raw().unwrap();
10982        let proc = config.processor("raw", "raw").unwrap();
10983        let _ = proc.is_no_op();
10984        let _ = proc.has_channel_crosstalk();
10985        let _ = proc.cache_id();
10986        if let Some(metadata) = proc.processor_metadata() {
10987            let _ = metadata.num_files();
10988            let _ = metadata.file(0);
10989            let _ = metadata.num_looks();
10990            let _ = metadata.look(0);
10991        }
10992    }
10993
10994    #[test]
10995    fn cpu_processor() {
10996        let config = Config::raw().unwrap();
10997        let proc = config.processor("raw", "raw").unwrap();
10998        // In stub mode, creating a CPU processor may or may not succeed
10999        if let Ok(cpu) = proc.default_cpu_processor() {
11000            let mut pixel = [0.5, 0.25, 0.125, 1.0];
11001            cpu.apply_rgba(&mut pixel);
11002            let _ = cpu.is_no_op();
11003            let _ = cpu.try_is_no_op();
11004            let _ = cpu.has_channel_crosstalk();
11005            let _ = cpu.try_has_channel_crosstalk();
11006            let _ = cpu.is_identity();
11007            let _ = cpu.try_is_identity();
11008            let _ = cpu.cache_id();
11009            let _ = cpu.input_bit_depth();
11010            let _ = cpu.output_bit_depth();
11011        }
11012    }
11013
11014    #[test]
11015    fn gpu_processor() {
11016        let config = Config::raw().unwrap();
11017        let proc = config.processor("raw", "raw").unwrap();
11018        if let Ok(gpu) = proc.default_gpu_processor() {
11019            let _ = gpu.is_no_op();
11020            let _ = gpu.try_is_no_op();
11021            let _ = gpu.has_channel_crosstalk();
11022            let _ = gpu.try_has_channel_crosstalk();
11023            let _ = gpu.cache_id();
11024        }
11025    }
11026
11027    #[test]
11028    #[allow(deprecated)]
11029    fn legacy_gpu_processor() {
11030        let config = Config::raw().unwrap();
11031        let proc = config.processor("raw", "raw").unwrap();
11032        if let Ok(gpu) = proc.optimized_legacy_gpu_processor(0, 32) {
11033            let _ = gpu.is_no_op();
11034            let _ = gpu.cache_id();
11035        }
11036    }
11037
11038    #[test]
11039    fn gpu_shader_desc() {
11040        if let Ok(desc) = GpuShaderDesc::create() {
11041            // Stub mode returns empty shader text
11042            let _ = desc.shader_text();
11043            let _ = desc.num_textures();
11044            let _ = desc.language();
11045            let _ = desc.function_name();
11046            let _ = desc.pixel_name();
11047            let _ = desc.resource_prefix();
11048            desc.set_language(GpuLanguage::Glsl1_2).unwrap();
11049            let _ = desc.set_function_name("main");
11050            let _ = desc.set_pixel_name("outColor");
11051            let _ = desc.set_resource_prefix("ocio_");
11052            desc.finalize().unwrap();
11053        }
11054    }
11055
11056    #[test]
11057    fn gpu_extract_shader_info_named_wrapper_no_crash() {
11058        let config = Config::raw().unwrap();
11059        let proc = config.processor("raw", "raw").unwrap();
11060        if let (Ok(gpu), Ok(mut desc)) = (proc.default_gpu_processor(), GpuShaderDesc::create()) {
11061            gpu.try_extract_shader_info(&mut desc).unwrap();
11062        }
11063    }
11064
11065    #[test]
11066    fn gpu_shader_desc_texture_max_no_crash() {
11067        if let Ok(desc) = GpuShaderDesc::create() {
11068            let _ = desc.texture_max_width();
11069        }
11070    }
11071
11072    #[test]
11073    fn gpu_shader_desc_cache_id_no_crash() {
11074        if let Ok(desc) = GpuShaderDesc::create() {
11075            let _ = desc.cache_id();
11076        }
11077    }
11078
11079    #[test]
11080    fn gpu_shader_desc_texture_uid_no_crash() {
11081        if let Ok(desc) = GpuShaderDesc::create() {
11082            let _ = desc.texture_uid(0);
11083        }
11084    }
11085
11086    #[test]
11087    fn processor_num_transforms() {
11088        let config = Config::raw().unwrap();
11089        let proc = config.processor("raw", "raw").unwrap();
11090        // Stub mode returns 0
11091        assert!(proc.num_transforms() >= 0);
11092    }
11093
11094    #[test]
11095    fn processor_create_group_transform() {
11096        let config = Config::raw().unwrap();
11097        let proc = config.processor("raw", "raw").unwrap();
11098        // Stub mode returns None
11099        let _ = proc.create_group_transform();
11100    }
11101
11102    #[test]
11103    fn dynamic_property() {
11104        let config = Config::raw().unwrap();
11105        let proc = config.processor("raw", "raw").unwrap();
11106        let _ = proc.has_dynamic_property_kind(DynamicPropertyType::Exposure);
11107        // In stub mode, creating a dynamic property may or may not succeed
11108        if let Ok(dp) = proc.dynamic_property(DynamicPropertyType::Exposure) {
11109            let _ = dp.property_type();
11110            let _ = dp.double_value();
11111            let _ = dp.set_double_value(1.5);
11112        }
11113    }
11114
11115    #[test]
11116    #[allow(deprecated)]
11117    fn processor_dynamic_property_compat_alias_no_crash() {
11118        let config = Config::raw().unwrap();
11119        let proc = config.processor("raw", "raw").unwrap();
11120        let _ = proc.has_dynamic_property(DynamicPropertyType::Exposure as i32);
11121    }
11122
11123    #[test]
11124    fn dynamic_property_grading_primary_no_crash() {
11125        let config = Config::raw().unwrap();
11126        let proc = config.processor("raw", "raw").unwrap();
11127        if let Ok(dp) = proc.dynamic_property(DynamicPropertyType::GradingPrimary) {
11128            let _ = dp.grading_primary_value();
11129            let v = crate::grading::GradingPrimary::new(crate::GradingStyle::Log);
11130            let _ = dp.set_grading_primary_value(&v);
11131        }
11132    }
11133
11134    #[test]
11135    fn dynamic_property_grading_tone_no_crash() {
11136        let config = Config::raw().unwrap();
11137        let proc = config.processor("raw", "raw").unwrap();
11138        if let Ok(dp) = proc.dynamic_property(DynamicPropertyType::GradingTone) {
11139            let _ = dp.grading_tone_value();
11140            let v = crate::grading::GradingTone::new(crate::GradingStyle::Log);
11141            let _ = dp.set_grading_tone_value(&v);
11142        }
11143    }
11144
11145    #[test]
11146    fn dynamic_property_grading_rgb_curve_no_crash() {
11147        let config = Config::raw().unwrap();
11148        let proc = config.processor("raw", "raw").unwrap();
11149        if let Ok(dp) = proc.dynamic_property(DynamicPropertyType::GradingRgbCurve) {
11150            for ct in [
11151                RGBCurveType::Red,
11152                RGBCurveType::Green,
11153                RGBCurveType::Blue,
11154                RGBCurveType::Master,
11155            ] {
11156                let _ = dp.grading_rgb_curve_num_control_points(ct);
11157                let _ = dp.grading_rgb_curve_control_point(ct, 0);
11158                let _ = dp.grading_rgb_curve_slope(ct, 0);
11159                let _ = dp.grading_rgb_curve_slopes_are_default(ct);
11160            }
11161            let _ = dp.grading_rgb_curve_set_num_control_points(RGBCurveType::Red, 2);
11162            let _ = dp.grading_rgb_curve_set_control_point(RGBCurveType::Red, 0, 0.0, 0.0);
11163            let _ = dp.grading_rgb_curve_set_slope(RGBCurveType::Red, 0, 1.0);
11164        }
11165    }
11166
11167    #[cfg(feature = "v2_5")]
11168    #[test]
11169    fn dynamic_property_grading_hue_curve_no_crash() {
11170        let config = Config::raw().unwrap();
11171        let proc = config.processor("raw", "raw").unwrap();
11172        if let Ok(dp) = proc.dynamic_property(DynamicPropertyType::GradingHueCurve) {
11173            for ct in [
11174                HueCurveType::HueHue,
11175                HueCurveType::HueSat,
11176                HueCurveType::HueLum,
11177                HueCurveType::LumSat,
11178            ] {
11179                let _ = dp.grading_hue_curve_num_control_points(ct);
11180                let _ = dp.grading_hue_curve_control_point(ct, 0);
11181                let _ = dp.grading_hue_curve_slope(ct, 0);
11182                let _ = dp.grading_hue_curve_slopes_are_default(ct);
11183            }
11184            let _ = dp.grading_hue_curve_set_num_control_points(HueCurveType::HueHue, 2);
11185            let _ = dp.grading_hue_curve_set_control_point(HueCurveType::HueHue, 0, 0.0, 0.0);
11186            let _ = dp.grading_hue_curve_set_slope(HueCurveType::HueHue, 0, 1.0);
11187        }
11188    }
11189
11190    #[test]
11191    fn cpu_processor_apply_pixels_no_crash() {
11192        let config = Config::raw().unwrap();
11193        let proc = config.processor("raw", "raw").unwrap();
11194        if let Ok(cpu) = proc.default_cpu_processor() {
11195            let mut rgba = vec![0.0f32; 16]; // 4 pixels RGBA
11196            cpu.try_apply_rgba_pixels(&mut rgba, 4, 4).unwrap();
11197            let mut rgb = vec![0.0f32; 12]; // 4 pixels RGB
11198            cpu.try_apply_rgb_pixels(&mut rgb, 4, 3).unwrap();
11199        }
11200    }
11201
11202    #[test]
11203    fn cpu_processor_apply_packed_no_crash() {
11204        let config = Config::raw().unwrap();
11205        let proc = config.processor("raw", "raw").unwrap();
11206        if let Ok(cpu) = proc.default_cpu_processor() {
11207            let mut rgba = vec![0u8; 32]; // 2 RGBA pixels as packed f32 bytes
11208            cpu.try_apply_rgba_packed_bit_depth(&mut rgba, BitDepth::F32, 2, 4)
11209                .unwrap();
11210            let mut rgb = vec![0u8; 24]; // 2 RGB pixels as packed f32 bytes
11211            cpu.try_apply_rgb_packed_bit_depth(&mut rgb, BitDepth::F32, 2, 3)
11212                .unwrap();
11213        }
11214    }
11215
11216    #[test]
11217    fn cpu_processor_try_apply_reports_invalid_input() {
11218        let config = Config::raw().unwrap();
11219        let proc = config.processor("raw", "raw").unwrap();
11220        if let Ok(cpu) = proc.default_cpu_processor() {
11221            let mut rgba = vec![0.0f32; 3];
11222            let err = cpu.try_apply_rgba_pixels(&mut rgba, 1, 4).unwrap_err();
11223            assert!(matches!(err, OcioError::InvalidInput(_)));
11224
11225            let mut packed = vec![0u8; 4];
11226            let err = cpu
11227                .try_apply_rgba_packed_bit_depth(&mut packed, BitDepth::Unknown, 1, 4)
11228                .unwrap_err();
11229            assert!(matches!(err, OcioError::InvalidInput(_)));
11230        }
11231    }
11232
11233    #[test]
11234    fn cpu_processor_pixel_layout_validation_covers_default_and_short_strides() {
11235        assert_eq!(
11236            required_scalar_len("test", 2, 0, 4).expect("default RGBA stride"),
11237            8
11238        );
11239        assert_eq!(
11240            required_scalar_len("test", 2, 6, 4).expect("padded RGBA stride"),
11241            10
11242        );
11243        assert!(required_scalar_len("test", 1, 3, 4).is_err());
11244
11245        let config = Config::raw().unwrap();
11246        let proc = config.processor("raw", "raw").unwrap();
11247        if let Ok(cpu) = proc.default_cpu_processor() {
11248            let mut too_short_default_stride = vec![0.0f32; 3];
11249            assert!(cpu
11250                .try_apply_rgba_pixels(&mut too_short_default_stride, 1, 0)
11251                .is_err());
11252
11253            let mut short_stride = vec![0.0f32; 4];
11254            assert!(cpu.try_apply_rgba_pixels(&mut short_stride, 1, 3).is_err());
11255
11256            let mut packed_short_stride = vec![0u8; 4];
11257            assert!(cpu
11258                .try_apply_rgb_packed_bit_depth(&mut packed_short_stride, BitDepth::Uint8, 1, 2)
11259                .is_err());
11260
11261            let mut overflowed_byte_stride = vec![0.0f32; 4];
11262            assert!(cpu
11263                .try_apply_rgba_pixels(&mut overflowed_byte_stride, 1, i64::MAX)
11264                .is_err());
11265
11266            let mut unaligned_storage = [0u8; 17];
11267            let unaligned_f32 = &mut unaligned_storage[1..];
11268            assert!(cpu
11269                .try_apply_rgba_packed_bit_depth(unaligned_f32, BitDepth::F32, 1, 4)
11270                .is_err());
11271        }
11272    }
11273
11274    #[test]
11275    fn cpu_processor_dynamic_property_typed_no_crash() {
11276        let config = Config::raw().unwrap();
11277        let proc = config.processor("raw", "raw").unwrap();
11278        if let Ok(cpu) = proc.default_cpu_processor() {
11279            let _ = cpu.has_dynamic_property_kind(DynamicPropertyType::Exposure);
11280            let _ = cpu.dynamic_property(DynamicPropertyType::Exposure);
11281        }
11282    }
11283
11284    #[cfg(feature = "v2_5")]
11285    #[test]
11286    fn gpu_shader_desc_structured_accessors_no_crash() {
11287        if let Ok(desc) = GpuShaderDesc::create() {
11288            let _ = desc.clone_desc();
11289            let _ = desc.num_uniforms();
11290            let _ = desc.uniform_buffer_size();
11291            let _ = desc.uniform(0);
11292            let _ = desc.uniform_name(0);
11293            let _ = desc.uniform_value_count(0);
11294            let _ = desc.uniform_values_f32(0);
11295            let _ = desc.uniform_values_i32(0);
11296            let _ = desc.uniforms();
11297            let _ = desc.texture_2d(0);
11298            let _ = desc.texture_shader_binding_index(0);
11299            let _ = desc.texture_values(0);
11300            let _ = desc.texture_value_count(0);
11301            let _ = desc.textures_2d();
11302            let _ = desc.texture_3d(0);
11303            let _ = desc.texture_3d_value_count(0);
11304            let _ = desc.texture_3d_values(0);
11305            let _ = desc.texture_3d_shader_binding_index(0);
11306            let _ = desc.textures_3d();
11307        }
11308    }
11309
11310    #[cfg(feature = "v2_5")]
11311    #[test]
11312    #[allow(deprecated)]
11313    fn gpu_shader_desc_compat_value_accessors_no_crash() {
11314        if let Ok(desc) = GpuShaderDesc::create() {
11315            let _ = desc.clone();
11316            let _ = desc.get_num_uniforms_u32();
11317            let _ = desc.get_uniform_buffer_size_bytes();
11318            let _ = desc.get_uniform_info(0);
11319            let _ = desc.get_uniform_value_count(0);
11320            let _ = desc.copy_uniform_f32_values(0);
11321            let _ = desc.copy_uniform_i32_values(0);
11322            let _ = desc.get_num_textures_u32();
11323            let _ = desc.get_texture_value_count(0);
11324            let _ = desc.copy_texture_values(0);
11325            let _ = desc.get_num3d_textures_u32();
11326            let _ = desc.get3d_texture_info(0);
11327            let _ = desc.get3d_texture_value_count(0);
11328            let _ = desc.copy3d_texture_values(0);
11329            let _ = desc.get_num3d_textures();
11330            let _ = desc.get3d_texture(0);
11331            let _ = desc.get3d_texture_values(0);
11332            let _ = desc.get3d_texture_shader_binding_index(0);
11333        }
11334    }
11335}