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
use glm::*;
use super::space::ColorSpace;
use super::rgb::Rgb;
use std::mem;
use rand::{ Rand, Rng };
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct YCbCr {
y: f32,
cb: f32,
cr: f32
}
impl YCbCr {
#[inline]
pub fn new(y: f32, cb: f32, cr: f32) -> YCbCr {
let lum = clamp(y, 0., 1.);
let uv = clamp_s(vec2(cb, cr), -0.5, 0.5);
YCbCr { y: lum, cb: uv.x, cr: uv.y }
}
pub fn as_vec3(&self) -> &Vec3 {
let v: &Vec3 = unsafe { mem::transmute(self) };
v
}
pub fn y(&self) -> f32 {
self.y
}
pub fn cb(&self) -> f32 {
self.cb
}
pub fn cr(&self) -> f32 {
self.cr
}
}
impl Eq for YCbCr {}
impl ApproxEq for YCbCr {
type BaseType = f32;
#[inline]
fn is_close_to(&self, other: &YCbCr, max_diff: f32) -> bool {
self.as_vec3().is_close_to(other.as_vec3(), max_diff)
}
}
impl Rand for YCbCr {
#[inline]
fn rand<R: Rng>(rng: &mut R) -> YCbCr {
let y = rng.gen::<f32>();
let uv = rng.gen::<Vec2>() - 0.5;
YCbCr::new(y, uv.x, uv.y)
}
}
impl ColorSpace for YCbCr {
#[inline]
fn from_rgb(rgb: Rgb) -> YCbCr {
let clr_mat = mat3(
0.2126, -0.1146, 0.5,
0.7152, -0.3854, -0.4542,
0.0722, 0.5, -0.0458
);
let v = clr_mat.mul_v(rgb.as_vec3());
YCbCr { y: v.x, cb: v.y, cr: v.z }
}
#[inline]
fn to_rgb(&self) -> Rgb {
let clr_mat = mat3(
1., 1., 1.,
0., -0.1873, 1.8556,
1.5748, -0.4682, 0.
);
let v = clr_mat.mul_v(self.as_vec3());
Rgb::new(v.x, v.y, v.z)
}
}
#[inline]
pub fn ycbcr(y: f32, cb: f32, cr: f32) -> YCbCr {
YCbCr::new(y, cb, cr)
}
#[cfg(test)]
mod test {
use glm::*;
use space::ColorSpace;
use rgb::Rgb;
use super::YCbCr;
use quickcheck::*;
#[test]
fn test_to_rgb() {
fn prop(clr: Rgb) -> bool {
let yuv: YCbCr = ColorSpace::from_rgb(clr);
let rgb = yuv.to_rgb();
abs(yuv.cb) <= 0.5 &&
abs(yuv.cr) <= 0.5 &&
is_close_to(&rgb, &clr, 0.0001)
}
quickcheck(prop as fn(Rgb) -> bool);
}
}