pic_scale/colors/
lch_scaler.rs

1/*
2 * Copyright (c) Radzivon Bartoshyk. 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
30use colorutils_rs::{
31    lch_to_rgb, lch_with_alpha_to_rgba, rgb_to_lch, rgba_to_lch_with_alpha, TransferFunction,
32    SRGB_TO_XYZ_D65, XYZ_TO_SRGB_D65,
33};
34
35use crate::pic_scale_error::PicScaleError;
36use crate::scaler::ScalingF32;
37use crate::support::check_image_size_overflow;
38use crate::{ImageStore, ImageStoreMut, ResamplingFunction, Scaler, Scaling, ThreadingPolicy};
39
40#[derive(Debug, Copy, Clone)]
41/// Converts image to *CIE LCH(uv)* components scales it and convert back
42pub struct LChScaler {
43    pub(crate) scaler: Scaler,
44}
45
46impl LChScaler {
47    pub fn new(filter: ResamplingFunction) -> Self {
48        LChScaler {
49            scaler: Scaler::new(filter),
50        }
51    }
52
53    fn rgba_to_lcha<'a>(store: &ImageStore<'a, u8, 4>) -> ImageStore<'a, f32, 4> {
54        let mut source_slice = vec![f32::default(); 4 * store.width * store.height];
55        let lab_stride = store.width as u32 * 4u32 * std::mem::size_of::<f32>() as u32;
56        rgba_to_lch_with_alpha(
57            store.buffer.as_ref(),
58            store.width as u32 * 4u32,
59            &mut source_slice,
60            lab_stride,
61            store.width as u32,
62            store.height as u32,
63            &SRGB_TO_XYZ_D65,
64            TransferFunction::Srgb,
65        );
66        let new_store = ImageStore::<f32, 4> {
67            buffer: std::borrow::Cow::Owned(source_slice),
68            channels: 4,
69            width: store.width,
70            height: store.height,
71            stride: store.width * 4,
72            bit_depth: store.bit_depth,
73        };
74        new_store
75    }
76
77    fn lcha_to_srgba<'a>(store: &ImageStoreMut<'a, f32, 4>, into: &mut ImageStoreMut<'a, u8, 4>) {
78        lch_with_alpha_to_rgba(
79            store.buffer.borrow(),
80            store.width as u32 * 4u32 * std::mem::size_of::<f32>() as u32,
81            into.buffer.borrow_mut(),
82            store.width as u32 * 4u32,
83            store.width as u32,
84            store.height as u32,
85            &XYZ_TO_SRGB_D65,
86            TransferFunction::Srgb,
87        );
88    }
89}
90
91impl Scaling for LChScaler {
92    fn set_threading_policy(&mut self, threading_policy: ThreadingPolicy) {
93        self.scaler.set_threading_policy(threading_policy)
94    }
95
96    fn resize_cbcr8<'a>(
97        &'a self,
98        _: &ImageStore<'a, u8, 2>,
99        _: &mut ImageStoreMut<'a, u8, 2>,
100    ) -> Result<(), PicScaleError> {
101        unimplemented!()
102    }
103
104    fn resize_rgb<'a>(
105        &'a self,
106        store: &ImageStore<'a, u8, 3>,
107        into: &mut ImageStoreMut<'a, u8, 3>,
108    ) -> Result<(), PicScaleError> {
109        let new_size = into.get_size();
110        into.validate()?;
111        store.validate()?;
112        if store.width == 0 || store.height == 0 || new_size.width == 0 || new_size.height == 0 {
113            return Err(PicScaleError::ZeroImageDimensions);
114        }
115
116        if check_image_size_overflow(store.width, store.height, store.channels) {
117            return Err(PicScaleError::SourceImageIsTooLarge);
118        }
119
120        if check_image_size_overflow(new_size.width, new_size.height, store.channels) {
121            return Err(PicScaleError::DestinationImageIsTooLarge);
122        }
123
124        if store.width == new_size.width && store.height == new_size.height {
125            store.copied_to_mut(into);
126            return Ok(());
127        }
128
129        const COMPONENTS: usize = 3;
130
131        let mut target_vertical = vec![f32::default(); store.width * store.height * COMPONENTS];
132
133        let mut lab_store = ImageStoreMut::<f32, COMPONENTS>::from_slice(
134            &mut target_vertical,
135            store.width,
136            store.height,
137        )?;
138        lab_store.bit_depth = into.bit_depth;
139
140        let lab_stride =
141            lab_store.width as u32 * COMPONENTS as u32 * std::mem::size_of::<f32>() as u32;
142        rgb_to_lch(
143            store.buffer.as_ref(),
144            store.width as u32 * COMPONENTS as u32,
145            lab_store.buffer.borrow_mut(),
146            lab_stride,
147            lab_store.width as u32,
148            lab_store.height as u32,
149            &SRGB_TO_XYZ_D65,
150            TransferFunction::Srgb,
151        );
152
153        let new_immutable_store = ImageStore::<f32, COMPONENTS> {
154            buffer: std::borrow::Cow::Owned(target_vertical),
155            channels: COMPONENTS,
156            width: store.width,
157            height: store.height,
158            stride: store.width * COMPONENTS,
159            bit_depth: into.bit_depth,
160        };
161
162        let mut new_store = ImageStoreMut::<f32, COMPONENTS>::alloc(into.width, into.height);
163        self.scaler
164            .resize_rgb_f32(&new_immutable_store, &mut new_store)?;
165
166        let new_lab_stride =
167            new_store.width as u32 * COMPONENTS as u32 * std::mem::size_of::<f32>() as u32;
168
169        lch_to_rgb(
170            new_store.buffer.borrow(),
171            new_lab_stride,
172            into.buffer.borrow_mut(),
173            into.width as u32 * COMPONENTS as u32,
174            new_store.width as u32,
175            new_store.height as u32,
176            &XYZ_TO_SRGB_D65,
177            TransferFunction::Srgb,
178        );
179        Ok(())
180    }
181
182    fn resize_rgba<'a>(
183        &'a self,
184        store: &ImageStore<'a, u8, 4>,
185        into: &mut ImageStoreMut<'a, u8, 4>,
186        premultiply_alpha: bool,
187    ) -> Result<(), PicScaleError> {
188        let new_size = into.get_size();
189        into.validate()?;
190        store.validate()?;
191        if store.width == 0 || store.height == 0 || new_size.width == 0 || new_size.height == 0 {
192            return Err(PicScaleError::ZeroImageDimensions);
193        }
194
195        if check_image_size_overflow(store.width, store.height, store.channels) {
196            return Err(PicScaleError::SourceImageIsTooLarge);
197        }
198
199        if check_image_size_overflow(new_size.width, new_size.height, store.channels) {
200            return Err(PicScaleError::DestinationImageIsTooLarge);
201        }
202
203        if store.width == new_size.width && store.height == new_size.height {
204            store.copied_to_mut(into);
205            return Ok(());
206        }
207
208        let lab_store = Self::rgba_to_lcha(store);
209        let mut new_target_store = ImageStoreMut::alloc(new_size.width, new_size.height);
210
211        self.scaler
212            .resize_rgba_f32(&lab_store, &mut new_target_store, premultiply_alpha)?;
213        Self::lcha_to_srgba(&new_target_store, into);
214        Ok(())
215    }
216}