forge
Explore
Log in

Don't you dare go Hollow

H.273 color model + dsp remap, ported from edith engine

Browse files at this commit

81a11c60cc1b6391c0f649c58d801e3ec26cd1abAhmet Kaan GümüşParent: 5dd56cf
  • feat
    • H.273 color model + dsp remap, ported from edith engine
Show full message
feat(core): H.273 color model + dsp remap, ported from edith engine

Ports the engine's first-party colorspace model into the family IR: the
three-tier resolve (container tags over bitstream tags over the 720-line
heuristic), the H.273 code tables, the HEVC/H.264/AV1 parameter-set walks
that read a VUI colour_description, and the HDR SEI/mdcv/clli readers.

ColorInfo keeps its raw CICP triplet and gains the meaning behind it
(tags/describe/primaries and a From<ColorDescription> back out);
VideoParameters gains the ContentLight the mastering-display and
content-light metadata needs, which costs those four structs their Eq.

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