1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
//! Defines `BareYCbCr` for YCbCr colors that don't store their model.

use crate::channel::{
    ChannelCast, ChannelFormatCast, ColorChannel, NormalBoundedChannel, NormalChannelScalar,
    PosNormalBoundedChannel, PosNormalChannelScalar,
};
use crate::color::{Bounded, Broadcast, Color, Flatten, FromTuple, HomogeneousColor, Invert, Lerp};
use crate::encoding::EncodableColor;
#[cfg(feature = "approx")]
use approx;
use num_traits;
use std::fmt;
use std::mem;
use std::slice;

use crate::rgb::Rgb;
use crate::tags::YCbCrTag;
use crate::ycbcr::model::YCbCrModel;
use crate::ycbcr::YCbCr;

/// Methods for handling out of gamut colors when converting to Rgb.
///
/// These are used by the `to_rgb` method. Using `TryFromColor` will instead
/// return `None` any time an out of gamut value is produced.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum YCbCrOutOfGamutMode {
    /// Return the exact result of the transformation.
    ///
    /// This can result in channels outside the normal range
    /// (eg. less than 0 or greater than 1).
    Preserve,
    /// Clip any out-of-bounds channels to their minimum or maximum value (0.0 or 1.0).
    ///
    /// For example, -0.2 would go to 0.0 and 2.0 would go to 1.
    Clip,
}

/// A YCbCr color that does not know its model.
///
/// `BareYCbCr` is used internally to implement `YCbCr` and is provided as
/// a separate type for performance reasons; generally, the use of `YCbCr` is preferred.
/// It is "bare" in the sense that it does not store the model information along with the
/// channel information. This makes it less smart, but can save memory when used with custom
/// models.
///
/// When using a custom model, `YCbCr` must store a reference to the model along with its
/// channel values. This can increase the memory footprint significantly, but gives greater
/// safety and convenience as well as forbidding illogical conversions and comparisons.
/// It is therefore only advised to use this when the extra memory consumption
/// has show to be an issue.
#[repr(C)]
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub struct BareYCbCr<T> {
    luma: PosNormalBoundedChannel<T>,
    cb: NormalBoundedChannel<T>,
    cr: NormalBoundedChannel<T>,
}

impl<T> BareYCbCr<T>
where
    T: NormalChannelScalar + PosNormalChannelScalar,
{
    /// Construct a `BareYCbCr` from channel values.
    pub fn new(luma: T, cb: T, cr: T) -> Self {
        BareYCbCr {
            luma: PosNormalBoundedChannel::new(luma),
            cb: NormalBoundedChannel::new(cb),
            cr: NormalBoundedChannel::new(cr),
        }
    }

    impl_color_color_cast_square!(BareYCbCr {luma, cb, cr},
        chan_traits={PosNormalChannelScalar, NormalChannelScalar});

    /// Get the luma (Y') channel.
    pub fn luma(&self) -> T {
        self.luma.0.clone()
    }
    /// Get the Cb channel.
    pub fn cb(&self) -> T {
        self.cb.0.clone()
    }
    /// Get the Cr channel.
    pub fn cr(&self) -> T {
        self.cr.0.clone()
    }
    /// Get a mutable reference to the luma (Y') channel.
    pub fn luma_mut(&mut self) -> &mut T {
        &mut self.luma.0
    }
    /// Get a mutable reference to the Cb channel.
    pub fn cb_mut(&mut self) -> &mut T {
        &mut self.cb.0
    }
    /// Get a mutable reference to the Cr channel.
    pub fn cr_mut(&mut self) -> &mut T {
        &mut self.cr.0
    }
    /// Set the luma (Y') channel to a value.
    pub fn set_luma(&mut self, val: T) {
        self.luma.0 = val;
    }
    /// Set the Cb channel to a value.
    pub fn set_cb(&mut self, val: T) {
        self.cb.0 = val;
    }
    /// Set the Cr channel to a value.
    pub fn set_cr(&mut self, val: T) {
        self.cr.0 = val;
    }

    /// Construct a new `YCbCr` object from `self` and a model.
    ///
    /// Equivalent to constructing the `YCbCr` object directly:
    ///
    /// ```rust
    /// # use prisma::ycbcr::{BareYCbCr, JpegModel, YCbCrJpeg};
    /// let c = BareYCbCr::new(0.5, 0.3, 0.2).with_model(JpegModel);
    /// assert_eq!(c, YCbCrJpeg::new(0.5, 0.3, 0.2));
    /// ```
    pub fn with_model<M>(self, model: M) -> YCbCr<T, M>
    where
        M: YCbCrModel<T>,
    {
        YCbCr::from_color_and_model(self, model)
    }
}

impl<T> Color for BareYCbCr<T>
where
    T: PosNormalChannelScalar + NormalChannelScalar,
{
    type Tag = YCbCrTag;
    type ChannelsTuple = (T, T, T);

    #[inline]
    fn num_channels() -> u32 {
        3
    }

    fn to_tuple(self) -> Self::ChannelsTuple {
        (self.luma.0, self.cb.0, self.cr.0)
    }
}

impl<T> FromTuple for BareYCbCr<T>
where
    T: PosNormalChannelScalar + NormalChannelScalar,
{
    fn from_tuple(values: Self::ChannelsTuple) -> Self {
        BareYCbCr::new(values.0, values.1, values.2)
    }
}

impl<T> Invert for BareYCbCr<T>
where
    T: PosNormalChannelScalar + NormalChannelScalar,
{
    impl_color_invert!(BareYCbCr { luma, cb, cr });
}

