Skip to main content

moxcms/conversions/avx/
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 */
29#![cfg(feature = "avx_luts")]
30use crate::conversions::LutBarycentricReduction;
31use crate::conversions::avx::interpolator_q0_15::*;
32use crate::conversions::interpolator::BarycentricWeight;
33use crate::transform::PointeeSizeExpressible;
34use crate::{CmsError, DataColorSpace, InterpolationMethod, Layout, TransformExecutor};
35use num_traits::AsPrimitive;
36use std::arch::x86_64::*;
37use std::marker::PhantomData;
38
39pub(crate) struct TransformLut4To3AvxQ0_15<
40    T,
41    U,
42    const LAYOUT: u8,
43    const GRID_SIZE: usize,
44    const BIT_DEPTH: usize,
45    const BINS: usize,
46    const BARYCENTRIC_BINS: usize,
47> {
48    pub(crate) lut: Vec<AvxAlignedI16>,
49    pub(crate) _phantom: PhantomData<T>,
50    pub(crate) _phantom1: PhantomData<U>,
51    pub(crate) interpolation_method: InterpolationMethod,
52    pub(crate) weights: Box<[BarycentricWeight<i16>; BINS]>,
53    pub(crate) color_space: DataColorSpace,
54    pub(crate) is_linear: bool,
55}
56
57impl<
58    T: Copy + AsPrimitive<f32> + Default + PointeeSizeExpressible,
59    U: AsPrimitive<usize>,
60    const LAYOUT: u8,
61    const GRID_SIZE: usize,
62    const BIT_DEPTH: usize,
63    const BINS: usize,
64    const BARYCENTRIC_BINS: usize,
65> TransformLut4To3AvxQ0_15<T, U, LAYOUT, GRID_SIZE, BIT_DEPTH, BINS, BARYCENTRIC_BINS>
66where
67    f32: AsPrimitive<T>,
68    u32: AsPrimitive<T>,
69    (): LutBarycentricReduction<T, U>,
70{
71    #[allow(unused_unsafe)]
72    #[target_feature(enable = "avx2")]
73    unsafe fn transform_chunk(
74        &self,
75        src: &[T],
76        dst: &mut [T],
77        interpolator: Box<dyn AvxMdInterpolationQ0_15Double + Send + Sync>,
78    ) {
79        unsafe {
80            let cn = Layout::from(LAYOUT);
81            let channels = cn.channels();
82            let grid_size = GRID_SIZE as i32;
83            let grid_size3 = grid_size * grid_size * grid_size;
84
85            let f_value_scale = _mm_set1_ps(1. / ((1 << 14i32) - 1) as f32);
86            let max_value = ((1u32 << BIT_DEPTH) - 1).as_();
87            let v_max_scale = if T::FINITE {
88                _mm_set1_epi16(((1i32 << BIT_DEPTH) - 1) as i16)
89            } else {
90                _mm_set1_epi16(((1i32 << 14i32) - 1) as i16)
91            };
92
93            for (src, dst) in src.chunks_exact(4).zip(dst.chunks_exact_mut(channels)) {
94                let c = <() as LutBarycentricReduction<T, U>>::reduce::<BIT_DEPTH, BARYCENTRIC_BINS>(
95                    src[0],
96                );
97                let m = <() as LutBarycentricReduction<T, U>>::reduce::<BIT_DEPTH, BARYCENTRIC_BINS>(
98                    src[1],
99                );
100                let y = <() as LutBarycentricReduction<T, U>>::reduce::<BIT_DEPTH, BARYCENTRIC_BINS>(
101                    src[2],
102                );
103                let k = <() as LutBarycentricReduction<T, U>>::reduce::<BIT_DEPTH, BARYCENTRIC_BINS>(
104                    src[3],
105                );
106
107                let k_weights = self.weights[k.as_()];
108
109                let w: i32 = k_weights.x;
110                let w_n: i32 = k_weights.x_n;
111                const Q: i16 = ((1i32 << 15) - 1) as i16;
112                let t: i16 = k_weights.w;
113                let t_n: i16 = Q - t;
114
115                let table1 = &self.lut[(w * grid_size3) as usize..];
116                let table2 = &self.lut[(w_n * grid_size3) as usize..];
117
118                let v = interpolator.inter3_sse(
119                    table1,
120                    table2,
121                    c.as_(),
122                    m.as_(),
123                    y.as_(),
124                    self.weights.as_slice(),
125                );
126                let (a0, b0) = (v.0.v, v.1.v);
127
128                let hp = _mm_mulhrs_epi16(_mm_set1_epi16(t_n), a0);
129                let v = _mm_add_epi16(hp, _mm_mulhrs_epi16(b0, _mm_set1_epi16(t)));
130
131                if T::FINITE {
132                    let mut o = _mm_max_epi16(v, _mm_setzero_si128());
133                    o = _mm_min_epi16(o, v_max_scale);
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 TransformLut4To3AvxQ0_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(TrilinearAvxQ0_15Double::<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(TetrahedralAvxQ0_15Double::<GRID_SIZE> {}),
200                        );
201                    }
202                    #[cfg(feature = "options")]
203                    InterpolationMethod::Pyramid => {
204                        self.transform_chunk(
205                            src,
206                            dst,
207                            Box::new(PyramidAvxFmaQ0_15Double::<GRID_SIZE> {}),
208                        );
209                    }
210                    #[cfg(feature = "options")]
211                    InterpolationMethod::Prism => {
212                        self.transform_chunk(
213                            src,
214                            dst,
215                            Box::new(PrismaticAvxQ0_15Double::<GRID_SIZE> {}),
216                        );
217                    }
218                    InterpolationMethod::Linear => {
219                        self.transform_chunk(
220                            src,
221                            dst,
222                            Box::new(TrilinearAvxQ0_15Double::<GRID_SIZE> {}),
223                        );
224                    }
225                }
226            }
227        }
228
229        Ok(())
230    }
231}