Skip to main content

moq_video/
color.rs

1//! [`Color`]: which color space a frame's samples are in.
2
3use crate::Size;
4
5/// Which color space a frame's samples are in: the YUV matrix and range that
6/// decode them to RGB, and the primaries and transfer curve that RGB means.
7///
8/// Video carries luma and chroma, not RGB, and the matrix that converts between
9/// them differs by generation (BT.601 for standard definition, BT.709 for high
10/// definition, BT.2020 for UHD) as does the numeric range (limited/studio swing
11/// pins luma to 16..235, full swing uses 0..255). Pairing samples with the
12/// wrong matrix is the classic tinted-video bug: it leaves grays untouched and
13/// skews saturated colors, so it survives a casual look at the picture. The
14/// primaries and transfer travel separately because sources mix them: a BT.601
15/// matrix over BT.709 primaries is common, and HDR changes only the transfer.
16///
17/// [`Surface::color`](crate::Surface::color) reports it where the crate knows:
18/// when the crate did the conversion itself, when a decoder read the stream's
19/// VUI, or when the surface carries the answer. It is `None` for pixels that
20/// merely passed through with nothing naming their space, a camera's raw YUYV
21/// among them. [`Color::infer`] is the fallback then.
22///
23/// Build one from [`BT601`](Self::BT601) or [`BT709`](Self::BT709) and change
24/// the fields that differ:
25///
26/// ```
27/// use moq_video::Color;
28/// use moq_video::color::{Primaries, Range};
29///
30/// let jpeg = Color { range: Range::Full, ..Color::BT601 };
31/// let webcam = Color { primaries: Primaries::Bt709, ..Color::BT601 };
32/// ```
33#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
34pub struct Color {
35	/// The matrix between RGB and Y'CbCr.
36	pub matrix: Matrix,
37	/// The numeric range of the samples.
38	pub range: Range,
39	/// The chromaticities of the RGB primaries.
40	pub primaries: Primaries,
41	/// The curve between linear light and the RGB values.
42	pub transfer: Transfer,
43}
44
45/// The matrix between RGB and Y'CbCr.
46#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
47#[non_exhaustive]
48pub enum Matrix {
49	/// BT.601 (SMPTE 170M and BT.470 System B/G define the same matrix).
50	Bt601,
51	/// BT.709.
52	Bt709,
53	/// BT.2020 non-constant luminance.
54	Bt2020,
55}
56
57/// The numeric range of the samples, the same type the catalog's colour carries.
58pub use hang::catalog::ColorRange as Range;
59
60/// The chromaticities of the RGB primaries.
61#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
62#[non_exhaustive]
63pub enum Primaries {
64	/// SMPTE 170M, the 525-line (NTSC) BT.601 primaries.
65	Smpte170m,
66	/// BT.470 System B/G, the 625-line (PAL) BT.601 primaries.
67	Bt470bg,
68	/// BT.709, which sRGB shares.
69	Bt709,
70	/// BT.2020, the UHD and HDR gamut.
71	Bt2020,
72}
73
74/// The curve between linear light and the RGB values.
75#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
76#[non_exhaustive]
77pub enum Transfer {
78	/// The SDR curve BT.709 defines, which BT.601 and BT.2020 share.
79	Bt709,
80	/// SMPTE ST 2084 perceptual quantizer, the HDR10 curve.
81	Pq,
82	/// ARIB STD-B67 hybrid log-gamma.
83	Hlg,
84}
85
86/// The ISO/IEC 23091-2 code points a VUI carries for a [`Color`].
87#[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	/// BT.601 as SD video uses it: SMPTE 170M primaries and matrix, the SDR
96	/// curve, limited range.
97	pub const BT601: Self = Self {
98		matrix: Matrix::Bt601,
99		range: Range::Limited,
100		primaries: Primaries::Smpte170m,
101		transfer: Transfer::Bt709,
102	};
103
104	/// BT.709 throughout, limited range: HD video.
105	pub const BT709: Self = Self {
106		matrix: Matrix::Bt709,
107		range: Range::Limited,
108		primaries: Primaries::Bt709,
109		transfer: Transfer::Bt709,
110	};
111
112	/// The conventional guess for a frame of this size: [`BT601`](Self::BT601)
113	/// up to standard definition (576 lines), [`BT709`](Self::BT709) above it.
114	///
115	/// What a player does when the bitstream carries no VUI color description,
116	/// which is most of the time. A guess, so prefer a known [`Color`] whenever
117	/// one is available.
118	pub fn infer(size: Size) -> Self {
119		match size.height <= 576 {
120			true => Self::BT601,
121			false => Self::BT709,
122		}
123	}
124
125	/// The same space in the given range.
126	pub(crate) const fn with_range(self, range: Range) -> Self {
127		Self { range, ..self }
128	}
129
130	/// The VUI code points for this space.
131	///
132	/// BT.601's matrix goes out as SMPTE 170M (6) whatever the primaries, since
133	/// BT.470 System B/G (5) defines the same one. The SDR curve goes out as
134	/// BT.709 (1): SMPTE 170M and BT.2020 define the same curve under other
135	/// numbers, and 1 is the one every backend can emit. Backends name these
136	/// through their own APIs; tests check what they wrote against this.
137	#[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	/// The space a VUI's code points name, or `None` when it names one this
160	/// type cannot hold (an RGB or YCgCo matrix, a film gamut, a gamma curve).
161	///
162	/// An unspecified field (code point 2, or an absent description) takes the
163	/// value [`infer`](Self::infer) guesses for `size`.
164	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				// SMPTE 240M shares SMPTE 170M's chromaticities.
183				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	/// The 8-bit RGB to Y'CbCr coefficients of this space, for a conversion the
198	/// crate runs itself (the GPU kernels).
199	///
200	/// Compiled for every test build so the cross-check against the `yuv` crate
201	/// runs without a GPU.
202	///
203	/// Display-referred RGB in: the samples are taken as already gamma-encoded,
204	/// which is what an 8-bit render target holds, so no transfer function is
205	/// applied on the way through. The offsets put chroma at 128 and, for limited
206	/// range, luma at 16; the scales fit the range (219/224 of 255 for limited,
207	/// all of it for full).
208	#[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		// Cb = (B - Y') / (2 (1 - Kb)) and Cr = (R - Y') / (2 (1 - Kr)), with Y'
217		// substituted so each channel is one weighted sum.
218		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	/// How the `yuv` crate names this space's matrix and range, for the RGB
228	/// conversions.
229	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	/// The luma weights (`kr`, `kb`) the matrix is derived from.
245	#[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/// The weights of one RGB to Y'CbCr conversion: each output sample is
256/// `[r, g, b, offset]` dotted with `(R, G, B, 1)`, all on the 0..255 scale.
257#[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	/// One pixel through the matrix, rounded and clamped the way the kernels do
268	/// it. The CPU reference for a GPU conversion, and what the tests compare
269	/// against the `yuv` crate.
270	#[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		// A signalled matrix with unspecified primaries and transfer.
335		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		// Same curve under SMPTE 170M's number.
348		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	/// The textbook 8-bit values for pure red: BT.709 limited is (63, 102, 240),
377	/// full range (54, 99, 255); BT.601 limited is (81, 90, 240).
378	#[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	/// The coefficients agree with the `yuv` crate's conversion, which every CPU
390	/// path uses, so a GPU frame converted with them decodes to the same picture
391	/// as the same pixels fed through `Surface::rgba`.
392	#[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				// A solid 2x2 block, so the crate's chroma subsampling changes nothing.
420				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}