1use crate::Size;
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
34pub struct Color {
35 pub matrix: Matrix,
37 pub range: Range,
39 pub primaries: Primaries,
41 pub transfer: Transfer,
43}
44
45#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
47#[non_exhaustive]
48pub enum Matrix {
49 Bt601,
51 Bt709,
53 Bt2020,
55}
56
57pub use hang::catalog::ColorRange as Range;
59
60#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
62#[non_exhaustive]
63pub enum Primaries {
64 Smpte170m,
66 Bt470bg,
68 Bt709,
70 Bt2020,
72}
73
74#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
76#[non_exhaustive]
77pub enum Transfer {
78 Bt709,
80 Pq,
82 Hlg,
84}
85
86#[derive(Clone, Copy, Debug, PartialEq, Eq)]
88pub(crate) struct CodePoints {
89 pub primaries: u8,
90 pub transfer: u8,
91 pub matrix: u8,
92}
93
94impl Color {
95 pub const BT601: Self = Self {
98 matrix: Matrix::Bt601,
99 range: Range::Limited,
100 primaries: Primaries::Smpte170m,
101 transfer: Transfer::Bt709,
102 };
103
104 pub const BT709: Self = Self {
106 matrix: Matrix::Bt709,
107 range: Range::Limited,
108 primaries: Primaries::Bt709,
109 transfer: Transfer::Bt709,
110 };
111
112 pub fn infer(size: Size) -> Self {
119 match size.height <= 576 {
120 true => Self::BT601,
121 false => Self::BT709,
122 }
123 }
124
125 pub(crate) const fn with_range(self, range: Range) -> Self {
127 Self { range, ..self }
128 }
129
130 #[cfg(test)]
138 pub(crate) fn code_points(self) -> CodePoints {
139 CodePoints {
140 primaries: match self.primaries {
141 Primaries::Smpte170m => 6,
142 Primaries::Bt470bg => 5,
143 Primaries::Bt709 => 1,
144 Primaries::Bt2020 => 9,
145 },
146 transfer: match self.transfer {
147 Transfer::Bt709 => 1,
148 Transfer::Pq => 16,
149 Transfer::Hlg => 18,
150 },
151 matrix: match self.matrix {
152 Matrix::Bt601 => 6,
153 Matrix::Bt709 => 1,
154 Matrix::Bt2020 => 9,
155 },
156 }
157 }
158
159 pub(crate) fn from_code_points(codes: Option<CodePoints>, range: Range, size: Size) -> Option<Self> {
165 let guess = Self::infer(size).with_range(range);
166 let Some(codes) = codes else {
167 return Some(guess);
168 };
169 Some(Self {
170 matrix: match codes.matrix {
171 2 => guess.matrix,
172 1 => Matrix::Bt709,
173 5 | 6 => Matrix::Bt601,
174 9 => Matrix::Bt2020,
175 _ => return None,
176 },
177 range,
178 primaries: match codes.primaries {
179 2 => guess.primaries,
180 1 => Primaries::Bt709,
181 5 => Primaries::Bt470bg,
182 6 | 7 => Primaries::Smpte170m,
184 9 => Primaries::Bt2020,
185 _ => return None,
186 },
187 transfer: match codes.transfer {
188 2 => guess.transfer,
189 1 | 6 | 14 | 15 => Transfer::Bt709,
190 16 => Transfer::Pq,
191 18 => Transfer::Hlg,
192 _ => return None,
193 },
194 })
195 }
196
197 #[cfg(any(test, all(target_os = "linux", feature = "nvidia"), all(apple, feature = "render")))]
209 pub(crate) fn coefficients(self) -> Coefficients {
210 let (kr, kb) = self.matrix.weights();
211 let kg = 1.0 - kr - kb;
212 let (luma_scale, chroma_scale, luma_offset) = match self.range {
213 Range::Limited => (219.0 / 255.0, 224.0 / 255.0, 16.0),
214 Range::Full => (1.0, 1.0, 0.0),
215 };
216 let cb = chroma_scale / (2.0 * (1.0 - kb));
219 let cr = chroma_scale / (2.0 * (1.0 - kr));
220 Coefficients {
221 y: [luma_scale * kr, luma_scale * kg, luma_scale * kb, luma_offset],
222 u: [-cb * kr, -cb * kg, cb * (1.0 - kb), 128.0],
223 v: [cr * (1.0 - kr), -cr * kg, -cr * kb, 128.0],
224 }
225 }
226
227 pub(crate) fn yuv(self) -> (yuv::YuvRange, yuv::YuvStandardMatrix) {
230 let range = match self.range {
231 Range::Limited => yuv::YuvRange::Limited,
232 Range::Full => yuv::YuvRange::Full,
233 };
234 let matrix = match self.matrix {
235 Matrix::Bt601 => yuv::YuvStandardMatrix::Bt601,
236 Matrix::Bt709 => yuv::YuvStandardMatrix::Bt709,
237 Matrix::Bt2020 => yuv::YuvStandardMatrix::Bt2020,
238 };
239 (range, matrix)
240 }
241}
242
243impl Matrix {
244 #[cfg(any(test, feature = "render", all(target_os = "linux", feature = "nvidia")))]
246 pub(crate) fn weights(self) -> (f32, f32) {
247 match self {
248 Matrix::Bt601 => (0.299, 0.114),
249 Matrix::Bt709 => (0.2126, 0.0722),
250 Matrix::Bt2020 => (0.2627, 0.0593),
251 }
252 }
253}
254
255#[cfg(any(test, all(target_os = "linux", feature = "nvidia"), all(apple, feature = "render")))]
258#[derive(Clone, Copy, Debug, PartialEq)]
259pub(crate) struct Coefficients {
260 pub y: [f32; 4],
261 pub u: [f32; 4],
262 pub v: [f32; 4],
263}
264
265#[cfg(any(test, all(target_os = "linux", feature = "nvidia"), all(apple, feature = "render")))]
266impl Coefficients {
267 #[cfg(test)]
271 pub(crate) fn apply(&self, rgb: [u8; 3]) -> [u8; 3] {
272 let dot = |w: [f32; 4]| {
273 let v = w[0] * rgb[0] as f32 + w[1] * rgb[1] as f32 + w[2] * rgb[2] as f32 + w[3];
274 v.round().clamp(0.0, 255.0) as u8
275 };
276 [dot(self.y), dot(self.u), dot(self.v)]
277 }
278}
279
280#[cfg(test)]
281mod tests {
282 use super::*;
283
284 #[test]
285 fn inference_splits_at_standard_definition() {
286 assert_eq!(Color::infer(Size::new(720, 480)), Color::BT601);
287 assert_eq!(Color::infer(Size::new(720, 576)), Color::BT601);
288 assert_eq!(Color::infer(Size::new(1280, 720)), Color::BT709);
289 }
290
291 #[test]
292 fn code_points_round_trip() {
293 let size = Size::new(1920, 1080);
294 for color in [
295 Color::BT601,
296 Color::BT709.with_range(Range::Full),
297 Color {
298 primaries: Primaries::Bt709,
299 ..Color::BT601
300 },
301 Color {
302 primaries: Primaries::Bt470bg,
303 ..Color::BT601
304 },
305 Color {
306 matrix: Matrix::Bt2020,
307 primaries: Primaries::Bt2020,
308 transfer: Transfer::Pq,
309 ..Color::BT709
310 },
311 Color {
312 matrix: Matrix::Bt2020,
313 primaries: Primaries::Bt2020,
314 transfer: Transfer::Hlg,
315 ..Color::BT709
316 },
317 ] {
318 assert_eq!(
319 Color::from_code_points(Some(color.code_points()), color.range, size),
320 Some(color)
321 );
322 }
323 }
324
325 #[test]
326 fn unspecified_code_points_take_the_size_guess() {
327 let sd = Size::new(640, 480);
328 let hd = Size::new(1920, 1080);
329 assert_eq!(Color::from_code_points(None, Range::Limited, hd), Some(Color::BT709));
330 assert_eq!(
331 Color::from_code_points(None, Range::Full, sd),
332 Some(Color::BT601.with_range(Range::Full))
333 );
334 let codes = CodePoints {
336 primaries: 2,
337 transfer: 2,
338 matrix: 1,
339 };
340 assert_eq!(
341 Color::from_code_points(Some(codes), Range::Limited, sd),
342 Some(Color {
343 matrix: Matrix::Bt709,
344 ..Color::BT601
345 })
346 );
347 let codes = CodePoints {
349 primaries: 6,
350 transfer: 6,
351 matrix: 6,
352 };
353 assert_eq!(
354 Color::from_code_points(Some(codes), Range::Limited, hd),
355 Some(Color::BT601)
356 );
357 }
358
359 #[test]
360 fn unrepresentable_code_points_are_refused() {
361 let hd = Size::new(1920, 1080);
362 let rgb = CodePoints {
363 primaries: 1,
364 transfer: 1,
365 matrix: 0,
366 };
367 assert_eq!(Color::from_code_points(Some(rgb), Range::Full, hd), None);
368 let srgb_curve = CodePoints {
369 primaries: 1,
370 transfer: 13,
371 matrix: 1,
372 };
373 assert_eq!(Color::from_code_points(Some(srgb_curve), Range::Full, hd), None);
374 }
375
376 #[test]
379 fn coefficients_match_the_textbook_values() {
380 let red = [255, 0, 0];
381 let full = |color: Color| color.with_range(Range::Full);
382 assert_eq!(Color::BT709.coefficients().apply(red), [63, 102, 240]);
383 assert_eq!(full(Color::BT709).coefficients().apply(red), [54, 99, 255]);
384 assert_eq!(Color::BT601.coefficients().apply(red), [81, 90, 240]);
385 assert_eq!(full(Color::BT601).coefficients().apply([255; 3]), [255, 128, 128]);
386 assert_eq!(Color::BT709.coefficients().apply([0; 3]), [16, 128, 128]);
387 }
388
389 #[test]
393 fn coefficients_agree_with_the_yuv_crate() {
394 use yuv::{YuvChromaSubsampling, YuvConversionMode, YuvPlanarImageMut, rgba_to_yuv420};
395
396 let bt2020 = Color {
397 matrix: Matrix::Bt2020,
398 ..Color::BT709
399 };
400 let colors = [
401 Color::BT601,
402 Color::BT601.with_range(Range::Full),
403 Color::BT709,
404 Color::BT709.with_range(Range::Full),
405 bt2020,
406 ];
407 let pixels: [[u8; 3]; 6] = [
408 [255, 0, 0],
409 [0, 255, 0],
410 [0, 0, 255],
411 [255, 255, 255],
412 [17, 200, 90],
413 [128, 128, 128],
414 ];
415 for color in colors {
416 let (range, matrix) = color.yuv();
417 let coefficients = color.coefficients();
418 for rgb in pixels {
419 let rgba: Vec<u8> = std::iter::repeat_n([rgb[0], rgb[1], rgb[2], 255], 4)
421 .flatten()
422 .collect();
423 let mut planar = YuvPlanarImageMut::alloc(2, 2, YuvChromaSubsampling::Yuv420);
424 rgba_to_yuv420(&mut planar, &rgba, 8, range, matrix, YuvConversionMode::Balanced).unwrap();
425 let expected = [
426 planar.y_plane.borrow()[0],
427 planar.u_plane.borrow()[0],
428 planar.v_plane.borrow()[0],
429 ];
430 let actual = coefficients.apply(rgb);
431 for (channel, (a, e)) in actual.iter().zip(expected).enumerate() {
432 assert!(
433 a.abs_diff(e) <= 1,
434 "{color:?} {rgb:?} channel {channel}: coefficients {actual:?}, yuv crate {expected:?}"
435 );
436 }
437 }
438 }
439 }
440}