1use alpha2_media::{ChromaLocation, ColorMetadata, SampleAspectRatio};
6
7#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum ParameterSetCodec {
10 H264,
12 Hevc,
14}
15
16#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
18pub struct CropWindow {
19 pub coded_width: u32,
21 pub coded_height: u32,
23 pub left: u32,
25 pub right: u32,
27 pub top: u32,
29 pub bottom: u32,
31}
32
33impl CropWindow {
34 #[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#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
56pub struct Vui {
57 pub sample_aspect_ratio: Option<SampleAspectRatio>,
59 pub color: Option<ColorMetadata>,
61 pub signal: Option<VideoSignal>,
63 pub chroma_location: Option<ChromaLocation>,
65}
66
67#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
69pub struct VideoSignal {
70 pub full_range: bool,
72 pub description: Option<[u8; 3]>,
75}
76
77#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
79pub struct SequenceFacts {
80 pub crop: CropWindow,
82 pub chroma_format: u32,
84 pub bit_depth_luma: u32,
86 pub bit_depth_chroma: u32,
88 pub vui: Vui,
90}
91
92impl SequenceFacts {
93 #[must_use]
96 pub fn chroma_location(&self) -> Option<ChromaLocation> {
97 self.vui
98 .chroma_location
99 .or((self.chroma_format == 1).then_some(ChromaLocation::Left))
100 }
101}
102
103#[must_use]
106pub fn sequence_facts(codec: ParameterSetCodec, extradata: &[u8]) -> Option<SequenceFacts> {
107 let hevc = codec == ParameterSetCodec::Hevc;
108 let nal = *sequence_parameter_sets(hevc, extradata).first()?;
109 if hevc { hevc_sps(nal) } else { h264_sps(nal) }
110}
111
112#[must_use]
115pub fn length_prefixed_units(annex_b: &[u8]) -> Vec<u8> {
116 let units = annex_b_units(annex_b);
117 let mut out = Vec::with_capacity(annex_b.len() + units.len());
118 for unit in units {
119 out.extend_from_slice(&u32::try_from(unit.len()).unwrap_or(u32::MAX).to_be_bytes());
120 out.extend_from_slice(unit);
121 }
122 out
123}
124
125#[must_use]
128pub fn avc_decoder_config(annex_b: &[u8]) -> Option<Vec<u8>> {
129 let units = annex_b_units(annex_b);
130 let of_type = |kind: u8| -> Vec<&[u8]> {
131 units
132 .iter()
133 .copied()
134 .filter(|unit| unit[0] & 0x1f == kind)
135 .collect()
136 };
137 let (sps, pps) = (of_type(7), of_type(8));
138 let first = *sps.first()?;
139 if pps.is_empty() || first.len() < 4 {
140 return None;
141 }
142 let facts = h264_sps(first)?;
143 let mut record = vec![1, first[1], first[2], first[3], 0xff];
144 record.push(0xe0 | u8::try_from(sps.len()).ok().filter(|count| *count < 32)?);
145 for unit in &sps {
146 record.extend_from_slice(&u16::try_from(unit.len()).ok()?.to_be_bytes());
147 record.extend_from_slice(unit);
148 }
149 record.push(u8::try_from(pps.len()).ok()?);
150 for unit in &pps {
151 record.extend_from_slice(&u16::try_from(unit.len()).ok()?.to_be_bytes());
152 record.extend_from_slice(unit);
153 }
154 if matches!(first[1], 100 | 110 | 122 | 144) {
156 record.push(0xfc | u8::try_from(facts.chroma_format & 3).ok()?);
157 record.push(0xf8 | u8::try_from(facts.bit_depth_luma.checked_sub(8)? & 7).ok()?);
158 record.push(0xf8 | u8::try_from(facts.bit_depth_chroma.checked_sub(8)? & 7).ok()?);
159 record.push(0);
160 }
161 Some(record)
162}
163
164#[must_use]
167pub fn hevc_decoder_config(annex_b: &[u8]) -> Option<Vec<u8>> {
168 let units = annex_b_units(annex_b);
169 let kind = |unit: &[u8]| (unit[0] >> 1) & 0x3f;
170 let sps = *units
171 .iter()
172 .find(|unit| unit.len() > 2 && kind(unit) == 33)?;
173 let facts = hevc_sps(sps)?;
174 let payload = unescape(sps.get(2..)?);
177 let general = payload.get(1..13)?;
178 let sub_layers = (payload[0] >> 1) & 7;
179 let nested = payload[0] & 1;
180 let mut record = vec![1];
181 record.extend_from_slice(general);
182 record.extend_from_slice(&[0xf0, 0x00, 0xfc]); record.push(0xfc | u8::try_from(facts.chroma_format & 3).ok()?);
184 record.push(0xf8 | u8::try_from(facts.bit_depth_luma.checked_sub(8)? & 7).ok()?);
185 record.push(0xf8 | u8::try_from(facts.bit_depth_chroma.checked_sub(8)? & 7).ok()?);
186 record.extend_from_slice(&[0, 0]); record.push(((sub_layers + 1) << 3) | (nested << 2) | 3);
188 let arrays = [32, 33, 34]
189 .into_iter()
190 .map(|wanted| {
191 units
192 .iter()
193 .copied()
194 .filter(|unit| unit.len() > 2 && kind(unit) == wanted)
195 .collect::<Vec<_>>()
196 })
197 .filter(|array| !array.is_empty())
198 .collect::<Vec<_>>();
199 record.push(u8::try_from(arrays.len()).ok()?);
200 for array in arrays {
201 record.push(0x80 | kind(array[0]));
202 record.extend_from_slice(&u16::try_from(array.len()).ok()?.to_be_bytes());
203 for unit in array {
204 record.extend_from_slice(&u16::try_from(unit.len()).ok()?.to_be_bytes());
205 record.extend_from_slice(unit);
206 }
207 }
208 Some(record)
209}
210
211fn crop_windows(codec: ParameterSetCodec, extradata: &[u8]) -> Option<Vec<CropWindow>> {
214 let hevc = codec == ParameterSetCodec::Hevc;
215 sequence_parameter_sets(hevc, extradata)
216 .into_iter()
217 .map(|nal| if hevc { hevc_sps(nal) } else { h264_sps(nal) }.map(|facts| facts.crop))
218 .collect()
219}
220
221#[must_use]
224pub fn crop_window(codec: ParameterSetCodec, extradata: &[u8]) -> Option<CropWindow> {
225 crop_windows(codec, extradata)?.first().copied()
226}
227
228#[must_use]
233pub fn leading_crop(codec: ParameterSetCodec, extradata: &[u8]) -> Option<(u32, u32)> {
234 let crops = crop_windows(codec, extradata)?;
235 let first = *crops.first()?;
236 let leading = crops
237 .into_iter()
238 .find(|crop| crop.left > 0 || crop.top > 0)
239 .unwrap_or(first);
240 Some((leading.left, leading.top))
241}
242
243#[derive(Clone, Copy, Debug, Eq, PartialEq)]
245pub enum HevcLayers {
246 Single,
248 AuxiliaryAlpha,
251 Extra,
253}
254
255#[must_use]
257pub fn hevc_layers(extradata: &[u8]) -> Option<HevcLayers> {
258 let units = match extradata {
259 [1, ..] => hvcc_units(extradata),
260 _ => annex_b_units(extradata),
261 };
262 let vps = units
263 .into_iter()
264 .find(|nal| matches!(nal, [first, ..] if (first >> 1) & 0x3f == 32))?;
265 let payload = unescape(vps.get(2..)?);
266 let mut bits = Bits::new(&payload);
267 bits.skip(4)?; let base_internal = bits.flag()?;
269 bits.skip(1)?; let max_layers = bits.read(6)?; if max_layers == 0 {
272 return Some(HevcLayers::Single);
273 }
274 Some(vps_auxiliary_layer(&mut bits, base_internal).unwrap_or(HevcLayers::Extra))
275}
276
277fn vps_auxiliary_layer(bits: &mut Bits<'_>, base_internal: bool) -> Option<HevcLayers> {
280 let sub_layers = bits.read(3)?; bits.skip(1 + 16)?; skip_profile_tier_level(bits, true, sub_layers)?;
283 let ordering_for_all = bits.flag()?; for _ in if ordering_for_all { 0 } else { sub_layers }..=sub_layers {
285 bits.ue()?; bits.ue()?; bits.ue()?; }
289 let max_layer_id = bits.read(6)?; let layer_sets = bits.ue()?; bits.skip(
292 usize::try_from(layer_sets)
293 .ok()?
294 .checked_mul(max_layer_id as usize + 1)?,
295 )?;
296 if bits.flag()? {
297 return None;
299 }
300 if !bits.flag()? {
301 return Some(HevcLayers::Extra);
303 }
304 while !bits.at.is_multiple_of(8) {
305 bits.skip(1)?; }
307 if base_internal {
308 skip_profile_tier_level(bits, false, sub_layers)?;
309 }
310 bits.skip(1)?; let mask = bits.read(16)?; Some(if mask & (1 << (15 - 3)) != 0 {
313 HevcLayers::AuxiliaryAlpha
314 } else {
315 HevcLayers::Extra
316 })
317}
318
319fn skip_profile_tier_level(
321 bits: &mut Bits<'_>,
322 profile_present: bool,
323 sub_layers: u32,
324) -> Option<()> {
325 bits.skip(if profile_present { 88 } else { 0 } + 8)?;
327 let mut present = Vec::new();
328 for _ in 0..sub_layers {
329 present.push((bits.flag()?, bits.flag()?));
330 }
331 if sub_layers > 0 {
332 bits.skip(2 * (8 - sub_layers as usize))?;
333 }
334 for (profile, level) in present {
335 bits.skip(if profile { 88 } else { 0 } + if level { 8 } else { 0 })?;
336 }
337 Some(())
338}
339
340fn sequence_parameter_sets(hevc: bool, extradata: &[u8]) -> Vec<&[u8]> {
342 let is_sps = |nal: &[u8]| match (hevc, nal) {
343 (false, [header, ..]) => header & 0x1f == 7,
344 (true, [first, second, ..]) => {
346 (first >> 1) & 0x3f == 33 && (first & 1) == 0 && second >> 3 == 0
347 }
348 _ => false,
349 };
350 let units = match (hevc, extradata) {
351 (false, [1, ..]) => avcc_units(extradata),
352 (true, [1, ..]) => hvcc_units(extradata),
353 _ => annex_b_units(extradata),
354 };
355 units.into_iter().filter(|nal| is_sps(nal)).collect()
356}
357
358fn avcc_units(data: &[u8]) -> Vec<&[u8]> {
360 let mut units = Vec::new();
361 let Some(&count) = data.get(5) else {
362 return units;
363 };
364 let mut at = 6;
365 for _ in 0..(count & 0x1f) {
366 let Some((nal, next)) = length_prefixed(data, at) else {
367 return units;
368 };
369 units.push(nal);
370 at = next;
371 }
372 let Some(&count) = data.get(at) else {
373 return units;
374 };
375 at += 1;
376 for _ in 0..count {
377 let Some((nal, next)) = length_prefixed(data, at) else {
378 break;
379 };
380 units.push(nal);
381 at = next;
382 }
383 units
384}
385
386fn hvcc_units(data: &[u8]) -> Vec<&[u8]> {
387 let mut units = Vec::new();
388 let Some(&arrays) = data.get(22) else {
389 return units;
390 };
391 let mut at = 23;
392 for _ in 0..arrays {
393 let Some(count) = data.get(at + 1..at + 3) else {
394 break;
395 };
396 let count = u16::from_be_bytes([count[0], count[1]]);
397 at += 3;
398 for _ in 0..count {
399 let Some((nal, next)) = length_prefixed(data, at) else {
400 return units;
401 };
402 units.push(nal);
403 at = next;
404 }
405 }
406 units
407}
408
409fn length_prefixed(data: &[u8], at: usize) -> Option<(&[u8], usize)> {
411 let length = data.get(at..at + 2)?;
412 let end = at + 2 + usize::from(u16::from_be_bytes([length[0], length[1]]));
413 Some((data.get(at + 2..end)?, end))
414}
415
416fn annex_b_units(data: &[u8]) -> Vec<&[u8]> {
417 let starts = (0..data.len().saturating_sub(2))
418 .filter(|&at| data[at..at + 3] == [0, 0, 1])
419 .map(|at| at + 3)
420 .collect::<Vec<_>>();
421 starts
422 .iter()
423 .enumerate()
424 .map(|(index, &start)| {
425 let end = starts.get(index + 1).map_or(data.len(), |next| next - 3);
426 let mut unit = &data[start..end.max(start)];
428 while let [rest @ .., 0] = unit {
429 unit = rest;
430 }
431 unit
432 })
433 .filter(|unit| !unit.is_empty())
434 .collect()
435}
436
437fn h264_sps(nal: &[u8]) -> Option<SequenceFacts> {
439 let payload = unescape(nal.get(1..)?);
440 let mut bits = Bits::new(&payload);
441 let profile = bits.read(8)?;
442 bits.skip(16)?; bits.ue()?; let (mut chroma_format, mut bit_depth_luma, mut bit_depth_chroma) = (1, 8, 8);
445 if matches!(
446 profile,
447 100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135
448 ) {
449 chroma_format = bits.ue()?;
450 if chroma_format == 3 {
451 bits.skip(1)?; }
453 bit_depth_luma = bits.ue()?.saturating_add(8);
454 bit_depth_chroma = bits.ue()?.saturating_add(8);
455 bits.skip(1)?; if bits.flag()? {
457 for list in 0..if chroma_format == 3 { 12 } else { 8 } {
458 if bits.flag()? {
459 skip_scaling_list(&mut bits, if list < 6 { 16 } else { 64 })?;
460 }
461 }
462 }
463 }
464 bits.ue()?; match bits.ue()? {
466 0 => {
467 bits.ue()?; }
469 1 => {
470 bits.skip(1)?; bits.se()?; bits.se()?; for _ in 0..bits.ue()?.min(255) {
474 bits.se()?; }
476 }
477 _ => {}
478 }
479 bits.ue()?; bits.skip(1)?; let width_in_mbs = bits.ue()?.saturating_add(1);
482 let height_in_map_units = bits.ue()?.saturating_add(1);
483 let frame_mbs_only = bits.flag()?;
484 let coded_width = width_in_mbs.saturating_mul(16);
485 let coded_height = height_in_map_units
486 .saturating_mul(16)
487 .saturating_mul(if frame_mbs_only { 1 } else { 2 });
488 if !frame_mbs_only {
489 bits.skip(1)?; }
491 bits.skip(1)?; let mut crop = CropWindow {
493 coded_width,
494 coded_height,
495 ..CropWindow::default()
496 };
497 if bits.flag()? {
498 let (left, right, top, bottom) = (bits.ue()?, bits.ue()?, bits.ue()?, bits.ue()?);
499 let (unit_x, unit_y) = crop_units(chroma_format);
502 let unit_y = unit_y * if frame_mbs_only { 1 } else { 2 };
503 crop.left = left.saturating_mul(unit_x);
504 crop.right = right.saturating_mul(unit_x);
505 crop.top = top.saturating_mul(unit_y);
506 crop.bottom = bottom.saturating_mul(unit_y);
507 }
508 let vui = bits
509 .flag()
510 .filter(|present| *present)
511 .and_then(|_| vui(&mut bits, chroma_format))
512 .unwrap_or_default();
513 Some(SequenceFacts {
514 crop,
515 chroma_format,
516 bit_depth_luma,
517 bit_depth_chroma,
518 vui,
519 })
520}
521
522const fn crop_units(chroma_format: u32) -> (u32, u32) {
524 match chroma_format {
525 1 => (2, 2),
526 2 => (2, 1),
527 _ => (1, 1),
528 }
529}
530
531fn vui(bits: &mut Bits<'_>, chroma_format: u32) -> Option<Vui> {
534 const RATIOS: [(u32, u32); 16] = [
536 (1, 1),
537 (12, 11),
538 (10, 11),
539 (16, 11),
540 (40, 33),
541 (24, 11),
542 (20, 11),
543 (32, 11),
544 (80, 33),
545 (18, 11),
546 (15, 11),
547 (64, 33),
548 (160, 99),
549 (4, 3),
550 (3, 2),
551 (2, 1),
552 ];
553 let mut vui = Vui::default();
554 if bits.flag()? {
555 let ratio = match bits.read(8)? {
556 255 => Some((bits.read(16)?, bits.read(16)?)),
557 idc @ 1..=16 => RATIOS.get(idc as usize - 1).copied(),
558 _ => None,
559 };
560 vui.sample_aspect_ratio = ratio
561 .filter(|(num, den)| *num > 0 && *den > 0)
562 .map(|(num, den)| SampleAspectRatio { num, den });
563 }
564 if bits.flag()? {
565 bits.skip(1)?; }
567 if bits.flag()? {
568 bits.skip(3)?; let full = bits.flag()?;
570 let code = |value: u32| u8::try_from(value).unwrap_or(2);
571 let description = if bits.flag()? {
572 Some([
573 code(bits.read(8)?),
574 code(bits.read(8)?),
575 code(bits.read(8)?),
576 ])
577 } else {
578 None
579 };
580 let [primaries, transfer, matrix] = description.unwrap_or([2, 2, 2]);
581 vui.color = ColorMetadata::from_h273(primaries, transfer, matrix, Some(full));
582 vui.signal = Some(VideoSignal {
583 full_range: full,
584 description,
585 });
586 }
587 if bits.flag()? {
588 let top = bits.ue()?;
589 bits.ue()?; if chroma_format == 1 {
591 vui.chroma_location = Some(match top {
592 0 => ChromaLocation::Left,
593 1 => ChromaLocation::Center,
594 2 => ChromaLocation::TopLeft,
595 _ => ChromaLocation::Unspecified,
596 });
597 }
598 }
599 Some(vui)
600}
601
602fn skip_scaling_list(bits: &mut Bits<'_>, size: usize) -> Option<()> {
604 let (mut last, mut next) = (8_i64, 8_i64);
605 for _ in 0..size {
606 if next != 0 {
607 next = (last + bits.se()? + 256).rem_euclid(256);
608 }
609 if next != 0 {
610 last = next;
611 }
612 }
613 Some(())
614}
615
616fn hevc_sps(nal: &[u8]) -> Option<SequenceFacts> {
619 let payload = unescape(nal.get(2..)?);
620 let mut bits = Bits::new(&payload);
621 bits.skip(4)?; let sub_layers = bits.read(3)?; bits.skip(1)?; bits.skip(96)?;
626 let mut present = Vec::new();
627 for _ in 0..sub_layers {
628 present.push((bits.flag()?, bits.flag()?));
629 }
630 if sub_layers > 0 {
631 bits.skip(2 * (8 - sub_layers as usize))?;
632 }
633 for (profile, level) in present {
634 bits.skip(if profile { 88 } else { 0 } + if level { 8 } else { 0 })?;
635 }
636 bits.ue()?; let chroma_format = bits.ue()?;
638 if chroma_format == 3 {
639 bits.skip(1)?; }
641 let coded_width = bits.ue()?;
642 let coded_height = bits.ue()?;
643 let mut crop = CropWindow {
644 coded_width,
645 coded_height,
646 ..CropWindow::default()
647 };
648 if bits.flag()? {
649 let (left, right, top, bottom) = (bits.ue()?, bits.ue()?, bits.ue()?, bits.ue()?);
650 let (unit_x, unit_y) = crop_units(chroma_format);
651 crop.left = left.saturating_mul(unit_x);
652 crop.right = right.saturating_mul(unit_x);
653 crop.top = top.saturating_mul(unit_y);
654 crop.bottom = bottom.saturating_mul(unit_y);
655 }
656 let bit_depth_luma = bits.ue()?.saturating_add(8);
657 let bit_depth_chroma = bits.ue()?.saturating_add(8);
658 let vui = hevc_vui(&mut bits, sub_layers, chroma_format).unwrap_or_default();
659 Some(SequenceFacts {
660 crop,
661 chroma_format,
662 bit_depth_luma,
663 bit_depth_chroma,
664 vui,
665 })
666}
667
668fn hevc_vui(bits: &mut Bits<'_>, sub_layers: u32, chroma_format: u32) -> Option<Vui> {
670 let poc_lsb_bits = bits.ue()?.checked_add(4)?;
671 let first = if bits.flag()? { 0 } else { sub_layers };
672 for _ in first..=sub_layers {
673 bits.ue()?; bits.ue()?; bits.ue()?; }
677 for _ in 0..6 {
678 bits.ue()?;
680 }
681 if bits.flag()? && bits.flag()? {
682 skip_hevc_scaling_lists(bits)?;
683 }
684 bits.skip(2)?; if bits.flag()? {
686 bits.skip(8)?; bits.ue()?; bits.ue()?; bits.skip(1)?; }
691 skip_short_term_ref_pic_sets(bits)?;
692 if bits.flag()? {
693 for _ in 0..bits.ue()?.min(32) {
694 bits.skip(poc_lsb_bits as usize)?; bits.skip(1)?; }
697 }
698 bits.skip(2)?; if !bits.flag()? {
700 return Some(Vui::default());
701 }
702 vui(bits, chroma_format)
703}
704
705fn skip_hevc_scaling_lists(bits: &mut Bits<'_>) -> Option<()> {
707 for size in 0..4_u32 {
708 let step = if size == 3 { 3 } else { 1 };
709 for _ in (0..6).step_by(step) {
710 if bits.flag()? {
711 let coefficients = 64.min(1 << (4 + (size << 1)));
712 if size > 1 {
713 bits.se()?; }
715 for _ in 0..coefficients {
716 bits.se()?; }
718 } else {
719 bits.ue()?; }
721 }
722 }
723 Some(())
724}
725
726fn skip_short_term_ref_pic_sets(bits: &mut Bits<'_>) -> Option<()> {
728 let count = bits.ue()?;
729 if count > 64 {
730 return None;
731 }
732 let mut delta_pocs: Vec<u32> = Vec::with_capacity(count as usize);
733 for index in 0..count {
734 let predicted = index != 0 && bits.flag()?;
735 let pictures = if predicted {
736 bits.skip(1)?; bits.ue()?; let reference = *delta_pocs.last()?;
739 let mut pictures = 0;
740 for _ in 0..=reference {
741 let used = bits.flag()?;
742 if used || bits.flag()? {
743 pictures += 1;
744 }
745 }
746 pictures
747 } else {
748 let negative = bits.ue()?;
749 let positive = bits.ue()?;
750 let pictures = negative
751 .checked_add(positive)
752 .filter(|total| *total <= 32)?;
753 for _ in 0..pictures {
754 bits.ue()?; bits.skip(1)?; }
757 pictures
758 };
759 delta_pocs.push(pictures);
760 }
761 Some(())
762}
763
764#[derive(Clone, Copy, Debug, Eq, PartialEq)]
767pub struct Vp9Format {
768 pub profile: u8,
770 pub bit_depth: u8,
772 pub subsampling: (bool, bool),
774 pub color_space: u8,
776 pub full_range: bool,
778 pub width: u32,
780 pub height: u32,
782}
783
784impl Vp9Format {
785 #[must_use]
789 pub fn vpcc_record(&self, color: Option<ColorMetadata>) -> [u8; 12] {
790 use alpha2_media::{ColorMatrix, ColorPrimaries, TransferFunction};
791 let (primaries, transfer, matrix) = match color {
792 Some(color) => (
793 match color.primaries {
794 ColorPrimaries::Bt601 => 6,
795 ColorPrimaries::Bt709 => 1,
796 ColorPrimaries::Bt2020 => 9,
797 ColorPrimaries::DisplayP3 => 12,
798 },
799 match color.transfer {
800 TransferFunction::Bt709 => 1,
801 TransferFunction::Srgb => 13,
802 TransferFunction::Pq => 16,
803 TransferFunction::Hlg => 18,
804 },
805 match color.matrix {
806 ColorMatrix::Bt601 => 6,
807 ColorMatrix::Bt709 => 1,
808 ColorMatrix::Bt2020Ncl => 9,
809 ColorMatrix::Rgb => 0,
810 },
811 ),
812 None => (
813 2,
814 2,
815 match self.color_space {
816 1 | 3 => 6,
817 2 => 1,
818 4 => 7,
819 5 => 9,
820 7 => 0,
821 _ => 2,
822 },
823 ),
824 };
825 let chroma = match self.subsampling {
827 (true, true) => 1,
828 (true, false) => 2,
829 (false, _) => 3,
830 };
831 let samples = u64::from(self.width) * u64::from(self.height);
833 let level = [
834 (36_864, 10),
835 (73_728, 11),
836 (122_880, 20),
837 (245_760, 21),
838 (552_960, 30),
839 (983_040, 31),
840 (2_228_224, 40),
841 (8_912_896, 50),
842 (35_651_584, 60),
843 ]
844 .iter()
845 .find(|(size, _)| samples <= *size)
846 .map_or(62, |(_, level)| *level);
847 [
848 1,
849 0,
850 0,
851 0,
852 self.profile,
853 level,
854 (self.bit_depth << 4) | (chroma << 1) | u8::from(self.full_range),
855 primaries,
856 transfer,
857 matrix,
858 0,
859 0,
860 ]
861 }
862}
863
864#[must_use]
868pub fn vp9_format(frame: &[u8]) -> Option<Vp9Format> {
869 const SYNC_CODE: u32 = 0x49_83_42;
870 const CS_RGB: u8 = 7;
871 let mut bits = Bits::new(frame);
872 if bits.read(2)? != 2 {
873 return None;
874 }
875 let low = bits.read(1)?;
876 let profile = u8::try_from((bits.read(1)? << 1) | low).ok()?;
877 if profile == 3 {
878 bits.skip(1)?;
879 }
880 if bits.flag()? {
881 return None;
882 }
883 let key_frame = !bits.flag()?;
884 let show_frame = bits.flag()?;
885 let error_resilient = bits.flag()?;
886 let mut format = Vp9Format {
887 profile,
888 bit_depth: 8,
889 subsampling: (true, true),
890 color_space: 1,
891 full_range: false,
892 width: 0,
893 height: 0,
894 };
895 let intra_only = if key_frame {
896 false
897 } else {
898 let intra_only = !show_frame && bits.flag()?;
899 if !error_resilient {
900 bits.skip(2)?;
901 }
902 if !intra_only {
903 return None;
904 }
905 true
906 };
907 if bits.read(24)? != SYNC_CODE {
908 return None;
909 }
910 if !intra_only || profile > 0 {
911 if profile >= 2 {
912 format.bit_depth = if bits.flag()? { 12 } else { 10 };
913 }
914 format.color_space = u8::try_from(bits.read(3)?).ok()?;
915 let four_four_four = profile == 1 || profile == 3;
916 if format.color_space == CS_RGB {
917 format.full_range = true;
918 if four_four_four {
919 format.subsampling = (false, false);
920 bits.skip(1)?;
921 }
922 } else {
923 format.full_range = bits.flag()?;
924 if four_four_four {
925 format.subsampling = (bits.flag()?, bits.flag()?);
926 bits.skip(1)?;
927 }
928 }
929 }
930 if intra_only {
931 bits.skip(8)?; }
933 format.width = bits.read(16)? + 1;
934 format.height = bits.read(16)? + 1;
935 Some(format)
936}
937
938fn unescape(escaped: &[u8]) -> Vec<u8> {
939 let mut payload = Vec::with_capacity(escaped.len());
940 let mut zeros = 0;
941 for &byte in escaped {
942 if zeros >= 2 && byte == 3 {
943 zeros = 0;
944 continue;
945 }
946 zeros = if byte == 0 { zeros + 1 } else { 0 };
947 payload.push(byte);
948 }
949 payload
950}
951
952struct Bits<'a> {
954 data: &'a [u8],
955 at: usize,
956}
957
958impl<'a> Bits<'a> {
959 const fn new(data: &'a [u8]) -> Self {
960 Self { data, at: 0 }
961 }
962
963 fn flag(&mut self) -> Option<bool> {
964 let byte = *self.data.get(self.at / 8)?;
965 let bit = (byte >> (7 - self.at % 8)) & 1;
966 self.at += 1;
967 Some(bit == 1)
968 }
969
970 fn read(&mut self, count: u32) -> Option<u32> {
971 (0..count).try_fold(0, |value, _| Some((value << 1) | u32::from(self.flag()?)))
972 }
973
974 fn skip(&mut self, count: usize) -> Option<()> {
975 let end = self.at.checked_add(count)?;
976 (end <= self.data.len() * 8).then(|| self.at = end)
977 }
978
979 fn ue(&mut self) -> Option<u32> {
981 let mut zeros = 0;
982 while !self.flag()? {
983 zeros += 1;
984 if zeros > 31 {
985 return None;
986 }
987 }
988 Some((1_u32 << zeros) - 1 + self.read(zeros)?)
989 }
990
991 fn se(&mut self) -> Option<i64> {
993 let code = i64::from(self.ue()?);
994 Some(if code % 2 == 1 {
995 (code + 1) / 2
996 } else {
997 -(code / 2)
998 })
999 }
1000}
1001
1002#[cfg(test)]
1003mod tests {
1004 use super::{
1005 HevcLayers, ParameterSetCodec, Vp9Format, avc_decoder_config, crop_window,
1006 hevc_decoder_config, hevc_layers, leading_crop, length_prefixed_units, sequence_facts,
1007 vp9_format,
1008 };
1009 use alpha2_media::ColorMetadata;
1010
1011 const ALPHA_VPS: [u8; 41] = [
1014 0x40, 0x01, 0x0c, 0x11, 0xff, 0xff, 0x01, 0x60, 0x00, 0x00, 0x03, 0x00, 0xb0, 0x00, 0x00,
1015 0x03, 0x00, 0x00, 0x03, 0x00, 0x1e, 0x17, 0x06, 0xff, 0x1e, 0x08, 0x00, 0x08, 0x30, 0x28,
1016 0x53, 0x80, 0x50, 0x00, 0x30, 0x50, 0x0c, 0x23, 0xf1, 0x7a, 0x40,
1017 ];
1018
1019 fn start_coded(nal: &[u8]) -> Vec<u8> {
1020 let mut data = vec![0, 0, 0, 1];
1021 data.extend_from_slice(nal);
1022 data
1023 }
1024
1025 #[test]
1026 fn hevc_alpha_is_detected_from_its_vps() {
1027 assert_eq!(
1028 hevc_layers(&start_coded(&ALPHA_VPS)),
1029 Some(HevcLayers::AuxiliaryAlpha)
1030 );
1031 let mut single = ALPHA_VPS;
1033 single[3] &= 0x0f;
1034 assert_eq!(hevc_layers(&start_coded(&single)), Some(HevcLayers::Single));
1035 let mut views = ALPHA_VPS;
1038 views[25] = 0x20;
1039 assert_eq!(hevc_layers(&start_coded(&views)), Some(HevcLayers::Extra));
1040 assert_eq!(hevc_layers(&[1, 2, 3]), None);
1041 }
1042
1043 fn h264_sps(window: &[u8]) -> Vec<u8> {
1046 let mut sps = vec![0x67, 0x64, 0x00, 0x0a, 0xac, 0xd9, 0x42, 0x0d];
1047 sps.extend_from_slice(window);
1048 sps.extend_from_slice(&[
1049 0x16, 0xa0, 0x20, 0x20, 0x28, 0x00, 0x00, 0x03, 0x00, 0x08, 0x00, 0x00, 0x03, 0x01,
1050 0xe0, 0x78, 0x91, 0x2c, 0xb0,
1051 ]);
1052 sps
1053 }
1054
1055 fn hevc_sps(window: &[u8]) -> Vec<u8> {
1057 let mut sps = vec![
1058 0x42, 0x01, 0x01, 0x01, 0x60, 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00,
1059 0x00, 0x03, 0x00, 0x1e, 0xa0, 0x20, 0x83,
1060 ];
1061 sps.extend_from_slice(window);
1062 sps.extend_from_slice(&[
1063 0x59, 0x59, 0xae, 0x4c, 0xaf, 0x01, 0x69, 0x6c, 0x20, 0x00, 0x00, 0x03, 0x00, 0x20,
1064 0x00, 0x00, 0x03, 0x03, 0xc1,
1065 ]);
1066 sps
1067 }
1068
1069 fn avcc(sps: &[u8]) -> Vec<u8> {
1070 let mut data = vec![1, 0x64, 0x00, 0x0a, 0xff, 0xe1];
1071 data.extend_from_slice(&u16::try_from(sps.len()).unwrap().to_be_bytes());
1072 data.extend_from_slice(sps);
1073 data.extend_from_slice(&[1, 0, 4, 0x68, 0xeb, 0xe3, 0xcb]);
1075 data
1076 }
1077
1078 fn hvcc(sps: &[u8]) -> Vec<u8> {
1079 let mut data = vec![1];
1080 data.extend_from_slice(&[0; 21]);
1081 data.extend_from_slice(&[2, 32, 0, 1, 0, 2, 0x40, 0x01, 33, 0, 1]);
1083 data.extend_from_slice(&u16::try_from(sps.len()).unwrap().to_be_bytes());
1084 data.extend_from_slice(sps);
1085 data
1086 }
1087
1088 fn annex_b(sps: &[u8]) -> Vec<u8> {
1089 let mut data = vec![0, 0, 0, 1];
1090 data.extend_from_slice(sps);
1091 data.extend_from_slice(&[0, 0, 1, 0x68, 0xeb, 0xe3, 0xcb]);
1092 data
1093 }
1094
1095 #[test]
1096 fn an_h264_sps_reports_the_columns_and_rows_it_crops_on_the_left_and_top() {
1097 for (window, expected) in [
1098 (&[0xb0][..], (0, 0)),
1099 (&[0xcb, 0xf0], (8, 0)),
1100 (&[0xf2, 0xf0], (0, 8)),
1101 (&[0xe5, 0xf0], (0, 0)),
1102 (&[0xf9, 0x30], (0, 0)),
1103 ] {
1104 let sps = h264_sps(window);
1105 for extradata in [avcc(&sps), annex_b(&sps)] {
1106 assert_eq!(
1107 leading_crop(ParameterSetCodec::H264, &extradata),
1108 Some(expected),
1109 "{window:02x?}"
1110 );
1111 }
1112 }
1113 }
1114
1115 #[test]
1116 fn an_hevc_sps_reports_the_columns_and_rows_its_window_takes_on_the_left_and_top() {
1117 for (window, expected) in [
1118 (&[0x16][..], (0, 0)),
1119 (&[0x19, 0x7e], (8, 0)),
1120 (&[0x1e, 0x5e], (0, 8)),
1121 (&[0x1c, 0xbe], (0, 0)),
1122 (&[0x1f, 0x2e], (0, 0)),
1123 ] {
1124 let sps = hevc_sps(window);
1125 for extradata in [hvcc(&sps), annex_b(&sps)] {
1126 assert_eq!(
1127 leading_crop(ParameterSetCodec::Hevc, &extradata),
1128 Some(expected),
1129 "{window:02x?}"
1130 );
1131 }
1132 }
1133 }
1134
1135 #[test]
1136 fn the_whole_crop_window_is_read_from_the_corpus() {
1137 let corpus = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/corpus");
1138 for (name, expected) in [
1139 ("h264-bt709-crop-left.mp4", (8, 0, 0, 0)),
1140 ("h264-bt709-crop-bottom.mp4", (0, 0, 0, 6)),
1141 ("h264-padded.mp4", (0, 0, 0, 12)),
1142 ("hevc-padded.mp4", (0, 0, 0, 4)),
1143 ] {
1144 let file = std::fs::read(corpus.join(name)).expect(name);
1145 let hevc = name.starts_with("hevc");
1146 let tag: &[u8] = if hevc { b"hvcC" } else { b"avcC" };
1147 let at = file
1148 .windows(4)
1149 .position(|window| window == tag)
1150 .expect("decoder configuration");
1151 let size = u32::from_be_bytes(file[at - 4..at].try_into().expect("size")) as usize;
1152 let record = &file[at + 4..at - 4 + size];
1153 let codec = if hevc {
1154 ParameterSetCodec::Hevc
1155 } else {
1156 ParameterSetCodec::H264
1157 };
1158 let crop = crop_window(codec, record).expect(name);
1159 assert_eq!(
1160 (crop.left, crop.right, crop.top, crop.bottom),
1161 expected,
1162 "{name}"
1163 );
1164 let visible = crop.visible().expect("a visible area");
1165 let probed = match name {
1166 "h264-bt709-crop-left.mp4" => (120, 96),
1167 "h264-bt709-crop-bottom.mp4" => (128, 90),
1168 _ => (320, 180),
1169 };
1170 assert_eq!((visible.width, visible.height), probed, "{name}");
1171 }
1172 }
1173
1174 #[test]
1175 fn the_vui_aspect_color_and_chroma_siting_are_read_from_the_corpus() {
1176 use alpha2_media::{ChromaLocation, ColorMetadata, SampleAspectRatio};
1177
1178 let corpus = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/corpus");
1179 let hlg = ColorMetadata::from_h273(9, 18, 9, Some(false));
1180 let bt709 = ColorMetadata::from_h273(1, 1, 1, Some(false));
1181 let range_only = ColorMetadata::from_h273(2, 2, 2, Some(false));
1182 let facts_of = |name: &str| {
1183 let file = std::fs::read(corpus.join(name)).expect(name);
1184 let hevc = name.starts_with("hevc");
1185 let tag: &[u8] = if hevc { b"hvcC" } else { b"avcC" };
1186 let at = file
1187 .windows(4)
1188 .position(|window| window == tag)
1189 .expect("decoder configuration");
1190 let size = u32::from_be_bytes(file[at - 4..at].try_into().expect("size")) as usize;
1191 let codec = if hevc {
1192 ParameterSetCodec::Hevc
1193 } else {
1194 ParameterSetCodec::H264
1195 };
1196 sequence_facts(codec, &file[at + 4..at - 4 + size]).expect(name)
1197 };
1198 for (name, ratio, color, chroma) in [
1200 (
1201 "h264-bt709-vui-sar.mp4",
1202 (4, 3),
1203 bt709,
1204 ChromaLocation::Left,
1205 ),
1206 (
1207 "hevc-topleft.mp4",
1208 (1, 1),
1209 range_only,
1210 ChromaLocation::TopLeft,
1211 ),
1212 ("hevc-hvc1.mp4", (1, 1), range_only, ChromaLocation::TopLeft),
1213 ("hdr-hlg.mp4", (1, 1), hlg, ChromaLocation::Left),
1214 ("hevc-padded.mp4", (1, 1), bt709, ChromaLocation::Left),
1215 ("h264-high10.mp4", (1, 1), None, ChromaLocation::Left),
1216 ] {
1217 let facts = facts_of(name);
1218 let (num, den) = ratio;
1219 assert_eq!(
1220 facts
1221 .vui
1222 .sample_aspect_ratio
1223 .unwrap_or(SampleAspectRatio { num: 1, den: 1 }),
1224 SampleAspectRatio { num, den },
1225 "{name}"
1226 );
1227 assert_eq!(facts.vui.color, color, "{name}");
1228 assert_eq!(facts.chroma_location(), Some(chroma), "{name}");
1229 }
1230 for (name, description) in [
1231 ("h264-bt709-transcode.mp4", Some([1, 1, 1])),
1232 ("h264-bt709-transcode-vui-bt601.mp4", Some([6, 6, 6])),
1233 ] {
1234 assert_eq!(
1235 facts_of(name).vui.signal,
1236 Some(super::VideoSignal {
1237 full_range: false,
1238 description
1239 }),
1240 "{name}"
1241 );
1242 }
1243 assert_eq!(facts_of("h264-high10.mp4").vui.signal, None);
1244 }
1245
1246 fn record(name: &str, tag: &[u8]) -> Vec<u8> {
1248 let corpus = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/corpus");
1249 let file = std::fs::read(corpus.join(name)).expect(name);
1250 let at = file
1251 .windows(4)
1252 .position(|window| window == tag)
1253 .expect("decoder configuration");
1254 let size = u32::from_be_bytes(file[at - 4..at].try_into().expect("size")) as usize;
1255 file[at + 4..at - 4 + size].to_vec()
1256 }
1257
1258 fn annex_b_of(units: &[&[u8]]) -> Vec<u8> {
1260 units
1261 .iter()
1262 .flat_map(|unit| [&[0, 0, 0, 1][..], unit].concat())
1263 .collect()
1264 }
1265
1266 #[test]
1267 fn decoder_configurations_are_rebuilt_from_annex_b_parameter_sets() {
1268 let avcc = record("h264-bt709-copy.mp4", b"avcC");
1269 let units = super::avcc_units(&avcc);
1270 let built = avc_decoder_config(&annex_b_of(&units)).expect("avcC");
1271 assert_eq!(built, avcc);
1272 let hvcc = record("hevc-hvc1.mp4", b"hvcC");
1273 let built = hevc_decoder_config(&annex_b_of(&super::hvcc_units(&hvcc))).expect("hvcC");
1274 assert_eq!(built[..13], hvcc[..13]);
1277 assert_eq!(built[16..19], hvcc[16..19]);
1278 assert_eq!(built[21] & 0x3f, hvcc[21] & 0x3f);
1279 let parameter_sets = |record: &[u8]| {
1280 super::hvcc_units(record)
1281 .into_iter()
1282 .filter(|unit| matches!((unit[0] >> 1) & 0x3f, 32..=34))
1283 .map(<[u8]>::to_vec)
1284 .collect::<Vec<_>>()
1285 };
1286 assert_eq!(parameter_sets(&built), parameter_sets(&hvcc));
1287 assert_eq!(built[22], 3);
1288 assert_eq!(
1289 length_prefixed_units(&[0, 0, 0, 1, 0x65, 9, 0, 0, 1, 0x41, 7]),
1290 [0, 0, 0, 2, 0x65, 9, 0, 0, 0, 2, 0x41, 7]
1291 );
1292 }
1293
1294 #[test]
1295 fn a_description_without_a_readable_sps_reports_nothing() {
1296 assert_eq!(leading_crop(ParameterSetCodec::H264, &[]), None);
1297 let mut truncated = h264_sps(&[0xcb, 0xf0]);
1299 truncated.truncate(9);
1300 assert_eq!(
1301 leading_crop(ParameterSetCodec::H264, &avcc(&truncated)),
1302 None
1303 );
1304 }
1305
1306 fn packed(bits: &str) -> Vec<u8> {
1308 let bits = bits.bytes().filter(|bit| *bit != b' ').collect::<Vec<_>>();
1309 bits.chunks(8)
1310 .map(|chunk| {
1311 (0..8).fold(0_u8, |byte, at| {
1312 (byte << 1) | u8::from(chunk.get(at) == Some(&b'1'))
1313 })
1314 })
1315 .collect()
1316 }
1317
1318 const VP9_SYNC: &str = "01001001 10000011 01000010";
1319
1320 const SIZE_128X96: &str = "00000000 01111111 00000000 01011111";
1322
1323 fn vp9(profile: u8, bit_depth: u8, subsampling: (bool, bool), color_space: u8) -> Vp9Format {
1324 Vp9Format {
1325 profile,
1326 bit_depth,
1327 subsampling,
1328 color_space,
1329 full_range: color_space == 7,
1330 width: 128,
1331 height: 96,
1332 }
1333 }
1334
1335 #[test]
1336 fn vp9_keyframes_declare_their_format() {
1337 let corpus = vp9_format(&[0x82, 0x49, 0x83, 0x42, 0x00, 0x07, 0xf0, 0x05, 0xf6]);
1339 assert_eq!(corpus, Some(vp9(0, 8, (true, true), 0)));
1340 let color = vp9_format(&[0x82, 0x49, 0x83, 0x42, 0x40, 0x0f, 0xf0, 0x03, 0xf6]);
1341 assert_eq!(
1342 color,
1343 Some(Vp9Format {
1344 color_space: 2,
1345 width: 256,
1346 height: 64,
1347 ..vp9(0, 8, (true, true), 2)
1348 })
1349 );
1350 assert_eq!(
1352 vp9_format(&packed(&format!(
1353 "10 0 1 0 0 1 0 {VP9_SYNC} 0 101 1 {SIZE_128X96}"
1354 ))),
1355 Some(Vp9Format {
1356 full_range: true,
1357 ..vp9(2, 10, (true, true), 5)
1358 })
1359 );
1360 assert_eq!(
1361 vp9_format(&packed(&format!(
1362 "10 0 1 0 0 1 0 {VP9_SYNC} 1 010 0 {SIZE_128X96}"
1363 ))),
1364 Some(vp9(2, 12, (true, true), 2))
1365 );
1366 assert_eq!(
1368 vp9_format(&packed(&format!(
1369 "10 1 0 0 0 1 0 {VP9_SYNC} 010 0 1 0 0 {SIZE_128X96}"
1370 ))),
1371 Some(vp9(1, 8, (true, false), 2))
1372 );
1373 assert_eq!(
1374 vp9_format(&packed(&format!(
1375 "10 1 1 0 0 0 1 0 {VP9_SYNC} 1 111 0 {SIZE_128X96}"
1376 ))),
1377 Some(vp9(3, 12, (false, false), 7))
1378 );
1379 }
1380
1381 #[test]
1382 fn vp9_intra_only_frames_declare_their_format() {
1383 assert_eq!(
1386 vp9_format(&packed(&format!(
1387 "10 0 1 0 1 0 0 1 00 {VP9_SYNC} 0 010 0 11111111 {SIZE_128X96}"
1388 ))),
1389 Some(vp9(2, 10, (true, true), 2))
1390 );
1391 assert_eq!(
1392 vp9_format(&packed(&format!(
1393 "10 0 0 0 1 0 0 1 00 {VP9_SYNC} 11111111 {SIZE_128X96}"
1394 ))),
1395 Some(vp9(0, 8, (true, true), 1))
1396 );
1397 }
1398
1399 #[test]
1400 fn vp9_frames_without_a_color_config_declare_nothing() {
1401 assert_eq!(vp9_format(&[0x86, 0x00, 0x00, 0x00]), None);
1404 assert_eq!(vp9_format(&[0x88]), None);
1405 assert_eq!(
1406 vp9_format(&[0x82, 0x49, 0x83, 0x43, 0x00, 0x07, 0xf0, 0x05]),
1407 None
1408 );
1409 assert_eq!(
1410 vp9_format(&[0x42, 0x49, 0x83, 0x42, 0x00, 0x07, 0xf0, 0x05]),
1411 None
1412 );
1413 assert_eq!(vp9_format(&[0x92, 0x49]), None);
1414 assert_eq!(vp9_format(&[0x82, 0x49, 0x83, 0x42, 0x00]), None);
1415 assert_eq!(vp9_format(&[]), None);
1416 }
1417
1418 #[test]
1419 fn a_vp9_format_makes_the_vpcc_body_videotoolbox_reads() {
1420 let hd = Vp9Format {
1421 width: 1920,
1422 height: 1080,
1423 ..vp9(0, 8, (true, true), 2)
1424 };
1425 assert_eq!(
1426 hd.vpcc_record(Some(ColorMetadata::EXPORT)),
1427 [1, 0, 0, 0, 0, 40, 0x82, 1, 1, 1, 0, 0]
1428 );
1429 assert_eq!(
1431 vp9(0, 8, (true, true), 2).vpcc_record(None),
1432 [1, 0, 0, 0, 0, 10, 0x82, 2, 2, 1, 0, 0]
1433 );
1434 let full = Vp9Format {
1435 full_range: true,
1436 ..vp9(2, 10, (true, true), 0)
1437 };
1438 assert_eq!(
1439 full.vpcc_record(None),
1440 [1, 0, 0, 0, 2, 10, 0xa3, 2, 2, 2, 0, 0]
1441 );
1442 assert_eq!(vp9(1, 8, (true, false), 1).vpcc_record(None)[6], 0x84);
1443 assert_eq!(
1444 vp9(3, 12, (false, false), 7).vpcc_record(None)[4..10],
1445 [3, 10, 0xc7, 2, 2, 0]
1446 );
1447 }
1448}