moxcms/conversions/sse/
rgb_xyz.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::TransformMatrixShaper;
30use crate::transform::PointeeSizeExpressible;
31use crate::{CmsError, Layout, TransformExecutor};
32use num_traits::AsPrimitive;
33#[cfg(target_arch = "x86")]
34use std::arch::x86::*;
35#[cfg(target_arch = "x86_64")]
36use std::arch::x86_64::*;
37
38#[repr(align(16), C)]
39pub(crate) struct SseAlignedU16(pub(crate) [u16; 8]);
40
41pub(crate) struct TransformShaperRgbSse<
42    T: Clone + Copy + 'static + PointeeSizeExpressible + Default,
43    const SRC_LAYOUT: u8,
44    const DST_LAYOUT: u8,
45    // deleting linear cap is in effective here
46    const LINEAR_CAP: usize,
47> {
48    // removing linear cap here is not worth it, at least in previous attempts
49    pub(crate) profile: TransformMatrixShaper<T, LINEAR_CAP>,
50    pub(crate) bit_depth: usize,
51    pub(crate) gamma_lut: usize,
52}
53
54impl<
55    T: Clone + Copy + 'static + PointeeSizeExpressible + Default,
56    const SRC_LAYOUT: u8,
57    const DST_LAYOUT: u8,
58    const LINEAR_CAP: usize,
59> TransformShaperRgbSse<T, SRC_LAYOUT, DST_LAYOUT, LINEAR_CAP>
60where
61    u32: AsPrimitive<T>,
62{
63    #[target_feature(enable = "sse4.1")]
64    unsafe fn transform_impl(&self, src: &[T], dst: &mut [T]) -> Result<(), CmsError> {
65        let src_cn = Layout::from(SRC_LAYOUT);
66        let dst_cn = Layout::from(DST_LAYOUT);
67        let src_channels = src_cn.channels();
68        let dst_channels = dst_cn.channels();
69
70        let mut temporary = SseAlignedU16([0; 8]);
71
72        if src.len() / src_channels != dst.len() / dst_channels {
73            return Err(CmsError::LaneSizeMismatch);
74        }
75        if src.len() % src_channels != 0 {
76            return Err(CmsError::LaneMultipleOfChannels);
77        }
78        if dst.len() % dst_channels != 0 {
79            return Err(CmsError::LaneMultipleOfChannels);
80        }
81
82        let t = self.profile.adaptation_matrix.transpose();
83
84        let scale = (self.gamma_lut - 1) as f32;
85        let max_colors: T = ((1 << self.bit_depth) - 1).as_();
86
87        unsafe {
88            let m0 = _mm_setr_ps(t.v[0][0], t.v[0][1], t.v[0][2], 0f32);
89            let m1 = _mm_setr_ps(t.v[1][0], t.v[1][1], t.v[1][2], 0f32);
90            let m2 = _mm_setr_ps(t.v[2][0], t.v[2][1], t.v[2][2], 0f32);
91
92            let zeros = _mm_setzero_ps();
93
94            let v_scale = _mm_set1_ps(scale);
95
96            for (src, dst) in src
97                .chunks_exact(src_channels)
98                .zip(dst.chunks_exact_mut(dst_channels))
99            {
100                let rp = &self.profile.r_linear[src[src_cn.r_i()]._as_usize()];
101                let gp = &self.profile.g_linear[src[src_cn.g_i()]._as_usize()];
102                let bp = &self.profile.b_linear[src[src_cn.b_i()]._as_usize()];
103
104                let mut r = _mm_load_ss(rp);
105                let mut g = _mm_load_ss(gp);
106                let mut b = _mm_load_ss(bp);
107                let a = if src_channels == 4 {
108                    src[src_cn.a_i()]
109                } else {
110                    max_colors
111                };
112
113                r = _mm_shuffle_ps::<0>(r, r);
114                g = _mm_shuffle_ps::<0>(g, g);
115                b = _mm_shuffle_ps::<0>(b, b);
116
117                let v0 = _mm_mul_ps(r, m0);
118                let v1 = _mm_mul_ps(g, m1);
119                let v2 = _mm_mul_ps(b, m2);
120
121                let mut v = _mm_add_ps(_mm_add_ps(v0, v1), v2);
122                v = _mm_max_ps(v, zeros);
123                v = _mm_mul_ps(v, v_scale);
124                v = _mm_min_ps(v, v_scale);
125
126                let zx = _mm_cvtps_epi32(v);
127                _mm_store_si128(temporary.0.as_mut_ptr() as *mut _, zx);
128
129                dst[dst_cn.r_i()] = self.profile.r_gamma[temporary.0[0] as usize];
130                dst[dst_cn.g_i()] = self.profile.g_gamma[temporary.0[2] as usize];
131                dst[dst_cn.b_i()] = self.profile.b_gamma[temporary.0[4] as usize];
132                if dst_channels == 4 {
133                    dst[dst_cn.a_i()] = a;
134                }
135            }
136        }
137
138        Ok(())
139    }
140}
141
142impl<
143    T: Clone + Copy + 'static + PointeeSizeExpressible + Default,
144    const SRC_LAYOUT: u8,
145    const DST_LAYOUT: u8,
146    const LINEAR_CAP: usize,
147> TransformExecutor<T> for TransformShaperRgbSse<T, SRC_LAYOUT, DST_LAYOUT, LINEAR_CAP>
148where
149    u32: AsPrimitive<T>,
150{
151    fn transform(&self, src: &[T], dst: &mut [T]) -> Result<(), CmsError> {
152        unsafe { self.transform_impl(src, dst) }
153    }
154}