forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB7f487c1Tahinli3 months ago659 commits

colorspace.rs1589 lines, 62.4 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 always: an HDR source is *tone-mapped* into this on the way out
100 /// ([`crate::tonemap`]), never carried through and re-tagged.
101 pub fn output(height: u32) -> Self {
102 Self {
103 matrix: if height >= 720 {
104 Matrix::Bt709
105 } else {
106 Matrix::Bt601
107 },
108 transfer: Transfer::Sdr,
109 full_range: false,
110 }
111 }
112
113 /// The H.273 code points a container writes this as: primaries, transfer
114 /// characteristics, matrix coefficients. The same table Matroska's `Colour`
115 /// and mp4's `colr` both index, so one answer serves both muxers.
116 pub fn codes(self) -> (u16, u16, u16) {
117 // Primaries and the SDR curve travel with the matrix: a 709 file is
118 // 1/1/1 and an SD one 6/6/6 (SMPTE 170M), which is what ffmpeg writes
119 // for each and what a player expects to see together.
120 let (primaries, sdr_transfer, matrix) = match self.matrix {
121 Matrix::Bt709 => (1, 1, 1),
122 Matrix::Bt601 => (6, 6, 6),
123 Matrix::Bt2020Ncl => (9, 14, 9),
124 };
125 let transfer = match self.transfer {
126 Transfer::Sdr => sdr_transfer,
127 Transfer::Pq => 16,
128 Transfer::Hlg => 18,
129 };
130 (primaries, transfer, matrix)
131 }
132}
133
134/// How bright a stream's pictures actually get, in cd/m^2 ("nits"), as the grade
135/// declared them. Absent from everything but HDR, which is why every field is an
136/// [`Option`] and why [`Default`] is all-[`None`]: an SDR file says nothing here
137/// and a tone map handed nothing must fall back to its assumed constant rather
138/// than to a zero.
139///
140/// Two different claims, which is why there are four numbers. `max_cll`/
141/// `max_fall` measure the *content* -- the brightest pixel anywhere in the
142/// stream, and the brightest frame average -- while the mastering pair describes
143/// the *display the grade was approved on*, which is a ceiling the film may
144/// never come near.
145///
146/// Parsed at open by both demuxers ([`crate::demux::Demuxer::light`]); nothing
147/// reads it yet. [`crate::tonemap`] is where it belongs, and wiring it there is
148/// its own change.
149#[derive(Debug, Clone, Copy, PartialEq, Default)]
150pub struct ContentLight {
151 /// MaxCLL: the brightest single pixel in the whole stream.
152 pub max_cll: Option<f32>,
153 /// MaxFALL: the brightest frame-average light level in the whole stream.
154 pub max_fall: Option<f32>,
155 /// The mastering display's peak white.
156 pub mastering_max: Option<f32>,
157 /// The mastering display's black, which is a hundredth of a nit or less on
158 /// the displays these grades are approved on.
159 pub mastering_min: Option<f32>,
160}
161
162impl ContentLight {
163 /// The peak a tone map should roll off from, or [`None`] for a file that
164 /// declared neither and has to be assumed at.
165 ///
166 /// MaxCLL first, and the order matters: it is the brightest pixel *in this
167 /// film*, measured over the finished encode. The mastering display's peak is
168 /// only the brightest thing the colourist *could* have used -- a film graded
169 /// on a 4000 nit display whose own brightest pixel is 600 comes out crushed
170 /// if that ceiling is believed instead of the measurement.
171 pub fn peak(self) -> Option<f32> {
172 self.max_cll.or(self.mastering_max)
173 }
174
175 /// Field-wise fallback, as [`Tags::over`] is for the colour tags: `self` is
176 /// the container's word and `under` the bitstream's. Per field rather than
177 /// per file because a remuxer that rewrote MaxCLL and dropped the mastering
178 /// block is a file that exists.
179 pub fn over(self, under: Self) -> Self {
180 Self {
181 max_cll: self.max_cll.or(under.max_cll),
182 max_fall: self.max_fall.or(under.max_fall),
183 mastering_max: self.mastering_max.or(under.mastering_max),
184 mastering_min: self.mastering_min.or(under.mastering_min),
185 }
186 }
187}
188
189/// A `MasteringDisplayColourVolume` payload: eight 16-bit chromaticities (green,
190/// blue, red -- that order -- then the white point) and the two luminances, in
191/// ten-thousandths of a nit. An mp4 `mdcv` box and an HEVC
192/// `mastering_display_colour_volume` SEI are these same 24 bytes, so one reader
193/// serves both; Matroska writes the same numbers as EBML floats instead and is
194/// read where it is walked.
195///
196/// The chromaticities are read past: what a tone map wants is the luminance
197/// pair, and the display's gamut is not something this engine can act on.
198/// A zero luminance is "not stated", which is what ffmpeg writes when it has
199/// nothing -- believing it would tell a tone map the film peaks at black.
200pub(crate) fn mdcv(payload: &[u8]) -> ContentLight {
201 let luminance = |at: usize| -> Option<f32> {
202 let raw = u32::from_be_bytes(payload.get(at..at + 4)?.try_into().ok()?);
203 Some(raw as f32 * 1e-4).filter(|v| *v > 0.0)
204 };
205 ContentLight {
206 mastering_max: luminance(16),
207 mastering_min: luminance(20),
208 ..ContentLight::default()
209 }
210}
211
212/// A `ContentLightLevel` payload: MaxCLL then MaxFALL, whole nits, 16 bits each.
213/// An mp4 `clli` box and an HEVC `content_light_level_info` SEI, again the same
214/// four bytes. Zero is "not stated" here too.
215pub(crate) fn clli(payload: &[u8]) -> ContentLight {
216 let level = |at: usize| -> Option<f32> {
217 let raw = u16::from_be_bytes(payload.get(at..at + 2)?.try_into().ok()?);
218 Some(f32::from(raw)).filter(|v| *v > 0.0)
219 };
220 ContentLight {
221 max_cll: level(0),
222 max_fall: level(2),
223 ..ContentLight::default()
224 }
225}
226
227/// The two HDR SEI messages of one Annex-B access unit. The tier below the
228/// container, and for a web rip the *only* tier: the encoder writes these ahead
229/// of every keyframe, and a muxer that never carried them into `Colour`/`mdcv`
230/// leaves them as the one place the film's real peak still exists (which is
231/// exactly what the 2160p HEVC rips this was read against do).
232pub fn hevc_sei_light(annex_b: &[u8]) -> ContentLight {
233 let mut light = ContentLight::default();
234 for nal in nal_units(annex_b) {
235 // 39 prefix SEI, 40 suffix SEI, and the HEVC NAL header is two bytes.
236 if nal.len() <= 2 || !matches!((nal[0] >> 1) & 0x3f, 39 | 40) {
237 continue;
238 }
239 let sei = rbsp(&nal[2..]);
240 let mut at = 0;
241 // sei_message() (H.265 §7.3.5): payload type and size are each a run of
242 // 0xff bytes plus a final smaller one. The trailing 0x80 of the RBSP
243 // reads as a type with no size behind it, which ends the walk.
244 while let (Some(kind), Some(size)) = (sei_value(&sei, &mut at), sei_value(&sei, &mut at)) {
245 let Some(payload) = sei.get(at..at + size) else {
246 break;
247 };
248 at += size;
249 match kind {
250 137 => light = light.over(mdcv(payload)),
251 144 => light = light.over(clli(payload)),
252 _ => {}
253 }
254 }
255 }
256 light
257}
258
259/// One `ff`-extended SEI count, advancing `at` past it. [`None`] at the end of
260/// the message and for a run long enough to be garbage rather than a value.
261fn sei_value(sei: &[u8], at: &mut usize) -> Option<usize> {
262 let mut value = 0usize;
263 loop {
264 let &byte = sei.get(*at)?;
265 *at += 1;
266 value += usize::from(byte);
267 if byte != 0xff {
268 return Some(value);
269 }
270 if value > 1 << 16 {
271 return None;
272 }
273 }
274}
275
276/// Rewrites planar 4:2:0 samples coded against `from` as the same picture coded
277/// against `to`, in place. Both spaces here are limited range with the same
278/// primaries, so this is the matrix and nothing else: no gamut mapping, no range
279/// scaling, and the 16/128/128 of black lands on itself either way -- which is
280/// what makes a letterboxed bar and a gap's black frame cost nothing.
281///
282/// Derived from the two matrices, not tabulated: with R,G,B eliminated between
283/// them, luma picks up a chroma term and the two chroma planes mix only with
284/// each other -- so chroma never needs the luma plane and is remapped at its own
285/// resolution, while luma reads the co-sited chroma sample the way
286/// [`crate::convert::i420_to_bgra`] does. 8.8 fixed point, the same as every
287/// other matrix in this engine.
288///
289/// A no-op when the two spaces are the same, so the caller may hand any pair.
290pub fn remap(from: Matrix, to: Matrix, y: &mut [u8], u: &mut [u8], v: &mut [u8], width: usize) {
291 // BT.2020 is never an output here (see [`ColorDescription::output`]) and a
292 // 2020 source arrives on the tone-mapping path, not this one.
293 // On normalised samples the two rows are Y' = Y - 0.1182 Cb - 0.2127 Cr,
294 // Cb' = 1.0185 Cb + 0.1146 Cr, Cr' = 0.0751 Cb + 1.0251 Cr; in *code* values
295 // the luma row's chroma terms carry a further 219/224, the ratio of the two
296 // limited-range spans, while the chroma rows' do not (both sides are
297 // chroma). That is the whole difference between these numbers and the
298 // published ones.
299 let coeffs = match (from, to) {
300 (Matrix::Bt601, Matrix::Bt709) => [-30, -53, 261, 29, 19, 262],
301 // ...and its inverse, which round-trips to within a code.
302 (Matrix::Bt709, Matrix::Bt601) => [25, 49, 253, -28, -19, 252],
303 _ => return,
304 };
305 let [yb, yr, ub, ur, vb, vr] = coeffs;
306 let cw = width.div_ceil(2);
307 for (i, y) in y.iter_mut().enumerate() {
308 let (row, col) = (i / width, i % width);
309 let ci = (row / 2) * cw + col / 2;
310 let (d, e) = (u[ci] as i32 - 128, v[ci] as i32 - 128);
311 *y = (*y as i32 + ((yb * d + yr * e + 128) >> 8)).clamp(0, 255) as u8;
312 }
313 for (u, v) in u.iter_mut().zip(v) {
314 let (d, e) = (*u as i32 - 128, *v as i32 - 128);
315 *u = (128 + ((ub * d + ur * e + 128) >> 8)).clamp(0, 255) as u8;
316 *v = (128 + ((vb * d + vr * e + 128) >> 8)).clamp(0, 255) as u8;
317 }
318}
319
320/// One tier's worth of colour tags: what that tier said, field by field, with
321/// [`None`] for "said nothing" and for "said something this does not implement".
322#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
323pub struct Tags {
324 pub matrix: Option<Matrix>,
325 pub transfer: Option<Transfer>,
326 pub full_range: Option<bool>,
327}
328
329impl Tags {
330 /// H.273 code points, as every container and every bitstream writes them.
331 /// `range` is the Matroska `Range` code -- 0 unspecified, 1 limited, 2 full,
332 /// 3 "whatever the matrix implies", which is a non-answer here. A source
333 /// that carries a plain `video_full_range_flag` instead passes `1 + flag`.
334 pub fn from_codes(matrix: u64, transfer: u64, range: u64) -> Self {
335 Self {
336 matrix: match matrix {
337 1 => Some(Matrix::Bt709),
338 // 5 is BT.470BG (PAL), 6 SMPTE 170M (NTSC): one matrix, two
339 // names for the two halves of the world's SD television.
340 5 | 6 => Some(Matrix::Bt601),
341 9 => Some(Matrix::Bt2020Ncl),
342 // 0 unspecified, 2 reserved, 4 FCC, 7 SMPTE 240M, 10 BT.2020
343 // constant-luminance, 14 ICtCp: nothing this renders with.
344 _ => None,
345 },
346 transfer: match transfer {
347 16 => Some(Transfer::Pq),
348 18 => Some(Transfer::Hlg),
349 // Unspecified and reserved say nothing; every other assigned
350 // curve is displayed the way an SDR one is here.
351 0 | 2 => None,
352 _ => Some(Transfer::Sdr),
353 },
354 full_range: match range {
355 1 => Some(false),
356 2 => Some(true),
357 _ => None,
358 },
359 }
360 }
361
362 /// This tier's answers, with `next`'s used for whatever this one left open.
363 fn over(self, next: Self) -> Self {
364 Self {
365 matrix: self.matrix.or(next.matrix),
366 transfer: self.transfer.or(next.transfer),
367 full_range: self.full_range.or(next.full_range),
368 }
369 }
370}
371
372/// What the *encoder* wrote into the stream itself, out of the parameter sets
373/// the demuxers already hold: the SPS VUI for H.264 and HEVC (Annex-B framed,
374/// which is how both demuxers keep them) and the sequence header OBU for AV1.
375///
376/// Empty [`Tags`] for VP9, whose colour space lives in the uncompressed header
377/// of every frame rather than out of band, and for anything malformed: this is
378/// a middle tier, and the tier below it always has an answer.
379pub fn bitstream_tags(codec: Codec, sets: &[u8]) -> Tags {
380 match codec {
381 // 7 is an H.264 SPS, 33 an HEVC one (whose NAL header is two bytes and
382 // whose type sits in bits 1..6 of the first).
383 Codec::H264 => nal_units(sets)
384 .find(|n| n.first().is_some_and(|b| b & 0x1f == 7))
385 .map(|n| h264_sps(&rbsp(&n[1..])))
386 .unwrap_or_default(),
387 Codec::Hevc => nal_units(sets)
388 .find(|n| n.first().is_some_and(|b| (b >> 1) & 0x3f == 33))
389 .filter(|n| n.len() > 2)
390 .map(|n| hevc_sps(&rbsp(&n[2..])))
391 .unwrap_or_default(),
392 Codec::Av1 => av1_sequence_header(sets),
393 Codec::Vp9 => Tags::default(),
394 }
395}
396
397/// The Annex-B NAL units in `buf`, payloads only: start codes are three or four
398/// bytes and both are written in practice (the demuxers write four, an in-band
399/// stream may carry either).
400fn nal_units(buf: &[u8]) -> impl Iterator<Item = &[u8]> {
401 let mut at = 0;
402 std::iter::from_fn(move || {
403 // Find the next start code, then the one after it, which is where this
404 // unit ends.
405 let start = (at..buf.len().saturating_sub(2)).find(|&i| buf[i..i + 3] == [0, 0, 1])? + 3;
406 let end = (start..buf.len().saturating_sub(2))
407 .find(|&i| buf[i..i + 3] == [0, 0, 1])
408 .map(|i| {
409 if i > start && buf[i - 1] == 0 {
410 i - 1
411 } else {
412 i
413 }
414 })
415 .unwrap_or(buf.len());
416 at = end;
417 Some(&buf[start..end])
418 })
419}
420
421/// A NAL payload with its emulation-prevention bytes removed (H.264 §7.4.1.1,
422/// H.265 §7.4.2): a `00 00 03` in the coded bytes is a `00 00` that would
423/// otherwise have looked like a start code, and the `03` is not part of the
424/// syntax.
425fn rbsp(nal: &[u8]) -> Vec<u8> {
426 let mut out = Vec::with_capacity(nal.len());
427 let mut zeros = 0;
428 for &b in nal {
429 if zeros == 2 && b == 3 {
430 zeros = 0;
431 continue;
432 }
433 zeros = if b == 0 { zeros + 1 } else { 0 };
434 out.push(b);
435 }
436 out
437}
438
439/// MSB-first bit reader over an RBSP or an OBU. Reads past the end return zero
440/// and raise [`Bits::overrun`], which every parser here checks before it
441/// believes anything it read -- a truncated parameter set must fall to the next
442/// tier, not report the colour of whatever the zeros decoded to.
443struct Bits<'a> {
444 buf: &'a [u8],
445 /// Bit position, MSB of byte 0 first.
446 at: usize,
447 over: bool,
448}
449
450impl<'a> Bits<'a> {
451 fn new(buf: &'a [u8]) -> Self {
452 Self {
453 buf,
454 at: 0,
455 over: false,
456 }
457 }
458
459 fn overrun(&self) -> bool {
460 self.over
461 }
462
463 fn bit(&mut self) -> u32 {
464 let Some(&byte) = self.buf.get(self.at / 8) else {
465 self.over = true;
466 return 0;
467 };
468 let bit = u32::from(byte >> (7 - self.at % 8)) & 1;
469 self.at += 1;
470 bit
471 }
472
473 /// `u(n)`, up to 32 bits.
474 fn u(&mut self, n: u32) -> u32 {
475 (0..n).fold(0, |acc, _| (acc << 1) | self.bit())
476 }
477
478 /// Bits nothing here reads, in one step -- profile/tier records and the
479 /// like, which run to 88 bits at a time.
480 fn skip(&mut self, n: usize) {
481 self.at += n;
482 if self.at > self.buf.len() * 8 {
483 self.over = true;
484 }
485 }
486
487 /// `ue(v)`, unsigned exp-Golomb: N leading zeros, a one, then N more bits.
488 /// Capped at 32 leading zeros, which is past any legal value and is what
489 /// keeps a garbage set from spinning here.
490 fn ue(&mut self) -> u32 {
491 let mut zeros = 0;
492 while self.bit() == 0 {
493 zeros += 1;
494 if zeros >= 32 || self.over {
495 self.over = true;
496 return 0;
497 }
498 }
499 ((1u32 << zeros) - 1).wrapping_add(self.u(zeros))
500 }
501
502 /// `se(v)`, signed exp-Golomb: the unsigned code zig-zagged.
503 fn se(&mut self) -> i32 {
504 let k = self.ue();
505 if k % 2 == 0 {
506 -((k / 2) as i32)
507 } else {
508 ((k + 1) / 2) as i32
509 }
510 }
511}
512
513/// H.264 `seq_parameter_set_data` (ITU-T H.264 §7.3.2.1.1) walked as far as the
514/// VUI's `colour_description` (Annex E, §E.1.1). Everything before it is read
515/// only to know how many bits it took -- which is why the scaling lists matter:
516/// a High-profile SPS that carries them and is walked as if it did not lands the
517/// VUI read somewhere in the middle of a coefficient.
518fn h264_sps(rbsp: &[u8]) -> Tags {
519 let mut b = Bits::new(rbsp);
520 let profile_idc = b.u(8);
521 b.skip(8 + 8); // constraint flags + reserved, level_idc
522 b.ue(); // seq_parameter_set_id
523 // The chroma/depth block exists only in the profiles that can code
524 // something other than 8-bit 4:2:0 (§7.3.2.1.1, the profile_idc list).
525 if matches!(
526 profile_idc,
527 100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135
528 ) {
529 let chroma_format_idc = b.ue();
530 if chroma_format_idc == 3 {
531 b.bit(); // separate_colour_plane_flag
532 }
533 b.ue(); // bit_depth_luma_minus8
534 b.ue(); // bit_depth_chroma_minus8
535 b.bit(); // qpprime_y_zero_transform_bypass_flag
536 if b.bit() == 1 {
537 // seq_scaling_matrix_present_flag: 8 lists (12 for 4:4:4), the
538 // first six 16 coefficients long and the rest 64 (§7.3.2.1.1.1).
539 let lists = if chroma_format_idc == 3 { 12 } else { 8 };
540 for i in 0..lists {
541 if b.bit() == 1 {
542 scaling_list(&mut b, if i < 6 { 16 } else { 64 });
543 }
544 }
545 }
546 }
547 b.ue(); // log2_max_frame_num_minus4
548 match b.ue() {
549 // pic_order_cnt_type
550 0 => {
551 b.ue(); // log2_max_pic_order_cnt_lsb_minus4
552 }
553 1 => {
554 b.bit(); // delta_pic_order_always_zero_flag
555 b.se(); // offset_for_non_ref_pic
556 b.se(); // offset_for_top_to_bottom_field
557 let cycle = b.ue();
558 if cycle > 255 {
559 return Tags::default();
560 }
561 for _ in 0..cycle {
562 b.se(); // offset_for_ref_frame[i]
563 }
564 }
565 _ => {}
566 }
567 b.ue(); // max_num_ref_frames
568 b.bit(); // gaps_in_frame_num_value_allowed_flag
569 b.ue(); // pic_width_in_mbs_minus1
570 b.ue(); // pic_height_in_map_units_minus1
571 if b.bit() == 0 {
572 b.bit(); // mb_adaptive_frame_field_flag, when !frame_mbs_only_flag
573 }
574 b.bit(); // direct_8x8_inference_flag
575 if b.bit() == 1 {
576 // frame_cropping_flag: four offsets
577 for _ in 0..4 {
578 b.ue();
579 }
580 }
581 if b.bit() == 0 {
582 return Tags::default(); // no VUI at all
583 }
584 vui_colour(&mut b)
585}
586
587/// One H.264 scaling list (§7.3.2.1.1.1): `size` deltas, the run stopping early
588/// once a `nextScale` of zero says the rest of the list is the default one.
589fn scaling_list(b: &mut Bits, size: usize) {
590 let mut next = 8;
591 for _ in 0..size {
592 if next != 0 {
593 next = (next + b.se() + 256) % 256;
594 }
595 if b.overrun() {
596 return;
597 }
598 }
599}
600
601/// HEVC `seq_parameter_set_rbsp` (ITU-T H.265 §7.3.2.2.1) to its VUI
602/// (§E.2.1). The two places bits are easy to lose are the profile/tier record
603/// (§7.3.3) and the short-term reference picture sets (§7.3.7), both of which
604/// are counted here rather than read.
605fn hevc_sps(rbsp: &[u8]) -> Tags {
606 let mut b = Bits::new(rbsp);
607 b.skip(4); // sps_video_parameter_set_id
608 let max_sub_layers_minus1 = b.u(3);
609 b.bit(); // sps_temporal_id_nesting_flag
610 profile_tier_level(&mut b, max_sub_layers_minus1);
611 b.ue(); // sps_seq_parameter_set_id
612 let chroma_format_idc = b.ue();
613 if chroma_format_idc == 3 {
614 b.bit(); // separate_colour_plane_flag
615 }
616 b.ue(); // pic_width_in_luma_samples
617 b.ue(); // pic_height_in_luma_samples
618 if b.bit() == 1 {
619 // conformance_window_flag
620 for _ in 0..4 {
621 b.ue();
622 }
623 }
624 b.ue(); // bit_depth_luma_minus8
625 b.ue(); // bit_depth_chroma_minus8
626 let log2_max_poc_lsb = b.ue() + 4;
627 let ordering_info = b.bit() == 1;
628 let first = if ordering_info {
629 0
630 } else {
631 max_sub_layers_minus1
632 };
633 for _ in first..=max_sub_layers_minus1 {
634 b.ue(); // sps_max_dec_pic_buffering_minus1
635 b.ue(); // sps_max_num_reorder_pics
636 b.ue(); // sps_max_latency_increase_plus1
637 }
638 for _ in 0..6 {
639 // log2_min_luma_coding_block_size_minus3 through
640 // max_transform_hierarchy_depth_intra: six plain ue(v)s.
641 b.ue();
642 }
643 if b.bit() == 1 && b.bit() == 1 {
644 // scaling_list_enabled_flag && sps_scaling_list_data_present_flag
645 scaling_list_data(&mut b);
646 }
647 b.bit(); // amp_enabled_flag
648 b.bit(); // sample_adaptive_offset_enabled_flag
649 if b.bit() == 1 {
650 // pcm_enabled_flag
651 b.skip(8); // pcm_sample_bit_depth_luma/chroma_minus1
652 b.ue(); // log2_min_pcm_luma_coding_block_size_minus3
653 b.ue(); // log2_diff_max_min_pcm_luma_coding_block_size
654 b.bit(); // pcm_loop_filter_disabled_flag
655 }
656 let sets = b.ue();
657 if sets > 64 || b.overrun() {
658 return Tags::default();
659 }
660 let mut counts = Vec::with_capacity(sets as usize);
661 for i in 0..sets as usize {
662 st_ref_pic_set(&mut b, i, &mut counts);
663 if b.overrun() {
664 return Tags::default();
665 }
666 }
667 if b.bit() == 1 {
668 // long_term_ref_pics_present_flag
669 let lt = b.ue();
670 if lt > 64 {
671 return Tags::default();
672 }
673 for _ in 0..lt {
674 b.skip(log2_max_poc_lsb as usize); // lt_ref_pic_poc_lsb_sps[i]
675 b.bit(); // used_by_curr_pic_lt_sps_flag[i]
676 }
677 }
678 b.bit(); // sps_temporal_mvp_enabled_flag
679 b.bit(); // strong_intra_smoothing_enabled_flag
680 if b.bit() == 0 {
681 return Tags::default(); // no VUI at all
682 }
683 vui_colour(&mut b)
684}
685
686/// `profile_tier_level` (§7.3.3), counted: 2+1+5 bits of general profile, 32
687/// compatibility flags, 48 bits of source/reserved flags and an 8-bit level,
688/// then one 88-bit record per sub-layer that declares one.
689fn profile_tier_level(b: &mut Bits, max_sub_layers_minus1: u32) {
690 b.skip(2 + 1 + 5 + 32 + 48 + 8);
691 let mut present = [(false, false); 8];
692 for slot in present.iter_mut().take(max_sub_layers_minus1 as usize) {
693 *slot = (b.bit() == 1, b.bit() == 1);
694 }
695 if max_sub_layers_minus1 > 0 {
696 // reserved_zero_2bits up to eight sub-layers.
697 b.skip(2 * (8 - max_sub_layers_minus1 as usize));
698 }
699 for &(profile, level) in present.iter().take(max_sub_layers_minus1 as usize) {
700 if profile {
701 b.skip(88);
702 }
703 if level {
704 b.skip(8);
705 }
706 }
707}
708
709/// `scaling_list_data` (§7.3.4): four sizes of six matrices each (the last size
710/// has two), either predicted from an earlier matrix or written out as deltas.
711fn scaling_list_data(b: &mut Bits) {
712 for size_id in 0..4 {
713 let step = if size_id == 3 { 3 } else { 1 };
714 for _ in (0..6).step_by(step) {
715 if b.bit() == 0 {
716 b.ue(); // scaling_list_pred_matrix_id_delta
717 continue;
718 }
719 let coefs = 64.min(1 << (4 + (size_id << 1)));
720 if size_id > 1 {
721 b.se(); // scaling_list_dc_coef_minus8
722 }
723 for _ in 0..coefs {
724 b.se(); // scaling_list_delta_coef
725 }
726 if b.overrun() {
727 return;
728 }
729 }
730 }
731}
732
733/// One `st_ref_pic_set` (§7.3.7), kept only for the number of pictures it
734/// holds: that count is what the *next* set spends a flag per picture on when
735/// it predicts from this one, so losing it loses the bit position.
736///
737/// corner-cut: the predicted case counts flags rather than deriving the POCs
738/// (§7.4.8, (7-59)..(7-71)), so a set whose `deltaRps` cancels a reference's
739/// own delta exactly -- a picture at POC distance zero, which is the current
740/// picture and which no encoder emits -- would be counted one too high. The
741/// upgrade path is carrying the `DeltaPocS0/S1` arrays through the loop; the
742/// price of being wrong is a VUI that reads as garbage and falls to the
743/// resolution heuristic, not a bad picture.
744fn st_ref_pic_set(b: &mut Bits, idx: usize, counts: &mut Vec<u32>) {
745 if idx > 0 && b.bit() == 1 {
746 b.bit(); // delta_rps_sign
747 b.ue(); // abs_delta_rps_minus1
748 let mut kept = 0;
749 for _ in 0..=counts[idx - 1] {
750 // used_by_curr_pic_flag, and use_delta_flag only when it is not.
751 let used = b.bit() == 1;
752 kept += u32::from(used || b.bit() == 1);
753 }
754 counts.push(kept);
755 return;
756 }
757 let negative = b.ue();
758 let positive = b.ue();
759 if negative > 64 || positive > 64 {
760 b.over = true;
761 counts.push(0);
762 return;
763 }
764 for _ in 0..negative + positive {
765 b.ue(); // delta_poc_s0/s1_minus1
766 b.bit(); // used_by_curr_pic_s0/s1_flag
767 }
768 counts.push(negative + positive);
769}
770
771/// The head of a VUI, H.264 (§E.1.1) and HEVC (§E.2.1) alike -- the two are
772/// byte-identical up to and including `colour_description`, which is all that is
773/// read here.
774fn vui_colour(b: &mut Bits) -> Tags {
775 if b.bit() == 1 {
776 // aspect_ratio_info_present_flag
777 if b.u(8) == 255 {
778 // Extended_SAR: the ratio is written out rather than indexed.
779 b.skip(32);
780 }
781 }
782 if b.bit() == 1 {
783 b.bit(); // overscan_appropriate_flag
784 }
785 if b.bit() == 0 {
786 return Tags::default(); // no video_signal_type at all
787 }
788 b.skip(3); // video_format
789 let full_range = b.bit();
790 if b.bit() == 0 || b.overrun() {
791 // colour_description_present_flag: the range flag still stands on its
792 // own, which is what an untagged-but-full-range stream says.
793 return Tags {
794 full_range: (!b.overrun()).then_some(full_range == 1),
795 ..Tags::default()
796 };
797 }
798 let (primaries, transfer, matrix) = (b.u(8), b.u(8), b.u(8));
799 let _ = primaries;
800 if b.overrun() {
801 return Tags::default();
802 }
803 Tags::from_codes(
804 u64::from(matrix),
805 u64::from(transfer),
806 u64::from(full_range) + 1,
807 )
808}
809
810/// `color_config` out of the sequence header OBU (AV1 §5.5.1, §5.5.2), which is
811/// what `av1C`/`CodecPrivate` carries and what both demuxers re-inject ahead of
812/// every keyframe. The whole header before it is counted, and most of it is
813/// conditional -- the operating points and the decoder model in particular.
814fn av1_sequence_header(obus: &[u8]) -> Tags {
815 let Some(payload) = sequence_header_obu(obus) else {
816 return Tags::default();
817 };
818 let mut b = Bits::new(payload);
819 let seq_profile = b.u(3);
820 b.bit(); // still_picture
821 let reduced = b.bit() == 1;
822 let mut decoder_model = false;
823 if reduced {
824 b.skip(5); // seq_level_idx[0]
825 } else {
826 if b.bit() == 1 {
827 // timing_info: two 32-bit ticks and, if the interval is fixed, a
828 // uvlc() -- the one variable-length code in this header.
829 b.skip(64);
830 if b.bit() == 1 {
831 uvlc(&mut b);
832 }
833 decoder_model = b.bit() == 1;
834 if decoder_model {
835 b.skip(5 + 32 + 5 + 5);
836 }
837 }
838 let initial_display_delay = b.bit() == 1;
839 let operating_points = b.u(5) + 1;
840 for _ in 0..operating_points {
841 b.skip(12); // operating_point_idc[i]
842 let level = b.u(5);
843 if level > 7 {
844 b.bit(); // seq_tier[i]
845 }
846 if decoder_model && b.bit() == 1 {
847 // operating_parameters_info: two delays of the length the
848 // decoder model declared, plus low_delay_mode_flag. The lengths
849 // were skipped above, so a file with a decoder model is where
850 // this walk stops being able to count.
851 return Tags::default();
852 }
853 if initial_display_delay && b.bit() == 1 {
854 b.skip(4); // initial_display_delay_minus_1[i]
855 }
856 }
857 }
858 let width_bits = b.u(4) + 1;
859 let height_bits = b.u(4) + 1;
860 b.skip((width_bits + height_bits) as usize); // max_frame_width/height_minus_1
861 if !reduced && b.bit() == 1 {
862 b.skip(4 + 3); // delta/additional frame id lengths
863 }
864 b.skip(3); // use_128x128_superblock, enable_filter_intra, intra_edge_filter
865 if !reduced {
866 b.skip(4); // enable_interintra_compound .. enable_dual_filter
867 let order_hint = b.bit() == 1;
868 if order_hint {
869 b.skip(2); // enable_jnt_comp, enable_ref_frame_mvs
870 }
871 // seq_choose_screen_content_tools, or the forced value when it is not
872 // chosen; the integer-mv pair after it exists only when the tools do.
873 let screen_content = if b.bit() == 1 { 2 } else { b.bit() };
874 if screen_content > 0 && b.bit() == 0 {
875 b.bit(); // seq_force_integer_mv
876 }
877 if order_hint {
878 b.skip(3); // order_hint_bits_minus_1
879 }
880 }
881 b.skip(3); // enable_superres, enable_cdef, enable_restoration
882 av1_color_config(&mut b, seq_profile)
883}
884
885/// The payload of the first sequence header OBU (type 1) in a low-overhead OBU
886/// stream (AV1 §5.3.1): a one-byte header, an optional extension byte, and an
887/// optional leb128 size.
888fn sequence_header_obu(mut buf: &[u8]) -> Option<&[u8]> {
889 while let Some((&head, rest)) = buf.split_first() {
890 let kind = (head >> 3) & 0xf;
891 let mut rest = rest;
892 if head & 0x4 != 0 {
893 rest = rest.get(1..)?; // obu_extension_flag: temporal/spatial ids
894 }
895 let size = if head & 0x2 != 0 {
896 let (size, read) = leb128(rest)?;
897 rest = rest.get(read..)?;
898 size.min(rest.len())
899 } else {
900 rest.len()
901 };
902 if kind == 1 {
903 return rest.get(..size);
904 }
905 buf = rest.get(size..)?;
906 }
907 None
908}
909
910/// leb128 as AV1 writes it (§4.10.5): seven bits a byte, low group first, the
911/// top bit saying another follows.
912fn leb128(buf: &[u8]) -> Option<(usize, usize)> {
913 let mut value = 0usize;
914 for i in 0..8 {
915 let &byte = buf.get(i)?;
916 value |= usize::from(byte & 0x7f) << (i * 7);
917 if byte & 0x80 == 0 {
918 return Some((value, i + 1));
919 }
920 }
921 None
922}
923
924/// `uvlc()` (AV1 §4.10.3): leading zeros, then that many bits, biased -- the
925/// same shape as exp-Golomb with a different bias.
926fn uvlc(b: &mut Bits) {
927 let mut zeros = 0;
928 while b.bit() == 0 && !b.overrun() {
929 zeros += 1;
930 if zeros >= 32 {
931 b.over = true;
932 return;
933 }
934 }
935 b.skip(zeros);
936}
937
938/// `color_config` (AV1 §5.5.2). The bit depth and the subsampling are read only
939/// as far as they cost bits before `color_range`.
940fn av1_color_config(b: &mut Bits, seq_profile: u32) -> Tags {
941 let high_bitdepth = b.bit() == 1;
942 if seq_profile == 2 && high_bitdepth {
943 b.bit(); // twelve_bit
944 }
945 let mono_chrome = seq_profile != 1 && b.bit() == 1;
946 let described = b.bit() == 1;
947 let (primaries, transfer, matrix) = if described {
948 (b.u(8), b.u(8), b.u(8))
949 } else {
950 (2, 2, 2) // CP/TC/MC_UNSPECIFIED
951 };
952 if b.overrun() {
953 return Tags::default();
954 }
955 let full_range = if mono_chrome {
956 b.bit() == 1
957 } else if primaries == 1 && transfer == 13 && matrix == 0 {
958 // sRGB in an identity matrix is full range by definition, and the flag
959 // is not written.
960 true
961 } else {
962 b.bit() == 1
963 };
964 if b.overrun() {
965 return Tags::default();
966 }
967 Tags {
968 full_range: Some(full_range),
969 ..Tags::from_codes(u64::from(matrix), u64::from(transfer), 0)
970 }
971}
972
973#[cfg(test)]
974mod tests {
975 use super::*;
976 use crate::demux::Demuxer;
977 use std::path::PathBuf;
978
979 fn asset(name: &str) -> PathBuf {
980 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
981 .join("../../assets")
982 .join(name)
983 }
984
985 fn color_of(name: &str) -> ColorDescription {
986 let (meta, _) = Demuxer::open(&asset(name)).unwrap_or_else(|e| panic!("open {name}: {e}"));
987 meta.color
988 }
989
990 /// The tier order itself: a container tag beats both a bitstream tag and the
991 /// heuristic, field by field.
992 #[test]
993 fn tiers_resolve_in_order() {
994 let container = Tags::from_codes(9, 16, 1);
995 let bitstream = Tags::from_codes(1, 1, 2);
996 assert_eq!(
997 ColorDescription::resolve(container, bitstream, 2160),
998 ColorDescription {
999 matrix: Matrix::Bt2020Ncl,
1000 transfer: Transfer::Pq,
1001 full_range: false,
1002 }
1003 );
1004 // A container that tagged only the range leaves the rest to the SPS.
1005 let range_only = Tags::from_codes(0, 0, 2);
1006 assert_eq!(
1007 ColorDescription::resolve(range_only, bitstream, 480),
1008 ColorDescription {
1009 matrix: Matrix::Bt709,
1010 transfer: Transfer::Sdr,
1011 full_range: true,
1012 }
1013 );
1014 // Nothing anywhere: the resolution decides, and only the resolution.
1015 let none = Tags::default();
1016 assert_eq!(
1017 ColorDescription::resolve(none, none, 1080).matrix,
1018 Matrix::Bt709
1019 );
1020 assert_eq!(
1021 ColorDescription::resolve(none, none, 719).matrix,
1022 Matrix::Bt601
1023 );
1024 assert_eq!(
1025 ColorDescription::default(),
1026 ColorDescription::resolve(none, none, 480)
1027 );
1028 }
1029
1030 /// Reserved and unimplemented code points are "said nothing", not a wrong
1031 /// answer: that is what makes them fall through.
1032 #[test]
1033 fn unknown_codes_fall_through() {
1034 assert_eq!(Tags::from_codes(2, 2, 3), Tags::default());
1035 assert_eq!(Tags::from_codes(7, 0, 0).matrix, None); // SMPTE 240M
1036 assert_eq!(Tags::from_codes(6, 1, 1).transfer, Some(Transfer::Sdr));
1037 assert_eq!(Tags::from_codes(0, 18, 2).transfer, Some(Transfer::Hlg));
1038 }
1039
1040 /// The bit reader, against a hand-built pattern: exp-Golomb is where a
1041 /// mis-read shifts everything after it.
1042 #[test]
1043 fn bit_reader_reads_exp_golomb() {
1044 // 1 | 010 | 011 | 00100 : ue = 0, 1, 2, 3
1045 let mut b = Bits::new(&[0b1010_0110, 0b0100_0000]);
1046 assert_eq!((b.ue(), b.ue(), b.ue(), b.ue()), (0, 1, 2, 3));
1047 assert!(!b.overrun());
1048 // se zig-zags: 0, 1, -1, 2
1049 let mut b = Bits::new(&[0b1010_0110, 0b0100_0000]);
1050 assert_eq!((b.se(), b.se(), b.se(), b.se()), (0, 1, -1, 2));
1051 // Past the end reads zero and says so.
1052 let mut b = Bits::new(&[0xff]);
1053 b.skip(8);
1054 assert_eq!(b.u(4), 0);
1055 assert!(b.overrun());
1056 }
1057
1058 /// Emulation prevention: the `03` is syntax-invisible, a third `00` is not.
1059 #[test]
1060 fn rbsp_drops_emulation_bytes() {
1061 assert_eq!(rbsp(&[0, 0, 3, 1, 0, 0, 3, 0]), vec![0, 0, 1, 0, 0, 0]);
1062 assert_eq!(rbsp(&[0, 3, 3]), vec![0, 3, 3]);
1063 }
1064
1065 /// A generated fixture whose *container* says BT.601 at 720 lines, where the
1066 /// heuristic would have said BT.709: proof the container tier is read and
1067 /// that it wins. Both containers, because both parse it themselves.
1068 #[test]
1069 fn container_tags_win_over_the_heuristic() {
1070 for name in ["test_bt601.mp4", "test_bt601.mkv"] {
1071 assert_eq!(
1072 color_of(name),
1073 ColorDescription {
1074 matrix: Matrix::Bt601,
1075 transfer: Transfer::Sdr,
1076 full_range: false,
1077 },
1078 "{name}"
1079 );
1080 }
1081 }
1082
1083 /// Bits written out as `'0'`/`'1'`, MSB first, for a hand-built SPS.
1084 fn bits_of(pattern: &str) -> Vec<u8> {
1085 let mut out = Vec::new();
1086 for (i, c) in pattern.chars().filter(|c| !c.is_whitespace()).enumerate() {
1087 if i % 8 == 0 {
1088 out.push(0);
1089 }
1090 if c == '1' {
1091 *out.last_mut().unwrap() |= 0x80 >> (i % 8);
1092 }
1093 }
1094 out
1095 }
1096
1097 /// A High-profile SPS written by hand, because no encoder here writes one
1098 /// with its scaling lists in the *sequence* parameter set (x264 puts its
1099 /// quant matrices in the PPS; the HEVC fixture below has real ones). The
1100 /// lists are what makes this test worth having: read as if they were not
1101 /// there, the VUI lands mid-coefficient and the colour comes out as noise.
1102 #[test]
1103 fn h264_scaling_lists_are_skipped_before_the_vui() {
1104 let sps = concat!(
1105 "01100100", // profile_idc 100 (High)
1106 "00000000", // constraint flags + reserved
1107 "00011110", // level_idc 30
1108 "1", // seq_parameter_set_id ue(0)
1109 "010", // chroma_format_idc ue(1), 4:2:0
1110 "1", // bit_depth_luma_minus8 ue(0)
1111 "1", // bit_depth_chroma_minus8 ue(0)
1112 "0", // qpprime_y_zero_transform_bypass_flag
1113 "1", // seq_scaling_matrix_present_flag
1114 "1", // ...list 0 present
1115 "000010001", // its first delta, se(-8): nextScale hits 0, so the
1116 // remaining 15 coefficients are the default ones and cost no bits
1117 "0000000", // lists 1..7 absent
1118 "1", // log2_max_frame_num_minus4 ue(0)
1119 "1", // pic_order_cnt_type ue(0)
1120 "1", // log2_max_pic_order_cnt_lsb_minus4 ue(0)
1121 "010", // max_num_ref_frames ue(1)
1122 "0", // gaps_in_frame_num_value_allowed_flag
1123 "00000101000", // pic_width_in_mbs_minus1 ue(39), i.e. 640
1124 "000011110", // pic_height_in_map_units_minus1 ue(29), i.e. 480
1125 "1", // frame_mbs_only_flag
1126 "1", // direct_8x8_inference_flag
1127 "0", // frame_cropping_flag
1128 "1", // vui_parameters_present_flag
1129 "0", // aspect_ratio_info_present_flag
1130 "0", // overscan_info_present_flag
1131 "1", // video_signal_type_present_flag
1132 "101", // video_format (unspecified)
1133 "0", // video_full_range_flag
1134 "1", // colour_description_present_flag
1135 "00000001", // colour_primaries 1
1136 "00000001", // transfer_characteristics 1
1137 "00000001", // matrix_coefficients 1 (BT.709)
1138 );
1139 assert_eq!(
1140 h264_sps(&bits_of(sps)),
1141 Tags {
1142 matrix: Some(Matrix::Bt709),
1143 transfer: Some(Transfer::Sdr),
1144 full_range: Some(false),
1145 }
1146 );
1147 }
1148
1149 /// The HEVC twin of the test above, and hand-built for the same reason:
1150 /// x265 writes `sps_scaling_list_data_present_flag` only for a *custom*
1151 /// list, and the fixture below carries the default one (a flag and no
1152 /// data). Custom lists are not exotic -- they are what a psy-tuned anime
1153 /// encode ships -- so the branch that counts them has to be measured.
1154 #[test]
1155 fn hevc_scaling_list_data_is_skipped_before_the_vui() {
1156 let mut sps = String::new();
1157 sps.push_str("0000"); // sps_video_parameter_set_id
1158 sps.push_str("000"); // sps_max_sub_layers_minus1: one layer
1159 sps.push('0'); // sps_temporal_id_nesting_flag
1160 sps.push_str(&"0".repeat(96)); // profile_tier_level, general only
1161 sps.push('1'); // sps_seq_parameter_set_id ue(0)
1162 sps.push_str("010"); // chroma_format_idc ue(1), 4:2:0
1163 sps.push_str("0000000001010000001"); // pic_width_in_luma_samples ue(640)
1164 sps.push_str("00000000111100001"); // pic_height_in_luma_samples ue(480)
1165 sps.push('0'); // conformance_window_flag
1166 sps.push_str("11"); // bit_depth_luma/chroma_minus8 ue(0)
1167 sps.push_str("00101"); // log2_max_pic_order_cnt_lsb_minus4 ue(4)
1168 sps.push('1'); // sps_sub_layer_ordering_info_present_flag
1169 sps.push_str("111"); // ...its three ue(0)s, for the one layer
1170 sps.push_str("111111"); // the six coding/transform-block ue(0)s
1171 sps.push_str("11"); // scaling_list_enabled + sps_scaling_list_data_present
1172 // scaling_list_data: the first 4x4 matrix written out (16 se(0) deltas,
1173 // no DC coefficient at this size), every other matrix predicted from an
1174 // earlier one -- 6+6+6+2 matrices in all.
1175 sps.push('1');
1176 sps.push_str(&"1".repeat(16));
1177 sps.push_str(&"01".repeat(5 + 6 + 6 + 2));
1178 sps.push_str("000"); // amp, sample_adaptive_offset, pcm_enabled
1179 sps.push('1'); // num_short_term_ref_pic_sets ue(0)
1180 sps.push('0'); // long_term_ref_pics_present_flag
1181 sps.push_str("00"); // sps_temporal_mvp, strong_intra_smoothing
1182 sps.push('1'); // vui_parameters_present_flag
1183 sps.push_str("00"); // aspect_ratio_info_present, overscan_info_present
1184 sps.push('1'); // video_signal_type_present_flag
1185 sps.push_str("101"); // video_format (unspecified)
1186 sps.push('0'); // video_full_range_flag
1187 sps.push('1'); // colour_description_present_flag
1188 sps.push_str("000000010000000100000001"); // primaries/transfer/matrix 1
1189 assert_eq!(
1190 hevc_sps(&bits_of(&sps)),
1191 Tags {
1192 matrix: Some(Matrix::Bt709),
1193 transfer: Some(Transfer::Sdr),
1194 full_range: Some(false),
1195 }
1196 );
1197 }
1198
1199 /// The bitstream tier, in the three codecs that carry one: fixtures tagged
1200 /// through the *encoder* alone (x264/x265 VUI, SVT-AV1 `color_config`) and
1201 /// muxed with no `colr` box at all, at 480 lines where the heuristic would
1202 /// have said BT.601. The absence of the box is asserted too: without it a
1203 /// fixture that grew container tags would pass this for the wrong reason.
1204 /// The H.264 one is High profile with `cqm=jvt`, i.e. a real SPS with
1205 /// scaling lists in front of its VUI.
1206 #[test]
1207 fn bitstream_tags_beat_the_heuristic() {
1208 for name in ["test_vui_h264.mp4", "test_vui_hevc.mp4", "test_vui_av1.mp4"] {
1209 let bytes = std::fs::read(asset(name)).unwrap_or_else(|e| panic!("read {name}: {e}"));
1210 assert!(
1211 !bytes.windows(4).any(|w| w == b"colr"),
1212 "{name} carries a colr box, so this would not be testing the bitstream"
1213 );
1214 assert_eq!(color_of(name).matrix, Matrix::Bt709, "{name}");
1215 }
1216 }
1217
1218 /// An untagged 360-line fixture: nothing in the container, nothing in the
1219 /// stream, so the heuristic answers -- BT.601 limited, which is what the
1220 /// engine assumed of everything before any of this was read.
1221 #[test]
1222 fn untagged_sd_falls_to_the_heuristic() {
1223 assert_eq!(color_of("test_mismatch.mp4"), ColorDescription::default());
1224 }
1225
1226 /// A real HDR film: BT.2020 non-constant-luminance, PQ, limited range, all
1227 /// three off the Matroska `Colour` element. Gated on the file being here --
1228 /// it is a 25 GB remux, not a fixture (`crate::real_library`).
1229 #[test]
1230 fn real_hdr_film_reads_bt2020_pq() {
1231 let Some(path) = crate::real_library::film("hevc_4k_hdr") else {
1232 return;
1233 };
1234 let (meta, _) = Demuxer::open(&path).expect("open the HDR film");
1235 assert_eq!(
1236 meta.color,
1237 ColorDescription {
1238 matrix: Matrix::Bt2020Ncl,
1239 transfer: Transfer::Pq,
1240 full_range: false,
1241 }
1242 );
1243 }
1244
1245 /// A real 720p film with no colour tags anywhere -- neither container nor
1246 /// SPS -- which is the case the heuristic exists for: BT.709, because it is
1247 /// HD material. Gated for the same reason as the one above.
1248 #[test]
1249 fn real_untagged_hd_film_reads_bt709() {
1250 let Some(path) = crate::real_library::film("h264_dual_audio") else {
1251 return;
1252 };
1253 let (meta, _) = Demuxer::open(&path).expect("open the untagged film");
1254 assert_eq!(
1255 meta.color,
1256 ColorDescription {
1257 matrix: Matrix::Bt709,
1258 transfer: Transfer::Sdr,
1259 full_range: false,
1260 }
1261 );
1262 }
1263
1264 /// The rule an export declares itself by, and the reason it is the *same*
1265 /// rule the heuristic reads: a file written here says out loud what a reader
1266 /// with no tags would have assumed anyway.
1267 #[test]
1268 fn an_output_declares_the_space_its_height_implies() {
1269 assert_eq!(ColorDescription::output(1080).matrix, Matrix::Bt709);
1270 assert_eq!(ColorDescription::output(720).matrix, Matrix::Bt709);
1271 assert_eq!(ColorDescription::output(576).matrix, Matrix::Bt601);
1272 for height in [480, 1080] {
1273 let out = ColorDescription::output(height);
1274 assert_eq!(out.transfer, Transfer::Sdr);
1275 assert!(!out.full_range, "both encoders here are limited range");
1276 }
1277 // What the two containers write, in the one table both index.
1278 assert_eq!(ColorDescription::output(1080).codes(), (1, 1, 1));
1279 assert_eq!(ColorDescription::output(480).codes(), (6, 6, 6));
1280 }
1281
1282 /// Limited-range 4:2:0 samples for one colour, in `matrix`, the float way --
1283 /// what a correct encoder would have written.
1284 fn encode(matrix: Matrix, rgb: [f64; 3]) -> (u8, u8, u8) {
1285 let (kr, kb) = weights(matrix);
1286 let [r, g, b] = rgb.map(|c| c / 255.0);
1287 let luma = kr * r + (1.0 - kr - kb) * g + kb * b;
1288 let round = |x: f64| x.round().clamp(0.0, 255.0) as u8;
1289 (
1290 round(16.0 + 219.0 * luma),
1291 round(128.0 + 224.0 * 0.5 * (b - luma) / (1.0 - kb)),
1292 round(128.0 + 224.0 * 0.5 * (r - luma) / (1.0 - kr)),
1293 )
1294 }
1295
1296 /// ...and back out of `matrix`, unrounded, which is what a player shows.
1297 fn decode(matrix: Matrix, (y, u, v): (u8, u8, u8)) -> [f64; 3] {
1298 let (kr, kb) = weights(matrix);
1299 let luma = (f64::from(y) - 16.0) / 219.0;
1300 let cb = (f64::from(u) - 128.0) / 224.0;
1301 let cr = (f64::from(v) - 128.0) / 224.0;
1302 let r = luma + 2.0 * (1.0 - kr) * cr;
1303 let b = luma + 2.0 * (1.0 - kb) * cb;
1304 let g = (luma - kr * r - kb * b) / (1.0 - kr - kb);
1305 [r, g, b].map(|c| c * 255.0)
1306 }
1307
1308 fn weights(matrix: Matrix) -> (f64, f64) {
1309 match matrix {
1310 Matrix::Bt601 => (0.299, 0.114),
1311 Matrix::Bt709 => (0.2126, 0.0722),
1312 Matrix::Bt2020Ncl => (0.2627, 0.0593),
1313 }
1314 }
1315
1316 /// One colour as a 2x2 picture -- four luma samples over one chroma pair,
1317 /// the smallest thing [`remap`] indexes the way it indexes a frame.
1318 fn tile((y, u, v): (u8, u8, u8)) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
1319 (vec![y; 4], vec![u], vec![v])
1320 }
1321
1322 /// The claim the whole reconcile rests on: samples coded against one matrix,
1323 /// remapped, and then *decoded by the other matrix* are the colour that went
1324 /// in -- not a second conversion of it. Within a code or two, which is what
1325 /// 8-bit 8.8 fixed point can promise.
1326 #[test]
1327 fn a_remap_is_the_same_colour_read_by_the_other_matrix() {
1328 let colours = [
1329 [255.0, 0.0, 0.0],
1330 [0.0, 255.0, 0.0],
1331 [0.0, 0.0, 255.0],
1332 [255.0, 255.0, 0.0],
1333 [18.0, 200.0, 140.0],
1334 [128.0, 128.0, 128.0],
1335 [235.0, 210.0, 30.0],
1336 ];
1337 for (from, to) in [
1338 (Matrix::Bt601, Matrix::Bt709),
1339 (Matrix::Bt709, Matrix::Bt601),
1340 ] {
1341 for rgb in colours {
1342 let (mut y, mut u, mut v) = tile(encode(from, rgb));
1343 remap(from, to, &mut y, &mut u, &mut v, 2);
1344 let out = decode(to, (y[0], u[0], v[0]));
1345 for (want, got) in rgb.iter().zip(&out) {
1346 assert!(
1347 (want - got).abs() <= 2.0,
1348 "{from:?}->{to:?} {rgb:?} came out {out:?}"
1349 );
1350 }
1351 }
1352 }
1353 }
1354
1355 /// Black, white and neutral grey are the same samples in both matrices, and
1356 /// a remap has to leave them alone: those are the letterbox bars, the gap
1357 /// frames and every grey in the picture, and a shift there is visible as a
1358 /// tint on nothing at all.
1359 #[test]
1360 fn a_remap_leaves_the_greys_where_they_are() {
1361 for (from, to) in [
1362 (Matrix::Bt601, Matrix::Bt709),
1363 (Matrix::Bt709, Matrix::Bt601),
1364 ] {
1365 for luma in [16u8, 128, 235] {
1366 let (mut y, mut u, mut v) = tile((luma, 128, 128));
1367 remap(from, to, &mut y, &mut u, &mut v, 2);
1368 assert_eq!((y[0], u[0], v[0]), (luma, 128, 128), "{from:?}->{to:?}");
1369 }
1370 }
1371 }
1372
1373 /// The export's zero-cost path, asserted where it is decided: a clip already
1374 /// in the file's own space comes out byte for byte the samples it went in
1375 /// as, so an ordinary single-space project is not touched by any of this.
1376 #[test]
1377 fn a_same_space_remap_touches_nothing() {
1378 let mut y: Vec<u8> = (0..64 * 48).map(|i| (i % 256) as u8).collect();
1379 let mut u: Vec<u8> = (0..32 * 24).map(|i| (i % 256) as u8).collect();
1380 let mut v: Vec<u8> = (0..32 * 24).map(|i| (255 - i % 256) as u8).collect();
1381 let (before_y, before_u, before_v) = (y.clone(), u.clone(), v.clone());
1382 for matrix in [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020Ncl] {
1383 remap(matrix, matrix, &mut y, &mut u, &mut v, 64);
1384 }
1385 assert_eq!((y, u, v), (before_y, before_u, before_v));
1386 }
1387
1388 /// There and back is the picture again: the two directions are one matrix
1389 /// and its inverse, not two independent approximations.
1390 #[test]
1391 fn a_remap_round_trips_within_a_code() {
1392 let y: Vec<u8> = (0..64 * 48).map(|i| (16 + i % 220) as u8).collect();
1393 let u: Vec<u8> = (0..32 * 24).map(|i| (16 + i % 225) as u8).collect();
1394 let v: Vec<u8> = (0..32 * 24).map(|i| (240 - i % 225) as u8).collect();
1395 let (mut ry, mut ru, mut rv) = (y.clone(), u.clone(), v.clone());
1396 remap(Matrix::Bt601, Matrix::Bt709, &mut ry, &mut ru, &mut rv, 64);
1397 remap(Matrix::Bt709, Matrix::Bt601, &mut ry, &mut ru, &mut rv, 64);
1398 let worst =
1399 |a: &[u8], b: &[u8]| a.iter().zip(b).map(|(x, y)| x.abs_diff(*y)).max().unwrap();
1400 assert!(worst(&y, &ry) <= 2, "luma drifted by {}", worst(&y, &ry));
1401 assert!(worst(&u, &ru) <= 2, "cb drifted by {}", worst(&u, &ru));
1402 assert!(worst(&v, &rv) <= 2, "cr drifted by {}", worst(&v, &rv));
1403 }
1404
1405 /// The grade `scripts/gen_fixtures.sh` writes into all three HDR fixtures:
1406 /// MaxCLL 1000, MaxFALL 400, a 1000 nit mastering display down to 0.005.
1407 const GRADE: ContentLight = ContentLight {
1408 max_cll: Some(1000.0),
1409 max_fall: Some(400.0),
1410 mastering_max: Some(1000.0),
1411 mastering_min: Some(0.005),
1412 };
1413
1414 /// Nits, compared the way three different encodings of them allow: Matroska
1415 /// writes 0.005 as a double and both mp4 and the SEI write 50 ten-thousandths
1416 /// of a nit, and those do not land on the same `f32`.
1417 #[track_caller]
1418 fn same_light(got: ContentLight, want: ContentLight) {
1419 let close = |a: Option<f32>, b: Option<f32>| match (a, b) {
1420 (Some(a), Some(b)) => (a - b).abs() <= b.abs() * 1e-4,
1421 (a, b) => a == b,
1422 };
1423 assert!(
1424 close(got.max_cll, want.max_cll)
1425 && close(got.max_fall, want.max_fall)
1426 && close(got.mastering_max, want.mastering_max)
1427 && close(got.mastering_min, want.mastering_min),
1428 "{got:?} is not {want:?}"
1429 );
1430 }
1431
1432 fn light_of(name: &str) -> ContentLight {
1433 let (_, demuxer) =
1434 Demuxer::open(&asset(name)).unwrap_or_else(|e| panic!("open {name}: {e}"));
1435 demuxer.light()
1436 }
1437
1438 /// The container tier, both containers: Matroska's `MaxCLL`/`MaxFALL` beside
1439 /// its `MasteringMetadata` floats, and an mp4's `clli`/`mdcv` beside its
1440 /// `colr`. Same grade in, same four numbers out.
1441 #[test]
1442 fn the_containers_carry_the_grades_brightness() {
1443 same_light(light_of("test_hdr_meta.mkv"), GRADE);
1444 same_light(light_of("test_hdr_meta.mp4"), GRADE);
1445 assert_eq!(light_of("test_hdr_meta.mkv").peak(), Some(1000.0));
1446 }
1447
1448 /// The bitstream tier, which is the only one a web rip has: test_hdr_sei.mkv
1449 /// is the x265 encode before the transcode that gave the other two their
1450 /// container elements -- its `Colour` element stops at the code points, and
1451 /// every one of these numbers comes out of the first access unit's SEI.
1452 #[test]
1453 fn an_sei_answers_for_a_container_that_says_nothing() {
1454 same_light(light_of("test_hdr_sei.mkv"), GRADE);
1455 }
1456
1457 /// ...and a file that carries neither tier says so, rather than reporting a
1458 /// zero peak that would tell a tone map the picture never leaves black.
1459 #[test]
1460 fn an_sdr_file_declares_no_brightness_at_all() {
1461 assert_eq!(light_of("test_av.mp4"), ContentLight::default());
1462 assert_eq!(light_of("test_av1.mkv"), ContentLight::default());
1463 assert_eq!(ContentLight::default().peak(), None);
1464 }
1465
1466 /// The number a tone map will ask for. MaxCLL is the film's own measured
1467 /// peak and wins; the mastering display is the fallback, and a grade that
1468 /// stated only the display is still worth more than an assumed constant.
1469 #[test]
1470 fn the_peak_is_the_measured_light_before_the_display_it_was_graded_on() {
1471 assert_eq!(GRADE.peak(), Some(1000.0));
1472 let display_only = ContentLight {
1473 max_cll: None,
1474 ..GRADE
1475 };
1476 assert_eq!(display_only.peak(), Some(1000.0), "the mastering display");
1477 let measured = ContentLight {
1478 max_cll: Some(600.0),
1479 mastering_max: Some(4000.0),
1480 ..ContentLight::default()
1481 };
1482 assert_eq!(
1483 measured.peak(),
1484 Some(600.0),
1485 "600 nits of content, not 4000"
1486 );
1487 // The tier fallback: field by field, container over bitstream.
1488 let container = ContentLight {
1489 max_cll: Some(1200.0),
1490 ..ContentLight::default()
1491 };
1492 assert_eq!(
1493 container.over(measured),
1494 ContentLight {
1495 max_cll: Some(1200.0),
1496 mastering_max: Some(4000.0),
1497 ..ContentLight::default()
1498 }
1499 );
1500 }
1501
1502 /// The SEI walk on bytes rather than on a file: a `mastering_display_colour_volume`
1503 /// (137) and a `content_light_level_info` (144) in one prefix SEI NAL, with
1504 /// an emulation-prevention byte inside the mastering payload -- which is not
1505 /// hypothetical, a 0.005 nit minimum *is* `00 00 00 32` before escaping.
1506 #[test]
1507 fn the_sei_walk_reads_past_an_emulation_prevention_byte() {
1508 let mut mastering = Vec::new();
1509 for coordinate in [8500u16, 39850, 6550, 2300, 35400, 14600, 15635, 16450] {
1510 mastering.extend_from_slice(&coordinate.to_be_bytes());
1511 }
1512 mastering.extend_from_slice(&10_000_000u32.to_be_bytes()); // 1000 nits
1513 mastering.extend_from_slice(&50u32.to_be_bytes()); // 0.005 nits
1514 let mut nal = vec![39 << 1, 1]; // prefix SEI, temporal id 1
1515 nal.extend_from_slice(&[137, 24]);
1516 // 00 00 00 32 is escaped into 00 00 03 00 32 by any encoder that writes
1517 // it, and the reader has to undo that or the luminances land a byte out.
1518 let mut escaped = Vec::new();
1519 let mut zeros = 0;
1520 for &byte in &mastering {
1521 if zeros == 2 && byte <= 3 {
1522 escaped.push(3);
1523 zeros = 0;
1524 }
1525 zeros = if byte == 0 { zeros + 1 } else { 0 };
1526 escaped.push(byte);
1527 }
1528 assert!(
1529 escaped.len() > mastering.len(),
1530 "the payload needed escaping"
1531 );
1532 nal.extend_from_slice(&escaped);
1533 nal.extend_from_slice(&[144, 4, 0x03, 0xe8, 0x01, 0x90]); // 1000 / 400
1534 nal.push(0x80); // rbsp_trailing_bits
1535 let mut annex_b = vec![0, 0, 0, 1];
1536 annex_b.extend_from_slice(&nal);
1537 same_light(hevc_sei_light(&annex_b), GRADE);
1538
1539 // Nothing to find is not a failure: a keyframe with no SEI at all, and a
1540 // truncated message, both come back empty rather than reading garbage.
1541 assert_eq!(
1542 hevc_sei_light(&[0, 0, 0, 1, 0x26, 0x01, 0xAA]),
1543 ContentLight::default()
1544 );
1545 assert_eq!(
1546 hevc_sei_light(&[0, 0, 0, 1, 39 << 1, 1, 144, 4, 0x03]),
1547 ContentLight::default()
1548 );
1549 }
1550
1551 /// Zero is what a muxer writes for "I was not told", in every one of the
1552 /// three encodings -- and it must not read back as a film that peaks at
1553 /// black.
1554 #[test]
1555 fn an_unstated_brightness_is_absent_and_not_a_zero() {
1556 assert_eq!(clli(&[0, 0, 0, 0]), ContentLight::default());
1557 assert_eq!(mdcv(&[0u8; 24]), ContentLight::default());
1558 // ...and a box shorter than its own syntax is absent too.
1559 assert_eq!(clli(&[0x03]), ContentLight::default());
1560 assert_eq!(mdcv(&[0u8; 16]), ContentLight::default());
1561 }
1562
1563 /// The real thing: a 4K HDR10 web rip, whose grade lives *only* in the
1564 /// bitstream -- its `Colour` element is four code points and stops. The
1565 /// numbers are what ffprobe reports for the same file (`Content light level
1566 /// metadata` 1759/202, `Mastering display metadata` 10000000/10000 down to
1567 /// 50/10000). Skipped, loudly, on a machine without the film.
1568 #[test]
1569 fn a_real_hdr_film_reports_the_peak_ffprobe_reports() {
1570 let Some(film) = crate::real_library::film("hevc_4k_hdr") else {
1571 return;
1572 };
1573 let (_, demuxer) = Demuxer::open(&film).expect("open the film");
1574 same_light(
1575 demuxer.light(),
1576 ContentLight {
1577 max_cll: Some(1759.0),
1578 max_fall: Some(202.0),
1579 mastering_max: Some(1000.0),
1580 mastering_min: Some(0.005),
1581 },
1582 );
1583 assert_eq!(
1584 demuxer.light().peak(),
1585 Some(1759.0),
1586 "the film's own peak, not the 1000 nit display it was graded on"
1587 );
1588 }
1589}