Skip to main content

alpha2_host_core/
parameter_sets.rs

1//! What H.264 and HEVC sequence parameter sets declare (coded size, cropping, the VUI's aspect
2//! ratio, color and chroma siting) and HEVC VPS layer declarations, read from a stream's sample
3//! description, and the format a VP9 frame header declares.
4
5use alpha2_media::{ChromaLocation, ColorMetadata, SampleAspectRatio};
6
7/// The codecs whose parameter sets this module reads.
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum ParameterSetCodec {
10    /// H.264 (`avcC` or Annex B).
11    H264,
12    /// HEVC (`hvcC` or Annex B).
13    Hevc,
14}
15
16/// The coded picture size an SPS declares and the luma samples it crops off each edge.
17#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
18pub struct CropWindow {
19    /// Coded width in luma samples.
20    pub coded_width: u32,
21    /// Coded height in luma samples.
22    pub coded_height: u32,
23    /// Columns off the left.
24    pub left: u32,
25    /// Columns off the right.
26    pub right: u32,
27    /// Rows off the top.
28    pub top: u32,
29    /// Rows off the bottom.
30    pub bottom: u32,
31}
32
33impl CropWindow {
34    /// The visible area: the coded picture less the crop, `None` when the crop leaves nothing.
35    #[must_use]
36    pub fn visible(&self) -> Option<alpha2_media::Rect> {
37        let width = self
38            .coded_width
39            .checked_sub(self.left)?
40            .checked_sub(self.right)?;
41        let height = self
42            .coded_height
43            .checked_sub(self.top)?
44            .checked_sub(self.bottom)?;
45        (width > 0 && height > 0).then_some(alpha2_media::Rect {
46            x: self.left,
47            y: self.top,
48            width,
49            height,
50        })
51    }
52}
53
54/// What an SPS's video usability information declares.
55#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
56pub struct Vui {
57    /// The pixel aspect ratio, when declared and not 0:0.
58    pub sample_aspect_ratio: Option<SampleAspectRatio>,
59    /// The color the video signal type declares.
60    pub color: Option<ColorMetadata>,
61    /// The chroma siting of a 4:2:0 stream, when declared.
62    pub chroma_location: Option<ChromaLocation>,
63}
64
65/// What one SPS declares.
66#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
67pub struct SequenceFacts {
68    /// The coded size and crop.
69    pub crop: CropWindow,
70    /// `chroma_format_idc`: 0 monochrome, 1 4:2:0, 2 4:2:2, 3 4:4:4.
71    pub chroma_format: u32,
72    /// Luma bits per sample.
73    pub bit_depth_luma: u32,
74    /// Chroma bits per sample.
75    pub bit_depth_chroma: u32,
76    /// The VUI; empty when absent or unreadable.
77    pub vui: Vui,
78}
79
80impl SequenceFacts {
81    /// The chroma siting frames have: the VUI's, else the 4:2:0 default both codecs infer
82    /// (type 0, left).
83    #[must_use]
84    pub fn chroma_location(&self) -> Option<ChromaLocation> {
85        self.vui
86            .chroma_location
87            .or((self.chroma_format == 1).then_some(ChromaLocation::Left))
88    }
89}
90
91/// What the first SPS in `extradata` (`avcC`, `hvcC` or Annex B) declares; `None` when there is
92/// none or its fields up to the crop do not parse.
93#[must_use]
94pub fn sequence_facts(codec: ParameterSetCodec, extradata: &[u8]) -> Option<SequenceFacts> {
95    let hevc = codec == ParameterSetCodec::Hevc;
96    let nal = *sequence_parameter_sets(hevc, extradata).first()?;
97    if hevc { hevc_sps(nal) } else { h264_sps(nal) }
98}
99
100/// `annex_b`'s NAL units with 4-byte big-endian lengths in place of start codes, as MP4 stores
101/// H.264 and HEVC samples.
102#[must_use]
103pub fn length_prefixed_units(annex_b: &[u8]) -> Vec<u8> {
104    let units = annex_b_units(annex_b);
105    let mut out = Vec::with_capacity(annex_b.len() + units.len());
106    for unit in units {
107        out.extend_from_slice(&u32::try_from(unit.len()).unwrap_or(u32::MAX).to_be_bytes());
108        out.extend_from_slice(unit);
109    }
110    out
111}
112
113/// The `avcC` record (ISO/IEC 14496-15 5.3.3.1) of the SPS and PPS units in `annex_b`, with
114/// 4-byte NAL lengths; `None` without a readable SPS and a PPS.
115#[must_use]
116pub fn avc_decoder_config(annex_b: &[u8]) -> Option<Vec<u8>> {
117    let units = annex_b_units(annex_b);
118    let of_type = |kind: u8| -> Vec<&[u8]> {
119        units
120            .iter()
121            .copied()
122            .filter(|unit| unit[0] & 0x1f == kind)
123            .collect()
124    };
125    let (sps, pps) = (of_type(7), of_type(8));
126    let first = *sps.first()?;
127    if pps.is_empty() || first.len() < 4 {
128        return None;
129    }
130    let facts = h264_sps(first)?;
131    let mut record = vec![1, first[1], first[2], first[3], 0xff];
132    record.push(0xe0 | u8::try_from(sps.len()).ok().filter(|count| *count < 32)?);
133    for unit in &sps {
134        record.extend_from_slice(&u16::try_from(unit.len()).ok()?.to_be_bytes());
135        record.extend_from_slice(unit);
136    }
137    record.push(u8::try_from(pps.len()).ok()?);
138    for unit in &pps {
139        record.extend_from_slice(&u16::try_from(unit.len()).ok()?.to_be_bytes());
140        record.extend_from_slice(unit);
141    }
142    // The High profiles' extension: chroma format and bit depths, no SPS extensions.
143    if matches!(first[1], 100 | 110 | 122 | 144) {
144        record.push(0xfc | u8::try_from(facts.chroma_format & 3).ok()?);
145        record.push(0xf8 | u8::try_from(facts.bit_depth_luma.checked_sub(8)? & 7).ok()?);
146        record.push(0xf8 | u8::try_from(facts.bit_depth_chroma.checked_sub(8)? & 7).ok()?);
147        record.push(0);
148    }
149    Some(record)
150}
151
152/// The `hvcC` record (ISO/IEC 14496-15 8.3.3.1) of the VPS, SPS and PPS units in `annex_b`, with
153/// 4-byte NAL lengths; `None` without a readable SPS.
154#[must_use]
155pub fn hevc_decoder_config(annex_b: &[u8]) -> Option<Vec<u8>> {
156    let units = annex_b_units(annex_b);
157    let kind = |unit: &[u8]| (unit[0] >> 1) & 0x3f;
158    let sps = *units
159        .iter()
160        .find(|unit| unit.len() > 2 && kind(unit) == 33)?;
161    let facts = hevc_sps(sps)?;
162    // After the NAL header: VPS id, sub-layer count and nesting, then the general profile, tier
163    // and level that the record repeats (12 bytes).
164    let payload = unescape(sps.get(2..)?);
165    let general = payload.get(1..13)?;
166    let sub_layers = (payload[0] >> 1) & 7;
167    let nested = payload[0] & 1;
168    let mut record = vec![1];
169    record.extend_from_slice(general);
170    record.extend_from_slice(&[0xf0, 0x00, 0xfc]); // no segmentation or parallelism declared
171    record.push(0xfc | u8::try_from(facts.chroma_format & 3).ok()?);
172    record.push(0xf8 | u8::try_from(facts.bit_depth_luma.checked_sub(8)? & 7).ok()?);
173    record.push(0xf8 | u8::try_from(facts.bit_depth_chroma.checked_sub(8)? & 7).ok()?);
174    record.extend_from_slice(&[0, 0]); // average frame rate unknown
175    record.push(((sub_layers + 1) << 3) | (nested << 2) | 3);
176    let arrays = [32, 33, 34]
177        .into_iter()
178        .map(|wanted| {
179            units
180                .iter()
181                .copied()
182                .filter(|unit| unit.len() > 2 && kind(unit) == wanted)
183                .collect::<Vec<_>>()
184        })
185        .filter(|array| !array.is_empty())
186        .collect::<Vec<_>>();
187    record.push(u8::try_from(arrays.len()).ok()?);
188    for array in arrays {
189        record.push(0x80 | kind(array[0]));
190        record.extend_from_slice(&u16::try_from(array.len()).ok()?.to_be_bytes());
191        for unit in array {
192            record.extend_from_slice(&u16::try_from(unit.len()).ok()?.to_be_bytes());
193            record.extend_from_slice(unit);
194        }
195    }
196    Some(record)
197}
198
199/// The crop windows of every SPS in `extradata` (`avcC`, `hvcC` or Annex B); `None` when one does
200/// not parse.
201fn crop_windows(codec: ParameterSetCodec, extradata: &[u8]) -> Option<Vec<CropWindow>> {
202    let hevc = codec == ParameterSetCodec::Hevc;
203    sequence_parameter_sets(hevc, extradata)
204        .into_iter()
205        .map(|nal| if hevc { hevc_sps(nal) } else { h264_sps(nal) }.map(|facts| facts.crop))
206        .collect()
207}
208
209/// The crop window of the first SPS in `extradata`; `None` when there is none or it does not
210/// parse.
211#[must_use]
212pub fn crop_window(codec: ParameterSetCodec, extradata: &[u8]) -> Option<CropWindow> {
213    crop_windows(codec, extradata)?.first().copied()
214}
215
216/// Luma columns and rows the first SPS that crops a leading edge takes off the left and top.
217///
218/// `(0, 0)` when every SPS crops only right/bottom; `None` when `extradata` (`avcC`, `hvcC` or
219/// Annex B) holds no readable parameter set.
220#[must_use]
221pub fn leading_crop(codec: ParameterSetCodec, extradata: &[u8]) -> Option<(u32, u32)> {
222    let crops = crop_windows(codec, extradata)?;
223    let first = *crops.first()?;
224    let leading = crops
225        .into_iter()
226        .find(|crop| crop.left > 0 || crop.top > 0)
227        .unwrap_or(first);
228    Some((leading.left, leading.top))
229}
230
231/// The layers besides the base one that an HEVC VPS declares.
232#[derive(Clone, Copy, Debug, Eq, PartialEq)]
233pub enum HevcLayers {
234    /// Only the base layer.
235    Single,
236    /// An auxiliary picture layer carrying alpha: `scalability_mask_flag[3]` in the VPS extension
237    /// (ITU-T H.265 F.7.4.3.1.1, Table F.1).
238    AuxiliaryAlpha,
239    /// More layers, none declared auxiliary, or a VPS extension this cannot read.
240    Extra,
241}
242
243/// The layers the first HEVC VPS in `extradata` declares, or `None` when there is none.
244#[must_use]
245pub fn hevc_layers(extradata: &[u8]) -> Option<HevcLayers> {
246    let units = match extradata {
247        [1, ..] => hvcc_units(extradata),
248        _ => annex_b_units(extradata),
249    };
250    let vps = units
251        .into_iter()
252        .find(|nal| matches!(nal, [first, ..] if (first >> 1) & 0x3f == 32))?;
253    let payload = unescape(vps.get(2..)?);
254    let mut bits = Bits::new(&payload);
255    bits.skip(4)?; // vps_video_parameter_set_id
256    let base_internal = bits.flag()?;
257    bits.skip(1)?; // vps_base_layer_available_flag
258    let max_layers = bits.read(6)?; // vps_max_layers_minus1
259    if max_layers == 0 {
260        return Some(HevcLayers::Single);
261    }
262    Some(vps_auxiliary_layer(&mut bits, base_internal).unwrap_or(HevcLayers::Extra))
263}
264
265/// Reads the rest of a multi-layer VPS up to its extension's scalability mask (ITU-T H.265 7.3.2.1,
266/// F.7.3.2.1.1). `None` when unread fields (timing, HRD) come first.
267fn vps_auxiliary_layer(bits: &mut Bits<'_>, base_internal: bool) -> Option<HevcLayers> {
268    let sub_layers = bits.read(3)?; // vps_max_sub_layers_minus1
269    bits.skip(1 + 16)?; // vps_temporal_id_nesting_flag, vps_reserved_0xffff_16bits
270    skip_profile_tier_level(bits, true, sub_layers)?;
271    let ordering_for_all = bits.flag()?; // vps_sub_layer_ordering_info_present_flag
272    for _ in if ordering_for_all { 0 } else { sub_layers }..=sub_layers {
273        bits.ue()?; // vps_max_dec_pic_buffering_minus1
274        bits.ue()?; // vps_max_num_reorder_pics
275        bits.ue()?; // vps_max_latency_increase_plus1
276    }
277    let max_layer_id = bits.read(6)?; // vps_max_layer_id
278    let layer_sets = bits.ue()?; // vps_num_layer_sets_minus1
279    bits.skip(
280        usize::try_from(layer_sets)
281            .ok()?
282            .checked_mul(max_layer_id as usize + 1)?,
283    )?;
284    if bits.flag()? {
285        // vps_timing_info_present_flag: HRD parameters follow, which this does not read.
286        return None;
287    }
288    if !bits.flag()? {
289        // vps_extension_flag unset: more layers with no extension to describe them.
290        return Some(HevcLayers::Extra);
291    }
292    while !bits.at.is_multiple_of(8) {
293        bits.skip(1)?; // vps_extension_alignment_bit_equal_to_one
294    }
295    if base_internal {
296        skip_profile_tier_level(bits, false, sub_layers)?;
297    }
298    bits.skip(1)?; // splitting_flag
299    let mask = bits.read(16)?; // scalability_mask_flag[0..16]
300    Some(if mask & (1 << (15 - 3)) != 0 {
301        HevcLayers::AuxiliaryAlpha
302    } else {
303        HevcLayers::Extra
304    })
305}
306
307/// Skips `profile_tier_level(profile_present, max_sub_layers_minus1)` (ITU-T H.265 7.3.3).
308fn skip_profile_tier_level(
309    bits: &mut Bits<'_>,
310    profile_present: bool,
311    sub_layers: u32,
312) -> Option<()> {
313    // The general profile (88 bits) when present, and the general level.
314    bits.skip(if profile_present { 88 } else { 0 } + 8)?;
315    let mut present = Vec::new();
316    for _ in 0..sub_layers {
317        present.push((bits.flag()?, bits.flag()?));
318    }
319    if sub_layers > 0 {
320        bits.skip(2 * (8 - sub_layers as usize))?;
321    }
322    for (profile, level) in present {
323        bits.skip(if profile { 88 } else { 0 } + if level { 8 } else { 0 })?;
324    }
325    Some(())
326}
327
328/// The SPS NAL units (header included, still escaped) of a sample description.
329fn sequence_parameter_sets(hevc: bool, extradata: &[u8]) -> Vec<&[u8]> {
330    let is_sps = |nal: &[u8]| match (hevc, nal) {
331        (false, [header, ..]) => header & 0x1f == 7,
332        // Type 33 at the base layer only: a higher layer's SPS is laid out differently.
333        (true, [first, second, ..]) => {
334            (first >> 1) & 0x3f == 33 && (first & 1) == 0 && second >> 3 == 0
335        }
336        _ => false,
337    };
338    let units = match (hevc, extradata) {
339        (false, [1, ..]) => avcc_units(extradata),
340        (true, [1, ..]) => hvcc_units(extradata),
341        _ => annex_b_units(extradata),
342    };
343    units.into_iter().filter(|nal| is_sps(nal)).collect()
344}
345
346/// The parameter sets of an `avcC` box body: its SPS list, then its PPS list.
347fn avcc_units(data: &[u8]) -> Vec<&[u8]> {
348    let mut units = Vec::new();
349    let Some(&count) = data.get(5) else {
350        return units;
351    };
352    let mut at = 6;
353    for _ in 0..(count & 0x1f) {
354        let Some((nal, next)) = length_prefixed(data, at) else {
355            return units;
356        };
357        units.push(nal);
358        at = next;
359    }
360    let Some(&count) = data.get(at) else {
361        return units;
362    };
363    at += 1;
364    for _ in 0..count {
365        let Some((nal, next)) = length_prefixed(data, at) else {
366            break;
367        };
368        units.push(nal);
369        at = next;
370    }
371    units
372}
373
374fn hvcc_units(data: &[u8]) -> Vec<&[u8]> {
375    let mut units = Vec::new();
376    let Some(&arrays) = data.get(22) else {
377        return units;
378    };
379    let mut at = 23;
380    for _ in 0..arrays {
381        let Some(count) = data.get(at + 1..at + 3) else {
382            break;
383        };
384        let count = u16::from_be_bytes([count[0], count[1]]);
385        at += 3;
386        for _ in 0..count {
387            let Some((nal, next)) = length_prefixed(data, at) else {
388                return units;
389            };
390            units.push(nal);
391            at = next;
392        }
393    }
394    units
395}
396
397/// The unit after a 16-bit length at `at`, and where the next length begins.
398fn length_prefixed(data: &[u8], at: usize) -> Option<(&[u8], usize)> {
399    let length = data.get(at..at + 2)?;
400    let end = at + 2 + usize::from(u16::from_be_bytes([length[0], length[1]]));
401    Some((data.get(at + 2..end)?, end))
402}
403
404fn annex_b_units(data: &[u8]) -> Vec<&[u8]> {
405    let starts = (0..data.len().saturating_sub(2))
406        .filter(|&at| data[at..at + 3] == [0, 0, 1])
407        .map(|at| at + 3)
408        .collect::<Vec<_>>();
409    starts
410        .iter()
411        .enumerate()
412        .map(|(index, &start)| {
413            let end = starts.get(index + 1).map_or(data.len(), |next| next - 3);
414            // A four-byte start code leaves its leading zero on the unit before.
415            let mut unit = &data[start..end.max(start)];
416            while let [rest @ .., 0] = unit {
417                unit = rest;
418            }
419            unit
420        })
421        .filter(|unit| !unit.is_empty())
422        .collect()
423}
424
425/// An H.264 SPS's coded size, crop offsets in luma samples and VUI (ITU-T H.264 7.3.2.1.1).
426fn h264_sps(nal: &[u8]) -> Option<SequenceFacts> {
427    let payload = unescape(nal.get(1..)?);
428    let mut bits = Bits::new(&payload);
429    let profile = bits.read(8)?;
430    bits.skip(16)?; // constraint flags and level_idc
431    bits.ue()?; // seq_parameter_set_id
432    let (mut chroma_format, mut bit_depth_luma, mut bit_depth_chroma) = (1, 8, 8);
433    if matches!(
434        profile,
435        100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135
436    ) {
437        chroma_format = bits.ue()?;
438        if chroma_format == 3 {
439            bits.skip(1)?; // separate_colour_plane_flag
440        }
441        bit_depth_luma = bits.ue()?.saturating_add(8);
442        bit_depth_chroma = bits.ue()?.saturating_add(8);
443        bits.skip(1)?; // qpprime_y_zero_transform_bypass_flag
444        if bits.flag()? {
445            for list in 0..if chroma_format == 3 { 12 } else { 8 } {
446                if bits.flag()? {
447                    skip_scaling_list(&mut bits, if list < 6 { 16 } else { 64 })?;
448                }
449            }
450        }
451    }
452    bits.ue()?; // log2_max_frame_num_minus4
453    match bits.ue()? {
454        0 => {
455            bits.ue()?; // log2_max_pic_order_cnt_lsb_minus4
456        }
457        1 => {
458            bits.skip(1)?; // delta_pic_order_always_zero_flag
459            bits.se()?; // offset_for_non_ref_pic
460            bits.se()?; // offset_for_top_to_bottom_field
461            for _ in 0..bits.ue()?.min(255) {
462                bits.se()?; // offset_for_ref_frame
463            }
464        }
465        _ => {}
466    }
467    bits.ue()?; // max_num_ref_frames
468    bits.skip(1)?; // gaps_in_frame_num_value_allowed_flag
469    let width_in_mbs = bits.ue()?.saturating_add(1);
470    let height_in_map_units = bits.ue()?.saturating_add(1);
471    let frame_mbs_only = bits.flag()?;
472    let coded_width = width_in_mbs.saturating_mul(16);
473    let coded_height = height_in_map_units
474        .saturating_mul(16)
475        .saturating_mul(if frame_mbs_only { 1 } else { 2 });
476    if !frame_mbs_only {
477        bits.skip(1)?; // mb_adaptive_frame_field_flag
478    }
479    bits.skip(1)?; // direct_8x8_inference_flag
480    let mut crop = CropWindow {
481        coded_width,
482        coded_height,
483        ..CropWindow::default()
484    };
485    if bits.flag()? {
486        let (left, right, top, bottom) = (bits.ue()?, bits.ue()?, bits.ue()?, bits.ue()?);
487        // Crop units (7-19, 7-20): chroma samples, and field pairs in a stream that may code
488        // fields.
489        let (unit_x, unit_y) = crop_units(chroma_format);
490        let unit_y = unit_y * if frame_mbs_only { 1 } else { 2 };
491        crop.left = left.saturating_mul(unit_x);
492        crop.right = right.saturating_mul(unit_x);
493        crop.top = top.saturating_mul(unit_y);
494        crop.bottom = bottom.saturating_mul(unit_y);
495    }
496    let vui = bits
497        .flag()
498        .filter(|present| *present)
499        .and_then(|_| vui(&mut bits, chroma_format))
500        .unwrap_or_default();
501    Some(SequenceFacts {
502        crop,
503        chroma_format,
504        bit_depth_luma,
505        bit_depth_chroma,
506        vui,
507    })
508}
509
510/// `SubWidthC` and `SubHeightC` (H.264 Table 6-1, H.265 Table 6-1).
511const fn crop_units(chroma_format: u32) -> (u32, u32) {
512    match chroma_format {
513        1 => (2, 2),
514        2 => (2, 1),
515        _ => (1, 1),
516    }
517}
518
519/// The leading fields of `vui_parameters()`, which H.264 (E.1.1) and HEVC (E.2.1) share: aspect
520/// ratio, overscan, video signal type and chroma location.
521fn vui(bits: &mut Bits<'_>, chroma_format: u32) -> Option<Vui> {
522    /// Table E-1: `aspect_ratio_idc` 1 to 16.
523    const RATIOS: [(u32, u32); 16] = [
524        (1, 1),
525        (12, 11),
526        (10, 11),
527        (16, 11),
528        (40, 33),
529        (24, 11),
530        (20, 11),
531        (32, 11),
532        (80, 33),
533        (18, 11),
534        (15, 11),
535        (64, 33),
536        (160, 99),
537        (4, 3),
538        (3, 2),
539        (2, 1),
540    ];
541    let mut vui = Vui::default();
542    if bits.flag()? {
543        let ratio = match bits.read(8)? {
544            255 => Some((bits.read(16)?, bits.read(16)?)),
545            idc @ 1..=16 => RATIOS.get(idc as usize - 1).copied(),
546            _ => None,
547        };
548        vui.sample_aspect_ratio = ratio
549            .filter(|(num, den)| *num > 0 && *den > 0)
550            .map(|(num, den)| SampleAspectRatio { num, den });
551    }
552    if bits.flag()? {
553        bits.skip(1)?; // overscan_appropriate_flag
554    }
555    if bits.flag()? {
556        bits.skip(3)?; // video_format
557        let full = bits.flag()?;
558        let (mut primaries, mut transfer, mut matrix) = (2, 2, 2);
559        if bits.flag()? {
560            primaries = bits.read(8)?;
561            transfer = bits.read(8)?;
562            matrix = bits.read(8)?;
563        }
564        let code = |value: u32| u8::try_from(value).unwrap_or(2);
565        vui.color =
566            ColorMetadata::from_h273(code(primaries), code(transfer), code(matrix), Some(full));
567    }
568    if bits.flag()? {
569        let top = bits.ue()?;
570        bits.ue()?; // chroma_sample_loc_type_bottom_field
571        if chroma_format == 1 {
572            vui.chroma_location = Some(match top {
573                0 => ChromaLocation::Left,
574                1 => ChromaLocation::Center,
575                2 => ChromaLocation::TopLeft,
576                _ => ChromaLocation::Unspecified,
577            });
578        }
579    }
580    Some(vui)
581}
582
583/// Skips one `scaling_list()` of `size` coefficients.
584fn skip_scaling_list(bits: &mut Bits<'_>, size: usize) -> Option<()> {
585    let (mut last, mut next) = (8_i64, 8_i64);
586    for _ in 0..size {
587        if next != 0 {
588            next = (last + bits.se()? + 256).rem_euclid(256);
589        }
590        if next != 0 {
591            last = next;
592        }
593    }
594    Some(())
595}
596
597/// An HEVC SPS's coded size, conformance window offsets in luma samples and VUI (ITU-T H.265
598/// 7.3.2.2.1).
599fn hevc_sps(nal: &[u8]) -> Option<SequenceFacts> {
600    let payload = unescape(nal.get(2..)?);
601    let mut bits = Bits::new(&payload);
602    bits.skip(4)?; // sps_video_parameter_set_id
603    let sub_layers = bits.read(3)?; // sps_max_sub_layers_minus1
604    bits.skip(1)?; // sps_temporal_id_nesting_flag
605    // profile_tier_level(1, sps_max_sub_layers_minus1): general profile and level, then sub-layers.
606    bits.skip(96)?;
607    let mut present = Vec::new();
608    for _ in 0..sub_layers {
609        present.push((bits.flag()?, bits.flag()?));
610    }
611    if sub_layers > 0 {
612        bits.skip(2 * (8 - sub_layers as usize))?;
613    }
614    for (profile, level) in present {
615        bits.skip(if profile { 88 } else { 0 } + if level { 8 } else { 0 })?;
616    }
617    bits.ue()?; // sps_seq_parameter_set_id
618    let chroma_format = bits.ue()?;
619    if chroma_format == 3 {
620        bits.skip(1)?; // separate_colour_plane_flag
621    }
622    let coded_width = bits.ue()?;
623    let coded_height = bits.ue()?;
624    let mut crop = CropWindow {
625        coded_width,
626        coded_height,
627        ..CropWindow::default()
628    };
629    if bits.flag()? {
630        let (left, right, top, bottom) = (bits.ue()?, bits.ue()?, bits.ue()?, bits.ue()?);
631        let (unit_x, unit_y) = crop_units(chroma_format);
632        crop.left = left.saturating_mul(unit_x);
633        crop.right = right.saturating_mul(unit_x);
634        crop.top = top.saturating_mul(unit_y);
635        crop.bottom = bottom.saturating_mul(unit_y);
636    }
637    let bit_depth_luma = bits.ue()?.saturating_add(8);
638    let bit_depth_chroma = bits.ue()?.saturating_add(8);
639    let vui = hevc_vui(&mut bits, sub_layers, chroma_format).unwrap_or_default();
640    Some(SequenceFacts {
641        crop,
642        chroma_format,
643        bit_depth_luma,
644        bit_depth_chroma,
645        vui,
646    })
647}
648
649/// The HEVC SPS fields from `log2_max_pic_order_cnt_lsb_minus4` to the VUI, then the VUI.
650fn hevc_vui(bits: &mut Bits<'_>, sub_layers: u32, chroma_format: u32) -> Option<Vui> {
651    let poc_lsb_bits = bits.ue()?.checked_add(4)?;
652    let first = if bits.flag()? { 0 } else { sub_layers };
653    for _ in first..=sub_layers {
654        bits.ue()?; // sps_max_dec_pic_buffering_minus1
655        bits.ue()?; // sps_max_num_reorder_pics
656        bits.ue()?; // sps_max_latency_increase_plus1
657    }
658    for _ in 0..6 {
659        // Coding and transform block sizes, transform hierarchy depths.
660        bits.ue()?;
661    }
662    if bits.flag()? && bits.flag()? {
663        skip_hevc_scaling_lists(bits)?;
664    }
665    bits.skip(2)?; // amp_enabled_flag, sample_adaptive_offset_enabled_flag
666    if bits.flag()? {
667        bits.skip(8)?; // PCM sample bit depths
668        bits.ue()?; // log2_min_pcm_luma_coding_block_size_minus3
669        bits.ue()?; // log2_diff_max_min_pcm_luma_coding_block_size
670        bits.skip(1)?; // pcm_loop_filter_disabled_flag
671    }
672    skip_short_term_ref_pic_sets(bits)?;
673    if bits.flag()? {
674        for _ in 0..bits.ue()?.min(32) {
675            bits.skip(poc_lsb_bits as usize)?; // lt_ref_pic_poc_lsb_sps
676            bits.skip(1)?; // used_by_curr_pic_lt_sps_flag
677        }
678    }
679    bits.skip(2)?; // sps_temporal_mvp_enabled_flag, strong_intra_smoothing_enabled_flag
680    if !bits.flag()? {
681        return Some(Vui::default());
682    }
683    vui(bits, chroma_format)
684}
685
686/// Skips `scaling_list_data()` (H.265 7.3.4).
687fn skip_hevc_scaling_lists(bits: &mut Bits<'_>) -> Option<()> {
688    for size in 0..4_u32 {
689        let step = if size == 3 { 3 } else { 1 };
690        for _ in (0..6).step_by(step) {
691            if bits.flag()? {
692                let coefficients = 64.min(1 << (4 + (size << 1)));
693                if size > 1 {
694                    bits.se()?; // scaling_list_dc_coef_minus8
695                }
696                for _ in 0..coefficients {
697                    bits.se()?; // scaling_list_delta_coef
698                }
699            } else {
700                bits.ue()?; // scaling_list_pred_matrix_id_delta
701            }
702        }
703    }
704    Some(())
705}
706
707/// Skips the SPS's `st_ref_pic_set()` list (H.265 7.3.7), which predicts sets from earlier ones.
708fn skip_short_term_ref_pic_sets(bits: &mut Bits<'_>) -> Option<()> {
709    let count = bits.ue()?;
710    if count > 64 {
711        return None;
712    }
713    let mut delta_pocs: Vec<u32> = Vec::with_capacity(count as usize);
714    for index in 0..count {
715        let predicted = index != 0 && bits.flag()?;
716        let pictures = if predicted {
717            bits.skip(1)?; // delta_rps_sign
718            bits.ue()?; // abs_delta_rps_minus1
719            let reference = *delta_pocs.last()?;
720            let mut pictures = 0;
721            for _ in 0..=reference {
722                let used = bits.flag()?;
723                if used || bits.flag()? {
724                    pictures += 1;
725                }
726            }
727            pictures
728        } else {
729            let negative = bits.ue()?;
730            let positive = bits.ue()?;
731            let pictures = negative
732                .checked_add(positive)
733                .filter(|total| *total <= 32)?;
734            for _ in 0..pictures {
735                bits.ue()?; // delta_poc_s0/s1_minus1
736                bits.skip(1)?; // used_by_curr_pic_s0/s1_flag
737            }
738            pictures
739        };
740        delta_pocs.push(pictures);
741    }
742    Some(())
743}
744
745/// The picture format a VP9 key frame or intra-only frame declares in its uncompressed header
746/// (VP9 bitstream 6.2).
747#[derive(Clone, Copy, Debug, Eq, PartialEq)]
748pub struct Vp9Format {
749    /// The profile, 0 to 3.
750    pub profile: u8,
751    /// Bits per sample: 8 for profiles 0 and 1, 10 or 12 for profiles 2 and 3.
752    pub bit_depth: u8,
753    /// `subsampling_x` and `subsampling_y`: `(true, true)` is 4:2:0, `(true, false)` 4:2:2.
754    pub subsampling: (bool, bool),
755    /// `color_space` (VP9 7.2.2): 1 BT.601, 2 BT.709, 3 SMPTE 170, 4 SMPTE 240, 5 BT.2020, 7 RGB.
756    pub color_space: u8,
757    /// `color_range`: full range when set.
758    pub full_range: bool,
759    /// Frame width in luma samples.
760    pub width: u32,
761    /// Frame height in luma samples.
762    pub height: u32,
763}
764
765impl Vp9Format {
766    /// A `vpcC` body (VP Codec ISO Media File Format Binding 2.2, version 1) for a stream of
767    /// this format. The color codes are `color`'s when the container declares one, else what
768    /// `color_space` implies, and the level is the lowest whose picture size holds the frame.
769    #[must_use]
770    pub fn vpcc_record(&self, color: Option<ColorMetadata>) -> [u8; 12] {
771        use alpha2_media::{ColorMatrix, ColorPrimaries, TransferFunction};
772        let (primaries, transfer, matrix) = match color {
773            Some(color) => (
774                match color.primaries {
775                    ColorPrimaries::Bt601 => 6,
776                    ColorPrimaries::Bt709 => 1,
777                    ColorPrimaries::Bt2020 => 9,
778                },
779                match color.transfer {
780                    TransferFunction::Bt709 => 1,
781                    TransferFunction::Srgb => 13,
782                    TransferFunction::Pq => 16,
783                    TransferFunction::Hlg => 18,
784                },
785                match color.matrix {
786                    ColorMatrix::Bt601 => 6,
787                    ColorMatrix::Bt709 => 1,
788                    ColorMatrix::Bt2020Ncl => 9,
789                    ColorMatrix::Rgb => 0,
790                },
791            ),
792            None => (
793                2,
794                2,
795                match self.color_space {
796                    1 | 3 => 6,
797                    2 => 1,
798                    4 => 7,
799                    5 => 9,
800                    7 => 0,
801                    _ => 2,
802                },
803            ),
804        };
805        // 0 and 1 are both 4:2:0 (1 sited with luma); 4:4:0 has no code.
806        let chroma = match self.subsampling {
807            (true, true) => 1,
808            (true, false) => 2,
809            (false, _) => 3,
810        };
811        // VP9 Annex A: the largest luma picture size of each level.
812        let samples = u64::from(self.width) * u64::from(self.height);
813        let level = [
814            (36_864, 10),
815            (73_728, 11),
816            (122_880, 20),
817            (245_760, 21),
818            (552_960, 30),
819            (983_040, 31),
820            (2_228_224, 40),
821            (8_912_896, 50),
822            (35_651_584, 60),
823        ]
824        .iter()
825        .find(|(size, _)| samples <= *size)
826        .map_or(62, |(_, level)| *level);
827        [
828            1,
829            0,
830            0,
831            0,
832            self.profile,
833            level,
834            (self.bit_depth << 4) | (chroma << 1) | u8::from(self.full_range),
835            primaries,
836            transfer,
837            matrix,
838            0,
839            0,
840        ]
841    }
842}
843
844/// The format a VP9 frame's uncompressed header declares. `None` for a frame without a color
845/// config (an inter frame, or one that shows an existing frame) or a header that does not parse.
846/// Intra-only frames of profile 0 carry no color config and are 8-bit 4:2:0 BT.601.
847#[must_use]
848pub fn vp9_format(frame: &[u8]) -> Option<Vp9Format> {
849    const SYNC_CODE: u32 = 0x49_83_42;
850    const CS_RGB: u8 = 7;
851    let mut bits = Bits::new(frame);
852    if bits.read(2)? != 2 {
853        return None;
854    }
855    let low = bits.read(1)?;
856    let profile = u8::try_from((bits.read(1)? << 1) | low).ok()?;
857    if profile == 3 {
858        bits.skip(1)?;
859    }
860    if bits.flag()? {
861        return None;
862    }
863    let key_frame = !bits.flag()?;
864    let show_frame = bits.flag()?;
865    let error_resilient = bits.flag()?;
866    let mut format = Vp9Format {
867        profile,
868        bit_depth: 8,
869        subsampling: (true, true),
870        color_space: 1,
871        full_range: false,
872        width: 0,
873        height: 0,
874    };
875    let intra_only = if key_frame {
876        false
877    } else {
878        let intra_only = !show_frame && bits.flag()?;
879        if !error_resilient {
880            bits.skip(2)?;
881        }
882        if !intra_only {
883            return None;
884        }
885        true
886    };
887    if bits.read(24)? != SYNC_CODE {
888        return None;
889    }
890    if !intra_only || profile > 0 {
891        if profile >= 2 {
892            format.bit_depth = if bits.flag()? { 12 } else { 10 };
893        }
894        format.color_space = u8::try_from(bits.read(3)?).ok()?;
895        let four_four_four = profile == 1 || profile == 3;
896        if format.color_space == CS_RGB {
897            format.full_range = true;
898            if four_four_four {
899                format.subsampling = (false, false);
900                bits.skip(1)?;
901            }
902        } else {
903            format.full_range = bits.flag()?;
904            if four_four_four {
905                format.subsampling = (bits.flag()?, bits.flag()?);
906                bits.skip(1)?;
907            }
908        }
909    }
910    if intra_only {
911        bits.skip(8)?; // refresh_frame_flags
912    }
913    format.width = bits.read(16)? + 1;
914    format.height = bits.read(16)? + 1;
915    Some(format)
916}
917
918fn unescape(escaped: &[u8]) -> Vec<u8> {
919    let mut payload = Vec::with_capacity(escaped.len());
920    let mut zeros = 0;
921    for &byte in escaped {
922        if zeros >= 2 && byte == 3 {
923            zeros = 0;
924            continue;
925        }
926        zeros = if byte == 0 { zeros + 1 } else { 0 };
927        payload.push(byte);
928    }
929    payload
930}
931
932/// A most-significant-bit-first reader over an unescaped payload.
933struct Bits<'a> {
934    data: &'a [u8],
935    at: usize,
936}
937
938impl<'a> Bits<'a> {
939    const fn new(data: &'a [u8]) -> Self {
940        Self { data, at: 0 }
941    }
942
943    fn flag(&mut self) -> Option<bool> {
944        let byte = *self.data.get(self.at / 8)?;
945        let bit = (byte >> (7 - self.at % 8)) & 1;
946        self.at += 1;
947        Some(bit == 1)
948    }
949
950    fn read(&mut self, count: u32) -> Option<u32> {
951        (0..count).try_fold(0, |value, _| Some((value << 1) | u32::from(self.flag()?)))
952    }
953
954    fn skip(&mut self, count: usize) -> Option<()> {
955        let end = self.at.checked_add(count)?;
956        (end <= self.data.len() * 8).then(|| self.at = end)
957    }
958
959    /// An unsigned Exp-Golomb value (9.1).
960    fn ue(&mut self) -> Option<u32> {
961        let mut zeros = 0;
962        while !self.flag()? {
963            zeros += 1;
964            if zeros > 31 {
965                return None;
966            }
967        }
968        Some((1_u32 << zeros) - 1 + self.read(zeros)?)
969    }
970
971    /// A signed Exp-Golomb value (9.1.1).
972    fn se(&mut self) -> Option<i64> {
973        let code = i64::from(self.ue()?);
974        Some(if code % 2 == 1 {
975            (code + 1) / 2
976        } else {
977            -(code / 2)
978        })
979    }
980}
981
982#[cfg(test)]
983mod tests {
984    use super::{
985        HevcLayers, ParameterSetCodec, Vp9Format, avc_decoder_config, crop_window,
986        hevc_decoder_config, hevc_layers, leading_crop, length_prefixed_units, sequence_facts,
987        vp9_format,
988    };
989    use alpha2_media::ColorMetadata;
990
991    /// The VPS of `tests/corpus/hevc-alpha.mov` (`hevc_videotoolbox` with `-alpha_quality`): two
992    /// layers, the second auxiliary.
993    const ALPHA_VPS: [u8; 41] = [
994        0x40, 0x01, 0x0c, 0x11, 0xff, 0xff, 0x01, 0x60, 0x00, 0x00, 0x03, 0x00, 0xb0, 0x00, 0x00,
995        0x03, 0x00, 0x00, 0x03, 0x00, 0x1e, 0x17, 0x06, 0xff, 0x1e, 0x08, 0x00, 0x08, 0x30, 0x28,
996        0x53, 0x80, 0x50, 0x00, 0x30, 0x50, 0x0c, 0x23, 0xf1, 0x7a, 0x40,
997    ];
998
999    fn start_coded(nal: &[u8]) -> Vec<u8> {
1000        let mut data = vec![0, 0, 0, 1];
1001        data.extend_from_slice(nal);
1002        data
1003    }
1004
1005    #[test]
1006    fn hevc_alpha_is_detected_from_its_vps() {
1007        assert_eq!(
1008            hevc_layers(&start_coded(&ALPHA_VPS)),
1009            Some(HevcLayers::AuxiliaryAlpha)
1010        );
1011        // The same VPS with one layer is the base alone.
1012        let mut single = ALPHA_VPS;
1013        single[3] &= 0x0f;
1014        assert_eq!(hevc_layers(&start_coded(&single)), Some(HevcLayers::Single));
1015        // Two layers with no auxiliary picture (MV-HEVC views): byte 25 holds
1016        // scalability_mask_flag[1] (0x20, multiview) and [3] (0x08, auxiliary).
1017        let mut views = ALPHA_VPS;
1018        views[25] = 0x20;
1019        assert_eq!(hevc_layers(&start_coded(&views)), Some(HevcLayers::Extra));
1020        assert_eq!(hevc_layers(&[1, 2, 3]), None);
1021    }
1022
1023    /// The corpus's 128x96 H.264 SPS (High, 4:2:0, frames only) with
1024    /// `window` from the ninth byte on.
1025    fn h264_sps(window: &[u8]) -> Vec<u8> {
1026        let mut sps = vec![0x67, 0x64, 0x00, 0x0a, 0xac, 0xd9, 0x42, 0x0d];
1027        sps.extend_from_slice(window);
1028        sps.extend_from_slice(&[
1029            0x16, 0xa0, 0x20, 0x20, 0x28, 0x00, 0x00, 0x03, 0x00, 0x08, 0x00, 0x00, 0x03, 0x01,
1030            0xe0, 0x78, 0x91, 0x2c, 0xb0,
1031        ]);
1032        sps
1033    }
1034
1035    /// The corpus's 64x48 HEVC SPS (Main) with `window` as its conformance window.
1036    fn hevc_sps(window: &[u8]) -> Vec<u8> {
1037        let mut sps = vec![
1038            0x42, 0x01, 0x01, 0x01, 0x60, 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00,
1039            0x00, 0x03, 0x00, 0x1e, 0xa0, 0x20, 0x83,
1040        ];
1041        sps.extend_from_slice(window);
1042        sps.extend_from_slice(&[
1043            0x59, 0x59, 0xae, 0x4c, 0xaf, 0x01, 0x69, 0x6c, 0x20, 0x00, 0x00, 0x03, 0x00, 0x20,
1044            0x00, 0x00, 0x03, 0x03, 0xc1,
1045        ]);
1046        sps
1047    }
1048
1049    fn avcc(sps: &[u8]) -> Vec<u8> {
1050        let mut data = vec![1, 0x64, 0x00, 0x0a, 0xff, 0xe1];
1051        data.extend_from_slice(&u16::try_from(sps.len()).unwrap().to_be_bytes());
1052        data.extend_from_slice(sps);
1053        // One PPS after it, as every `avcC` carries.
1054        data.extend_from_slice(&[1, 0, 4, 0x68, 0xeb, 0xe3, 0xcb]);
1055        data
1056    }
1057
1058    fn hvcc(sps: &[u8]) -> Vec<u8> {
1059        let mut data = vec![1];
1060        data.extend_from_slice(&[0; 21]);
1061        // Two arrays: a stand-in VPS, then the SPS.
1062        data.extend_from_slice(&[2, 32, 0, 1, 0, 2, 0x40, 0x01, 33, 0, 1]);
1063        data.extend_from_slice(&u16::try_from(sps.len()).unwrap().to_be_bytes());
1064        data.extend_from_slice(sps);
1065        data
1066    }
1067
1068    fn annex_b(sps: &[u8]) -> Vec<u8> {
1069        let mut data = vec![0, 0, 0, 1];
1070        data.extend_from_slice(sps);
1071        data.extend_from_slice(&[0, 0, 1, 0x68, 0xeb, 0xe3, 0xcb]);
1072        data
1073    }
1074
1075    #[test]
1076    fn an_h264_sps_reports_the_columns_and_rows_it_crops_on_the_left_and_top() {
1077        for (window, expected) in [
1078            (&[0xb0][..], (0, 0)),
1079            (&[0xcb, 0xf0], (8, 0)),
1080            (&[0xf2, 0xf0], (0, 8)),
1081            (&[0xe5, 0xf0], (0, 0)),
1082            (&[0xf9, 0x30], (0, 0)),
1083        ] {
1084            let sps = h264_sps(window);
1085            for extradata in [avcc(&sps), annex_b(&sps)] {
1086                assert_eq!(
1087                    leading_crop(ParameterSetCodec::H264, &extradata),
1088                    Some(expected),
1089                    "{window:02x?}"
1090                );
1091            }
1092        }
1093    }
1094
1095    #[test]
1096    fn an_hevc_sps_reports_the_columns_and_rows_its_window_takes_on_the_left_and_top() {
1097        for (window, expected) in [
1098            (&[0x16][..], (0, 0)),
1099            (&[0x19, 0x7e], (8, 0)),
1100            (&[0x1e, 0x5e], (0, 8)),
1101            (&[0x1c, 0xbe], (0, 0)),
1102            (&[0x1f, 0x2e], (0, 0)),
1103        ] {
1104            let sps = hevc_sps(window);
1105            for extradata in [hvcc(&sps), annex_b(&sps)] {
1106                assert_eq!(
1107                    leading_crop(ParameterSetCodec::Hevc, &extradata),
1108                    Some(expected),
1109                    "{window:02x?}"
1110                );
1111            }
1112        }
1113    }
1114
1115    #[test]
1116    fn the_whole_crop_window_is_read_from_the_corpus() {
1117        let corpus = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/corpus");
1118        for (name, expected) in [
1119            ("h264-bt709-crop-left.mp4", (8, 0, 0, 0)),
1120            ("h264-bt709-crop-bottom.mp4", (0, 0, 0, 6)),
1121            ("h264-padded.mp4", (0, 0, 0, 12)),
1122            ("hevc-padded.mp4", (0, 0, 0, 4)),
1123        ] {
1124            let file = std::fs::read(corpus.join(name)).expect(name);
1125            let hevc = name.starts_with("hevc");
1126            let tag: &[u8] = if hevc { b"hvcC" } else { b"avcC" };
1127            let at = file
1128                .windows(4)
1129                .position(|window| window == tag)
1130                .expect("decoder configuration");
1131            let size = u32::from_be_bytes(file[at - 4..at].try_into().expect("size")) as usize;
1132            let record = &file[at + 4..at - 4 + size];
1133            let codec = if hevc {
1134                ParameterSetCodec::Hevc
1135            } else {
1136                ParameterSetCodec::H264
1137            };
1138            let crop = crop_window(codec, record).expect(name);
1139            assert_eq!(
1140                (crop.left, crop.right, crop.top, crop.bottom),
1141                expected,
1142                "{name}"
1143            );
1144            let visible = crop.visible().expect("a visible area");
1145            let probed = match name {
1146                "h264-bt709-crop-left.mp4" => (120, 96),
1147                "h264-bt709-crop-bottom.mp4" => (128, 90),
1148                _ => (320, 180),
1149            };
1150            assert_eq!((visible.width, visible.height), probed, "{name}");
1151        }
1152    }
1153
1154    #[test]
1155    fn the_vui_aspect_color_and_chroma_siting_are_read_from_the_corpus() {
1156        use alpha2_media::{ChromaLocation, ColorMetadata, SampleAspectRatio};
1157
1158        let corpus = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/corpus");
1159        let hlg = ColorMetadata::from_h273(9, 18, 9, Some(false));
1160        let bt709 = ColorMetadata::from_h273(1, 1, 1, Some(false));
1161        let range_only = ColorMetadata::from_h273(2, 2, 2, Some(false));
1162        // As ffprobe reports them.
1163        for (name, ratio, color, chroma) in [
1164            (
1165                "h264-bt709-vui-sar.mp4",
1166                (4, 3),
1167                bt709,
1168                ChromaLocation::Left,
1169            ),
1170            (
1171                "hevc-topleft.mp4",
1172                (1, 1),
1173                range_only,
1174                ChromaLocation::TopLeft,
1175            ),
1176            ("hevc-hvc1.mp4", (1, 1), range_only, ChromaLocation::TopLeft),
1177            ("hdr-hlg.mp4", (1, 1), hlg, ChromaLocation::Left),
1178            ("hevc-padded.mp4", (1, 1), bt709, ChromaLocation::Left),
1179            ("h264-high10.mp4", (1, 1), None, ChromaLocation::Left),
1180        ] {
1181            let file = std::fs::read(corpus.join(name)).expect(name);
1182            let hevc = name.starts_with("hevc");
1183            let tag: &[u8] = if hevc { b"hvcC" } else { b"avcC" };
1184            let at = file
1185                .windows(4)
1186                .position(|window| window == tag)
1187                .expect("decoder configuration");
1188            let size = u32::from_be_bytes(file[at - 4..at].try_into().expect("size")) as usize;
1189            let codec = if hevc {
1190                ParameterSetCodec::Hevc
1191            } else {
1192                ParameterSetCodec::H264
1193            };
1194            let facts = sequence_facts(codec, &file[at + 4..at - 4 + size]).expect(name);
1195            let (num, den) = ratio;
1196            assert_eq!(
1197                facts
1198                    .vui
1199                    .sample_aspect_ratio
1200                    .unwrap_or(SampleAspectRatio { num: 1, den: 1 }),
1201                SampleAspectRatio { num, den },
1202                "{name}"
1203            );
1204            assert_eq!(facts.vui.color, color, "{name}");
1205            assert_eq!(facts.chroma_location(), Some(chroma), "{name}");
1206        }
1207    }
1208
1209    /// The configuration record after `tag` in a corpus file.
1210    fn record(name: &str, tag: &[u8]) -> Vec<u8> {
1211        let corpus = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/corpus");
1212        let file = std::fs::read(corpus.join(name)).expect(name);
1213        let at = file
1214            .windows(4)
1215            .position(|window| window == tag)
1216            .expect("decoder configuration");
1217        let size = u32::from_be_bytes(file[at - 4..at].try_into().expect("size")) as usize;
1218        file[at + 4..at - 4 + size].to_vec()
1219    }
1220
1221    /// Parameter sets with start codes, as an encoder emits them.
1222    fn annex_b_of(units: &[&[u8]]) -> Vec<u8> {
1223        units
1224            .iter()
1225            .flat_map(|unit| [&[0, 0, 0, 1][..], unit].concat())
1226            .collect()
1227    }
1228
1229    #[test]
1230    fn decoder_configurations_are_rebuilt_from_annex_b_parameter_sets() {
1231        let avcc = record("h264-bt709-copy.mp4", b"avcC");
1232        let units = super::avcc_units(&avcc);
1233        let built = avc_decoder_config(&annex_b_of(&units)).expect("avcC");
1234        assert_eq!(built, avcc);
1235        let hvcc = record("hevc-hvc1.mp4", b"hvcC");
1236        let built = hevc_decoder_config(&annex_b_of(&super::hvcc_units(&hvcc))).expect("hvcC");
1237        // Equal but for what the encoder may declare beyond the parameter sets: spatial
1238        // segmentation, parallelism, frame rate and its SEI array.
1239        assert_eq!(built[..13], hvcc[..13]);
1240        assert_eq!(built[16..19], hvcc[16..19]);
1241        assert_eq!(built[21] & 0x3f, hvcc[21] & 0x3f);
1242        let parameter_sets = |record: &[u8]| {
1243            super::hvcc_units(record)
1244                .into_iter()
1245                .filter(|unit| matches!((unit[0] >> 1) & 0x3f, 32..=34))
1246                .map(<[u8]>::to_vec)
1247                .collect::<Vec<_>>()
1248        };
1249        assert_eq!(parameter_sets(&built), parameter_sets(&hvcc));
1250        assert_eq!(built[22], 3);
1251        assert_eq!(
1252            length_prefixed_units(&[0, 0, 0, 1, 0x65, 9, 0, 0, 1, 0x41, 7]),
1253            [0, 0, 0, 2, 0x65, 9, 0, 0, 0, 2, 0x41, 7]
1254        );
1255    }
1256
1257    #[test]
1258    fn a_description_without_a_readable_sps_reports_nothing() {
1259        assert_eq!(leading_crop(ParameterSetCodec::H264, &[]), None);
1260        // Cut short inside the crop window.
1261        let mut truncated = h264_sps(&[0xcb, 0xf0]);
1262        truncated.truncate(9);
1263        assert_eq!(
1264            leading_crop(ParameterSetCodec::H264, &avcc(&truncated)),
1265            None
1266        );
1267    }
1268
1269    /// MSB-first bytes of a string of `0` and `1`, zero-padded to whole bytes.
1270    fn packed(bits: &str) -> Vec<u8> {
1271        let bits = bits.bytes().filter(|bit| *bit != b' ').collect::<Vec<_>>();
1272        bits.chunks(8)
1273            .map(|chunk| {
1274                (0..8).fold(0_u8, |byte, at| {
1275                    (byte << 1) | u8::from(chunk.get(at) == Some(&b'1'))
1276                })
1277            })
1278            .collect()
1279    }
1280
1281    const VP9_SYNC: &str = "01001001 10000011 01000010";
1282
1283    /// 16-bit `frame_width_minus_1` and `frame_height_minus_1` of a 128x96 frame.
1284    const SIZE_128X96: &str = "00000000 01111111 00000000 01011111";
1285
1286    fn vp9(profile: u8, bit_depth: u8, subsampling: (bool, bool), color_space: u8) -> Vp9Format {
1287        Vp9Format {
1288            profile,
1289            bit_depth,
1290            subsampling,
1291            color_space,
1292            full_range: color_space == 7,
1293            width: 128,
1294            height: 96,
1295        }
1296    }
1297
1298    #[test]
1299    fn vp9_keyframes_declare_their_format() {
1300        // The first bytes of the key frames of `tests/corpus/vp9.webm` and `vp9-color.webm`.
1301        let corpus = vp9_format(&[0x82, 0x49, 0x83, 0x42, 0x00, 0x07, 0xf0, 0x05, 0xf6]);
1302        assert_eq!(corpus, Some(vp9(0, 8, (true, true), 0)));
1303        let color = vp9_format(&[0x82, 0x49, 0x83, 0x42, 0x40, 0x0f, 0xf0, 0x03, 0xf6]);
1304        assert_eq!(
1305            color,
1306            Some(Vp9Format {
1307                color_space: 2,
1308                width: 256,
1309                height: 64,
1310                ..vp9(0, 8, (true, true), 2)
1311            })
1312        );
1313        // Profile 2 at 10 and 12 bits, BT.2020, full range.
1314        assert_eq!(
1315            vp9_format(&packed(&format!(
1316                "10 0 1 0 0 1 0 {VP9_SYNC} 0 101 1 {SIZE_128X96}"
1317            ))),
1318            Some(Vp9Format {
1319                full_range: true,
1320                ..vp9(2, 10, (true, true), 5)
1321            })
1322        );
1323        assert_eq!(
1324            vp9_format(&packed(&format!(
1325                "10 0 1 0 0 1 0 {VP9_SYNC} 1 010 0 {SIZE_128X96}"
1326            ))),
1327            Some(vp9(2, 12, (true, true), 2))
1328        );
1329        // Profile 1 4:2:2, then profile 3 (a reserved bit after the profile) 12-bit RGB 4:4:4.
1330        assert_eq!(
1331            vp9_format(&packed(&format!(
1332                "10 1 0 0 0 1 0 {VP9_SYNC} 010 0 1 0 0 {SIZE_128X96}"
1333            ))),
1334            Some(vp9(1, 8, (true, false), 2))
1335        );
1336        assert_eq!(
1337            vp9_format(&packed(&format!(
1338                "10 1 1 0 0 0 1 0 {VP9_SYNC} 1 111 0 {SIZE_128X96}"
1339            ))),
1340            Some(vp9(3, 12, (false, false), 7))
1341        );
1342    }
1343
1344    #[test]
1345    fn vp9_intra_only_frames_declare_their_format() {
1346        // Not shown, not error resilient, intra-only, two bits of reset_frame_context, then the
1347        // color config of profiles above 0 and eight bits of refresh_frame_flags.
1348        assert_eq!(
1349            vp9_format(&packed(&format!(
1350                "10 0 1 0 1 0 0 1 00 {VP9_SYNC} 0 010 0 11111111 {SIZE_128X96}"
1351            ))),
1352            Some(vp9(2, 10, (true, true), 2))
1353        );
1354        assert_eq!(
1355            vp9_format(&packed(&format!(
1356                "10 0 0 0 1 0 0 1 00 {VP9_SYNC} 11111111 {SIZE_128X96}"
1357            ))),
1358            Some(vp9(0, 8, (true, true), 1))
1359        );
1360    }
1361
1362    #[test]
1363    fn vp9_frames_without_a_color_config_declare_nothing() {
1364        // An inter frame, a frame showing an existing one, a broken sync code, a wrong marker,
1365        // headers cut short in the sync code and before the frame size.
1366        assert_eq!(vp9_format(&[0x86, 0x00, 0x00, 0x00]), None);
1367        assert_eq!(vp9_format(&[0x88]), None);
1368        assert_eq!(
1369            vp9_format(&[0x82, 0x49, 0x83, 0x43, 0x00, 0x07, 0xf0, 0x05]),
1370            None
1371        );
1372        assert_eq!(
1373            vp9_format(&[0x42, 0x49, 0x83, 0x42, 0x00, 0x07, 0xf0, 0x05]),
1374            None
1375        );
1376        assert_eq!(vp9_format(&[0x92, 0x49]), None);
1377        assert_eq!(vp9_format(&[0x82, 0x49, 0x83, 0x42, 0x00]), None);
1378        assert_eq!(vp9_format(&[]), None);
1379    }
1380
1381    #[test]
1382    fn a_vp9_format_makes_the_vpcc_body_videotoolbox_reads() {
1383        let hd = Vp9Format {
1384            width: 1920,
1385            height: 1080,
1386            ..vp9(0, 8, (true, true), 2)
1387        };
1388        assert_eq!(
1389            hd.vpcc_record(Some(ColorMetadata::EXPORT)),
1390            [1, 0, 0, 0, 0, 40, 0x82, 1, 1, 1, 0, 0]
1391        );
1392        // Without a container color only the matrix is known; a small frame is level 1.
1393        assert_eq!(
1394            vp9(0, 8, (true, true), 2).vpcc_record(None),
1395            [1, 0, 0, 0, 0, 10, 0x82, 2, 2, 1, 0, 0]
1396        );
1397        let full = Vp9Format {
1398            full_range: true,
1399            ..vp9(2, 10, (true, true), 0)
1400        };
1401        assert_eq!(
1402            full.vpcc_record(None),
1403            [1, 0, 0, 0, 2, 10, 0xa3, 2, 2, 2, 0, 0]
1404        );
1405        assert_eq!(vp9(1, 8, (true, false), 1).vpcc_record(None)[6], 0x84);
1406        assert_eq!(
1407            vp9(3, 12, (false, false), 7).vpcc_record(None)[4..10],
1408            [3, 10, 0xc7, 2, 2, 0]
1409        );
1410    }
1411}