Coverage Report

Created: 2026-03-07 07:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/moxcms-0.8.0/src/conversions/lut4.rs
Line
Count
Source
1
/*
2
 * // Copyright (c) Radzivon Bartoshyk 3/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
 */
29
#![cfg(feature = "lut")]
30
#[cfg(feature = "any_to_any")]
31
use crate::conversions::katana::KatanaInitialStage;
32
use crate::err::try_vec;
33
use crate::profile::LutDataType;
34
use crate::safe_math::{SafeMul, SafePowi};
35
use crate::trc::lut_interp_linear_float;
36
use crate::{
37
    CmsError, DataColorSpace, Hypercube, InterpolationMethod, MalformedSize,
38
    PointeeSizeExpressible, Stage, TransformOptions, Vector3f,
39
};
40
use num_traits::AsPrimitive;
41
use std::marker::PhantomData;
42
43
#[allow(unused)]
44
#[derive(Default)]
45
struct Lut4x3 {
46
    linearization: [Vec<f32>; 4],
47
    clut: Vec<f32>,
48
    grid_size: u8,
49
    output: [Vec<f32>; 3],
50
    interpolation_method: InterpolationMethod,
51
    pcs: DataColorSpace,
52
}
53
54
#[allow(unused)]
55
#[derive(Default)]
56
struct KatanaLut4x3<T: Copy + PointeeSizeExpressible + AsPrimitive<f32>> {
57
    linearization: [Vec<f32>; 4],
58
    clut: Vec<f32>,
59
    grid_size: u8,
60
    output: [Vec<f32>; 3],
61
    interpolation_method: InterpolationMethod,
62
    pcs: DataColorSpace,
63
    _phantom: PhantomData<T>,
64
    bit_depth: usize,
65
}
66
67
#[allow(unused)]
68
impl Lut4x3 {
69
0
    fn transform_impl<Fetch: Fn(f32, f32, f32, f32) -> Vector3f>(
70
0
        &self,
71
0
        src: &[f32],
72
0
        dst: &mut [f32],
73
0
        fetch: Fetch,
74
0
    ) -> Result<(), CmsError> {
75
0
        let linearization_0 = &self.linearization[0];
76
0
        let linearization_1 = &self.linearization[1];
77
0
        let linearization_2 = &self.linearization[2];
78
0
        let linearization_3 = &self.linearization[3];
79
0
        for (dest, src) in dst.chunks_exact_mut(3).zip(src.chunks_exact(4)) {
80
0
            debug_assert!(self.grid_size as i32 >= 1);
81
0
            let linear_x = lut_interp_linear_float(src[0], linearization_0);
82
0
            let linear_y = lut_interp_linear_float(src[1], linearization_1);
83
0
            let linear_z = lut_interp_linear_float(src[2], linearization_2);
84
0
            let linear_w = lut_interp_linear_float(src[3], linearization_3);
85
86
0
            let clut = fetch(linear_x, linear_y, linear_z, linear_w);
87
88
0
            let pcs_x = lut_interp_linear_float(clut.v[0], &self.output[0]);
89
0
            let pcs_y = lut_interp_linear_float(clut.v[1], &self.output[1]);
90
0
            let pcs_z = lut_interp_linear_float(clut.v[2], &self.output[2]);
91
0
            dest[0] = pcs_x;
92
0
            dest[1] = pcs_y;
93
0
            dest[2] = pcs_z;
94
        }
95
0
        Ok(())
96
0
    }
Unexecuted instantiation: <moxcms::conversions::lut4::Lut4x3>::transform_impl::<<moxcms::conversions::lut4::Lut4x3 as moxcms::transform::Stage>::transform::{closure#0}>
Unexecuted instantiation: <moxcms::conversions::lut4::Lut4x3>::transform_impl::<<moxcms::conversions::lut4::Lut4x3 as moxcms::transform::Stage>::transform::{closure#1}>
97
}
98
99
macro_rules! define_lut4_dispatch {
100
    ($dispatcher: ident) => {
101
        impl Stage for $dispatcher {
102
0
            fn transform(&self, src: &[f32], dst: &mut [f32]) -> Result<(), CmsError> {
103
0
                let l_tbl = Hypercube::new(&self.clut, self.grid_size as usize, 3)?;
104
105
                // If Source PCS is LAB trilinear should be used
106
0
                if self.pcs == DataColorSpace::Lab || self.pcs == DataColorSpace::Xyz {
107
0
                    return self
108
0
                        .transform_impl(src, dst, |x, y, z, w| l_tbl.quadlinear_vec3(x, y, z, w));
109
0
                }
110
111
0
                match self.interpolation_method {
112
                    #[cfg(feature = "options")]
113
                    InterpolationMethod::Tetrahedral => {
114
                        self.transform_impl(src, dst, |x, y, z, w| l_tbl.tetra_vec3(x, y, z, w))?;
115
                    }
116
                    #[cfg(feature = "options")]
117
                    InterpolationMethod::Pyramid => {
118
                        self.transform_impl(src, dst, |x, y, z, w| l_tbl.pyramid_vec3(x, y, z, w))?;
119
                    }
120
                    #[cfg(feature = "options")]
121
                    InterpolationMethod::Prism => {
122
                        self.transform_impl(src, dst, |x, y, z, w| l_tbl.prism_vec3(x, y, z, w))?
123
                    }
124
                    InterpolationMethod::Linear => {
125
0
                        self.transform_impl(src, dst, |x, y, z, w| {
126
0
                            l_tbl.quadlinear_vec3(x, y, z, w)
127
0
                        })?
128
                    }
129
                }
130
0
                Ok(())
131
0
            }
132
        }
133
    };
134
}
135
136
#[cfg(feature = "any_to_any")]
137
impl<T: Copy + PointeeSizeExpressible + AsPrimitive<f32>> KatanaLut4x3<T> {
138
    fn to_pcs_impl<Fetch: Fn(f32, f32, f32, f32) -> Vector3f>(
139
        &self,
140
        input: &[T],
141
        fetch: Fetch,
142
    ) -> Result<Vec<f32>, CmsError> {
143
        if input.len() % 4 != 0 {
144
            return Err(CmsError::LaneMultipleOfChannels);
145
        }
146
        let norm_value = if T::FINITE {
147
            1.0 / ((1u32 << self.bit_depth) - 1) as f32
148
        } else {
149
            1.0
150
        };
151
        let mut dst = try_vec![0.; (input.len() / 4) * 3];
152
        let linearization_0 = &self.linearization[0];
153
        let linearization_1 = &self.linearization[1];
154
        let linearization_2 = &self.linearization[2];
155
        let linearization_3 = &self.linearization[3];
156
        for (dest, src) in dst.chunks_exact_mut(3).zip(input.chunks_exact(4)) {
157
            let linear_x = lut_interp_linear_float(src[0].as_() * norm_value, linearization_0);
158
            let linear_y = lut_interp_linear_float(src[1].as_() * norm_value, linearization_1);
159
            let linear_z = lut_interp_linear_float(src[2].as_() * norm_value, linearization_2);
160
            let linear_w = lut_interp_linear_float(src[3].as_() * norm_value, linearization_3);
161
162
            let clut = fetch(linear_x, linear_y, linear_z, linear_w);
163
164
            let pcs_x = lut_interp_linear_float(clut.v[0], &self.output[0]);
165
            let pcs_y = lut_interp_linear_float(clut.v[1], &self.output[1]);
166
            let pcs_z = lut_interp_linear_float(clut.v[2], &self.output[2]);
167
            dest[0] = pcs_x;
168
            dest[1] = pcs_y;
169
            dest[2] = pcs_z;
170
        }
171
        Ok(dst)
172
    }
173
}
174
175
#[cfg(feature = "any_to_any")]
176
impl<T: Copy + PointeeSizeExpressible + AsPrimitive<f32>> KatanaInitialStage<f32, T>
177
    for KatanaLut4x3<T>
178
{
179
    fn to_pcs(&self, input: &[T]) -> Result<Vec<f32>, CmsError> {
180
        if input.len() % 4 != 0 {
181
            return Err(CmsError::LaneMultipleOfChannels);
182
        }
183
        let l_tbl = Hypercube::new(&self.clut, self.grid_size as usize, 3)?;
184
185
        // If Source PCS is LAB trilinear should be used
186
        if self.pcs == DataColorSpace::Lab || self.pcs == DataColorSpace::Xyz {
187
            return self.to_pcs_impl(input, |x, y, z, w| l_tbl.quadlinear_vec3(x, y, z, w));
188
        }
189
190
        match self.interpolation_method {
191
            #[cfg(feature = "options")]
192
            InterpolationMethod::Tetrahedral => {
193
                self.to_pcs_impl(input, |x, y, z, w| l_tbl.tetra_vec3(x, y, z, w))
194
            }
195
            #[cfg(feature = "options")]
196
            InterpolationMethod::Pyramid => {
197
                self.to_pcs_impl(input, |x, y, z, w| l_tbl.pyramid_vec3(x, y, z, w))
198
            }
199
            #[cfg(feature = "options")]
200
            InterpolationMethod::Prism => {
201
                self.to_pcs_impl(input, |x, y, z, w| l_tbl.prism_vec3(x, y, z, w))
202
            }
203
            InterpolationMethod::Linear => {
204
                self.to_pcs_impl(input, |x, y, z, w| l_tbl.quadlinear_vec3(x, y, z, w))
205
            }
206
        }
207
    }
208
}
209
210
define_lut4_dispatch!(Lut4x3);
211
212
0
fn make_lut_4x3(
213
0
    lut: &LutDataType,
214
0
    options: TransformOptions,
215
0
    pcs: DataColorSpace,
216
0
) -> Result<Lut4x3, CmsError> {
217
    // There is 4 possible cases:
218
    // - All curves are non-linear
219
    // - Linearization curves are non-linear, but gamma is linear
220
    // - Gamma curves are non-linear, but linearization is linear
221
    // - All curves linear
222
0
    let clut_length: usize = (lut.num_clut_grid_points as usize)
223
0
        .safe_powi(lut.num_input_channels as u32)?
224
0
        .safe_mul(lut.num_output_channels as usize)?;
225
226
0
    let clut_table = lut.clut_table.to_clut_f32();
227
0
    if clut_table.len() != clut_length {
228
0
        return Err(CmsError::MalformedClut(MalformedSize {
229
0
            size: clut_table.len(),
230
0
            expected: clut_length,
231
0
        }));
232
0
    }
233
234
0
    let linearization_table = lut.input_table.to_clut_f32();
235
236
0
    if linearization_table.len() < lut.num_input_table_entries as usize * 4 {
237
0
        return Err(CmsError::MalformedCurveLutTable(MalformedSize {
238
0
            size: linearization_table.len(),
239
0
            expected: lut.num_input_table_entries as usize * 4,
240
0
        }));
241
0
    }
242
243
0
    let lin_curve0 = linearization_table[0..lut.num_input_table_entries as usize].to_vec();
244
0
    let lin_curve1 = linearization_table
245
0
        [lut.num_input_table_entries as usize..lut.num_input_table_entries as usize * 2]
246
0
        .to_vec();
247
0
    let lin_curve2 = linearization_table
248
0
        [lut.num_input_table_entries as usize * 2..lut.num_input_table_entries as usize * 3]
249
0
        .to_vec();
250
0
    let lin_curve3 = linearization_table
251
0
        [lut.num_input_table_entries as usize * 3..lut.num_input_table_entries as usize * 4]
252
0
        .to_vec();
253
254
0
    let gamma_table = lut.output_table.to_clut_f32();
255
256
0
    if gamma_table.len() < lut.num_output_table_entries as usize * 3 {
257
0
        return Err(CmsError::MalformedCurveLutTable(MalformedSize {
258
0
            size: gamma_table.len(),
259
0
            expected: lut.num_output_table_entries as usize * 3,
260
0
        }));
261
0
    }
262
263
0
    let gamma_curve0 = gamma_table[..lut.num_output_table_entries as usize].to_vec();
264
0
    let gamma_curve1 = gamma_table
265
0
        [lut.num_output_table_entries as usize..lut.num_output_table_entries as usize * 2]
266
0
        .to_vec();
267
0
    let gamma_curve2 = gamma_table
268
0
        [lut.num_output_table_entries as usize * 2..lut.num_output_table_entries as usize * 3]
269
0
        .to_vec();
270
271
0
    let transform = Lut4x3 {
272
0
        linearization: [lin_curve0, lin_curve1, lin_curve2, lin_curve3],
273
0
        interpolation_method: options.interpolation_method,
274
0
        pcs,
275
0
        clut: clut_table,
276
0
        grid_size: lut.num_clut_grid_points,
277
0
        output: [gamma_curve0, gamma_curve1, gamma_curve2],
278
0
    };
279
0
    Ok(transform)
280
0
}
281
282
0
fn stage_lut_4x3(
283
0
    lut: &LutDataType,
284
0
    options: TransformOptions,
285
0
    pcs: DataColorSpace,
286
0
) -> Result<Box<dyn Stage>, CmsError> {
287
0
    let lut = make_lut_4x3(lut, options, pcs)?;
288
0
    let transform = Lut4x3 {
289
0
        linearization: lut.linearization,
290
0
        interpolation_method: lut.interpolation_method,
291
0
        pcs: lut.pcs,
292
0
        clut: lut.clut,
293
0
        grid_size: lut.grid_size,
294
0
        output: lut.output,
295
0
    };
296
0
    Ok(Box::new(transform))
297
0
}
298
299
#[cfg(feature = "any_to_any")]
300
pub(crate) fn katana_input_stage_lut_4x3<
301
    T: Copy + PointeeSizeExpressible + AsPrimitive<f32> + Send + Sync,
302
>(
303
    lut: &LutDataType,
304
    options: TransformOptions,
305
    pcs: DataColorSpace,
306
    bit_depth: usize,
307
) -> Result<Box<dyn KatanaInitialStage<f32, T> + Send + Sync>, CmsError> {
308
    // There is 4 possible cases:
309
    // - All curves are non-linear
310
    // - Linearization curves are non-linear, but gamma is linear
311
    // - Gamma curves are non-linear, but linearization is linear
312
    // - All curves linear
313
    let lut = make_lut_4x3(lut, options, pcs)?;
314
315
    let transform = KatanaLut4x3::<T> {
316
        linearization: lut.linearization,
317
        interpolation_method: lut.interpolation_method,
318
        pcs: lut.pcs,
319
        clut: lut.clut,
320
        grid_size: lut.grid_size,
321
        output: lut.output,
322
        _phantom: PhantomData,
323
        bit_depth,
324
    };
325
    Ok(Box::new(transform))
326
}
327
328
0
pub(crate) fn create_lut4_norm_samples<const SAMPLES: usize>() -> Vec<f32> {
329
0
    let lut_size: u32 = (4 * SAMPLES * SAMPLES * SAMPLES * SAMPLES) as u32;
330
331
0
    let mut src = Vec::with_capacity(lut_size as usize);
332
333
0
    let recpeq = 1f32 / (SAMPLES - 1) as f32;
334
0
    for k in 0..SAMPLES {
335
0
        for c in 0..SAMPLES {
336
0
            for m in 0..SAMPLES {
337
0
                for y in 0..SAMPLES {
338
0
                    src.push(c as f32 * recpeq);
339
0
                    src.push(m as f32 * recpeq);
340
0
                    src.push(y as f32 * recpeq);
341
0
                    src.push(k as f32 * recpeq);
342
0
                }
343
            }
344
        }
345
    }
346
0
    src
347
0
}
348
349
0
pub(crate) fn create_lut4<const SAMPLES: usize>(
350
0
    lut: &LutDataType,
351
0
    options: TransformOptions,
352
0
    pcs: DataColorSpace,
353
0
) -> Result<Vec<f32>, CmsError> {
354
0
    if lut.num_input_channels != 4 {
355
0
        return Err(CmsError::UnsupportedProfileConnection);
356
0
    }
357
0
    let lut_size: u32 = (4 * SAMPLES * SAMPLES * SAMPLES * SAMPLES) as u32;
358
359
0
    let src = create_lut4_norm_samples::<SAMPLES>();
360
0
    let mut dest = try_vec![0.; (lut_size as usize) / 4 * 3];
361
362
0
    let lut_stage = stage_lut_4x3(lut, options, pcs)?;
363
0
    lut_stage.transform(&src, &mut dest)?;
364
0
    Ok(dest)
365
0
}