moxcms/conversions/sse/
lut4_to_3_q0_15.rs

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 */
29use crate::conversions::LutBarycentricReduction;
30use crate::conversions::interpolator::BarycentricWeight;
31use crate::conversions::sse::interpolator_q0_15::*;
32use crate::transform::PointeeSizeExpressible;
33use crate::{CmsError, DataColorSpace, InterpolationMethod, Layout, TransformExecutor};
34use num_traits::AsPrimitive;
35#[cfg(target_arch = "x86")]
36use std::arch::x86::*;
37#[cfg(target_arch = "x86_64")]
38use std::arch::x86_64::*;
39use std::marker::PhantomData;
40
41pub(crate) struct TransformLut4To3SseQ0_15<
42    T,
43    U,
44    const LAYOUT: u8,
45    const GRID_SIZE: usize,
46    const BIT_DEPTH: usize,
47    const BINS: usize,
48    const BARYCENTRIC_BINS: usize,
49> {
50    pub(crate) lut: Vec<SseAlignedI16x4>,
51    pub(crate) _phantom: PhantomData<T>,
52    pub(crate) _phantom1: PhantomData<U>,
53    pub(crate) interpolation_method: InterpolationMethod,
54    pub(crate) weights: Box<[BarycentricWeight<i16>; BINS]>,
55    pub(crate) color_space: DataColorSpace,
56    pub(crate) is_linear: bool,
57}
58
59impl<
60    T: Copy + AsPrimitive<f32> + Default + PointeeSizeExpressible,
61    U: AsPrimitive<usize>,
62    const LAYOUT: u8,
63    const GRID_SIZE: usize,
64    const BIT_DEPTH: usize,
65    const BINS: usize,
66    const BARYCENTRIC_BINS: usize,
67> TransformLut4To3SseQ0_15<T, U, LAYOUT, GRID_SIZE, BIT_DEPTH, BINS, BARYCENTRIC_BINS>
68where
69    f32: AsPrimitive<T>,
70    u32: AsPrimitive<T>,
71    (): LutBarycentricReduction<T, U>,
72{
73    #[allow(unused_unsafe)]
74    #[target_feature(enable = "sse4.1")]
75    unsafe fn transform_chunk(
76        &self,
77        src: &[T],
78        dst: &mut [T],
79        interpolator: Box<dyn SseMdInterpolationQ0_15 + Send + Sync>,
80    ) {
81        unsafe {
82            let cn = Layout::from(LAYOUT);
83            let channels = cn.channels();
84            let grid_size = GRID_SIZE as i32;
85            let grid_size3 = grid_size * grid_size * grid_size;
86
87            let f_value_scale = _mm_set1_ps(1. / ((1 << 14i32) - 1) as f32);
88            let max_value = ((1u32 << BIT_DEPTH) - 1).as_();
89            let v_max_scale = if T::FINITE {
90                _mm_set1_epi16(((1i32 << BIT_DEPTH) - 1) as i16)
91            } else {
92                _mm_set1_epi16(((1i32 << 14i32) - 1) as i16)
93            };
94
95            for (src, dst) in src.chunks_exact(4).zip(dst.chunks_exact_mut(channels)) {
96                let c = <() as LutBarycentricReduction<T, U>>::reduce::<BIT_DEPTH, BARYCENTRIC_BINS>(
97                    src[0],
98                );
99                let m = <() as LutBarycentricReduction<T, U>>::reduce::<BIT_DEPTH, BARYCENTRIC_BINS>(
100                    src[1],
101                );
102                let y = <() as LutBarycentricReduction<T, U>>::reduce::<BIT_DEPTH, BARYCENTRIC_BINS>(
103                    src[2],
104                );
105                let k = <() as LutBarycentricReduction<T, U>>::reduce::<BIT_DEPTH, BARYCENTRIC_BINS>(
106                    src[3],
107                );
108
109                let k_weights = self.weights[k.as_()];
110
111                let w: i32 = k_weights.x;
112                let w_n: i32 = k_weights.x_n;
113                const Q: i16 = ((1i32 << 15) - 1) as i16;
114                let t: i16 = k_weights.w;
115                let t_n: i16 = Q - t;
116
117                let table1 = &self.lut[(w * grid_size3) as usize..];
118                let table2 = &self.lut[(w_n * grid_size3) as usize..];
119
120                let a0 = interpolator
121                    .inter3_sse(table1, c.as_(), m.as_(), y.as_(), self.weights.as_slice())
122                    .v;
123                let b0 = interpolator
124                    .inter3_sse(table2, c.as_(), m.as_(), y.as_(), self.weights.as_slice())
125                    .v;
126
127                let hp = _mm_mulhrs_epi16(_mm_set1_epi16(t_n), a0);
128                let v = _mm_add_epi16(hp, _mm_mulhrs_epi16(b0, _mm_set1_epi16(t)));
129
130                if T::FINITE {
131                    let mut o = _mm_max_epi16(v, _mm_setzero_si128());
132                    o = _mm_min_epi16(o, v_max_scale);
133
134                    let x = _mm_extract_epi16::<0>(o);
135                    let y = _mm_extract_epi16::<1>(o);
136                    let z = _mm_extract_epi16::<2>(o);
137
138                    dst[cn.r_i()] = (x as u32).as_();
139                    dst[cn.g_i()] = (y as u32).as_();
140                    dst[cn.b_i()] = (z as u32).as_();
141                } else {
142                    let mut r = _mm_cvtepi32_ps(_mm_cvtepi16_epi32(v));
143                    r = _mm_mul_ps(r, f_value_scale);
144                    dst[cn.r_i()] = f32::from_bits(_mm_extract_ps::<0>(r) as u32).as_();
145                    dst[cn.g_i()] = f32::from_bits(_mm_extract_ps::<1>(r) as u32).as_();
146                    dst[cn.b_i()] = f32::from_bits(_mm_extract_ps::<2>(r) as u32).as_();
147                }
148                if channels == 4 {
149                    dst[cn.a_i()] = max_value;
150                }
151            }
152        }
153    }
154}
155
156impl<
157    T: Copy + AsPrimitive<f32> + Default + PointeeSizeExpressible,
158    U: AsPrimitive<usize>,
159    const LAYOUT: u8,
160    const GRID_SIZE: usize,
161    const BIT_DEPTH: usize,
162    const BINS: usize,
163    const BARYCENTRIC_BINS: usize,
164> TransformExecutor<T>
165    for TransformLut4To3SseQ0_15<T, U, LAYOUT, GRID_SIZE, BIT_DEPTH, BINS, BARYCENTRIC_BINS>
166where
167    f32: AsPrimitive<T>,
168    u32: AsPrimitive<T>,
169    (): LutBarycentricReduction<T, U>,
170{
171    fn transform(&self, src: &[T], dst: &mut [T]) -> Result<(), CmsError> {
172        let cn = Layout::from(LAYOUT);
173        let channels = cn.channels();
174        if src.len() % 4 != 0 {
175            return Err(CmsError::LaneMultipleOfChannels);
176        }
177        if dst.len() % channels != 0 {
178            return Err(CmsError::LaneMultipleOfChannels);
179        }
180        let src_chunks = src.len() / 4;
181        let dst_chunks = dst.len() / channels;
182        if src_chunks != dst_chunks {
183            return Err(CmsError::LaneSizeMismatch);
184        }
185
186        unsafe {
187            if self.color_space == DataColorSpace::Lab
188                || (self.is_linear && self.color_space == DataColorSpace::Rgb)
189                || self.color_space == DataColorSpace::Xyz
190            {
191                self.transform_chunk(src, dst, Box::new(TrilinearSseQ0_15::<GRID_SIZE> {}));
192            } else {
193                match self.interpolation_method {
194                    #[cfg(feature = "options")]
195                    InterpolationMethod::Tetrahedral => {
196                        self.transform_chunk(
197                            src,
198                            dst,
199                            Box::new(TetrahedralSseQ0_15::<GRID_SIZE> {}),
200                        );
201                    }
202                    #[cfg(feature = "options")]
203                    InterpolationMethod::Pyramid => {
204                        self.transform_chunk(src, dst, Box::new(PyramidalSseQ0_15::<GRID_SIZE> {}));
205                    }
206                    #[cfg(feature = "options")]
207                    InterpolationMethod::Prism => {
208                        self.transform_chunk(src, dst, Box::new(PrismaticSseQ0_15::<GRID_SIZE> {}));
209                    }
210                    InterpolationMethod::Linear => {
211                        self.transform_chunk(src, dst, Box::new(TrilinearSseQ0_15::<GRID_SIZE> {}));
212                    }
213                }
214            }
215        }
216
217        Ok(())
218    }
219}