1use alpha2_media::{ColorMetadata, ColorPrimaries, TransferFunction, YuvEncoding};
2
3use crate::RenderError;
4use crate::hdr::{HdrToneMap, gamut_matrix, hdr_to_working, is_working_gamut};
5
6#[derive(Copy, Clone, Debug, PartialEq)]
8pub struct YuvSample {
9 pub y: f32,
11 pub u: f32,
13 pub v: f32,
15 pub alpha: f32,
17}
18
19#[derive(Copy, Clone, Debug, Eq, PartialEq)]
21pub enum ColorPolicy {
22 RejectHdr,
24 WarnHdr,
26 ToneMapHdr(HdrToneMap),
28}
29
30#[must_use]
32pub const fn is_hdr(color: ColorMetadata) -> bool {
33 color.is_hdr()
34}
35
36#[derive(Clone, Debug, Eq, PartialEq)]
38pub enum ColorDiagnostic {
39 MissingMetadataFallback,
41 UnsupportedHdr,
43 ToneMappedHdr,
45}
46
47#[derive(Clone, Debug, Eq, PartialEq)]
49#[non_exhaustive]
50pub enum ColorError {
51 InvalidBitDepth,
53 InvalidSample,
55 UnsupportedHdr,
57}
58
59impl std::fmt::Display for ColorError {
60 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61 formatter.write_str(match self {
62 Self::InvalidBitDepth => "color bit depth must be within 8..=16",
63 Self::InvalidSample => "color sample is non-finite or out of range",
64 Self::UnsupportedHdr => "HDR input is unsupported by the selected policy",
65 })
66 }
67}
68
69impl std::error::Error for ColorError {}
70
71pub fn convert_yuv_to_linear_rgba(
76 sample: YuvSample,
77 bit_depth: u8,
78 metadata: Option<ColorMetadata>,
79 policy: ColorPolicy,
80) -> Result<([f32; 4], Vec<ColorDiagnostic>), ColorError> {
81 if !(8..=16).contains(&bit_depth) {
82 return Err(ColorError::InvalidBitDepth);
83 }
84 if ![sample.y, sample.u, sample.v, sample.alpha]
85 .into_iter()
86 .all(f32::is_finite)
87 || !(0.0..=1.0).contains(&sample.alpha)
88 {
89 return Err(ColorError::InvalidSample);
90 }
91 let mut diagnostics = Vec::new();
92 let color = metadata.unwrap_or_else(|| {
93 diagnostics.push(ColorDiagnostic::MissingMetadataFallback);
94 ColorMetadata::UNDECLARED
95 });
96 let tone = if is_hdr(color) {
97 match policy {
98 ColorPolicy::RejectHdr => {
99 diagnostics.push(ColorDiagnostic::UnsupportedHdr);
100 return Err(ColorError::UnsupportedHdr);
101 }
102 ColorPolicy::WarnHdr => {
103 diagnostics.push(ColorDiagnostic::UnsupportedHdr);
104 return Ok(([0.0, 0.0, 0.0, 0.0], diagnostics));
105 }
106 ColorPolicy::ToneMapHdr(tone) => {
107 diagnostics.push(ColorDiagnostic::ToneMappedHdr);
108 Some(tone)
109 }
110 }
111 } else {
112 None
113 };
114
115 let encoded = if let Some((kr, kb)) = color.matrix.luma_weights() {
116 let levels = color.range.levels(bit_depth);
117 let (y, cb, cr) = (
118 (sample.y * levels.maximum - levels.luma_black) / levels.luma_span,
119 (sample.u * levels.maximum - levels.chroma_center) / levels.chroma_span,
120 (sample.v * levels.maximum - levels.chroma_center) / levels.chroma_span,
121 );
122 let kg = 1.0 - kr - kb;
123 [
124 y + 2.0 * (1.0 - kr) * cr,
125 y - 2.0 * kb * (1.0 - kb) / kg * cb - 2.0 * kr * (1.0 - kr) / kg * cr,
126 y + 2.0 * (1.0 - kb) * cb,
127 ]
128 } else {
129 [sample.y, sample.u, sample.v]
130 };
131 let encoded = encoded.map(|component| component.clamp(0.0, 1.0));
132 let linear = match tone {
133 Some(tone) if matches!(color.transfer, TransferFunction::Pq | TransferFunction::Hlg) => {
134 hdr_to_working(encoded, color.transfer, color.primaries, tone)
135 }
136 _ => {
137 let decoded = encoded.map(decode_sdr);
138 if is_working_gamut(color.primaries) {
139 decoded
140 } else {
141 gamut_matrix(color.primaries, ColorPrimaries::Bt709).map(|row| {
143 row.iter()
144 .zip(decoded)
145 .map(|(weight, value)| weight * value)
146 .sum::<f32>()
147 .clamp(0.0, 1.0)
148 })
149 }
150 }
151 };
152 let mut output = [0.0; 4];
153 for (destination, component) in output[..3].iter_mut().zip(linear) {
154 *destination = component * sample.alpha;
155 }
156 output[3] = sample.alpha;
157 Ok((output, diagnostics))
158}
159
160pub(crate) fn check_packable(encoding: YuvEncoding) -> Result<(), RenderError> {
161 let color = encoding.color;
162 if color.is_hdr() || !is_working_gamut(color.primaries) {
163 return Err(RenderError::UnsupportedOutputColor(color));
164 }
165 Ok(())
166}
167
168#[cfg(test)]
169pub(crate) fn encode_srgb(rgb: [f32; 3]) -> [f32; 3] {
170 rgb.map(|value| {
171 let value = value.clamp(0.0, 1.0);
172 if value <= 0.003_130_8 {
173 12.92 * value
174 } else {
175 1.055 * libm::powf(value, 1.0 / 2.4) - 0.055
176 }
177 })
178}
179
180fn decode_sdr(value: f32) -> f32 {
185 if value <= 0.040_45 {
186 value / 12.92
187 } else {
188 libm::powf((value + 0.055) / 1.055, 2.4)
189 }
190}
191
192#[derive(Copy, Clone, Debug, PartialEq)]
199pub struct Color {
200 pub red: f64,
202 pub green: f64,
204 pub blue: f64,
206 pub alpha: f64,
208}
209
210#[cfg(test)]
211#[allow(clippy::items_after_test_module)]
212mod tests {
213 use super::*;
214 use alpha2_media::{ColorMatrix, ColorPrimaries, ColorRange, DynamicRange};
215
216 fn metadata(matrix: ColorMatrix, range: ColorRange) -> ColorMetadata {
217 ColorMetadata {
218 primaries: ColorPrimaries::Bt709,
219 transfer: TransferFunction::Bt709,
220 matrix,
221 range,
222 dynamic_range: DynamicRange::Sdr,
223 }
224 }
225
226 #[test]
227 fn the_packs_take_only_the_working_gamut_and_an_sdr_transfer() {
228 let pack = |primaries, transfer| {
229 check_packable(YuvEncoding::new(
230 ColorMetadata {
231 primaries,
232 transfer,
233 dynamic_range: if matches!(transfer, TransferFunction::Pq) {
234 DynamicRange::Hdr
235 } else {
236 DynamicRange::Sdr
237 },
238 ..ColorMetadata::EXPORT
239 },
240 alpha2_media::ChromaLocation::Center,
241 ))
242 .is_ok()
243 };
244 assert!(pack(ColorPrimaries::Bt709, TransferFunction::Bt709));
245 assert!(pack(ColorPrimaries::Bt601, TransferFunction::Srgb));
246 assert!(!pack(ColorPrimaries::Bt2020, TransferFunction::Bt709));
247 assert!(!pack(ColorPrimaries::DisplayP3, TransferFunction::Bt709));
248 assert!(!pack(ColorPrimaries::Bt709, TransferFunction::Pq));
249 }
250
251 #[test]
252 fn neutral_black_and_white_match_all_sdr_matrices_and_ranges() {
253 for matrix in [
254 ColorMatrix::Bt601,
255 ColorMatrix::Bt709,
256 ColorMatrix::Bt2020Ncl,
257 ] {
258 for range in [ColorRange::Limited, ColorRange::Full] {
259 let neutral = 128.0 / 255.0;
260 let black_y = if range == ColorRange::Limited {
261 16.0 / 255.0
262 } else {
263 0.0
264 };
265 let (black, _) = convert_yuv_to_linear_rgba(
266 YuvSample {
267 y: black_y,
268 u: neutral,
269 v: neutral,
270 alpha: 1.0,
271 },
272 8,
273 Some(metadata(matrix, range)),
274 ColorPolicy::RejectHdr,
275 )
276 .expect("SDR");
277 assert!(black[..3].iter().all(|value| value.abs() < 1.0e-5));
278 let white_y = if range == ColorRange::Limited {
279 235.0 / 255.0
280 } else {
281 1.0
282 };
283 let (white, _) = convert_yuv_to_linear_rgba(
284 YuvSample {
285 y: white_y,
286 u: neutral,
287 v: neutral,
288 alpha: 0.5,
289 },
290 8,
291 Some(metadata(matrix, range)),
292 ColorPolicy::RejectHdr,
293 )
294 .expect("SDR");
295 assert!(white[..3].iter().all(|value| (*value - 0.5).abs() < 2.0e-4));
296 }
297 }
298 }
299
300 #[test]
301 fn wide_gamut_sdr_converts_into_bt709_primaries_and_clips_what_they_cannot_hold() {
302 let bt2020_sdr = ColorMetadata {
304 primaries: ColorPrimaries::Bt2020,
305 ..metadata(ColorMatrix::Rgb, ColorRange::Full)
306 };
307 let linear = |encoded: [f32; 3]| {
308 let (output, diagnostics) = convert_yuv_to_linear_rgba(
309 YuvSample {
310 y: encoded[0],
311 u: encoded[1],
312 v: encoded[2],
313 alpha: 1.0,
314 },
315 8,
316 Some(bt2020_sdr),
317 ColorPolicy::RejectHdr,
318 )
319 .expect("wide-gamut SDR is not HDR");
320 assert!(diagnostics.is_empty(), "{diagnostics:?}");
321 [output[0], output[1], output[2]]
322 };
323 let bt2087 = [
325 [1.6605, -0.5876, -0.0728],
326 [-0.1246, 1.1329, -0.0083],
327 [-0.0182, -0.1006, 1.1187],
328 ];
329 let encoded = [0.55_f32, 0.6, 0.5];
330 let decoded = encoded.map(decode_sdr);
331 let expected = bt2087.map(|row| row.iter().zip(decoded).map(|(m, v)| m * v).sum::<f32>());
332 assert!(expected.iter().all(|value| (0.0..=1.0).contains(value)));
333 let converted = linear(encoded);
334 for (got, want) in converted.iter().zip(expected) {
335 assert!((got - want).abs() < 2.0e-3, "{converted:?} != {expected:?}");
336 }
337 assert!(
338 (converted[0] - decoded[0]).abs() > 0.01,
339 "{converted:?}: the BT.2020 row is not the identity"
340 );
341 let gray = linear([0.5; 3]);
342 assert!(
343 gray.iter()
344 .all(|value| (value - decode_sdr(0.5)).abs() < 1.0e-4),
345 "{gray:?}"
346 );
347 assert_eq!(
349 linear([0.0, 1.0, 0.0]).map(f32::to_bits),
350 [0.0_f32, 1.0, 0.0].map(f32::to_bits)
351 );
352 let (bt709, _) = convert_yuv_to_linear_rgba(
353 YuvSample {
354 y: encoded[0],
355 u: encoded[1],
356 v: encoded[2],
357 alpha: 1.0,
358 },
359 8,
360 Some(metadata(ColorMatrix::Rgb, ColorRange::Full)),
361 ColorPolicy::RejectHdr,
362 )
363 .expect("SDR");
364 assert_eq!(
365 [bt709[0], bt709[1], bt709[2]].map(f32::to_bits),
366 decoded.map(f32::to_bits)
367 );
368 }
369
370 #[test]
371 fn sdr_decode_is_the_inverse_of_the_srgb_export_encode_for_every_tag() {
372 for transfer in [TransferFunction::Bt709, TransferFunction::Srgb] {
373 for code in 16_u8..=235 {
374 let (linear, _) = convert_yuv_to_linear_rgba(
375 YuvSample {
376 y: f32::from(code) / 255.0,
377 u: 128.0 / 255.0,
378 v: 128.0 / 255.0,
379 alpha: 1.0,
380 },
381 8,
382 Some(ColorMetadata {
383 transfer,
384 ..metadata(ColorMatrix::Bt709, ColorRange::Limited)
385 }),
386 ColorPolicy::RejectHdr,
387 )
388 .expect("SDR");
389 let encoded = encode_srgb([linear[0], linear[1], linear[2]]);
390 let expected = (f32::from(code) - 16.0) / 219.0;
391 assert!(
392 encoded
393 .iter()
394 .all(|value| (value - expected).abs() * 219.0 < 0.01),
395 "{transfer:?} code {code}: {encoded:?} != {expected}"
396 );
397 }
398 }
399 }
400
401 #[test]
402 fn rgb_matrix_preserves_encoded_components() {
403 let (red, diagnostics) = convert_yuv_to_linear_rgba(
404 YuvSample {
405 y: 1.0,
406 u: 0.0,
407 v: 0.0,
408 alpha: 1.0,
409 },
410 8,
411 Some(metadata(ColorMatrix::Rgb, ColorRange::Limited)),
412 ColorPolicy::RejectHdr,
413 )
414 .expect("RGB SDR input");
415 assert_eq!(diagnostics, [] as [ColorDiagnostic; 0]);
416 assert_eq!(
417 red.map(f32::to_bits),
418 [1.0, 0.0, 0.0, 1.0].map(f32::to_bits)
419 );
420 }
421
422 #[test]
423 fn fallback_and_hdr_are_observable() {
424 let (_, diagnostics) = convert_yuv_to_linear_rgba(
425 YuvSample {
426 y: 16.0 / 255.0,
427 u: 128.0 / 255.0,
428 v: 128.0 / 255.0,
429 alpha: 1.0,
430 },
431 8,
432 None,
433 ColorPolicy::RejectHdr,
434 )
435 .expect("fallback");
436 assert_eq!(diagnostics, [ColorDiagnostic::MissingMetadataFallback]);
437 let hdr = ColorMetadata {
438 dynamic_range: DynamicRange::Hdr,
439 ..metadata(ColorMatrix::Bt2020Ncl, ColorRange::Limited)
440 };
441 assert_eq!(
442 convert_yuv_to_linear_rgba(
443 YuvSample {
444 y: 0.5,
445 u: 0.5,
446 v: 0.5,
447 alpha: 1.0
448 },
449 10,
450 Some(hdr),
451 ColorPolicy::RejectHdr
452 ),
453 Err(ColorError::UnsupportedHdr)
454 );
455 }
456}
457
458const PREMULTIPLIED_SLACK: f64 = 1e-6;
461
462impl Color {
463 pub const BLACK: Self = Self::rgba(0.0, 0.0, 0.0, 1.0);
465
466 #[must_use]
468 pub const fn rgba(red: f64, green: f64, blue: f64, alpha: f64) -> Self {
469 Self {
470 red,
471 green,
472 blue,
473 alpha,
474 }
475 }
476
477 pub(crate) fn is_valid(self) -> bool {
480 let in_range = [self.red, self.green, self.blue, self.alpha]
481 .into_iter()
482 .all(|component| component.is_finite() && (0.0..=1.0).contains(&component));
483 in_range
484 && [self.red, self.green, self.blue]
485 .into_iter()
486 .all(|component| component <= self.alpha + PREMULTIPLIED_SLACK)
487 }
488
489 #[must_use]
492 pub fn source_over(self, source: Self) -> Self {
493 let remaining = 1.0 - source.alpha;
494 Self::rgba(
495 source.red + self.red * remaining,
496 source.green + self.green * remaining,
497 source.blue + self.blue * remaining,
498 source.alpha + self.alpha * remaining,
499 )
500 }
501}