moxcms/conversions/
md_luts_factory.rs

1/*
2 * // Copyright (c) Radzivon Bartoshyk 6/2025. All rights reserved.
3 * //
4 * // Redistribution and use in source and binary forms, with or without modification,
5 * // are permitted provided that the following conditions are met:
6 * //
7 * // 1.  Redistributions of source code must retain the above copyright notice, this
8 * // list of conditions and the following disclaimer.
9 * //
10 * // 2.  Redistributions in binary form must reproduce the above copyright notice,
11 * // this list of conditions and the following disclaimer in the documentation
12 * // and/or other materials provided with the distribution.
13 * //
14 * // 3.  Neither the name of the copyright holder nor the names of its
15 * // contributors may be used to endorse or promote products derived from
16 * // this software without specific prior written permission.
17 * //
18 * // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 * // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 * // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22 * // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24 * // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25 * // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26 * // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29use crate::conversions::LutBarycentricReduction;
30use crate::conversions::katana::{
31    CopyAlphaStage, InjectAlphaStage, Katana, KatanaInitialStage, KatanaIntermediateStage,
32    KatanaPostFinalizationStage, KatanaStageLabToXyz, KatanaStageXyzToLab,
33    katana_create_rgb_lin_lut, katana_input_make_lut_nx3, katana_multi_dimensional_3xn_to_device,
34    katana_multi_dimensional_nx3_to_pcs, katana_output_make_lut_3xn, katana_pcs_lab_v2_to_v4,
35    katana_pcs_lab_v4_to_v2, katana_prepare_inverse_lut_rgb_xyz,
36};
37use crate::{
38    CmsError, ColorProfile, DataColorSpace, GammaLutInterpolate, Layout, LutWarehouse,
39    PointeeSizeExpressible, TransformExecutor, TransformOptions,
40};
41use num_traits::AsPrimitive;
42
43pub(crate) fn do_any_to_any<
44    T: Copy
45        + Default
46        + AsPrimitive<f32>
47        + Send
48        + Sync
49        + AsPrimitive<usize>
50        + PointeeSizeExpressible
51        + GammaLutInterpolate,
52    const BIT_DEPTH: usize,
53    const LINEAR_CAP: usize,
54    const GAMMA_LUT: usize,
55>(
56    src_layout: Layout,
57    source: &ColorProfile,
58    dst_layout: Layout,
59    dest: &ColorProfile,
60    options: TransformOptions,
61) -> Result<Box<dyn TransformExecutor<T> + Send + Sync>, CmsError>
62where
63    f32: AsPrimitive<T>,
64    u32: AsPrimitive<T>,
65    (): LutBarycentricReduction<T, u8>,
66    (): LutBarycentricReduction<T, u16>,
67{
68    let mut stages: Vec<Box<dyn KatanaIntermediateStage<f32> + Send + Sync>> = Vec::new();
69
70    let initial_stage: Box<dyn KatanaInitialStage<f32, T> + Send + Sync> = match source
71        .is_matrix_shaper()
72    {
73        true => {
74            let state =
75                katana_create_rgb_lin_lut::<T, BIT_DEPTH, LINEAR_CAP>(src_layout, source, options)?;
76            stages.extend(state.stages);
77            state.initial_stage
78        }
79        false => match source.get_device_to_pcs(options.rendering_intent).ok_or(
80            CmsError::UnsupportedLutRenderingIntent(source.rendering_intent),
81        )? {
82            LutWarehouse::Lut(lut) => katana_input_make_lut_nx3::<T>(
83                src_layout,
84                src_layout.channels(),
85                lut,
86                options,
87                source.pcs,
88                BIT_DEPTH,
89            )?,
90            LutWarehouse::Multidimensional(mab) => katana_multi_dimensional_nx3_to_pcs::<T>(
91                src_layout, mab, options, source.pcs, BIT_DEPTH,
92            )?,
93        },
94    };
95
96    stages.push(katana_pcs_lab_v2_to_v4(source));
97    if source.pcs == DataColorSpace::Lab {
98        stages.push(Box::new(KatanaStageLabToXyz::default()));
99    }
100    if dest.pcs == DataColorSpace::Lab {
101        stages.push(Box::new(KatanaStageXyzToLab::default()));
102    }
103    stages.push(katana_pcs_lab_v4_to_v2(dest));
104
105    let final_stage = if dest.has_pcs_to_device_lut() {
106        let pcs_to_device = dest
107            .get_pcs_to_device(options.rendering_intent)
108            .ok_or(CmsError::UnsupportedProfileConnection)?;
109        match pcs_to_device {
110            LutWarehouse::Lut(lut) => katana_output_make_lut_3xn::<T>(
111                dst_layout,
112                lut,
113                options,
114                dest.color_space,
115                BIT_DEPTH,
116            )?,
117            LutWarehouse::Multidimensional(mab) => katana_multi_dimensional_3xn_to_device::<T>(
118                dst_layout, mab, options, dest.pcs, BIT_DEPTH,
119            )?,
120        }
121    } else if dest.is_matrix_shaper() {
122        let state = katana_prepare_inverse_lut_rgb_xyz::<T, BIT_DEPTH, GAMMA_LUT>(
123            dest, dst_layout, options,
124        )?;
125        stages.extend(state.stages);
126        state.final_stage
127    } else {
128        return Err(CmsError::UnsupportedProfileConnection);
129    };
130
131    let mut post_finalization: Vec<Box<dyn KatanaPostFinalizationStage<T> + Send + Sync>> =
132        Vec::new();
133    if let Some(stage) =
134        prepare_alpha_finalizer::<T>(src_layout, source, dst_layout, dest, BIT_DEPTH)
135    {
136        post_finalization.push(stage);
137    }
138
139    Ok(Box::new(Katana::<f32, T> {
140        initial_stage,
141        final_stage,
142        stages,
143        post_finalization,
144    }))
145}
146
147pub(crate) fn prepare_alpha_finalizer<
148    T: Copy
149        + Default
150        + AsPrimitive<f32>
151        + Send
152        + Sync
153        + AsPrimitive<usize>
154        + PointeeSizeExpressible
155        + GammaLutInterpolate,
156>(
157    src_layout: Layout,
158    source: &ColorProfile,
159    dst_layout: Layout,
160    dest: &ColorProfile,
161    bit_depth: usize,
162) -> Option<Box<dyn KatanaPostFinalizationStage<T> + Send + Sync>>
163where
164    f32: AsPrimitive<T>,
165{
166    if (dst_layout == Layout::GrayAlpha && dest.color_space == DataColorSpace::Gray)
167        || (dst_layout == Layout::Rgba || dest.color_space == DataColorSpace::Rgb)
168    {
169        return if (src_layout == Layout::GrayAlpha && source.color_space == DataColorSpace::Gray)
170            || (src_layout == Layout::Rgba || source.color_space == DataColorSpace::Rgb)
171        {
172            Some(Box::new(CopyAlphaStage {
173                src_layout,
174                dst_layout,
175                target_color_space: dest.color_space,
176                _phantom: Default::default(),
177            }))
178        } else {
179            Some(Box::new(InjectAlphaStage {
180                dst_layout,
181                target_color_space: dest.color_space,
182                _phantom: Default::default(),
183                bit_depth,
184            }))
185        };
186    }
187    None
188}