1#![allow(clippy::excessive_precision)]
2use zenpixels::Primaries;
11
12#[derive(Clone, Copy, Debug, PartialEq)]
26pub struct GamutMatrix(pub(crate) [[f32; 3]; 3]);
27
28impl GamutMatrix {
29 #[inline]
31 #[must_use]
32 pub const fn from_rows(rows: [[f32; 3]; 3]) -> Self {
33 Self(rows)
34 }
35
36 #[inline]
38 #[must_use]
39 pub const fn rows(&self) -> &[[f32; 3]; 3] {
40 &self.0
41 }
42
43 #[inline]
45 #[must_use]
46 pub const fn to_xyz(primaries: Primaries) -> Option<&'static Self> {
47 #[allow(unreachable_patterns)]
48 match primaries {
49 Primaries::Bt709 => Some(&BT709_TO_XYZ),
50 Primaries::DisplayP3 => Some(&DISPLAY_P3_TO_XYZ),
51 Primaries::Bt2020 => Some(&BT2020_TO_XYZ),
52 Primaries::AdobeRgb => Some(&ADOBE_RGB_TO_XYZ),
53 _ => None,
54 }
55 }
56
57 #[inline]
59 #[must_use]
60 pub const fn from_xyz(primaries: Primaries) -> Option<&'static Self> {
61 #[allow(unreachable_patterns)]
62 match primaries {
63 Primaries::Bt709 => Some(&XYZ_TO_BT709),
64 Primaries::DisplayP3 => Some(&XYZ_TO_DISPLAY_P3),
65 Primaries::Bt2020 => Some(&XYZ_TO_BT2020),
66 Primaries::AdobeRgb => Some(&XYZ_TO_ADOBE_RGB),
67 _ => None,
68 }
69 }
70
71 #[must_use]
76 pub const fn between(from: Primaries, to: Primaries) -> Option<Self> {
77 match from.gamut_matrix_to(to) {
78 Some(rows) => Some(Self(rows)),
79 None => None,
80 }
81 }
82
83 #[must_use]
85 pub fn then(&self, next: &Self) -> Self {
86 let (a, b) = (&next.0, &self.0);
87 Self(core::array::from_fn(|i| {
88 core::array::from_fn(|j| a[i][0] * b[0][j] + a[i][1] * b[1][j] + a[i][2] * b[2][j])
89 }))
90 }
91
92 #[must_use]
94 pub fn inverse(&self) -> Option<Self> {
95 let [[a, b, c], [d, e, f], [g, h, i]] = self.0;
96 let det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);
97 if det.abs() < 1e-30 {
98 return None;
99 }
100 let inv = 1.0 / det;
101 Some(Self([
102 [
103 (e * i - f * h) * inv,
104 -(b * i - c * h) * inv,
105 (b * f - c * e) * inv,
106 ],
107 [
108 -(d * i - f * g) * inv,
109 (a * i - c * g) * inv,
110 -(a * f - c * d) * inv,
111 ],
112 [
113 (d * h - e * g) * inv,
114 -(a * h - b * g) * inv,
115 (a * e - b * d) * inv,
116 ],
117 ]))
118 }
119
120 #[inline]
122 #[must_use]
123 pub fn apply(&self, [r, g, b]: [f32; 3]) -> [f32; 3] {
124 let m = &self.0;
125 [
126 m[0][0] * r + m[0][1] * g + m[0][2] * b,
127 m[1][0] * r + m[1][1] * g + m[1][2] * b,
128 m[2][0] * r + m[2][1] * g + m[2][2] * b,
129 ]
130 }
131
132 #[inline]
134 pub fn apply_row_rgb(&self, row: &mut [[f32; 3]]) {
135 for px in row {
136 *px = self.apply(*px);
137 }
138 }
139
140 #[inline]
142 pub fn apply_row_rgba(&self, row: &mut [[f32; 4]]) {
143 for px in row {
144 let [r, g, b] = self.apply([px[0], px[1], px[2]]);
145 px[0] = r;
146 px[1] = g;
147 px[2] = b;
148 }
149 }
150}
151
152pub(crate) const BT709_TO_XYZ: GamutMatrix = GamutMatrix([
158 [0.4123907993, 0.3575843394, 0.1804807884],
159 [0.2126390059, 0.7151686788, 0.0721923154],
160 [0.0193308187, 0.1191947798, 0.9505321522],
161]);
162
163pub(crate) const XYZ_TO_BT709: GamutMatrix = GamutMatrix([
165 [3.2409699419, -1.5373831776, -0.4986107603],
166 [-0.9692436363, 1.8759675015, 0.0415550574],
167 [0.0556300797, -0.2039769589, 1.0569715142],
168]);
169
170pub(crate) const DISPLAY_P3_TO_XYZ: GamutMatrix = GamutMatrix([
172 [0.4865709486, 0.2656676932, 0.1982172852],
173 [0.2289745641, 0.6917385218, 0.0792869141],
174 [0.0000000000, 0.0451133819, 1.0439443689],
175]);
176
177pub(crate) const XYZ_TO_DISPLAY_P3: GamutMatrix = GamutMatrix([
179 [2.4934969119, -0.9313836179, -0.4027107845],
180 [-0.8294889696, 1.7626640603, 0.0236246858],
181 [0.0358458302, -0.0761723893, 0.9568845240],
182]);
183
184pub(crate) const BT2020_TO_XYZ: GamutMatrix = GamutMatrix([
186 [0.6369580484, 0.1446169036, 0.1688809752],
187 [0.2627002120, 0.6779980715, 0.0593017165],
188 [0.0000000000, 0.0280726930, 1.0609850578],
189]);
190
191pub(crate) const XYZ_TO_BT2020: GamutMatrix = GamutMatrix([
193 [1.7166511880, -0.3556707838, -0.2533662814],
194 [-0.6666843518, 1.6164812366, 0.0157685458],
195 [0.0176398574, -0.0427706133, 0.9421031212],
196]);
197
198pub(crate) const ADOBE_RGB_TO_XYZ: GamutMatrix = GamutMatrix([
200 [0.5766690429, 0.1855582379, 0.1882286462],
201 [0.2973449753, 0.6273635663, 0.0752914585],
202 [0.0270313614, 0.0706888525, 0.9913375368],
203]);
204
205pub(crate) const XYZ_TO_ADOBE_RGB: GamutMatrix = GamutMatrix([
207 [2.0415879038, -0.5650069743, -0.3447313508],
208 [-0.9692436363, 1.8759675015, 0.0415550574],
209 [0.0134442806, -0.1183623922, 1.0151749944],
210]);
211
212#[allow(dead_code)]
215pub(crate) fn conversion_matrix(from: Primaries, to: Primaries) -> Option<GamutMatrix> {
216 if from == to {
217 return None;
218 }
219 GamutMatrix::between(from, to)
220}
221
222#[cfg(test)]
223mod tests {
224 use super::*;
225
226 use zenpixels::Primaries as ColorPrimaries;
227
228 #[test]
230 fn bt709_bt2020_roundtrip() {
231 let fwd = GamutMatrix::between(ColorPrimaries::Bt709, ColorPrimaries::Bt2020).unwrap();
232 let inv = GamutMatrix::between(ColorPrimaries::Bt2020, ColorPrimaries::Bt709).unwrap();
233 let test_rgb = [0.5f32, 0.3, 0.8];
234 let mut rgb = test_rgb;
235 rgb = fwd.apply(rgb);
236 rgb = inv.apply(rgb);
237 for c in 0..3 {
238 assert!(
239 (rgb[c] - test_rgb[c]).abs() < 1e-4,
240 "BT.709→BT.2020→BT.709 roundtrip error in ch{c}: {:.6} vs {:.6}",
241 rgb[c],
242 test_rgb[c]
243 );
244 }
245 }
246
247 #[test]
249 fn bt709_displayp3_roundtrip() {
250 let fwd = GamutMatrix::between(ColorPrimaries::Bt709, ColorPrimaries::DisplayP3).unwrap();
251 let inv = GamutMatrix::between(ColorPrimaries::DisplayP3, ColorPrimaries::Bt709).unwrap();
252 let test_rgb = [0.5f32, 0.3, 0.8];
253 let mut rgb = test_rgb;
254 rgb = fwd.apply(rgb);
255 rgb = inv.apply(rgb);
256 for c in 0..3 {
257 assert!(
258 (rgb[c] - test_rgb[c]).abs() < 1e-4,
259 "BT.709→P3→BT.709 roundtrip error in ch{c}: {:.6} vs {:.6}",
260 rgb[c],
261 test_rgb[c]
262 );
263 }
264 }
265
266 #[test]
268 fn white_point_preservation() {
269 let m = GamutMatrix::between(ColorPrimaries::Bt709, ColorPrimaries::Bt2020).unwrap();
270 let mut rgb = [1.0f32, 1.0, 1.0];
271 rgb = m.apply(rgb);
272 for (c, &val) in rgb.iter().enumerate() {
273 assert!(
274 (val - 1.0).abs() < 1e-4,
275 "White point not preserved in ch{c}: {val:.6}",
276 );
277 }
278 }
279
280 #[test]
282 fn rgba_alpha_preserved() {
283 let m = GamutMatrix::between(ColorPrimaries::Bt709, ColorPrimaries::Bt2020).unwrap();
284 let mut row = [0.5f32, 0.3, 0.8, 0.42, 0.1, 0.9, 0.2, 0.99];
285 m.apply_row_rgba(&mut row.as_chunks_mut::<4>().0[..2]);
286 assert_eq!(row[3], 0.42);
287 assert_eq!(row[7], 0.99);
288 }
289
290 #[test]
292 fn xyz_bt709_roundtrip() {
293 let rgb = [0.5f32, 0.3, 0.8];
294 let mut v = rgb;
295 v = BT709_TO_XYZ.apply(v);
296 v = XYZ_TO_BT709.apply(v);
297 for c in 0..3 {
298 assert!(
299 (v[c] - rgb[c]).abs() < 1e-4,
300 "XYZ BT.709 roundtrip ch{c}: {:.6} vs {:.6}",
301 v[c],
302 rgb[c]
303 );
304 }
305 }
306
307 #[test]
309 fn xyz_displayp3_roundtrip() {
310 let rgb = [0.5f32, 0.3, 0.8];
311 let mut v = rgb;
312 v = DISPLAY_P3_TO_XYZ.apply(v);
313 v = XYZ_TO_DISPLAY_P3.apply(v);
314 for c in 0..3 {
315 assert!(
316 (v[c] - rgb[c]).abs() < 1e-4,
317 "XYZ P3 roundtrip ch{c}: {:.6} vs {:.6}",
318 v[c],
319 rgb[c]
320 );
321 }
322 }
323
324 #[test]
326 fn xyz_bt2020_roundtrip() {
327 let rgb = [0.5f32, 0.3, 0.8];
328 let mut v = rgb;
329 v = BT2020_TO_XYZ.apply(v);
330 v = XYZ_TO_BT2020.apply(v);
331 for c in 0..3 {
332 assert!(
333 (v[c] - rgb[c]).abs() < 1e-4,
334 "XYZ BT.2020 roundtrip ch{c}: {:.6} vs {:.6}",
335 v[c],
336 rgb[c]
337 );
338 }
339 }
340
341 #[test]
343 fn xyz_white_point() {
344 for (name, to, from) in [
345 ("BT.709", &BT709_TO_XYZ, &XYZ_TO_BT709),
346 ("P3", &DISPLAY_P3_TO_XYZ, &XYZ_TO_DISPLAY_P3),
347 ("BT.2020", &BT2020_TO_XYZ, &XYZ_TO_BT2020),
348 ] {
349 let mut rgb = [1.0f32; 3];
350 rgb = to.apply(rgb);
351 rgb = from.apply(rgb);
352 for (c, &val) in rgb.iter().enumerate() {
353 assert!(
354 (val - 1.0).abs() < 1e-3,
355 "{name} XYZ white point ch{c}: {val:.6}",
356 );
357 }
358 }
359 }
360
361 #[test]
363 fn mat3_mul_inverse() {
364 let identity = XYZ_TO_BT709.then(&BT709_TO_XYZ);
365 for (i, row) in identity.rows().iter().enumerate() {
366 for (j, &val) in row.iter().enumerate() {
367 let expected = if i == j { 1.0 } else { 0.0 };
368 assert!(
369 (val - expected).abs() < 1e-4,
370 "mat3_mul identity [{i}][{j}] = {val:.6}, expected {expected:.1}",
371 );
372 }
373 }
374 }
375
376 #[test]
378 fn xyz_cross_gamut_consistency() {
379 let via_xyz = BT709_TO_XYZ.then(&XYZ_TO_BT2020);
380 let direct = GamutMatrix::between(ColorPrimaries::Bt709, ColorPrimaries::Bt2020).unwrap();
381 let rgb = [0.5f32, 0.3, 0.8];
382 let mut v1 = rgb;
383 v1 = via_xyz.apply(v1);
384 let mut v2 = rgb;
385 v2 = direct.apply(v2);
386 for c in 0..3 {
387 assert!(
388 (v1[c] - v2[c]).abs() < 1e-3,
389 "cross-gamut ch{c}: via_xyz={:.6} vs direct={:.6}",
390 v1[c],
391 v2[c]
392 );
393 }
394 }
395}