impl<T> Bounded for BareYCbCr<T>
where
    T: PosNormalChannelScalar + NormalChannelScalar,
{
    impl_color_bounded!(BareYCbCr { luma, cb, cr });
}

impl<T> Lerp for BareYCbCr<T>
where
    T: PosNormalChannelScalar + NormalChannelScalar + Lerp,
{
    type Position = <T as Lerp>::Position;
    impl_color_lerp_square!(BareYCbCr { luma, cb, cr });
}

impl<T> HomogeneousColor for BareYCbCr<T>
where
    T: PosNormalChannelScalar + NormalChannelScalar,
{
    type ChannelFormat = T;

    impl_color_homogeneous_color_square!(BareYCbCr<T> {luma, cb, cr});
}

impl<T> Broadcast for BareYCbCr<T>
where
    T: PosNormalChannelScalar + NormalChannelScalar,
{
    fn broadcast(value: T) -> Self {
        BareYCbCr {
            luma: PosNormalBoundedChannel(value.clone()),
            cb: NormalBoundedChannel(value.clone()),
            cr: NormalBoundedChannel(value.clone()),
        }
    }
}

impl<T> Flatten for BareYCbCr<T>
where
    T: PosNormalChannelScalar + NormalChannelScalar,
{
    impl_color_as_slice!(T);
    impl_color_from_slice_square!(BareYCbCr<T> {luma:PosNormalBoundedChannel - 0,
        cb:NormalBoundedChannel - 1, cr:NormalBoundedChannel - 2});
}

impl<T> EncodableColor for BareYCbCr<T> where T: PosNormalChannelScalar + NormalChannelScalar {}

#[cfg(feature = "approx")]
impl<T> approx::AbsDiffEq for BareYCbCr<T>
where
    T: PosNormalChannelScalar + NormalChannelScalar + approx::AbsDiffEq,
    T::Epsilon: Clone,
{
    impl_abs_diff_eq!({luma, cb, cr});
}
#[cfg(feature = "approx")]
impl<T> approx::RelativeEq for BareYCbCr<T>
where
    T: PosNormalChannelScalar + NormalChannelScalar + approx::RelativeEq,
    T::Epsilon: Clone,
{
    impl_rel_eq!({luma, cb, cr});
}
#[cfg(feature = "approx")]
impl<T> approx::UlpsEq for BareYCbCr<T>
where
    T: PosNormalChannelScalar + NormalChannelScalar + approx::UlpsEq,
    T::Epsilon: Clone,
{
    impl_ulps_eq!({luma, cb, cr});
}

impl<T> Default for BareYCbCr<T>
where
    T: PosNormalChannelScalar + NormalChannelScalar + num_traits::Zero,
{
    impl_color_default!(BareYCbCr {
        luma: PosNormalBoundedChannel,
        cb: NormalBoundedChannel,
        cr: NormalBoundedChannel
    });
}

impl<T> fmt::Display for BareYCbCr<T>
where
    T: PosNormalChannelScalar + NormalChannelScalar + fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "YCbCr({}, {}, {})", self.luma, self.cb, self.cr)
    }
}

impl<T> BareYCbCr<T>
where
    T: NormalChannelScalar + PosNormalChannelScalar + num_traits::NumCast,
{
    /// Construct a `BareYCbCr` by converting from an Rgb `value`.
    ///
    /// `model` is only used within the conversion, it is up to the user
    /// to remember which model any `BareYCbCr` is using.
    pub fn from_rgb_and_model<M: YCbCrModel<T>>(from: &Rgb<T>, model: &M) -> Self {
        let transform = model.forward_transform();
        let shift = model.shift();

        let (y, cb, cr) = transform.transform_vector(from.clone().to_tuple());

        BareYCbCr::new(y + shift.0, cb + shift.1, cr + shift.2)
    }

    /// Convert from YCbCr to Rgb.
    ///
    /// # Params
    ///
    /// * model - The model to use for the conversion. Note that this does not change the model
    ///   of the color being converted. If you convert to YCbCr from Rgb and convert back under a
    ///   different model, the resulting colors will be different.
    /// * out_of_gamut_mode - How to handle colors that are out of gamut in `Rgb`. See
    ///   [OutOfGamutMode](enum.OutOfGamutMode.html) for a description the options.
    pub fn to_rgb<M: YCbCrModel<T>>(
        &self,
        model: &M,
        out_of_gamut_mode: YCbCrOutOfGamutMode,
    ) -> Rgb<T> {
        let transform = model.inverse_transform();
        let shift = model.shift();

        let (i1, i2, i3) = self.clone().to_tuple();
        let shifted_color = (
            num_traits::cast::<_, f64>(i1).unwrap() - num_traits::cast::<_, f64>(shift.0).unwrap(),
            num_traits::cast::<_, f64>(i2).unwrap() - num_traits::cast::<_, f64>(shift.1).unwrap(),
            num_traits::cast::<_, f64>(i3).unwrap() - num_traits::cast::<_, f64>(shift.2).unwrap(),
        );

        let (r, g, b) = transform.transform_vector(shifted_color);

        let out = Rgb::new(
            num_traits::cast(r).unwrap(),
            num_traits::cast(g).unwrap(),
            num_traits::cast(b).unwrap(),
        );

        match out_of_gamut_mode {
            YCbCrOutOfGamutMode::Preserve => out,
            YCbCrOutOfGamutMode::Clip => out.normalize(),
        }
    }
}