forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

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