forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

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