forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBcc667e6Tahinli3 months ago285 commits

colorspace.rs1269 lines, 48.9 KiBHistoryRawDownload
1//! What the numbers in a decoded picture *mean*: which YUV->RGB matrix they
2//! were coded against, which transfer curve, and whether they span the full
3//! byte or the limited 16..235 range. Everything but [`remap`] is read off the
4//! file; that one is the other direction -- what an export does to a clip whose
5//! matrix is not the one the file being written declares.
6//!
7//! Three tiers, in this order, per field:
8//!
9//! 1. the **container**'s own tags -- Matroska `Colour`, mp4 `colr` -- which is
10//! what a remuxer rewrites and therefore the most recently asserted truth,
11//! 2. the **bitstream**'s: an H.264 or HEVC SPS VUI `colour_description`, an
12//! AV1 sequence header `color_config`, which is what the *encoder* wrote and
13//! what survives a container that dropped its tags,
14//! 3. the **resolution heuristic** ffmpeg and mpv both fall back to: a picture
15//! 720 lines or taller is BT.709, anything smaller is BT.601, limited range
16//! either way.
17//!
18//! Per field, not per file: a Matroska that tags `Range` and nothing else
19//! leaves the matrix to the SPS below it. A code this does not know -- reserved,
20//! unspecified, or a matrix with no implementation here -- is the same as an
21//! absent one and falls to the next tier, which is the whole reason the tiers
22//! carry [`Option`]s rather than resolved values.
23//!
24//! Code values are ISO/IEC 23091-2 (= ITU-T H.273), the one table Matroska, mp4
25//! `colr`, H.264 VUI, HEVC VUI and AV1 `color_config` all point at.
26
27use crate::demux::Codec;
28
29/// The YUV->RGB matrix a stream's chroma was coded against. Only the three that
30/// exist in practice: SD (BT.601), HD (BT.709) and UHD/HDR (BT.2020
31/// non-constant-luminance). Constant-luminance BT.2020 is not here because no
32/// encoder writes it.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum Matrix {
35 Bt601,
36 Bt709,
37 Bt2020Ncl,
38}
39
40/// The transfer curve the samples are on. `Sdr` covers every curve that is
41/// displayed as-is -- BT.709's, sRGB's, SMPTE 170M's, which differ by less than
42/// a display's own calibration -- against the two HDR ones, which do not.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum Transfer {
45 Sdr,
46 /// SMPTE ST 2084, "PQ": what an HDR10 file is on.
47 Pq,
48 /// ARIB STD-B67, "HLG": broadcast HDR.
49 Hlg,
50}
51
52/// What one video stream's samples mean, resolved through all three tiers.
53/// [`Default`] is what this engine assumed of every file before it read any of
54/// this: BT.601, SDR, limited range.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub struct ColorDescription {
57 pub matrix: Matrix,
58 pub transfer: Transfer,
59 /// `true` when the samples use all 256 codes (JPEG/"pc" range) rather than
60 /// the broadcast 16..235 luma / 16..240 chroma.
61 pub full_range: bool,
62}
63
64impl Default for ColorDescription {
65 fn default() -> Self {
66 Self {
67 matrix: Matrix::Bt601,
68 transfer: Transfer::Sdr,
69 full_range: false,
70 }
71 }
72}
73
74impl ColorDescription {
75 /// The three tiers collapsed into one answer. `height` is the coded picture
76 /// height the heuristic reads when nothing else said anything.
77 pub fn resolve(container: Tags, bitstream: Tags, height: u32) -> Self {
78 let tags = container.over(bitstream);
79 Self {
80 // The ffmpeg/mpv rule, and the reason it is a rule: an untagged
81 // 1080p file is HD material and an untagged 480p one came off SD
82 // material, and guessing the other way is a visible green/magenta
83 // shift on faces.
84 matrix: tags.matrix.unwrap_or(if height >= 720 {
85 Matrix::Bt709
86 } else {
87 Matrix::Bt601
88 }),
89 transfer: tags.transfer.unwrap_or(Transfer::Sdr),
90 full_range: tags.full_range.unwrap_or(false),
91 }
92 }
93
94 /// What an export of a `height`-line canvas *declares itself to be*, and
95 /// therefore what every clip on it is remapped into: the same 720-line rule
96 /// [`resolve`](Self::resolve)'s heuristic reads, so a file written here is
97 /// read back as the space it was written in even by a reader that drops the
98 /// tags. Limited range because both encoders here are configured for it, and
99 /// SDR because nothing on this path tone-maps yet.
100 pub fn output(height: u32) -> Self {
101 Self {
102 matrix: if height >= 720 {
103 Matrix::Bt709
104 } else {
105 Matrix::Bt601
106 },
107 transfer: Transfer::Sdr,
108 full_range: false,
109 }
110 }
111
112 /// The H.273 code points a container writes this as: primaries, transfer
113 /// characteristics, matrix coefficients. The same table Matroska's `Colour`
114 /// and mp4's `colr` both index, so one answer serves both muxers.
115 pub fn codes(self) -> (u16, u16, u16) {
116 // Primaries and the SDR curve travel with the matrix: a 709 file is
117 // 1/1/1 and an SD one 6/6/6 (SMPTE 170M), which is what ffmpeg writes
118 // for each and what a player expects to see together.
119 let (primaries, sdr_transfer, matrix) = match self.matrix {
120 Matrix::Bt709 => (1, 1, 1),
121 Matrix::Bt601 => (6, 6, 6),
122 Matrix::Bt2020Ncl => (9, 14, 9),
123 };
124 let transfer = match self.transfer {
125 Transfer::Sdr => sdr_transfer,
126 Transfer::Pq => 16,
127 Transfer::Hlg => 18,
128 };
129 (primaries, transfer, matrix)
130 }
131}
132
133/// Rewrites planar 4:2:0 samples coded against `from` as the same picture coded
134/// against `to`, in place. Both spaces here are limited range with the same
135/// primaries, so this is the matrix and nothing else: no gamut mapping, no range
136/// scaling, and the 16/128/128 of black lands on itself either way -- which is
137/// what makes a letterboxed bar and a gap's black frame cost nothing.
138///
139/// Derived from the two matrices, not tabulated: with R,G,B eliminated between
140/// them, luma picks up a chroma term and the two chroma planes mix only with
141/// each other -- so chroma never needs the luma plane and is remapped at its own
142/// resolution, while luma reads the co-sited chroma sample the way
143/// [`crate::convert::i420_to_bgra`] does. 8.8 fixed point, the same as every
144/// other matrix in this engine.
145///
146/// A no-op when the two spaces are the same, so the caller may hand any pair.
147pub fn remap(from: Matrix, to: Matrix, y: &mut [u8], u: &mut [u8], v: &mut [u8], width: usize) {
148 // BT.2020 is never an output here (see [`ColorDescription::output`]) and a
149 // 2020 source arrives on the tone-mapping path, not this one.
150 // On normalised samples the two rows are Y' = Y - 0.1182 Cb - 0.2127 Cr,
151 // Cb' = 1.0185 Cb + 0.1146 Cr, Cr' = 0.0751 Cb + 1.0251 Cr; in *code* values
152 // the luma row's chroma terms carry a further 219/224, the ratio of the two
153 // limited-range spans, while the chroma rows' do not (both sides are
154 // chroma). That is the whole difference between these numbers and the
155 // published ones.
156 let coeffs = match (from, to) {
157 (Matrix::Bt601, Matrix::Bt709) => [-30, -53, 261, 29, 19, 262],
158 // ...and its inverse, which round-trips to within a code.
159 (Matrix::Bt709, Matrix::Bt601) => [25, 49, 253, -28, -19, 252],
160 _ => return,
161 };
162 let [yb, yr, ub, ur, vb, vr] = coeffs;
163 let cw = width.div_ceil(2);
164 for (i, y) in y.iter_mut().enumerate() {
165 let (row, col) = (i / width, i % width);
166 let ci = (row / 2) * cw + col / 2;
167 let (d, e) = (u[ci] as i32 - 128, v[ci] as i32 - 128);
168 *y = (*y as i32 + ((yb * d + yr * e + 128) >> 8)).clamp(0, 255) as u8;
169 }
170 for (u, v) in u.iter_mut().zip(v) {
171 let (d, e) = (*u as i32 - 128, *v as i32 - 128);
172 *u = (128 + ((ub * d + ur * e + 128) >> 8)).clamp(0, 255) as u8;
173 *v = (128 + ((vb * d + vr * e + 128) >> 8)).clamp(0, 255) as u8;
174 }
175}
176
177/// One tier's worth of colour tags: what that tier said, field by field, with
178/// [`None`] for "said nothing" and for "said something this does not implement".
179#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
180pub struct Tags {
181 pub matrix: Option<Matrix>,
182 pub transfer: Option<Transfer>,
183 pub full_range: Option<bool>,
184}
185
186impl Tags {
187 /// H.273 code points, as every container and every bitstream writes them.
188 /// `range` is the Matroska `Range` code -- 0 unspecified, 1 limited, 2 full,
189 /// 3 "whatever the matrix implies", which is a non-answer here. A source
190 /// that carries a plain `video_full_range_flag` instead passes `1 + flag`.
191 pub fn from_codes(matrix: u64, transfer: u64, range: u64) -> Self {
192 Self {
193 matrix: match matrix {
194 1 => Some(Matrix::Bt709),
195 // 5 is BT.470BG (PAL), 6 SMPTE 170M (NTSC): one matrix, two
196 // names for the two halves of the world's SD television.
197 5 | 6 => Some(Matrix::Bt601),
198 9 => Some(Matrix::Bt2020Ncl),
199 // 0 unspecified, 2 reserved, 4 FCC, 7 SMPTE 240M, 10 BT.2020
200 // constant-luminance, 14 ICtCp: nothing this renders with.
201 _ => None,
202 },
203 transfer: match transfer {
204 16 => Some(Transfer::Pq),
205 18 => Some(Transfer::Hlg),
206 // Unspecified and reserved say nothing; every other assigned
207 // curve is displayed the way an SDR one is here.
208 0 | 2 => None,
209 _ => Some(Transfer::Sdr),
210 },
211 full_range: match range {
212 1 => Some(false),
213 2 => Some(true),
214 _ => None,
215 },
216 }
217 }
218
219 /// This tier's answers, with `next`'s used for whatever this one left open.
220 fn over(self, next: Self) -> Self {
221 Self {
222 matrix: self.matrix.or(next.matrix),
223 transfer: self.transfer.or(next.transfer),
224 full_range: self.full_range.or(next.full_range),
225 }
226 }
227}
228
229/// What the *encoder* wrote into the stream itself, out of the parameter sets
230/// the demuxers already hold: the SPS VUI for H.264 and HEVC (Annex-B framed,
231/// which is how both demuxers keep them) and the sequence header OBU for AV1.
232///
233/// Empty [`Tags`] for VP9, whose colour space lives in the uncompressed header
234/// of every frame rather than out of band, and for anything malformed: this is
235/// a middle tier, and the tier below it always has an answer.
236pub fn bitstream_tags(codec: Codec, sets: &[u8]) -> Tags {
237 match codec {
238 // 7 is an H.264 SPS, 33 an HEVC one (whose NAL header is two bytes and
239 // whose type sits in bits 1..6 of the first).
240 Codec::H264 => nal_units(sets)
241 .find(|n| n.first().is_some_and(|b| b & 0x1f == 7))
242 .map(|n| h264_sps(&rbsp(&n[1..])))
243 .unwrap_or_default(),
244 Codec::Hevc => nal_units(sets)
245 .find(|n| n.first().is_some_and(|b| (b >> 1) & 0x3f == 33))
246 .filter(|n| n.len() > 2)
247 .map(|n| hevc_sps(&rbsp(&n[2..])))
248 .unwrap_or_default(),
249 Codec::Av1 => av1_sequence_header(sets),
250 Codec::Vp9 => Tags::default(),
251 }
252}
253
254/// The Annex-B NAL units in `buf`, payloads only: start codes are three or four
255/// bytes and both are written in practice (the demuxers write four, an in-band
256/// stream may carry either).
257fn nal_units(buf: &[u8]) -> impl Iterator<Item = &[u8]> {
258 let mut at = 0;
259 std::iter::from_fn(move || {
260 // Find the next start code, then the one after it, which is where this
261 // unit ends.
262 let start = (at..buf.len().saturating_sub(2)).find(|&i| buf[i..i + 3] == [0, 0, 1])? + 3;
263 let end = (start..buf.len().saturating_sub(2))
264 .find(|&i| buf[i..i + 3] == [0, 0, 1])
265 .map(|i| {
266 if i > start && buf[i - 1] == 0 {
267 i - 1
268 } else {
269 i
270 }
271 })
272 .unwrap_or(buf.len());
273 at = end;
274 Some(&buf[start..end])
275 })
276}
277
278/// A NAL payload with its emulation-prevention bytes removed (H.264 §7.4.1.1,
279/// H.265 §7.4.2): a `00 00 03` in the coded bytes is a `00 00` that would
280/// otherwise have looked like a start code, and the `03` is not part of the
281/// syntax.
282fn rbsp(nal: &[u8]) -> Vec<u8> {
283 let mut out = Vec::with_capacity(nal.len());
284 let mut zeros = 0;
285 for &b in nal {
286 if zeros == 2 && b == 3 {
287 zeros = 0;
288 continue;
289 }
290 zeros = if b == 0 { zeros + 1 } else { 0 };
291 out.push(b);
292 }
293 out
294}
295
296/// MSB-first bit reader over an RBSP or an OBU. Reads past the end return zero
297/// and raise [`Bits::overrun`], which every parser here checks before it
298/// believes anything it read -- a truncated parameter set must fall to the next
299/// tier, not report the colour of whatever the zeros decoded to.
300struct Bits<'a> {
301 buf: &'a [u8],
302 /// Bit position, MSB of byte 0 first.
303 at: usize,
304 over: bool,
305}
306
307impl<'a> Bits<'a> {
308 fn new(buf: &'a [u8]) -> Self {
309 Self {
310 buf,
311 at: 0,
312 over: false,
313 }
314 }
315
316 fn overrun(&self) -> bool {
317 self.over
318 }
319
320 fn bit(&mut self) -> u32 {
321 let Some(&byte) = self.buf.get(self.at / 8) else {
322 self.over = true;
323 return 0;
324 };
325 let bit = u32::from(byte >> (7 - self.at % 8)) & 1;
326 self.at += 1;
327 bit
328 }
329
330 /// `u(n)`, up to 32 bits.
331 fn u(&mut self, n: u32) -> u32 {
332 (0..n).fold(0, |acc, _| (acc << 1) | self.bit())
333 }
334
335 /// Bits nothing here reads, in one step -- profile/tier records and the
336 /// like, which run to 88 bits at a time.
337 fn skip(&mut self, n: usize) {
338 self.at += n;
339 if self.at > self.buf.len() * 8 {
340 self.over = true;
341 }
342 }
343
344 /// `ue(v)`, unsigned exp-Golomb: N leading zeros, a one, then N more bits.
345 /// Capped at 32 leading zeros, which is past any legal value and is what
346 /// keeps a garbage set from spinning here.
347 fn ue(&mut self) -> u32 {
348 let mut zeros = 0;
349 while self.bit() == 0 {
350 zeros += 1;
351 if zeros >= 32 || self.over {
352 self.over = true;
353 return 0;
354 }
355 }
356 ((1u32 << zeros) - 1).wrapping_add(self.u(zeros))
357 }
358
359 /// `se(v)`, signed exp-Golomb: the unsigned code zig-zagged.
360 fn se(&mut self) -> i32 {
361 let k = self.ue();
362 if k % 2 == 0 {
363 -((k / 2) as i32)
364 } else {
365 ((k + 1) / 2) as i32
366 }
367 }
368}
369
370/// H.264 `seq_parameter_set_data` (ITU-T H.264 §7.3.2.1.1) walked as far as the
371/// VUI's `colour_description` (Annex E, §E.1.1). Everything before it is read
372/// only to know how many bits it took -- which is why the scaling lists matter:
373/// a High-profile SPS that carries them and is walked as if it did not lands the
374/// VUI read somewhere in the middle of a coefficient.
375fn h264_sps(rbsp: &[u8]) -> Tags {
376 let mut b = Bits::new(rbsp);
377 let profile_idc = b.u(8);
378 b.skip(8 + 8); // constraint flags + reserved, level_idc
379 b.ue(); // seq_parameter_set_id
380 // The chroma/depth block exists only in the profiles that can code
381 // something other than 8-bit 4:2:0 (§7.3.2.1.1, the profile_idc list).
382 if matches!(
383 profile_idc,
384 100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135
385 ) {
386 let chroma_format_idc = b.ue();
387 if chroma_format_idc == 3 {
388 b.bit(); // separate_colour_plane_flag
389 }
390 b.ue(); // bit_depth_luma_minus8
391 b.ue(); // bit_depth_chroma_minus8
392 b.bit(); // qpprime_y_zero_transform_bypass_flag
393 if b.bit() == 1 {
394 // seq_scaling_matrix_present_flag: 8 lists (12 for 4:4:4), the
395 // first six 16 coefficients long and the rest 64 (§7.3.2.1.1.1).
396 let lists = if chroma_format_idc == 3 { 12 } else { 8 };
397 for i in 0..lists {
398 if b.bit() == 1 {
399 scaling_list(&mut b, if i < 6 { 16 } else { 64 });
400 }
401 }
402 }
403 }
404 b.ue(); // log2_max_frame_num_minus4
405 match b.ue() {
406 // pic_order_cnt_type
407 0 => {
408 b.ue(); // log2_max_pic_order_cnt_lsb_minus4
409 }
410 1 => {
411 b.bit(); // delta_pic_order_always_zero_flag
412 b.se(); // offset_for_non_ref_pic
413 b.se(); // offset_for_top_to_bottom_field
414 let cycle = b.ue();
415 if cycle > 255 {
416 return Tags::default();
417 }
418 for _ in 0..cycle {
419 b.se(); // offset_for_ref_frame[i]
420 }
421 }
422 _ => {}
423 }
424 b.ue(); // max_num_ref_frames
425 b.bit(); // gaps_in_frame_num_value_allowed_flag
426 b.ue(); // pic_width_in_mbs_minus1
427 b.ue(); // pic_height_in_map_units_minus1
428 if b.bit() == 0 {
429 b.bit(); // mb_adaptive_frame_field_flag, when !frame_mbs_only_flag
430 }
431 b.bit(); // direct_8x8_inference_flag
432 if b.bit() == 1 {
433 // frame_cropping_flag: four offsets
434 for _ in 0..4 {
435 b.ue();
436 }
437 }
438 if b.bit() == 0 {
439 return Tags::default(); // no VUI at all
440 }
441 vui_colour(&mut b)
442}
443
444/// One H.264 scaling list (§7.3.2.1.1.1): `size` deltas, the run stopping early
445/// once a `nextScale` of zero says the rest of the list is the default one.
446fn scaling_list(b: &mut Bits, size: usize) {
447 let mut next = 8;
448 for _ in 0..size {
449 if next != 0 {
450 next = (next + b.se() + 256) % 256;
451 }
452 if b.overrun() {
453 return;
454 }
455 }
456}
457
458/// HEVC `seq_parameter_set_rbsp` (ITU-T H.265 §7.3.2.2.1) to its VUI
459/// (§E.2.1). The two places bits are easy to lose are the profile/tier record
460/// (§7.3.3) and the short-term reference picture sets (§7.3.7), both of which
461/// are counted here rather than read.
462fn hevc_sps(rbsp: &[u8]) -> Tags {
463 let mut b = Bits::new(rbsp);
464 b.skip(4); // sps_video_parameter_set_id
465 let max_sub_layers_minus1 = b.u(3);
466 b.bit(); // sps_temporal_id_nesting_flag
467 profile_tier_level(&mut b, max_sub_layers_minus1);
468 b.ue(); // sps_seq_parameter_set_id
469 let chroma_format_idc = b.ue();
470 if chroma_format_idc == 3 {
471 b.bit(); // separate_colour_plane_flag
472 }
473 b.ue(); // pic_width_in_luma_samples
474 b.ue(); // pic_height_in_luma_samples
475 if b.bit() == 1 {
476 // conformance_window_flag
477 for _ in 0..4 {
478 b.ue();
479 }
480 }
481 b.ue(); // bit_depth_luma_minus8
482 b.ue(); // bit_depth_chroma_minus8
483 let log2_max_poc_lsb = b.ue() + 4;
484 let ordering_info = b.bit() == 1;
485 let first = if ordering_info {
486 0
487 } else {
488 max_sub_layers_minus1
489 };
490 for _ in first..=max_sub_layers_minus1 {
491 b.ue(); // sps_max_dec_pic_buffering_minus1
492 b.ue(); // sps_max_num_reorder_pics
493 b.ue(); // sps_max_latency_increase_plus1
494 }
495 for _ in 0..6 {
496 // log2_min_luma_coding_block_size_minus3 through
497 // max_transform_hierarchy_depth_intra: six plain ue(v)s.
498 b.ue();
499 }
500 if b.bit() == 1 && b.bit() == 1 {
501 // scaling_list_enabled_flag && sps_scaling_list_data_present_flag
502 scaling_list_data(&mut b);
503 }
504 b.bit(); // amp_enabled_flag
505 b.bit(); // sample_adaptive_offset_enabled_flag
506 if b.bit() == 1 {
507 // pcm_enabled_flag
508 b.skip(8); // pcm_sample_bit_depth_luma/chroma_minus1
509 b.ue(); // log2_min_pcm_luma_coding_block_size_minus3
510 b.ue(); // log2_diff_max_min_pcm_luma_coding_block_size
511 b.bit(); // pcm_loop_filter_disabled_flag
512 }
513 let sets = b.ue();
514 if sets > 64 || b.overrun() {
515 return Tags::default();
516 }
517 let mut counts = Vec::with_capacity(sets as usize);
518 for i in 0..sets as usize {
519 st_ref_pic_set(&mut b, i, &mut counts);
520 if b.overrun() {
521 return Tags::default();
522 }
523 }
524 if b.bit() == 1 {
525 // long_term_ref_pics_present_flag
526 let lt = b.ue();
527 if lt > 64 {
528 return Tags::default();
529 }
530 for _ in 0..lt {
531 b.skip(log2_max_poc_lsb as usize); // lt_ref_pic_poc_lsb_sps[i]
532 b.bit(); // used_by_curr_pic_lt_sps_flag[i]
533 }
534 }
535 b.bit(); // sps_temporal_mvp_enabled_flag
536 b.bit(); // strong_intra_smoothing_enabled_flag
537 if b.bit() == 0 {
538 return Tags::default(); // no VUI at all
539 }
540 vui_colour(&mut b)
541}
542
543/// `profile_tier_level` (§7.3.3), counted: 2+1+5 bits of general profile, 32
544/// compatibility flags, 48 bits of source/reserved flags and an 8-bit level,
545/// then one 88-bit record per sub-layer that declares one.
546fn profile_tier_level(b: &mut Bits, max_sub_layers_minus1: u32) {
547 b.skip(2 + 1 + 5 + 32 + 48 + 8);
548 let mut present = [(false, false); 8];
549 for slot in present.iter_mut().take(max_sub_layers_minus1 as usize) {
550 *slot = (b.bit() == 1, b.bit() == 1);
551 }
552 if max_sub_layers_minus1 > 0 {
553 // reserved_zero_2bits up to eight sub-layers.
554 b.skip(2 * (8 - max_sub_layers_minus1 as usize));
555 }
556 for &(profile, level) in present.iter().take(max_sub_layers_minus1 as usize) {
557 if profile {
558 b.skip(88);
559 }
560 if level {
561 b.skip(8);
562 }
563 }
564}
565
566/// `scaling_list_data` (§7.3.4): four sizes of six matrices each (the last size
567/// has two), either predicted from an earlier matrix or written out as deltas.
568fn scaling_list_data(b: &mut Bits) {
569 for size_id in 0..4 {
570 let step = if size_id == 3 { 3 } else { 1 };
571 for _ in (0..6).step_by(step) {
572 if b.bit() == 0 {
573 b.ue(); // scaling_list_pred_matrix_id_delta
574 continue;
575 }
576 let coefs = 64.min(1 << (4 + (size_id << 1)));
577 if size_id > 1 {
578 b.se(); // scaling_list_dc_coef_minus8
579 }
580 for _ in 0..coefs {
581 b.se(); // scaling_list_delta_coef
582 }
583 if b.overrun() {
584 return;
585 }
586 }
587 }
588}
589
590/// One `st_ref_pic_set` (§7.3.7), kept only for the number of pictures it
591/// holds: that count is what the *next* set spends a flag per picture on when
592/// it predicts from this one, so losing it loses the bit position.
593///
594/// ponytail: the predicted case counts flags rather than deriving the POCs
595/// (§7.4.8, (7-59)..(7-71)), so a set whose `deltaRps` cancels a reference's
596/// own delta exactly -- a picture at POC distance zero, which is the current
597/// picture and which no encoder emits -- would be counted one too high. The
598/// upgrade path is carrying the `DeltaPocS0/S1` arrays through the loop; the
599/// price of being wrong is a VUI that reads as garbage and falls to the
600/// resolution heuristic, not a bad picture.
601fn st_ref_pic_set(b: &mut Bits, idx: usize, counts: &mut Vec<u32>) {
602 if idx > 0 && b.bit() == 1 {
603 b.bit(); // delta_rps_sign
604 b.ue(); // abs_delta_rps_minus1
605 let mut kept = 0;
606 for _ in 0..=counts[idx - 1] {
607 // used_by_curr_pic_flag, and use_delta_flag only when it is not.
608 let used = b.bit() == 1;
609 kept += u32::from(used || b.bit() == 1);
610 }
611 counts.push(kept);
612 return;
613 }
614 let negative = b.ue();
615 let positive = b.ue();
616 if negative > 64 || positive > 64 {
617 b.over = true;
618 counts.push(0);
619 return;
620 }
621 for _ in 0..negative + positive {
622 b.ue(); // delta_poc_s0/s1_minus1
623 b.bit(); // used_by_curr_pic_s0/s1_flag
624 }
625 counts.push(negative + positive);
626}
627
628/// The head of a VUI, H.264 (§E.1.1) and HEVC (§E.2.1) alike -- the two are
629/// byte-identical up to and including `colour_description`, which is all that is
630/// read here.
631fn vui_colour(b: &mut Bits) -> Tags {
632 if b.bit() == 1 {
633 // aspect_ratio_info_present_flag
634 if b.u(8) == 255 {
635 // Extended_SAR: the ratio is written out rather than indexed.
636 b.skip(32);
637 }
638 }
639 if b.bit() == 1 {
640 b.bit(); // overscan_appropriate_flag
641 }
642 if b.bit() == 0 {
643 return Tags::default(); // no video_signal_type at all
644 }
645 b.skip(3); // video_format
646 let full_range = b.bit();
647 if b.bit() == 0 || b.overrun() {
648 // colour_description_present_flag: the range flag still stands on its
649 // own, which is what an untagged-but-full-range stream says.
650 return Tags {
651 full_range: (!b.overrun()).then_some(full_range == 1),
652 ..Tags::default()
653 };
654 }
655 let (primaries, transfer, matrix) = (b.u(8), b.u(8), b.u(8));
656 let _ = primaries;
657 if b.overrun() {
658 return Tags::default();
659 }
660 Tags::from_codes(
661 u64::from(matrix),
662 u64::from(transfer),
663 u64::from(full_range) + 1,
664 )
665}
666
667/// `color_config` out of the sequence header OBU (AV1 §5.5.1, §5.5.2), which is
668/// what `av1C`/`CodecPrivate` carries and what both demuxers re-inject ahead of
669/// every keyframe. The whole header before it is counted, and most of it is
670/// conditional -- the operating points and the decoder model in particular.
671fn av1_sequence_header(obus: &[u8]) -> Tags {
672 let Some(payload) = sequence_header_obu(obus) else {
673 return Tags::default();
674 };
675 let mut b = Bits::new(payload);
676 let seq_profile = b.u(3);
677 b.bit(); // still_picture
678 let reduced = b.bit() == 1;
679 let mut decoder_model = false;
680 if reduced {
681 b.skip(5); // seq_level_idx[0]
682 } else {
683 if b.bit() == 1 {
684 // timing_info: two 32-bit ticks and, if the interval is fixed, a
685 // uvlc() -- the one variable-length code in this header.
686 b.skip(64);
687 if b.bit() == 1 {
688 uvlc(&mut b);
689 }
690 decoder_model = b.bit() == 1;
691 if decoder_model {
692 b.skip(5 + 32 + 5 + 5);
693 }
694 }
695 let initial_display_delay = b.bit() == 1;
696 let operating_points = b.u(5) + 1;
697 for _ in 0..operating_points {
698 b.skip(12); // operating_point_idc[i]
699 let level = b.u(5);
700 if level > 7 {
701 b.bit(); // seq_tier[i]
702 }
703 if decoder_model && b.bit() == 1 {
704 // operating_parameters_info: two delays of the length the
705 // decoder model declared, plus low_delay_mode_flag. The lengths
706 // were skipped above, so a file with a decoder model is where
707 // this walk stops being able to count.
708 return Tags::default();
709 }
710 if initial_display_delay && b.bit() == 1 {
711 b.skip(4); // initial_display_delay_minus_1[i]
712 }
713 }
714 }
715 let width_bits = b.u(4) + 1;
716 let height_bits = b.u(4) + 1;
717 b.skip((width_bits + height_bits) as usize); // max_frame_width/height_minus_1
718 if !reduced && b.bit() == 1 {
719 b.skip(4 + 3); // delta/additional frame id lengths
720 }
721 b.skip(3); // use_128x128_superblock, enable_filter_intra, intra_edge_filter
722 if !reduced {
723 b.skip(4); // enable_interintra_compound .. enable_dual_filter
724 let order_hint = b.bit() == 1;
725 if order_hint {
726 b.skip(2); // enable_jnt_comp, enable_ref_frame_mvs
727 }
728 // seq_choose_screen_content_tools, or the forced value when it is not
729 // chosen; the integer-mv pair after it exists only when the tools do.
730 let screen_content = if b.bit() == 1 { 2 } else { b.bit() };
731 if screen_content > 0 && b.bit() == 0 {
732 b.bit(); // seq_force_integer_mv
733 }
734 if order_hint {
735 b.skip(3); // order_hint_bits_minus_1
736 }
737 }
738 b.skip(3); // enable_superres, enable_cdef, enable_restoration
739 av1_color_config(&mut b, seq_profile)
740}
741
742/// The payload of the first sequence header OBU (type 1) in a low-overhead OBU
743/// stream (AV1 §5.3.1): a one-byte header, an optional extension byte, and an
744/// optional leb128 size.
745fn sequence_header_obu(mut buf: &[u8]) -> Option<&[u8]> {
746 while let Some((&head, rest)) = buf.split_first() {
747 let kind = (head >> 3) & 0xf;
748 let mut rest = rest;
749 if head & 0x4 != 0 {
750 rest = rest.get(1..)?; // obu_extension_flag: temporal/spatial ids
751 }
752 let size = if head & 0x2 != 0 {
753 let (size, read) = leb128(rest)?;
754 rest = rest.get(read..)?;
755 size.min(rest.len())
756 } else {
757 rest.len()
758 };
759 if kind == 1 {
760 return rest.get(..size);
761 }
762 buf = rest.get(size..)?;
763 }
764 None
765}
766
767/// leb128 as AV1 writes it (§4.10.5): seven bits a byte, low group first, the
768/// top bit saying another follows.
769fn leb128(buf: &[u8]) -> Option<(usize, usize)> {
770 let mut value = 0usize;
771 for i in 0..8 {
772 let &byte = buf.get(i)?;
773 value |= usize::from(byte & 0x7f) << (i * 7);
774 if byte & 0x80 == 0 {
775 return Some((value, i + 1));
776 }
777 }
778 None
779}
780
781/// `uvlc()` (AV1 §4.10.3): leading zeros, then that many bits, biased -- the
782/// same shape as exp-Golomb with a different bias.
783fn uvlc(b: &mut Bits) {
784 let mut zeros = 0;
785 while b.bit() == 0 && !b.overrun() {
786 zeros += 1;
787 if zeros >= 32 {
788 b.over = true;
789 return;
790 }
791 }
792 b.skip(zeros);
793}
794
795/// `color_config` (AV1 §5.5.2). The bit depth and the subsampling are read only
796/// as far as they cost bits before `color_range`.
797fn av1_color_config(b: &mut Bits, seq_profile: u32) -> Tags {
798 let high_bitdepth = b.bit() == 1;
799 if seq_profile == 2 && high_bitdepth {
800 b.bit(); // twelve_bit
801 }
802 let mono_chrome = seq_profile != 1 && b.bit() == 1;
803 let described = b.bit() == 1;
804 let (primaries, transfer, matrix) = if described {
805 (b.u(8), b.u(8), b.u(8))
806 } else {
807 (2, 2, 2) // CP/TC/MC_UNSPECIFIED
808 };
809 if b.overrun() {
810 return Tags::default();
811 }
812 let full_range = if mono_chrome {
813 b.bit() == 1
814 } else if primaries == 1 && transfer == 13 && matrix == 0 {
815 // sRGB in an identity matrix is full range by definition, and the flag
816 // is not written.
817 true
818 } else {
819 b.bit() == 1
820 };
821 if b.overrun() {
822 return Tags::default();
823 }
824 Tags {
825 full_range: Some(full_range),
826 ..Tags::from_codes(u64::from(matrix), u64::from(transfer), 0)
827 }
828}
829
830#[cfg(test)]
831mod tests {
832 use super::*;
833 use crate::demux::Demuxer;
834 use std::path::{Path, PathBuf};
835
836 fn asset(name: &str) -> PathBuf {
837 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
838 .join("../../assets")
839 .join(name)
840 }
841
842 fn color_of(name: &str) -> ColorDescription {
843 let (meta, _) = Demuxer::open(&asset(name)).unwrap_or_else(|e| panic!("open {name}: {e}"));
844 meta.color
845 }
846
847 /// The tier order itself: a container tag beats both a bitstream tag and the
848 /// heuristic, field by field.
849 #[test]
850 fn tiers_resolve_in_order() {
851 let container = Tags::from_codes(9, 16, 1);
852 let bitstream = Tags::from_codes(1, 1, 2);
853 assert_eq!(
854 ColorDescription::resolve(container, bitstream, 2160),
855 ColorDescription {
856 matrix: Matrix::Bt2020Ncl,
857 transfer: Transfer::Pq,
858 full_range: false,
859 }
860 );
861 // A container that tagged only the range leaves the rest to the SPS.
862 let range_only = Tags::from_codes(0, 0, 2);
863 assert_eq!(
864 ColorDescription::resolve(range_only, bitstream, 480),
865 ColorDescription {
866 matrix: Matrix::Bt709,
867 transfer: Transfer::Sdr,
868 full_range: true,
869 }
870 );
871 // Nothing anywhere: the resolution decides, and only the resolution.
872 let none = Tags::default();
873 assert_eq!(
874 ColorDescription::resolve(none, none, 1080).matrix,
875 Matrix::Bt709
876 );
877 assert_eq!(
878 ColorDescription::resolve(none, none, 719).matrix,
879 Matrix::Bt601
880 );
881 assert_eq!(
882 ColorDescription::default(),
883 ColorDescription::resolve(none, none, 480)
884 );
885 }
886
887 /// Reserved and unimplemented code points are "said nothing", not a wrong
888 /// answer: that is what makes them fall through.
889 #[test]
890 fn unknown_codes_fall_through() {
891 assert_eq!(Tags::from_codes(2, 2, 3), Tags::default());
892 assert_eq!(Tags::from_codes(7, 0, 0).matrix, None); // SMPTE 240M
893 assert_eq!(Tags::from_codes(6, 1, 1).transfer, Some(Transfer::Sdr));
894 assert_eq!(Tags::from_codes(0, 18, 2).transfer, Some(Transfer::Hlg));
895 }
896
897 /// The bit reader, against a hand-built pattern: exp-Golomb is where a
898 /// mis-read shifts everything after it.
899 #[test]
900 fn bit_reader_reads_exp_golomb() {
901 // 1 | 010 | 011 | 00100 : ue = 0, 1, 2, 3
902 let mut b = Bits::new(&[0b1010_0110, 0b0100_0000]);
903 assert_eq!((b.ue(), b.ue(), b.ue(), b.ue()), (0, 1, 2, 3));
904 assert!(!b.overrun());
905 // se zig-zags: 0, 1, -1, 2
906 let mut b = Bits::new(&[0b1010_0110, 0b0100_0000]);
907 assert_eq!((b.se(), b.se(), b.se(), b.se()), (0, 1, -1, 2));
908 // Past the end reads zero and says so.
909 let mut b = Bits::new(&[0xff]);
910 b.skip(8);
911 assert_eq!(b.u(4), 0);
912 assert!(b.overrun());
913 }
914
915 /// Emulation prevention: the `03` is syntax-invisible, a third `00` is not.
916 #[test]
917 fn rbsp_drops_emulation_bytes() {
918 assert_eq!(rbsp(&[0, 0, 3, 1, 0, 0, 3, 0]), vec![0, 0, 1, 0, 0, 0]);
919 assert_eq!(rbsp(&[0, 3, 3]), vec![0, 3, 3]);
920 }
921
922 /// A generated fixture whose *container* says BT.601 at 720 lines, where the
923 /// heuristic would have said BT.709: proof the container tier is read and
924 /// that it wins. Both containers, because both parse it themselves.
925 #[test]
926 fn container_tags_win_over_the_heuristic() {
927 for name in ["test_bt601.mp4", "test_bt601.mkv"] {
928 assert_eq!(
929 color_of(name),
930 ColorDescription {
931 matrix: Matrix::Bt601,
932 transfer: Transfer::Sdr,
933 full_range: false,
934 },
935 "{name}"
936 );
937 }
938 }
939
940 /// Bits written out as `'0'`/`'1'`, MSB first, for a hand-built SPS.
941 fn bits_of(pattern: &str) -> Vec<u8> {
942 let mut out = Vec::new();
943 for (i, c) in pattern.chars().filter(|c| !c.is_whitespace()).enumerate() {
944 if i % 8 == 0 {
945 out.push(0);
946 }
947 if c == '1' {
948 *out.last_mut().unwrap() |= 0x80 >> (i % 8);
949 }
950 }
951 out
952 }
953
954 /// A High-profile SPS written by hand, because no encoder here writes one
955 /// with its scaling lists in the *sequence* parameter set (x264 puts its
956 /// quant matrices in the PPS; the HEVC fixture below has real ones). The
957 /// lists are what makes this test worth having: read as if they were not
958 /// there, the VUI lands mid-coefficient and the colour comes out as noise.
959 #[test]
960 fn h264_scaling_lists_are_skipped_before_the_vui() {
961 let sps = concat!(
962 "01100100", // profile_idc 100 (High)
963 "00000000", // constraint flags + reserved
964 "00011110", // level_idc 30
965 "1", // seq_parameter_set_id ue(0)
966 "010", // chroma_format_idc ue(1), 4:2:0
967 "1", // bit_depth_luma_minus8 ue(0)
968 "1", // bit_depth_chroma_minus8 ue(0)
969 "0", // qpprime_y_zero_transform_bypass_flag
970 "1", // seq_scaling_matrix_present_flag
971 "1", // ...list 0 present
972 "000010001", // its first delta, se(-8): nextScale hits 0, so the
973 // remaining 15 coefficients are the default ones and cost no bits
974 "0000000", // lists 1..7 absent
975 "1", // log2_max_frame_num_minus4 ue(0)
976 "1", // pic_order_cnt_type ue(0)
977 "1", // log2_max_pic_order_cnt_lsb_minus4 ue(0)
978 "010", // max_num_ref_frames ue(1)
979 "0", // gaps_in_frame_num_value_allowed_flag
980 "00000101000", // pic_width_in_mbs_minus1 ue(39), i.e. 640
981 "000011110", // pic_height_in_map_units_minus1 ue(29), i.e. 480
982 "1", // frame_mbs_only_flag
983 "1", // direct_8x8_inference_flag
984 "0", // frame_cropping_flag
985 "1", // vui_parameters_present_flag
986 "0", // aspect_ratio_info_present_flag
987 "0", // overscan_info_present_flag
988 "1", // video_signal_type_present_flag
989 "101", // video_format (unspecified)
990 "0", // video_full_range_flag
991 "1", // colour_description_present_flag
992 "00000001", // colour_primaries 1
993 "00000001", // transfer_characteristics 1
994 "00000001", // matrix_coefficients 1 (BT.709)
995 );
996 assert_eq!(
997 h264_sps(&bits_of(sps)),
998 Tags {
999 matrix: Some(Matrix::Bt709),
1000 transfer: Some(Transfer::Sdr),
1001 full_range: Some(false),
1002 }
1003 );
1004 }
1005
1006 /// The HEVC twin of the test above, and hand-built for the same reason:
1007 /// x265 writes `sps_scaling_list_data_present_flag` only for a *custom*
1008 /// list, and the fixture below carries the default one (a flag and no
1009 /// data). Custom lists are not exotic -- they are what a psy-tuned anime
1010 /// encode ships -- so the branch that counts them has to be measured.
1011 #[test]
1012 fn hevc_scaling_list_data_is_skipped_before_the_vui() {
1013 let mut sps = String::new();
1014 sps.push_str("0000"); // sps_video_parameter_set_id
1015 sps.push_str("000"); // sps_max_sub_layers_minus1: one layer
1016 sps.push('0'); // sps_temporal_id_nesting_flag
1017 sps.push_str(&"0".repeat(96)); // profile_tier_level, general only
1018 sps.push('1'); // sps_seq_parameter_set_id ue(0)
1019 sps.push_str("010"); // chroma_format_idc ue(1), 4:2:0
1020 sps.push_str("0000000001010000001"); // pic_width_in_luma_samples ue(640)
1021 sps.push_str("00000000111100001"); // pic_height_in_luma_samples ue(480)
1022 sps.push('0'); // conformance_window_flag
1023 sps.push_str("11"); // bit_depth_luma/chroma_minus8 ue(0)
1024 sps.push_str("00101"); // log2_max_pic_order_cnt_lsb_minus4 ue(4)
1025 sps.push('1'); // sps_sub_layer_ordering_info_present_flag
1026 sps.push_str("111"); // ...its three ue(0)s, for the one layer
1027 sps.push_str("111111"); // the six coding/transform-block ue(0)s
1028 sps.push_str("11"); // scaling_list_enabled + sps_scaling_list_data_present
1029 // scaling_list_data: the first 4x4 matrix written out (16 se(0) deltas,
1030 // no DC coefficient at this size), every other matrix predicted from an
1031 // earlier one -- 6+6+6+2 matrices in all.
1032 sps.push('1');
1033 sps.push_str(&"1".repeat(16));
1034 sps.push_str(&"01".repeat(5 + 6 + 6 + 2));
1035 sps.push_str("000"); // amp, sample_adaptive_offset, pcm_enabled
1036 sps.push('1'); // num_short_term_ref_pic_sets ue(0)
1037 sps.push('0'); // long_term_ref_pics_present_flag
1038 sps.push_str("00"); // sps_temporal_mvp, strong_intra_smoothing
1039 sps.push('1'); // vui_parameters_present_flag
1040 sps.push_str("00"); // aspect_ratio_info_present, overscan_info_present
1041 sps.push('1'); // video_signal_type_present_flag
1042 sps.push_str("101"); // video_format (unspecified)
1043 sps.push('0'); // video_full_range_flag
1044 sps.push('1'); // colour_description_present_flag
1045 sps.push_str("000000010000000100000001"); // primaries/transfer/matrix 1
1046 assert_eq!(
1047 hevc_sps(&bits_of(&sps)),
1048 Tags {
1049 matrix: Some(Matrix::Bt709),
1050 transfer: Some(Transfer::Sdr),
1051 full_range: Some(false),
1052 }
1053 );
1054 }
1055
1056 /// The bitstream tier, in the three codecs that carry one: fixtures tagged
1057 /// through the *encoder* alone (x264/x265 VUI, SVT-AV1 `color_config`) and
1058 /// muxed with no `colr` box at all, at 480 lines where the heuristic would
1059 /// have said BT.601. The absence of the box is asserted too: without it a
1060 /// fixture that grew container tags would pass this for the wrong reason.
1061 /// The H.264 one is High profile with `cqm=jvt`, i.e. a real SPS with
1062 /// scaling lists in front of its VUI.
1063 #[test]
1064 fn bitstream_tags_beat_the_heuristic() {
1065 for name in ["test_vui_h264.mp4", "test_vui_hevc.mp4", "test_vui_av1.mp4"] {
1066 let bytes = std::fs::read(asset(name)).unwrap_or_else(|e| panic!("read {name}: {e}"));
1067 assert!(
1068 !bytes.windows(4).any(|w| w == b"colr"),
1069 "{name} carries a colr box, so this would not be testing the bitstream"
1070 );
1071 assert_eq!(color_of(name).matrix, Matrix::Bt709, "{name}");
1072 }
1073 }
1074
1075 /// An untagged 360-line fixture: nothing in the container, nothing in the
1076 /// stream, so the heuristic answers -- BT.601 limited, which is what the
1077 /// engine assumed of everything before any of this was read.
1078 #[test]
1079 fn untagged_sd_falls_to_the_heuristic() {
1080 assert_eq!(color_of("test_mismatch.mp4"), ColorDescription::default());
1081 }
1082
1083 /// A real HDR film: BT.2020 non-constant-luminance, PQ, limited range, all
1084 /// three off the Matroska `Colour` element. Gated on the file being here --
1085 /// it is a 25 GB download, not a fixture.
1086 #[test]
1087 fn real_hdr_film_reads_bt2020_pq() {
1088 let path = Path::new(
1089 "/path/to/a-real-4k-hdr10-film.mkv",
1090 );
1091 if !path.exists() {
1092 eprintln!("skipped: {} is not on this machine", path.display());
1093 return;
1094 }
1095 let (meta, _) = Demuxer::open(path).expect("open the HDR film");
1096 assert_eq!(
1097 meta.color,
1098 ColorDescription {
1099 matrix: Matrix::Bt2020Ncl,
1100 transfer: Transfer::Pq,
1101 full_range: false,
1102 }
1103 );
1104 }
1105
1106 /// A real 720p film with no colour tags anywhere -- neither container nor
1107 /// SPS -- which is the case the heuristic exists for: BT.709, because it is
1108 /// HD material. Gated for the same reason as the one above.
1109 #[test]
1110 fn real_untagged_hd_film_reads_bt709() {
1111 let path = Path::new(
1112 "/path/to/a-real-h264-dual-audio-film.mkv",
1113 );
1114 if !path.exists() {
1115 eprintln!("skipped: {} is not on this machine", path.display());
1116 return;
1117 }
1118 let (meta, _) = Demuxer::open(path).expect("open the untagged film");
1119 assert_eq!(
1120 meta.color,
1121 ColorDescription {
1122 matrix: Matrix::Bt709,
1123 transfer: Transfer::Sdr,
1124 full_range: false,
1125 }
1126 );
1127 }
1128
1129 /// The rule an export declares itself by, and the reason it is the *same*
1130 /// rule the heuristic reads: a file written here says out loud what a reader
1131 /// with no tags would have assumed anyway.
1132 #[test]
1133 fn an_output_declares_the_space_its_height_implies() {
1134 assert_eq!(ColorDescription::output(1080).matrix, Matrix::Bt709);
1135 assert_eq!(ColorDescription::output(720).matrix, Matrix::Bt709);
1136 assert_eq!(ColorDescription::output(576).matrix, Matrix::Bt601);
1137 for height in [480, 1080] {
1138 let out = ColorDescription::output(height);
1139 assert_eq!(out.transfer, Transfer::Sdr);
1140 assert!(!out.full_range, "both encoders here are limited range");
1141 }
1142 // What the two containers write, in the one table both index.
1143 assert_eq!(ColorDescription::output(1080).codes(), (1, 1, 1));
1144 assert_eq!(ColorDescription::output(480).codes(), (6, 6, 6));
1145 }
1146
1147 /// Limited-range 4:2:0 samples for one colour, in `matrix`, the float way --
1148 /// what a correct encoder would have written.
1149 fn encode(matrix: Matrix, rgb: [f64; 3]) -> (u8, u8, u8) {
1150 let (kr, kb) = weights(matrix);
1151 let [r, g, b] = rgb.map(|c| c / 255.0);
1152 let luma = kr * r + (1.0 - kr - kb) * g + kb * b;
1153 let round = |x: f64| x.round().clamp(0.0, 255.0) as u8;
1154 (
1155 round(16.0 + 219.0 * luma),
1156 round(128.0 + 224.0 * 0.5 * (b - luma) / (1.0 - kb)),
1157 round(128.0 + 224.0 * 0.5 * (r - luma) / (1.0 - kr)),
1158 )
1159 }
1160
1161 /// ...and back out of `matrix`, unrounded, which is what a player shows.
1162 fn decode(matrix: Matrix, (y, u, v): (u8, u8, u8)) -> [f64; 3] {
1163 let (kr, kb) = weights(matrix);
1164 let luma = (f64::from(y) - 16.0) / 219.0;
1165 let cb = (f64::from(u) - 128.0) / 224.0;
1166 let cr = (f64::from(v) - 128.0) / 224.0;
1167 let r = luma + 2.0 * (1.0 - kr) * cr;
1168 let b = luma + 2.0 * (1.0 - kb) * cb;
1169 let g = (luma - kr * r - kb * b) / (1.0 - kr - kb);
1170 [r, g, b].map(|c| c * 255.0)
1171 }
1172
1173 fn weights(matrix: Matrix) -> (f64, f64) {
1174 match matrix {
1175 Matrix::Bt601 => (0.299, 0.114),
1176 Matrix::Bt709 => (0.2126, 0.0722),
1177 Matrix::Bt2020Ncl => (0.2627, 0.0593),
1178 }
1179 }
1180
1181 /// One colour as a 2x2 picture -- four luma samples over one chroma pair,
1182 /// the smallest thing [`remap`] indexes the way it indexes a frame.
1183 fn tile((y, u, v): (u8, u8, u8)) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
1184 (vec![y; 4], vec![u], vec![v])
1185 }
1186
1187 /// The claim the whole reconcile rests on: samples coded against one matrix,
1188 /// remapped, and then *decoded by the other matrix* are the colour that went
1189 /// in -- not a second conversion of it. Within a code or two, which is what
1190 /// 8-bit 8.8 fixed point can promise.
1191 #[test]
1192 fn a_remap_is_the_same_colour_read_by_the_other_matrix() {
1193 let colours = [
1194 [255.0, 0.0, 0.0],
1195 [0.0, 255.0, 0.0],
1196 [0.0, 0.0, 255.0],
1197 [255.0, 255.0, 0.0],
1198 [18.0, 200.0, 140.0],
1199 [128.0, 128.0, 128.0],
1200 [235.0, 210.0, 30.0],
1201 ];
1202 for (from, to) in [
1203 (Matrix::Bt601, Matrix::Bt709),
1204 (Matrix::Bt709, Matrix::Bt601),
1205 ] {
1206 for rgb in colours {
1207 let (mut y, mut u, mut v) = tile(encode(from, rgb));
1208 remap(from, to, &mut y, &mut u, &mut v, 2);
1209 let out = decode(to, (y[0], u[0], v[0]));
1210 for (want, got) in rgb.iter().zip(&out) {
1211 assert!(
1212 (want - got).abs() <= 2.0,
1213 "{from:?}->{to:?} {rgb:?} came out {out:?}"
1214 );
1215 }
1216 }
1217 }
1218 }
1219
1220 /// Black, white and neutral grey are the same samples in both matrices, and
1221 /// a remap has to leave them alone: those are the letterbox bars, the gap
1222 /// frames and every grey in the picture, and a shift there is visible as a
1223 /// tint on nothing at all.
1224 #[test]
1225 fn a_remap_leaves_the_greys_where_they_are() {
1226 for (from, to) in [
1227 (Matrix::Bt601, Matrix::Bt709),
1228 (Matrix::Bt709, Matrix::Bt601),
1229 ] {
1230 for luma in [16u8, 128, 235] {
1231 let (mut y, mut u, mut v) = tile((luma, 128, 128));
1232 remap(from, to, &mut y, &mut u, &mut v, 2);
1233 assert_eq!((y[0], u[0], v[0]), (luma, 128, 128), "{from:?}->{to:?}");
1234 }
1235 }
1236 }
1237
1238 /// The export's zero-cost path, asserted where it is decided: a clip already
1239 /// in the file's own space comes out byte for byte the samples it went in
1240 /// as, so an ordinary single-space project is not touched by any of this.
1241 #[test]
1242 fn a_same_space_remap_touches_nothing() {
1243 let mut y: Vec<u8> = (0..64 * 48).map(|i| (i % 256) as u8).collect();
1244 let mut u: Vec<u8> = (0..32 * 24).map(|i| (i % 256) as u8).collect();
1245 let mut v: Vec<u8> = (0..32 * 24).map(|i| (255 - i % 256) as u8).collect();
1246 let (before_y, before_u, before_v) = (y.clone(), u.clone(), v.clone());
1247 for matrix in [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020Ncl] {
1248 remap(matrix, matrix, &mut y, &mut u, &mut v, 64);
1249 }
1250 assert_eq!((y, u, v), (before_y, before_u, before_v));
1251 }
1252
1253 /// There and back is the picture again: the two directions are one matrix
1254 /// and its inverse, not two independent approximations.
1255 #[test]
1256 fn a_remap_round_trips_within_a_code() {
1257 let y: Vec<u8> = (0..64 * 48).map(|i| (16 + i % 220) as u8).collect();
1258 let u: Vec<u8> = (0..32 * 24).map(|i| (16 + i % 225) as u8).collect();
1259 let v: Vec<u8> = (0..32 * 24).map(|i| (240 - i % 225) as u8).collect();
1260 let (mut ry, mut ru, mut rv) = (y.clone(), u.clone(), v.clone());
1261 remap(Matrix::Bt601, Matrix::Bt709, &mut ry, &mut ru, &mut rv, 64);
1262 remap(Matrix::Bt709, Matrix::Bt601, &mut ry, &mut ru, &mut rv, 64);
1263 let worst =
1264 |a: &[u8], b: &[u8]| a.iter().zip(b).map(|(x, y)| x.abs_diff(*y)).max().unwrap();
1265 assert!(worst(&y, &ry) <= 2, "luma drifted by {}", worst(&y, &ry));
1266 assert!(worst(&u, &ru) <= 2, "cb drifted by {}", worst(&u, &ru));
1267 assert!(worst(&v, &rv) <= 2, "cr drifted by {}", worst(&v, &rv));
1268 }
1269}