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) => {
91                katana_multi_dimensional_nx3_to_pcs::<T, BIT_DEPTH>(
92                    src_layout, mab, options, source.pcs,
93                )?
94            }
95        },
96    };
97
98    stages.push(katana_pcs_lab_v2_to_v4(source));
99    if source.pcs == DataColorSpace::Lab {
100        stages.push(Box::new(KatanaStageLabToXyz::default()));
101    }
102    if dest.pcs == DataColorSpace::Lab {
103        stages.push(Box::new(KatanaStageXyzToLab::default()));
104    }
105    stages.push(katana_pcs_lab_v4_to_v2(dest));
106
107    let final_stage = if dest.has_pcs_to_device_lut() {
108        let pcs_to_device = dest
109            .get_pcs_to_device(options.rendering_intent)
110            .ok_or(CmsError::UnsupportedProfileConnection)?;
111        match pcs_to_device {
112            LutWarehouse::Lut(lut) => katana_output_make_lut_3xn::<T>(
113                dst_layout,
114                lut,
115                options,
116                dest.color_space,
117                BIT_DEPTH,
118            )?,
119            LutWarehouse::Multidimensional(mab) => katana_multi_dimensional_3xn_to_device::<T>(
120                dst_layout, mab, options, dest.pcs, BIT_DEPTH,
121            )?,
122        }
123    } else if dest.is_matrix_shaper() {
124        let state = katana_prepare_inverse_lut_rgb_xyz::<T, BIT_DEPTH, GAMMA_LUT>(
125            dest, dst_layout, options,
126        )?;
127        stages.extend(state.stages);
128        state.final_stage
129    } else {
130        return Err(CmsError::UnsupportedProfileConnection);
131    };
132
133    let mut post_finalization: Vec<Box<dyn KatanaPostFinalizationStage<T> + Send + Sync>> =
134        Vec::new();
135    if let Some(stage) =
136        prepare_alpha_finalizer::<T>(src_layout, source, dst_layout, dest, BIT_DEPTH)
137    {
138        post_finalization.push(stage);
139    }
140
141    Ok(Box::new(Katana::<f32, T> {
142        initial_stage,
143        final_stage,
144        stages,
145        post_finalization,
146    }))
147}
148
149pub(crate) fn prepare_alpha_finalizer<
150    T: Copy
151        + Default
152        + AsPrimitive<f32>
153        + Send
154        + Sync
155        + AsPrimitive<usize>
156        + PointeeSizeExpressible
157        + GammaLutInterpolate,
158>(
159    src_layout: Layout,
160    source: &ColorProfile,
161    dst_layout: Layout,
162    dest: &ColorProfile,
163    bit_depth: usize,
164) -> Option<Box<dyn KatanaPostFinalizationStage<T> + Send + Sync>>
165where
166    f32: AsPrimitive<T>,
167{
168    if (dst_layout == Layout::GrayAlpha && dest.color_space == DataColorSpace::Gray)
169        || (dst_layout == Layout::Rgba || dest.color_space == DataColorSpace::Rgb)
170    {
171        return if (src_layout == Layout::GrayAlpha && source.color_space == DataColorSpace::Gray)
172            || (src_layout == Layout::Rgba || source.color_space == DataColorSpace::Rgb)
173        {
174            Some(Box::new(CopyAlphaStage {
175                src_layout,
176                dst_layout,
177                target_color_space: dest.color_space,
178                _phantom: Default::default(),
179            }))
180        } else {
181            Some(Box::new(InjectAlphaStage {
182                dst_layout,
183                target_color_space: dest.color_space,
184                _phantom: Default::default(),
185                bit_depth,
186            }))
187        };
188    }
189    None
190}