forge
Explore
Log in

Don't you dare go Hollow

A file says which matrix and curve its numbers are in, and edith reads it

Browse files at this commit

070ffe6fb7873be5e184993f032e14f47a1307f5Ahmet Kaan GümüşParent: 5c39124
  • feat
    • a file says which matrix and curve its numbers are in, and edith reads it
Show full message
✨ feat(colorspace): a file says which matrix and curve its numbers are in, and edith reads it

Three tiers, per field: the container's own tags (Matroska `Colour`, mp4
`colr`), then the bitstream's (H.264/HEVC SPS VUI, AV1 `color_config`),
then the ffmpeg/mpv resolution rule -- 720 lines or taller is BT.709,
below it BT.601, limited either way. A code that says nothing, or says
something with no implementation here, falls to the next tier rather than
answering wrongly.

`VideoMeta` carries the answer; nothing consumes it yet. Everything still
renders through the hardcoded BT.601 it always did, which is the bug this
is the foundation for fixing.

The bit-level walks are where this can quietly go wrong: an SPS whose
scaling lists are counted wrongly lands the VUI read in the middle of a
coefficient. Both are measured -- H.264 and HEVC against hand-built
parameter sets (no encoder here writes SPS scaling lists), the rest
against fixtures tagged in the container, tagged only in the bitstream,
and tagged nowhere, plus the two real films: a 4K HDR remux that reads
BT.2020/PQ and a fully untagged 720p one that reads BT.709.
crates/engine/src/colorspace.rsadded+1045 -0
@@ -0,0 +1,1045 @@
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 here is read off the file;
4+//! nothing here converts anything yet.
5+//!
6+//! Three tiers, in this order, per field:
7+//!
8+//! 1. the **container**'s own tags -- Matroska `Colour`, mp4 `colr` -- which is
9+//! what a remuxer rewrites and therefore the most recently asserted truth,
10+//! 2. the **bitstream**'s: an H.264 or HEVC SPS VUI `colour_description`, an
11+//! AV1 sequence header `color_config`, which is what the *encoder* wrote and
12+//! what survives a container that dropped its tags,
13+//! 3. the **resolution heuristic** ffmpeg and mpv both fall back to: a picture
14+//! 720 lines or taller is BT.709, anything smaller is BT.601, limited range
15+//! either way.
16+//!
17+//! Per field, not per file: a Matroska that tags `Range` and nothing else
18+//! leaves the matrix to the SPS below it. A code this does not know -- reserved,
19+//! unspecified, or a matrix with no implementation here -- is the same as an
20+//! absent one and falls to the next tier, which is the whole reason the tiers
21+//! carry [`Option`]s rather than resolved values.
22+//!
23+//! Code values are ISO/IEC 23091-2 (= ITU-T H.273), the one table Matroska, mp4
24+//! `colr`, H.264 VUI, HEVC VUI and AV1 `color_config` all point at.
25+
26+use crate::demux::Codec;
27+
28+/// The YUV->RGB matrix a stream's chroma was coded against. Only the three that
29+/// exist in practice: SD (BT.601), HD (BT.709) and UHD/HDR (BT.2020
30+/// non-constant-luminance). Constant-luminance BT.2020 is not here because no
31+/// encoder writes it.
32+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33+pub enum Matrix {
34+ Bt601,
35+ Bt709,
36+ Bt2020Ncl,
37+}
38+
39+/// The transfer curve the samples are on. `Sdr` covers every curve that is
40+/// displayed as-is -- BT.709's, sRGB's, SMPTE 170M's, which differ by less than
41+/// a display's own calibration -- against the two HDR ones, which do not.
42+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43+pub enum Transfer {
44+ Sdr,
45+ /// SMPTE ST 2084, "PQ": what an HDR10 file is on.
46+ Pq,
47+ /// ARIB STD-B67, "HLG": broadcast HDR.
48+ Hlg,
49+}
50+
51+/// What one video stream's samples mean, resolved through all three tiers.
52+/// [`Default`] is what this engine assumed of every file before it read any of
53+/// this: BT.601, SDR, limited range.
54+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55+pub struct ColorDescription {
56+ pub matrix: Matrix,
57+ pub transfer: Transfer,
58+ /// `true` when the samples use all 256 codes (JPEG/"pc" range) rather than
59+ /// the broadcast 16..235 luma / 16..240 chroma.
60+ pub full_range: bool,
61+}
62+
63+impl Default for ColorDescription {
64+ fn default() -> Self {
65+ Self {
66+ matrix: Matrix::Bt601,
67+ transfer: Transfer::Sdr,
68+ full_range: false,
69+ }
70+ }
71+}
72+
73+impl ColorDescription {
74+ /// The three tiers collapsed into one answer. `height` is the coded picture
75+ /// height the heuristic reads when nothing else said anything.
76+ pub fn resolve(container: Tags, bitstream: Tags, height: u32) -> Self {
77+ let tags = container.over(bitstream);
78+ Self {
79+ // The ffmpeg/mpv rule, and the reason it is a rule: an untagged
80+ // 1080p file is HD material and an untagged 480p one came off SD
81+ // material, and guessing the other way is a visible green/magenta
82+ // shift on faces.
83+ matrix: tags.matrix.unwrap_or(if height >= 720 {
84+ Matrix::Bt709
85+ } else {
86+ Matrix::Bt601
87+ }),
88+ transfer: tags.transfer.unwrap_or(Transfer::Sdr),
89+ full_range: tags.full_range.unwrap_or(false),
90+ }
91+ }
92+}
93+
94+/// One tier's worth of colour tags: what that tier said, field by field, with
95+/// [`None`] for "said nothing" and for "said something this does not implement".
96+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
97+pub struct Tags {
98+ pub matrix: Option<Matrix>,
99+ pub transfer: Option<Transfer>,
100+ pub full_range: Option<bool>,
101+}
102+
103+impl Tags {
104+ /// H.273 code points, as every container and every bitstream writes them.
105+ /// `range` is the Matroska `Range` code -- 0 unspecified, 1 limited, 2 full,
106+ /// 3 "whatever the matrix implies", which is a non-answer here. A source
107+ /// that carries a plain `video_full_range_flag` instead passes `1 + flag`.
108+ pub fn from_codes(matrix: u64, transfer: u64, range: u64) -> Self {
109+ Self {
110+ matrix: match matrix {
111+ 1 => Some(Matrix::Bt709),
112+ // 5 is BT.470BG (PAL), 6 SMPTE 170M (NTSC): one matrix, two
113+ // names for the two halves of the world's SD television.
114+ 5 | 6 => Some(Matrix::Bt601),
115+ 9 => Some(Matrix::Bt2020Ncl),
116+ // 0 unspecified, 2 reserved, 4 FCC, 7 SMPTE 240M, 10 BT.2020
117+ // constant-luminance, 14 ICtCp: nothing this renders with.
118+ _ => None,
119+ },
120+ transfer: match transfer {
121+ 16 => Some(Transfer::Pq),
122+ 18 => Some(Transfer::Hlg),
123+ // Unspecified and reserved say nothing; every other assigned
124+ // curve is displayed the way an SDR one is here.
125+ 0 | 2 => None,
126+ _ => Some(Transfer::Sdr),
127+ },
128+ full_range: match range {
129+ 1 => Some(false),
130+ 2 => Some(true),
131+ _ => None,
132+ },
133+ }
134+ }
135+
136+ /// This tier's answers, with `next`'s used for whatever this one left open.
137+ fn over(self, next: Self) -> Self {
138+ Self {
139+ matrix: self.matrix.or(next.matrix),
140+ transfer: self.transfer.or(next.transfer),
141+ full_range: self.full_range.or(next.full_range),
142+ }
143+ }
144+}
145+
146+/// What the *encoder* wrote into the stream itself, out of the parameter sets
147+/// the demuxers already hold: the SPS VUI for H.264 and HEVC (Annex-B framed,
148+/// which is how both demuxers keep them) and the sequence header OBU for AV1.
149+///
150+/// Empty [`Tags`] for VP9, whose colour space lives in the uncompressed header
151+/// of every frame rather than out of band, and for anything malformed: this is
152+/// a middle tier, and the tier below it always has an answer.
153+pub fn bitstream_tags(codec: Codec, sets: &[u8]) -> Tags {
154+ match codec {
155+ // 7 is an H.264 SPS, 33 an HEVC one (whose NAL header is two bytes and
156+ // whose type sits in bits 1..6 of the first).
157+ Codec::H264 => nal_units(sets)
158+ .find(|n| n.first().is_some_and(|b| b & 0x1f == 7))
159+ .map(|n| h264_sps(&rbsp(&n[1..])))
160+ .unwrap_or_default(),
161+ Codec::Hevc => nal_units(sets)
162+ .find(|n| n.first().is_some_and(|b| (b >> 1) & 0x3f == 33))
163+ .filter(|n| n.len() > 2)
164+ .map(|n| hevc_sps(&rbsp(&n[2..])))
165+ .unwrap_or_default(),
166+ Codec::Av1 => av1_sequence_header(sets),
167+ Codec::Vp9 => Tags::default(),
168+ }
169+}
170+
171+/// The Annex-B NAL units in `buf`, payloads only: start codes are three or four
172+/// bytes and both are written in practice (the demuxers write four, an in-band
173+/// stream may carry either).
174+fn nal_units(buf: &[u8]) -> impl Iterator<Item = &[u8]> {
175+ let mut at = 0;
176+ std::iter::from_fn(move || {
177+ // Find the next start code, then the one after it, which is where this
178+ // unit ends.
179+ let start = (at..buf.len().saturating_sub(2)).find(|&i| buf[i..i + 3] == [0, 0, 1])? + 3;
180+ let end = (start..buf.len().saturating_sub(2))
181+ .find(|&i| buf[i..i + 3] == [0, 0, 1])
182+ .map(|i| {
183+ if i > start && buf[i - 1] == 0 {
184+ i - 1
185+ } else {
186+ i
187+ }
188+ })
189+ .unwrap_or(buf.len());
190+ at = end;
191+ Some(&buf[start..end])
192+ })
193+}
194+
195+/// A NAL payload with its emulation-prevention bytes removed (H.264 §7.4.1.1,
196+/// H.265 §7.4.2): a `00 00 03` in the coded bytes is a `00 00` that would
197+/// otherwise have looked like a start code, and the `03` is not part of the
198+/// syntax.
199+fn rbsp(nal: &[u8]) -> Vec<u8> {
200+ let mut out = Vec::with_capacity(nal.len());
201+ let mut zeros = 0;
202+ for &b in nal {
203+ if zeros == 2 && b == 3 {
204+ zeros = 0;
205+ continue;
206+ }
207+ zeros = if b == 0 { zeros + 1 } else { 0 };
208+ out.push(b);
209+ }
210+ out
211+}
212+
213+/// MSB-first bit reader over an RBSP or an OBU. Reads past the end return zero
214+/// and raise [`Bits::overrun`], which every parser here checks before it
215+/// believes anything it read -- a truncated parameter set must fall to the next
216+/// tier, not report the colour of whatever the zeros decoded to.
217+struct Bits<'a> {
218+ buf: &'a [u8],
219+ /// Bit position, MSB of byte 0 first.
220+ at: usize,
221+ over: bool,
222+}
223+
224+impl<'a> Bits<'a> {
225+ fn new(buf: &'a [u8]) -> Self {
226+ Self {
227+ buf,
228+ at: 0,
229+ over: false,
230+ }
231+ }
232+
233+ fn overrun(&self) -> bool {
234+ self.over
235+ }
236+
237+ fn bit(&mut self) -> u32 {
238+ let Some(&byte) = self.buf.get(self.at / 8) else {
239+ self.over = true;
240+ return 0;
241+ };
242+ let bit = u32::from(byte >> (7 - self.at % 8)) & 1;
243+ self.at += 1;
244+ bit
245+ }
246+
247+ /// `u(n)`, up to 32 bits.
248+ fn u(&mut self, n: u32) -> u32 {
249+ (0..n).fold(0, |acc, _| (acc << 1) | self.bit())
250+ }
251+
252+ /// Bits nothing here reads, in one step -- profile/tier records and the
253+ /// like, which run to 88 bits at a time.
254+ fn skip(&mut self, n: usize) {
255+ self.at += n;
256+ if self.at > self.buf.len() * 8 {
257+ self.over = true;
258+ }
259+ }
260+
261+ /// `ue(v)`, unsigned exp-Golomb: N leading zeros, a one, then N more bits.
262+ /// Capped at 32 leading zeros, which is past any legal value and is what
263+ /// keeps a garbage set from spinning here.
264+ fn ue(&mut self) -> u32 {
265+ let mut zeros = 0;
266+ while self.bit() == 0 {
267+ zeros += 1;
268+ if zeros >= 32 || self.over {
269+ self.over = true;
270+ return 0;
271+ }
272+ }
273+ ((1u32 << zeros) - 1).wrapping_add(self.u(zeros))
274+ }
275+
276+ /// `se(v)`, signed exp-Golomb: the unsigned code zig-zagged.
277+ fn se(&mut self) -> i32 {
278+ let k = self.ue();
279+ if k % 2 == 0 {
280+ -((k / 2) as i32)
281+ } else {
282+ ((k + 1) / 2) as i32
283+ }
284+ }
285+}
286+
287+/// H.264 `seq_parameter_set_data` (ITU-T H.264 §7.3.2.1.1) walked as far as the
288+/// VUI's `colour_description` (Annex E, §E.1.1). Everything before it is read
289+/// only to know how many bits it took -- which is why the scaling lists matter:
290+/// a High-profile SPS that carries them and is walked as if it did not lands the
291+/// VUI read somewhere in the middle of a coefficient.
292+fn h264_sps(rbsp: &[u8]) -> Tags {
293+ let mut b = Bits::new(rbsp);
294+ let profile_idc = b.u(8);
295+ b.skip(8 + 8); // constraint flags + reserved, level_idc
296+ b.ue(); // seq_parameter_set_id
297+ // The chroma/depth block exists only in the profiles that can code
298+ // something other than 8-bit 4:2:0 (§7.3.2.1.1, the profile_idc list).
299+ if matches!(
300+ profile_idc,
301+ 100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135
302+ ) {
303+ let chroma_format_idc = b.ue();
304+ if chroma_format_idc == 3 {
305+ b.bit(); // separate_colour_plane_flag
306+ }
307+ b.ue(); // bit_depth_luma_minus8
308+ b.ue(); // bit_depth_chroma_minus8
309+ b.bit(); // qpprime_y_zero_transform_bypass_flag
310+ if b.bit() == 1 {
311+ // seq_scaling_matrix_present_flag: 8 lists (12 for 4:4:4), the
312+ // first six 16 coefficients long and the rest 64 (§7.3.2.1.1.1).
313+ let lists = if chroma_format_idc == 3 { 12 } else { 8 };
314+ for i in 0..lists {
315+ if b.bit() == 1 {
316+ scaling_list(&mut b, if i < 6 { 16 } else { 64 });
317+ }
318+ }
319+ }
320+ }
321+ b.ue(); // log2_max_frame_num_minus4
322+ match b.ue() {
323+ // pic_order_cnt_type
324+ 0 => {
325+ b.ue(); // log2_max_pic_order_cnt_lsb_minus4
326+ }
327+ 1 => {
328+ b.bit(); // delta_pic_order_always_zero_flag
329+ b.se(); // offset_for_non_ref_pic
330+ b.se(); // offset_for_top_to_bottom_field
331+ let cycle = b.ue();
332+ if cycle > 255 {
333+ return Tags::default();
334+ }
335+ for _ in 0..cycle {
336+ b.se(); // offset_for_ref_frame[i]
337+ }
338+ }
339+ _ => {}
340+ }
341+ b.ue(); // max_num_ref_frames
342+ b.bit(); // gaps_in_frame_num_value_allowed_flag
343+ b.ue(); // pic_width_in_mbs_minus1
344+ b.ue(); // pic_height_in_map_units_minus1
345+ if b.bit() == 0 {
346+ b.bit(); // mb_adaptive_frame_field_flag, when !frame_mbs_only_flag
347+ }
348+ b.bit(); // direct_8x8_inference_flag
349+ if b.bit() == 1 {
350+ // frame_cropping_flag: four offsets
351+ for _ in 0..4 {
352+ b.ue();
353+ }
354+ }
355+ if b.bit() == 0 {
356+ return Tags::default(); // no VUI at all
357+ }
358+ vui_colour(&mut b)
359+}
360+
361+/// One H.264 scaling list (§7.3.2.1.1.1): `size` deltas, the run stopping early
362+/// once a `nextScale` of zero says the rest of the list is the default one.
363+fn scaling_list(b: &mut Bits, size: usize) {
364+ let mut next = 8;
365+ for _ in 0..size {
366+ if next != 0 {
367+ next = (next + b.se() + 256) % 256;
368+ }
369+ if b.overrun() {
370+ return;
371+ }
372+ }
373+}
374+
375+/// HEVC `seq_parameter_set_rbsp` (ITU-T H.265 §7.3.2.2.1) to its VUI
376+/// (§E.2.1). The two places bits are easy to lose are the profile/tier record
377+/// (§7.3.3) and the short-term reference picture sets (§7.3.7), both of which
378+/// are counted here rather than read.
379+fn hevc_sps(rbsp: &[u8]) -> Tags {
380+ let mut b = Bits::new(rbsp);
381+ b.skip(4); // sps_video_parameter_set_id
382+ let max_sub_layers_minus1 = b.u(3);
383+ b.bit(); // sps_temporal_id_nesting_flag
384+ profile_tier_level(&mut b, max_sub_layers_minus1);
385+ b.ue(); // sps_seq_parameter_set_id
386+ let chroma_format_idc = b.ue();
387+ if chroma_format_idc == 3 {
388+ b.bit(); // separate_colour_plane_flag
389+ }
390+ b.ue(); // pic_width_in_luma_samples
391+ b.ue(); // pic_height_in_luma_samples
392+ if b.bit() == 1 {
393+ // conformance_window_flag
394+ for _ in 0..4 {
395+ b.ue();
396+ }
397+ }
398+ b.ue(); // bit_depth_luma_minus8
399+ b.ue(); // bit_depth_chroma_minus8
400+ let log2_max_poc_lsb = b.ue() + 4;
401+ let ordering_info = b.bit() == 1;
402+ let first = if ordering_info {
403+ 0
404+ } else {
405+ max_sub_layers_minus1
406+ };
407+ for _ in first..=max_sub_layers_minus1 {
408+ b.ue(); // sps_max_dec_pic_buffering_minus1
409+ b.ue(); // sps_max_num_reorder_pics
410+ b.ue(); // sps_max_latency_increase_plus1
411+ }
412+ for _ in 0..6 {
413+ // log2_min_luma_coding_block_size_minus3 through
414+ // max_transform_hierarchy_depth_intra: six plain ue(v)s.
415+ b.ue();
416+ }
417+ if b.bit() == 1 && b.bit() == 1 {
418+ // scaling_list_enabled_flag && sps_scaling_list_data_present_flag
419+ scaling_list_data(&mut b);
420+ }
421+ b.bit(); // amp_enabled_flag
422+ b.bit(); // sample_adaptive_offset_enabled_flag
423+ if b.bit() == 1 {
424+ // pcm_enabled_flag
425+ b.skip(8); // pcm_sample_bit_depth_luma/chroma_minus1
426+ b.ue(); // log2_min_pcm_luma_coding_block_size_minus3
427+ b.ue(); // log2_diff_max_min_pcm_luma_coding_block_size
428+ b.bit(); // pcm_loop_filter_disabled_flag
429+ }
430+ let sets = b.ue();
431+ if sets > 64 || b.overrun() {
432+ return Tags::default();
433+ }
434+ let mut counts = Vec::with_capacity(sets as usize);
435+ for i in 0..sets as usize {
436+ st_ref_pic_set(&mut b, i, &mut counts);
437+ if b.overrun() {
438+ return Tags::default();
439+ }
440+ }
441+ if b.bit() == 1 {
442+ // long_term_ref_pics_present_flag
443+ let lt = b.ue();
444+ if lt > 64 {
445+ return Tags::default();
446+ }
447+ for _ in 0..lt {
448+ b.skip(log2_max_poc_lsb as usize); // lt_ref_pic_poc_lsb_sps[i]
449+ b.bit(); // used_by_curr_pic_lt_sps_flag[i]
450+ }
451+ }
452+ b.bit(); // sps_temporal_mvp_enabled_flag
453+ b.bit(); // strong_intra_smoothing_enabled_flag
454+ if b.bit() == 0 {
455+ return Tags::default(); // no VUI at all
456+ }
457+ vui_colour(&mut b)
458+}
459+
460+/// `profile_tier_level` (§7.3.3), counted: 2+1+5 bits of general profile, 32
461+/// compatibility flags, 48 bits of source/reserved flags and an 8-bit level,
462+/// then one 88-bit record per sub-layer that declares one.
463+fn profile_tier_level(b: &mut Bits, max_sub_layers_minus1: u32) {
464+ b.skip(2 + 1 + 5 + 32 + 48 + 8);
465+ let mut present = [(false, false); 8];
466+ for slot in present.iter_mut().take(max_sub_layers_minus1 as usize) {
467+ *slot = (b.bit() == 1, b.bit() == 1);
468+ }
469+ if max_sub_layers_minus1 > 0 {
470+ // reserved_zero_2bits up to eight sub-layers.
471+ b.skip(2 * (8 - max_sub_layers_minus1 as usize));
472+ }
473+ for &(profile, level) in present.iter().take(max_sub_layers_minus1 as usize) {
474+ if profile {
475+ b.skip(88);
476+ }
477+ if level {
478+ b.skip(8);
479+ }
480+ }
481+}
482+
483+/// `scaling_list_data` (§7.3.4): four sizes of six matrices each (the last size
484+/// has two), either predicted from an earlier matrix or written out as deltas.
485+fn scaling_list_data(b: &mut Bits) {
486+ for size_id in 0..4 {
487+ let step = if size_id == 3 { 3 } else { 1 };
488+ for _ in (0..6).step_by(step) {
489+ if b.bit() == 0 {
490+ b.ue(); // scaling_list_pred_matrix_id_delta
491+ continue;
492+ }
493+ let coefs = 64.min(1 << (4 + (size_id << 1)));
494+ if size_id > 1 {
495+ b.se(); // scaling_list_dc_coef_minus8
496+ }
497+ for _ in 0..coefs {
498+ b.se(); // scaling_list_delta_coef
499+ }
500+ if b.overrun() {
501+ return;
502+ }
503+ }
504+ }
505+}
506+
507+/// One `st_ref_pic_set` (§7.3.7), kept only for the number of pictures it
508+/// holds: that count is what the *next* set spends a flag per picture on when
509+/// it predicts from this one, so losing it loses the bit position.
510+///
511+/// ponytail: the predicted case counts flags rather than deriving the POCs
512+/// (§7.4.8, (7-59)..(7-71)), so a set whose `deltaRps` cancels a reference's
513+/// own delta exactly -- a picture at POC distance zero, which is the current
514+/// picture and which no encoder emits -- would be counted one too high. The
515+/// upgrade path is carrying the `DeltaPocS0/S1` arrays through the loop; the
516+/// price of being wrong is a VUI that reads as garbage and falls to the
517+/// resolution heuristic, not a bad picture.
518+fn st_ref_pic_set(b: &mut Bits, idx: usize, counts: &mut Vec<u32>) {
519+ if idx > 0 && b.bit() == 1 {
520+ b.bit(); // delta_rps_sign
521+ b.ue(); // abs_delta_rps_minus1
522+ let mut kept = 0;
523+ for _ in 0..=counts[idx - 1] {
524+ // used_by_curr_pic_flag, and use_delta_flag only when it is not.
525+ let used = b.bit() == 1;
526+ kept += u32::from(used || b.bit() == 1);
527+ }
528+ counts.push(kept);
529+ return;
530+ }
531+ let negative = b.ue();
532+ let positive = b.ue();
533+ if negative > 64 || positive > 64 {
534+ b.over = true;
535+ counts.push(0);
536+ return;
537+ }
538+ for _ in 0..negative + positive {
539+ b.ue(); // delta_poc_s0/s1_minus1
540+ b.bit(); // used_by_curr_pic_s0/s1_flag
541+ }
542+ counts.push(negative + positive);
543+}
544+
545+/// The head of a VUI, H.264 (§E.1.1) and HEVC (§E.2.1) alike -- the two are
546+/// byte-identical up to and including `colour_description`, which is all that is
547+/// read here.
548+fn vui_colour(b: &mut Bits) -> Tags {
549+ if b.bit() == 1 {
550+ // aspect_ratio_info_present_flag
551+ if b.u(8) == 255 {
552+ // Extended_SAR: the ratio is written out rather than indexed.
553+ b.skip(32);
554+ }
555+ }
556+ if b.bit() == 1 {
557+ b.bit(); // overscan_appropriate_flag
558+ }
559+ if b.bit() == 0 {
560+ return Tags::default(); // no video_signal_type at all
561+ }
562+ b.skip(3); // video_format
563+ let full_range = b.bit();
564+ if b.bit() == 0 || b.overrun() {
565+ // colour_description_present_flag: the range flag still stands on its
566+ // own, which is what an untagged-but-full-range stream says.
567+ return Tags {
568+ full_range: (!b.overrun()).then_some(full_range == 1),
569+ ..Tags::default()
570+ };
571+ }
572+ let (primaries, transfer, matrix) = (b.u(8), b.u(8), b.u(8));
573+ let _ = primaries;
574+ if b.overrun() {
575+ return Tags::default();
576+ }
577+ Tags::from_codes(
578+ u64::from(matrix),
579+ u64::from(transfer),
580+ u64::from(full_range) + 1,
581+ )
582+}
583+
584+/// `color_config` out of the sequence header OBU (AV1 §5.5.1, §5.5.2), which is
585+/// what `av1C`/`CodecPrivate` carries and what both demuxers re-inject ahead of
586+/// every keyframe. The whole header before it is counted, and most of it is
587+/// conditional -- the operating points and the decoder model in particular.
588+fn av1_sequence_header(obus: &[u8]) -> Tags {
589+ let Some(payload) = sequence_header_obu(obus) else {
590+ return Tags::default();
591+ };
592+ let mut b = Bits::new(payload);
593+ let seq_profile = b.u(3);
594+ b.bit(); // still_picture
595+ let reduced = b.bit() == 1;
596+ let mut decoder_model = false;
597+ if reduced {
598+ b.skip(5); // seq_level_idx[0]
599+ } else {
600+ if b.bit() == 1 {
601+ // timing_info: two 32-bit ticks and, if the interval is fixed, a
602+ // uvlc() -- the one variable-length code in this header.
603+ b.skip(64);
604+ if b.bit() == 1 {
605+ uvlc(&mut b);
606+ }
607+ decoder_model = b.bit() == 1;
608+ if decoder_model {
609+ b.skip(5 + 32 + 5 + 5);
610+ }
611+ }
612+ let initial_display_delay = b.bit() == 1;
613+ let operating_points = b.u(5) + 1;
614+ for _ in 0..operating_points {
615+ b.skip(12); // operating_point_idc[i]
616+ let level = b.u(5);
617+ if level > 7 {
618+ b.bit(); // seq_tier[i]
619+ }
620+ if decoder_model && b.bit() == 1 {
621+ // operating_parameters_info: two delays of the length the
622+ // decoder model declared, plus low_delay_mode_flag. The lengths
623+ // were skipped above, so a file with a decoder model is where
624+ // this walk stops being able to count.
625+ return Tags::default();
626+ }
627+ if initial_display_delay && b.bit() == 1 {
628+ b.skip(4); // initial_display_delay_minus_1[i]
629+ }
630+ }
631+ }
632+ let width_bits = b.u(4) + 1;
633+ let height_bits = b.u(4) + 1;
634+ b.skip((width_bits + height_bits) as usize); // max_frame_width/height_minus_1
635+ if !reduced && b.bit() == 1 {
636+ b.skip(4 + 3); // delta/additional frame id lengths
637+ }
638+ b.skip(3); // use_128x128_superblock, enable_filter_intra, intra_edge_filter
639+ if !reduced {
640+ b.skip(4); // enable_interintra_compound .. enable_dual_filter
641+ let order_hint = b.bit() == 1;
642+ if order_hint {
643+ b.skip(2); // enable_jnt_comp, enable_ref_frame_mvs
644+ }
645+ // seq_choose_screen_content_tools, or the forced value when it is not
646+ // chosen; the integer-mv pair after it exists only when the tools do.
647+ let screen_content = if b.bit() == 1 { 2 } else { b.bit() };
648+ if screen_content > 0 && b.bit() == 0 {
649+ b.bit(); // seq_force_integer_mv
650+ }
651+ if order_hint {
652+ b.skip(3); // order_hint_bits_minus_1
653+ }
654+ }
655+ b.skip(3); // enable_superres, enable_cdef, enable_restoration
656+ av1_color_config(&mut b, seq_profile)
657+}
658+
659+/// The payload of the first sequence header OBU (type 1) in a low-overhead OBU
660+/// stream (AV1 §5.3.1): a one-byte header, an optional extension byte, and an
661+/// optional leb128 size.
662+fn sequence_header_obu(mut buf: &[u8]) -> Option<&[u8]> {
663+ while let Some((&head, rest)) = buf.split_first() {
664+ let kind = (head >> 3) & 0xf;
665+ let mut rest = rest;
666+ if head & 0x4 != 0 {
667+ rest = rest.get(1..)?; // obu_extension_flag: temporal/spatial ids
668+ }
669+ let size = if head & 0x2 != 0 {
670+ let (size, read) = leb128(rest)?;
671+ rest = rest.get(read..)?;
672+ size.min(rest.len())
673+ } else {
674+ rest.len()
675+ };
676+ if kind == 1 {
677+ return rest.get(..size);
678+ }
679+ buf = rest.get(size..)?;
680+ }
681+ None
682+}
683+
684+/// leb128 as AV1 writes it (§4.10.5): seven bits a byte, low group first, the
685+/// top bit saying another follows.
686+fn leb128(buf: &[u8]) -> Option<(usize, usize)> {
687+ let mut value = 0usize;
688+ for i in 0..8 {
689+ let &byte = buf.get(i)?;
690+ value |= usize::from(byte & 0x7f) << (i * 7);
691+ if byte & 0x80 == 0 {
692+ return Some((value, i + 1));
693+ }
694+ }
695+ None
696+}
697+
698+/// `uvlc()` (AV1 §4.10.3): leading zeros, then that many bits, biased -- the
699+/// same shape as exp-Golomb with a different bias.
700+fn uvlc(b: &mut Bits) {
701+ let mut zeros = 0;
702+ while b.bit() == 0 && !b.overrun() {
703+ zeros += 1;
704+ if zeros >= 32 {
705+ b.over = true;
706+ return;
707+ }
708+ }
709+ b.skip(zeros);
710+}
711+
712+/// `color_config` (AV1 §5.5.2). The bit depth and the subsampling are read only
713+/// as far as they cost bits before `color_range`.
714+fn av1_color_config(b: &mut Bits, seq_profile: u32) -> Tags {
715+ let high_bitdepth = b.bit() == 1;
716+ if seq_profile == 2 && high_bitdepth {
717+ b.bit(); // twelve_bit
718+ }
719+ let mono_chrome = seq_profile != 1 && b.bit() == 1;
720+ let described = b.bit() == 1;
721+ let (primaries, transfer, matrix) = if described {
722+ (b.u(8), b.u(8), b.u(8))
723+ } else {
724+ (2, 2, 2) // CP/TC/MC_UNSPECIFIED
725+ };
726+ if b.overrun() {
727+ return Tags::default();
728+ }
729+ let full_range = if mono_chrome {
730+ b.bit() == 1
731+ } else if primaries == 1 && transfer == 13 && matrix == 0 {
732+ // sRGB in an identity matrix is full range by definition, and the flag
733+ // is not written.
734+ true
735+ } else {
736+ b.bit() == 1
737+ };
738+ if b.overrun() {
739+ return Tags::default();
740+ }
741+ Tags {
742+ full_range: Some(full_range),
743+ ..Tags::from_codes(u64::from(matrix), u64::from(transfer), 0)
744+ }
745+}
746+
747+#[cfg(test)]
748+mod tests {
749+ use super::*;
750+ use crate::demux::Demuxer;
751+ use std::path::{Path, PathBuf};
752+
753+ fn asset(name: &str) -> PathBuf {
754+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
755+ .join("../../assets")
756+ .join(name)
757+ }
758+
759+ fn color_of(name: &str) -> ColorDescription {
760+ let (meta, _) = Demuxer::open(&asset(name)).unwrap_or_else(|e| panic!("open {name}: {e}"));
761+ meta.color
762+ }
763+
764+ /// The tier order itself: a container tag beats both a bitstream tag and the
765+ /// heuristic, field by field.
766+ #[test]
767+ fn tiers_resolve_in_order() {
768+ let container = Tags::from_codes(9, 16, 1);
769+ let bitstream = Tags::from_codes(1, 1, 2);
770+ assert_eq!(
771+ ColorDescription::resolve(container, bitstream, 2160),
772+ ColorDescription {
773+ matrix: Matrix::Bt2020Ncl,
774+ transfer: Transfer::Pq,
775+ full_range: false,
776+ }
777+ );
778+ // A container that tagged only the range leaves the rest to the SPS.
779+ let range_only = Tags::from_codes(0, 0, 2);
780+ assert_eq!(
781+ ColorDescription::resolve(range_only, bitstream, 480),
782+ ColorDescription {
783+ matrix: Matrix::Bt709,
784+ transfer: Transfer::Sdr,
785+ full_range: true,
786+ }
787+ );
788+ // Nothing anywhere: the resolution decides, and only the resolution.
789+ let none = Tags::default();
790+ assert_eq!(
791+ ColorDescription::resolve(none, none, 1080).matrix,
792+ Matrix::Bt709
793+ );
794+ assert_eq!(
795+ ColorDescription::resolve(none, none, 719).matrix,
796+ Matrix::Bt601
797+ );
798+ assert_eq!(
799+ ColorDescription::default(),
800+ ColorDescription::resolve(none, none, 480)
801+ );
802+ }
803+
804+ /// Reserved and unimplemented code points are "said nothing", not a wrong
805+ /// answer: that is what makes them fall through.
806+ #[test]
807+ fn unknown_codes_fall_through() {
808+ assert_eq!(Tags::from_codes(2, 2, 3), Tags::default());
809+ assert_eq!(Tags::from_codes(7, 0, 0).matrix, None); // SMPTE 240M
810+ assert_eq!(Tags::from_codes(6, 1, 1).transfer, Some(Transfer::Sdr));
811+ assert_eq!(Tags::from_codes(0, 18, 2).transfer, Some(Transfer::Hlg));
812+ }
813+
814+ /// The bit reader, against a hand-built pattern: exp-Golomb is where a
815+ /// mis-read shifts everything after it.
816+ #[test]
817+ fn bit_reader_reads_exp_golomb() {
818+ // 1 | 010 | 011 | 00100 : ue = 0, 1, 2, 3
819+ let mut b = Bits::new(&[0b1010_0110, 0b0100_0000]);
820+ assert_eq!((b.ue(), b.ue(), b.ue(), b.ue()), (0, 1, 2, 3));
821+ assert!(!b.overrun());
822+ // se zig-zags: 0, 1, -1, 2
823+ let mut b = Bits::new(&[0b1010_0110, 0b0100_0000]);
824+ assert_eq!((b.se(), b.se(), b.se(), b.se()), (0, 1, -1, 2));
825+ // Past the end reads zero and says so.
826+ let mut b = Bits::new(&[0xff]);
827+ b.skip(8);
828+ assert_eq!(b.u(4), 0);
829+ assert!(b.overrun());
830+ }
831+
832+ /// Emulation prevention: the `03` is syntax-invisible, a third `00` is not.
833+ #[test]
834+ fn rbsp_drops_emulation_bytes() {
835+ assert_eq!(rbsp(&[0, 0, 3, 1, 0, 0, 3, 0]), vec![0, 0, 1, 0, 0, 0]);
836+ assert_eq!(rbsp(&[0, 3, 3]), vec![0, 3, 3]);
837+ }
838+
839+ /// A generated fixture whose *container* says BT.601 at 720 lines, where the
840+ /// heuristic would have said BT.709: proof the container tier is read and
841+ /// that it wins. Both containers, because both parse it themselves.
842+ #[test]
843+ fn container_tags_win_over_the_heuristic() {
844+ for name in ["test_bt601.mp4", "test_bt601.mkv"] {
845+ assert_eq!(
846+ color_of(name),
847+ ColorDescription {
848+ matrix: Matrix::Bt601,
849+ transfer: Transfer::Sdr,
850+ full_range: false,
851+ },
852+ "{name}"
853+ );
854+ }
855+ }
856+
857+ /// Bits written out as `'0'`/`'1'`, MSB first, for a hand-built SPS.
858+ fn bits_of(pattern: &str) -> Vec<u8> {
859+ let mut out = Vec::new();
860+ for (i, c) in pattern.chars().filter(|c| !c.is_whitespace()).enumerate() {
861+ if i % 8 == 0 {
862+ out.push(0);
863+ }
864+ if c == '1' {
865+ *out.last_mut().unwrap() |= 0x80 >> (i % 8);
866+ }
867+ }
868+ out
869+ }
870+
871+ /// A High-profile SPS written by hand, because no encoder here writes one
872+ /// with its scaling lists in the *sequence* parameter set (x264 puts its
873+ /// quant matrices in the PPS; the HEVC fixture below has real ones). The
874+ /// lists are what makes this test worth having: read as if they were not
875+ /// there, the VUI lands mid-coefficient and the colour comes out as noise.
876+ #[test]
877+ fn h264_scaling_lists_are_skipped_before_the_vui() {
878+ let sps = concat!(
879+ "01100100", // profile_idc 100 (High)
880+ "00000000", // constraint flags + reserved
881+ "00011110", // level_idc 30
882+ "1", // seq_parameter_set_id ue(0)
883+ "010", // chroma_format_idc ue(1), 4:2:0
884+ "1", // bit_depth_luma_minus8 ue(0)
885+ "1", // bit_depth_chroma_minus8 ue(0)
886+ "0", // qpprime_y_zero_transform_bypass_flag
887+ "1", // seq_scaling_matrix_present_flag
888+ "1", // ...list 0 present
889+ "000010001", // its first delta, se(-8): nextScale hits 0, so the
890+ // remaining 15 coefficients are the default ones and cost no bits
891+ "0000000", // lists 1..7 absent
892+ "1", // log2_max_frame_num_minus4 ue(0)
893+ "1", // pic_order_cnt_type ue(0)
894+ "1", // log2_max_pic_order_cnt_lsb_minus4 ue(0)
895+ "010", // max_num_ref_frames ue(1)
896+ "0", // gaps_in_frame_num_value_allowed_flag
897+ "00000101000", // pic_width_in_mbs_minus1 ue(39), i.e. 640
898+ "000011110", // pic_height_in_map_units_minus1 ue(29), i.e. 480
899+ "1", // frame_mbs_only_flag
900+ "1", // direct_8x8_inference_flag
901+ "0", // frame_cropping_flag
902+ "1", // vui_parameters_present_flag
903+ "0", // aspect_ratio_info_present_flag
904+ "0", // overscan_info_present_flag
905+ "1", // video_signal_type_present_flag
906+ "101", // video_format (unspecified)
907+ "0", // video_full_range_flag
908+ "1", // colour_description_present_flag
909+ "00000001", // colour_primaries 1
910+ "00000001", // transfer_characteristics 1
911+ "00000001", // matrix_coefficients 1 (BT.709)
912+ );
913+ assert_eq!(
914+ h264_sps(&bits_of(sps)),
915+ Tags {
916+ matrix: Some(Matrix::Bt709),
917+ transfer: Some(Transfer::Sdr),
918+ full_range: Some(false),
919+ }
920+ );
921+ }
922+
923+ /// The HEVC twin of the test above, and hand-built for the same reason:
924+ /// x265 writes `sps_scaling_list_data_present_flag` only for a *custom*
925+ /// list, and the fixture below carries the default one (a flag and no
926+ /// data). Custom lists are not exotic -- they are what a psy-tuned anime
927+ /// encode ships -- so the branch that counts them has to be measured.
928+ #[test]
929+ fn hevc_scaling_list_data_is_skipped_before_the_vui() {
930+ let mut sps = String::new();
931+ sps.push_str("0000"); // sps_video_parameter_set_id
932+ sps.push_str("000"); // sps_max_sub_layers_minus1: one layer
933+ sps.push('0'); // sps_temporal_id_nesting_flag
934+ sps.push_str(&"0".repeat(96)); // profile_tier_level, general only
935+ sps.push('1'); // sps_seq_parameter_set_id ue(0)
936+ sps.push_str("010"); // chroma_format_idc ue(1), 4:2:0
937+ sps.push_str("0000000001010000001"); // pic_width_in_luma_samples ue(640)
938+ sps.push_str("00000000111100001"); // pic_height_in_luma_samples ue(480)
939+ sps.push('0'); // conformance_window_flag
940+ sps.push_str("11"); // bit_depth_luma/chroma_minus8 ue(0)
941+ sps.push_str("00101"); // log2_max_pic_order_cnt_lsb_minus4 ue(4)
942+ sps.push('1'); // sps_sub_layer_ordering_info_present_flag
943+ sps.push_str("111"); // ...its three ue(0)s, for the one layer
944+ sps.push_str("111111"); // the six coding/transform-block ue(0)s
945+ sps.push_str("11"); // scaling_list_enabled + sps_scaling_list_data_present
946+ // scaling_list_data: the first 4x4 matrix written out (16 se(0) deltas,
947+ // no DC coefficient at this size), every other matrix predicted from an
948+ // earlier one -- 6+6+6+2 matrices in all.
949+ sps.push('1');
950+ sps.push_str(&"1".repeat(16));
951+ sps.push_str(&"01".repeat(5 + 6 + 6 + 2));
952+ sps.push_str("000"); // amp, sample_adaptive_offset, pcm_enabled
953+ sps.push('1'); // num_short_term_ref_pic_sets ue(0)
954+ sps.push('0'); // long_term_ref_pics_present_flag
955+ sps.push_str("00"); // sps_temporal_mvp, strong_intra_smoothing
956+ sps.push('1'); // vui_parameters_present_flag
957+ sps.push_str("00"); // aspect_ratio_info_present, overscan_info_present
958+ sps.push('1'); // video_signal_type_present_flag
959+ sps.push_str("101"); // video_format (unspecified)
960+ sps.push('0'); // video_full_range_flag
961+ sps.push('1'); // colour_description_present_flag
962+ sps.push_str("000000010000000100000001"); // primaries/transfer/matrix 1
963+ assert_eq!(
964+ hevc_sps(&bits_of(&sps)),
965+ Tags {
966+ matrix: Some(Matrix::Bt709),
967+ transfer: Some(Transfer::Sdr),
968+ full_range: Some(false),
969+ }
970+ );
971+ }
972+
973+ /// The bitstream tier, in the three codecs that carry one: fixtures tagged
974+ /// through the *encoder* alone (x264/x265 VUI, SVT-AV1 `color_config`) and
975+ /// muxed with no `colr` box at all, at 480 lines where the heuristic would
976+ /// have said BT.601. The absence of the box is asserted too: without it a
977+ /// fixture that grew container tags would pass this for the wrong reason.
978+ /// The H.264 one is High profile with `cqm=jvt`, i.e. a real SPS with
979+ /// scaling lists in front of its VUI.
980+ #[test]
981+ fn bitstream_tags_beat_the_heuristic() {
982+ for name in ["test_vui_h264.mp4", "test_vui_hevc.mp4", "test_vui_av1.mp4"] {
983+ let bytes = std::fs::read(asset(name)).unwrap_or_else(|e| panic!("read {name}: {e}"));
984+ assert!(
985+ !bytes.windows(4).any(|w| w == b"colr"),
986+ "{name} carries a colr box, so this would not be testing the bitstream"
987+ );
988+ assert_eq!(color_of(name).matrix, Matrix::Bt709, "{name}");
989+ }
990+ }
991+
992+ /// An untagged 360-line fixture: nothing in the container, nothing in the
993+ /// stream, so the heuristic answers -- BT.601 limited, which is what the
994+ /// engine assumed of everything before any of this was read.
995+ #[test]
996+ fn untagged_sd_falls_to_the_heuristic() {
997+ assert_eq!(color_of("test_mismatch.mp4"), ColorDescription::default());
998+ }
999+
1000+ /// A real HDR film: BT.2020 non-constant-luminance, PQ, limited range, all
1001+ /// three off the Matroska `Colour` element. Gated on the file being here --
1002+ /// it is a 25 GB download, not a fixture.
1003+ #[test]
1004+ fn real_hdr_film_reads_bt2020_pq() {
1005+ let path = Path::new(
1006+ "/path/to/a-real-4k-hdr10-film.mkv",
1007+ );
1008+ if !path.exists() {
1009+ eprintln!("skipped: {} is not on this machine", path.display());
1010+ return;
1011+ }
1012+ let (meta, _) = Demuxer::open(path).expect("open the HDR film");
1013+ assert_eq!(
1014+ meta.color,
1015+ ColorDescription {
1016+ matrix: Matrix::Bt2020Ncl,
1017+ transfer: Transfer::Pq,
1018+ full_range: false,
1019+ }
1020+ );
1021+ }
1022+
1023+ /// A real 720p film with no colour tags anywhere -- neither container nor
1024+ /// SPS -- which is the case the heuristic exists for: BT.709, because it is
1025+ /// HD material. Gated for the same reason as the one above.
1026+ #[test]
1027+ fn real_untagged_hd_film_reads_bt709() {
1028+ let path = Path::new(
1029+ "/path/to/a-real-h264-dual-audio-film.mkv",
1030+ );
1031+ if !path.exists() {
1032+ eprintln!("skipped: {} is not on this machine", path.display());
1033+ return;
1034+ }
1035+ let (meta, _) = Demuxer::open(path).expect("open the untagged film");
1036+ assert_eq!(
1037+ meta.color,
1038+ ColorDescription {
1039+ matrix: Matrix::Bt709,
1040+ transfer: Transfer::Sdr,
1041+ full_range: false,
1042+ }
1043+ );
1044+ }
1045+}
crates/engine/src/demux.rsmodified+83 -0
@@ -19,6 +19,7 @@ use std::path::Path;
19 use mp4::{MediaType, Mp4Reader, Mp4Track, TrackType};19 use mp4::{MediaType, Mp4Reader, Mp4Track, TrackType};
20 20
21 use crate::audio::{edit_media_time, packet_at, stts_pairs};21 use crate::audio::{edit_media_time, packet_at, stts_pairs};
22+use crate::colorspace::{ColorDescription, Tags, bitstream_tags};
22 23
23 const START_CODE: [u8; 4] = [0, 0, 0, 1];24 const START_CODE: [u8; 4] = [0, 0, 0, 1];
24 25
@@ -63,6 +64,10 @@ pub struct VideoMeta {
63 pub frame_rate: f64,64 pub frame_rate: f64,
64 pub frame_count: u32,65 pub frame_count: u32,
65 pub codec: Codec,66 pub codec: Codec,
67+ /// What this stream's samples mean -- which matrix, which transfer curve,
68+ /// which range -- resolved off the container's tags, the bitstream's, and
69+ /// the resolution, in that order. See [`crate::colorspace`].
70+ pub color: ColorDescription,
66 }71 }
67 72
68 /// The file, whichever container it came in. Which one is decided by the73 /// The file, whichever container it came in. Which one is decided by the
@@ -193,6 +198,9 @@ impl Mp4Demuxer {
193 frame_rate: frame_rate(track),198 frame_rate: frame_rate(track),
194 frame_count: 0,199 frame_count: 0,
195 codec,200 codec,
201+ // Filled below, once the parameter sets the bitstream tier reads are
202+ // in hand.
203+ color: ColorDescription::default(),
196 };204 };
197 let first_sample = first_frame_sample(stts_pairs(track), trim_ticks(track));205 let first_sample = first_frame_sample(stts_pairs(track), trim_ticks(track));
198 let mut parameter_sets = Vec::new();206 let mut parameter_sets = Vec::new();
@@ -261,6 +269,11 @@ impl Mp4Demuxer {
261 // The samples the edit list trims off the front are not frames of269 // The samples the edit list trims off the front are not frames of
262 // the presentation, so they are not counted as ones.270 // the presentation, so they are not counted as ones.
263 frame_count: sample_count.saturating_sub(first_sample - 1),271 frame_count: sample_count.saturating_sub(first_sample - 1),
272+ color: ColorDescription::resolve(
273+ colr_tags(path, track_id).unwrap_or_default(),
274+ bitstream_tags(codec, &parameter_sets),
275+ meta.height,
276+ ),
264 ..meta277 ..meta
265 },278 },
266 Self {279 Self {
@@ -441,6 +454,14 @@ impl MkvDemuxer {
441 frame_rate,454 frame_rate,
442 frame_count: blocks.len() as u32,455 frame_count: blocks.len() as u32,
443 codec: video.codec,456 codec: video.codec,
457+ // `config` is the parameter sets by now -- Annex-B for H.264 and
458+ // HEVC, the sequence header OBU for AV1 -- which is what the
459+ // bitstream tier reads.
460+ color: ColorDescription::resolve(
461+ video.tags,
462+ bitstream_tags(video.codec, &video.config),
463+ video.height,
464+ ),
444 };465 };
445 Ok((466 Ok((
446 meta,467 meta,
@@ -667,6 +688,8 @@ struct MkvVideo {
667 number: u64,688 number: u64,
668 width: u32,689 width: u32,
669 height: u32,690 height: u32,
691+ /// What the track's `Colour` element declared, empty when it has none.
692+ tags: Tags,
670 default_duration: Option<u64>,693 default_duration: Option<u64>,
671 timestamp_scale: u64,694 timestamp_scale: u64,
672 codec: Codec,695 codec: Codec,
@@ -801,6 +824,13 @@ const DEFAULT_DURATION: u32 = 0x23E383;
801 const VIDEO: u32 = 0xE0;824 const VIDEO: u32 = 0xE0;
802 const PIXEL_WIDTH: u32 = 0xB0;825 const PIXEL_WIDTH: u32 = 0xB0;
803 const PIXEL_HEIGHT: u32 = 0xBA;826 const PIXEL_HEIGHT: u32 = 0xBA;
827+// The `Colour` element and the three of its children this reads. Byte-verified
828+// against real files rather than taken off a spec table: published tables that
829+// list Range as 0x55B3 are describing ChromaSubsamplingHorz.
830+const COLOUR: u32 = 0x55B0;
831+const MATRIX_COEFFICIENTS: u32 = 0x55B1;
832+const RANGE: u32 = 0x55B9;
833+const TRANSFER_CHARACTERISTICS: u32 = 0x55BA;
804 const TRACK_LANGUAGE: u32 = 0x22B59C;834 const TRACK_LANGUAGE: u32 = 0x22B59C;
805 const TRACK_NAME: u32 = 0x536E;835 const TRACK_NAME: u32 = 0x536E;
806 const CONTENT_ENCODINGS: u32 = 0x6D80;836 const CONTENT_ENCODINGS: u32 = 0x6D80;
@@ -903,6 +933,7 @@ fn mkv_track_entry(
903 let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None);933 let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None);
904 let (mut width, mut height, mut config) = (0, 0, Vec::new());934 let (mut width, mut height, mut config) = (0, 0, Vec::new());
905 let (mut language, mut name) = (String::new(), String::new());935 let (mut language, mut name) = (String::new(), String::new());
936+ let mut tags = Tags::default();
906 let mut unpack = Unpack::None;937 let mut unpack = Unpack::None;
907 let mut at = body;938 let mut at = body;
908 while let Some((id, body, stop)) = ebml_element(file, at, end)? {939 while let Some((id, body, stop)) = ebml_element(file, at, end)? {
@@ -925,6 +956,27 @@ fn mkv_track_entry(
925 match e.0 {956 match e.0 {
926 PIXEL_WIDTH => width = ebml_uint(file, e.1, e.2)? as u32,957 PIXEL_WIDTH => width = ebml_uint(file, e.1, e.2)? as u32,
927 PIXEL_HEIGHT => height = ebml_uint(file, e.1, e.2)? as u32,958 PIXEL_HEIGHT => height = ebml_uint(file, e.1, e.2)? as u32,
959+ // `Colour`: what the file says its picture's numbers
960+ // mean, in the same H.273 code points the bitstream
961+ // uses. An element the file leaves out stays 0, which
962+ // is "unspecified" in every one of those tables and
963+ // falls to the tier below (see [`crate::colorspace`]).
964+ COLOUR => {
965+ let (mut matrix, mut transfer, mut range) = (0, 0, 0);
966+ let mut at = e.1;
967+ while let Some(c) = ebml_element(file, at, e.2)? {
968+ match c.0 {
969+ MATRIX_COEFFICIENTS => matrix = ebml_uint(file, c.1, c.2)?,
970+ TRANSFER_CHARACTERISTICS => {
971+ transfer = ebml_uint(file, c.1, c.2)?
972+ }
973+ RANGE => range = ebml_uint(file, c.1, c.2)?,
974+ _ => {}
975+ }
976+ at = c.2;
977+ }
978+ tags = Tags::from_codes(matrix, transfer, range);
979+ }
928 _ => {}980 _ => {}
929 }981 }
930 at = e.2;982 at = e.2;
@@ -976,6 +1028,7 @@ fn mkv_track_entry(
976 number,1028 number,
977 width,1029 width,
978 height,1030 height,
1031+ tags,
979 default_duration,1032 default_duration,
980 timestamp_scale,1033 timestamp_scale,
981 codec,1034 codec,
@@ -1475,6 +1528,36 @@ fn hvcc_record(path: &Path, track_id: u32) -> crate::Result<Vec<u8>> {
1475 Ok(hvcc.to_vec())1528 Ok(hvcc.to_vec())
1476 }1529 }
1477 1530
1531+/// The `colr` box of `track_id`'s sample entry (ISO 14496-12 §12.1.5), which is
1532+/// where an mp4 says what its picture's numbers mean. `nclx` is what every
1533+/// muxer writes now and carries a range flag; `nclc`, QuickTime's older twin,
1534+/// is the same three code points with no range byte after them. Anything else
1535+/// (`rICC`, `prof`: ICC profiles) is not a code-point description at all and is
1536+/// left to the tier below.
1537+///
1538+/// [`None`] rather than an error for a file with no such box, which is most of
1539+/// them -- an untagged mp4 is not a broken one.
1540+fn colr_tags(path: &Path, track_id: u32) -> Option<Tags> {
1541+ let (_, entry) = sample_entry(path, track_id).ok()?;
1542+ // The same fixed 78-byte VisualSampleEntry header `hvcC` sits behind.
1543+ let colr = child(entry.get(78..).unwrap_or_default(), b"colr")?;
1544+ let kind: &[u8; 4] = colr.get(..4)?.try_into().ok()?;
1545+ if kind != b"nclx" && kind != b"nclc" {
1546+ return None;
1547+ }
1548+ let code = |at: usize| -> Option<u64> {
1549+ Some(u64::from(u16::from_be_bytes(
1550+ colr.get(at..at + 2)?.try_into().ok()?,
1551+ )))
1552+ };
1553+ // Matroska's Range codes are 1 limited / 2 full; a `colr` flag is a bit.
1554+ let range = match kind {
1555+ b"nclx" => colr.get(10).map_or(0, |b| 1 + u64::from(b >> 7)),
1556+ _ => 0,
1557+ };
1558+ Some(Tags::from_codes(code(8)?, code(6)?, range))
1559+}
1560+
1478 /// The four-character code of `track_id`'s first `stsd` sample entry and that1561 /// The four-character code of `track_id`'s first `stsd` sample entry and that
1479 /// entry's payload. Read by hand for the same reason the record above is: the1562 /// entry's payload. Read by hand for the same reason the record above is: the
1480 /// crate keeps no fourcc for a sample entry it does not recognise, so this is1563 /// crate keeps no fourcc for a sample entry it does not recognise, so this is
crates/engine/src/export.rsmodified+2 -0
@@ -2432,6 +2432,7 @@ mod tests {
2432 frame_rate,2432 frame_rate,
2433 frame_count: 1,2433 frame_count: 1,
2434 codec: crate::demux::Codec::H264,2434 codec: crate::demux::Codec::H264,
2435+ color: Default::default(),
2435 };2436 };
2436 // 1280 * 720 * 30 * 0.12437 // 1280 * 720 * 30 * 0.1
2437 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800);2438 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800);
@@ -2446,6 +2447,7 @@ mod tests {
2446 frame_rate: 30.0,2447 frame_rate: 30.0,
2447 frame_count: 1,2448 frame_count: 1,
2448 codec: crate::demux::Codec::H264,2449 codec: crate::demux::Codec::H264,
2450+ color: Default::default(),
2449 }2451 }
2450 }2452 }
2451 2453
crates/engine/src/lib.rsmodified+1 -0
@@ -5,6 +5,7 @@ pub mod audio;
5 pub mod caps;5 pub mod caps;
6 pub mod clock;6 pub mod clock;
7 pub mod color;7 pub mod color;
8+pub mod colorspace;
8 pub mod convert;9 pub mod convert;
9 pub mod decode;10 pub mod decode;
10 pub mod demux;11 pub mod demux;
crates/engine/src/playback.rsmodified+7 -0
@@ -22,6 +22,7 @@ use crate::ao::AoSession;
22 use crate::audio::{AudioChunk, AudioSession};22 use crate::audio::{AudioChunk, AudioSession};
23 use crate::clock::{ClockSource, PlaybackClock};23 use crate::clock::{ClockSource, PlaybackClock};
24 use crate::color::ColorParams;24 use crate::color::ColorParams;
25+use crate::colorspace::ColorDescription;
25 use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker};26 use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker};
26 use crate::demux::{Codec, Demuxer, VideoMeta};27 use crate::demux::{Codec, Demuxer, VideoMeta};
27 use crate::eq::EqParams;28 use crate::eq::EqParams;
@@ -404,6 +405,9 @@ impl PlaybackSession {
404 frame_count: audio_frames(path, frame_rate)405 frame_count: audio_frames(path, frame_rate)
405 .map_err(|e| format!("{}: {e}", path.display()))?,406 .map_err(|e| format!("{}: {e}", path.display()))?,
406 codec: Codec::H264,407 codec: Codec::H264,
408+ // A canvas this engine drew itself, not a stream that was read:
409+ // the default description is what it is drawn in.
410+ color: ColorDescription::default(),
407 };411 };
408 let (audio, audio_disabled) = open_audio(path, 0);412 let (audio, audio_disabled) = open_audio(path, 0);
409 // Through `from_parts` rather than `Project::single`, which is the413 // Through `from_parts` rather than `Project::single`, which is the
@@ -481,6 +485,7 @@ impl PlaybackSession {
481 // playing time is -- see [`image_frames`].485 // playing time is -- see [`image_frames`].
482 frame_count: image_frames(IMAGE_ONLY_RATE),486 frame_count: image_frames(IMAGE_ONLY_RATE),
483 codec: Codec::H264,487 codec: Codec::H264,
488+ color: ColorDescription::default(),
484 };489 };
485 let clip = Clip {490 let clip = Clip {
486 start: 0,491 start: 0,
@@ -608,6 +613,7 @@ impl PlaybackSession {
608 frame_count: audio_frames(&first.path, frame_rate)613 frame_count: audio_frames(&first.path, frame_rate)
609 .map_err(|e| format!("source {}: {e}", first.path.display()))?,614 .map_err(|e| format!("source {}: {e}", first.path.display()))?,
610 codec: Codec::H264,615 codec: Codec::H264,
616+ color: ColorDescription::default(),
611 };617 };
612 (meta, DecodeSession::open_black(width, height, 1))618 (meta, DecodeSession::open_black(width, height, 1))
613 }619 }
@@ -624,6 +630,7 @@ impl PlaybackSession {
624 frame_rate,630 frame_rate,
625 frame_count: image_frames(frame_rate),631 frame_count: image_frames(frame_rate),
626 codec: Codec::H264,632 codec: Codec::H264,
633+ color: ColorDescription::default(),
627 };634 };
628 let stream = DecodeSession::open_still(635 let stream = DecodeSession::open_still(
629 &first.path,636 &first.path,
crates/engine/tests/audio_export.rsmodified+2 -0
@@ -354,6 +354,7 @@ fn a_still_and_a_song_export_as_an_mp4_with_sound() {
354 frame_rate: 30.0,354 frame_rate: 30.0,
355 frame_count: 60,355 frame_count: 60,
356 codec: engine::Codec::H264,356 codec: engine::Codec::H264,
357+ color: Default::default(),
357 };358 };
358 let out = out_path("still_song", "mp4");359 let out = out_path("still_song", "mp4");
359 let handle = engine::export::start(project, meta, &out, &ExportSettings::default());360 let handle = engine::export::start(project, meta, &out, &ExportSettings::default());
@@ -656,6 +657,7 @@ fn the_sound_is_written_at_the_rate_that_was_asked_for() {
656 frame_rate: 30.0,657 frame_rate: 30.0,
657 frame_count: 60,658 frame_count: 60,
658 codec: engine::Codec::H264,659 codec: engine::Codec::H264,
660+ color: Default::default(),
659 };661 };
660 for want in [128u32, 320] {662 for want in [128u32, 320] {
661 let out = out_path(&format!("mp4_aac_{want}"), "mp4");663 let out = out_path(&format!("mp4_aac_{want}"), "mp4");
crates/engine/tests/export.rsmodified+1 -0
@@ -217,6 +217,7 @@ fn exports_at_the_project_resolution_with_the_watched_geometry() {
217 frame_rate: FPS,217 frame_rate: FPS,
218 frame_count: 20,218 frame_count: 20,
219 codec: engine::Codec::H264,219 codec: engine::Codec::H264,
220+ color: Default::default(),
220 };221 };
221 let out = out_path("mixed");222 let out = out_path("mixed");
222 let handle = engine::export::start(project, meta, &out, &ExportSettings::default());223 let handle = engine::export::start(project, meta, &out, &ExportSettings::default());
scripts/gen_fixtures.shmodified+37 -0
@@ -213,6 +213,43 @@ ffmpeg -y -f lavfi -i testsrc2=size=320x180:rate=30:duration=2 \
213 -c:a aac -ar 44100 -ac 2 \213 -c:a aac -ar 44100 -ac 2 \
214 -metadata:s:a:0 language=eng -metadata:s:a:1 language=fra \214 -metadata:s:a:0 language=eng -metadata:s:a:1 language=fra \
215 assets/test_multiaudio.mkv215 assets/test_multiaudio.mkv
216+# Colour-tag fixtures. The picture is irrelevant here -- what is measured is
217+# what the file *says* its numbers mean (`engine::colorspace`), so these are
218+# one-second clips with nothing in them.
219+#
220+# First pair: SMPTE 170M (BT.601) tagged in the container, at 720 lines, where
221+# the resolution heuristic would have said BT.709. That is the point: it is the
222+# fixture that shows the container tags being read and outranking the guess.
223+# Both containers, because the `colr` box and the Matroska `Colour` element are
224+# parsed by different code.
225+for out in assets/test_bt601.mp4 assets/test_bt601.mkv; do
226+ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=1 \
227+ -c:v libx264 -profile:v baseline -pix_fmt yuv420p \
228+ -colorspace smpte170m -color_primaries smpte170m -color_trc smpte170m \
229+ "$out"
230+done
231+# ...and the tier below it: BT.709 written into the *bitstream* by the encoder
232+# and nowhere else. Passing the codes through `-x264-params`/`-x265-params`/
233+# `-svtav1-params` rather than through ffmpeg's stream tags leaves the muxer
234+# with nothing to write, so these files have no `colr` box at all -- checked by
235+# the test. 480 lines, so the heuristic would say BT.601 and a pass means the
236+# VUI (or AV1 `color_config`) was really read. The HEVC one asks for
237+# `scaling-lists=default` on purpose: a set of scaling lists sits between the
238+# SPS header and its VUI, and a walk that counts them wrongly reads the colour
239+# out of the middle of a coefficient. (x264 writes its quant matrices into the
240+# PPS instead, so the H.264 side of that is a synthetic SPS in the unit tests.)
241+ffmpeg -y -f lavfi -i testsrc2=size=640x480:rate=30:duration=1 \
242+ -c:v libx264 -profile:v high -pix_fmt yuv420p \
243+ -x264-params colormatrix=bt709:transfer=bt709:colorprim=bt709 \
244+ assets/test_vui_h264.mp4
245+ffmpeg -y -f lavfi -i testsrc2=size=640x480:rate=30:duration=1 \
246+ -c:v libx265 -pix_fmt yuv420p \
247+ -x265-params log-level=error:scaling-lists=default:colormatrix=bt709:transfer=bt709:colorprim=bt709 \
248+ assets/test_vui_hevc.mp4
249+ffmpeg -y -f lavfi -i testsrc2=size=640x480:rate=30:duration=1 \
250+ -c:v libsvtav1 -preset 8 -pix_fmt yuv420p \
251+ -svtav1-params color-primaries=1:transfer-characteristics=1:matrix-coefficients=1 \
252+ assets/test_vui_av1.mp4
216 # Sync fixture: one flash and one beep, at the same instant. Black picture with253 # Sync fixture: one flash and one beep, at the same instant. Black picture with
217 # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that254 # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that
218 # stretch — so a test can find each of them and say how far apart they came out.255 # stretch — so a test can find each of them and say how far apart they came out.