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 chroma_location: Option<ChromaLocation>,
63}
64
65#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
67pub struct SequenceFacts {
68 pub crop: CropWindow,
70 pub chroma_format: u32,
72 pub bit_depth_luma: u32,
74 pub bit_depth_chroma: u32,
76 pub vui: Vui,
78}
79
80impl SequenceFacts {
81 #[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#[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#[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#[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 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#[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 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]); 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]); 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
199fn 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#[must_use]
212pub fn crop_window(codec: ParameterSetCodec, extradata: &[u8]) -> Option<CropWindow> {
213 crop_windows(codec, extradata)?.first().copied()
214}
215
216#[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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
233pub enum HevcLayers {
234 Single,
236 AuxiliaryAlpha,
239 Extra,
241}
242
243#[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)?; let base_internal = bits.flag()?;
257 bits.skip(1)?; let max_layers = bits.read(6)?; 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
265fn vps_auxiliary_layer(bits: &mut Bits<'_>, base_internal: bool) -> Option<HevcLayers> {
268 let sub_layers = bits.read(3)?; bits.skip(1 + 16)?; skip_profile_tier_level(bits, true, sub_layers)?;
271 let ordering_for_all = bits.flag()?; for _ in if ordering_for_all { 0 } else { sub_layers }..=sub_layers {
273 bits.ue()?; bits.ue()?; bits.ue()?; }
277 let max_layer_id = bits.read(6)?; let layer_sets = bits.ue()?; 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 return None;
287 }
288 if !bits.flag()? {
289 return Some(HevcLayers::Extra);
291 }
292 while !bits.at.is_multiple_of(8) {
293 bits.skip(1)?; }
295 if base_internal {
296 skip_profile_tier_level(bits, false, sub_layers)?;
297 }
298 bits.skip(1)?; let mask = bits.read(16)?; Some(if mask & (1 << (15 - 3)) != 0 {
301 HevcLayers::AuxiliaryAlpha
302 } else {
303 HevcLayers::Extra
304 })
305}
306
307fn skip_profile_tier_level(
309 bits: &mut Bits<'_>,
310 profile_present: bool,
311 sub_layers: u32,
312) -> Option<()> {
313 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
328fn 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 (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
346fn 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
397fn 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 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
425fn 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)?; bits.ue()?; 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)?; }
441 bit_depth_luma = bits.ue()?.saturating_add(8);
442 bit_depth_chroma = bits.ue()?.saturating_add(8);
443 bits.skip(1)?; 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()?; match bits.ue()? {
454 0 => {
455 bits.ue()?; }
457 1 => {
458 bits.skip(1)?; bits.se()?; bits.se()?; for _ in 0..bits.ue()?.min(255) {
462 bits.se()?; }
464 }
465 _ => {}
466 }
467 bits.ue()?; bits.skip(1)?; 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)?; }
479 bits.skip(1)?; 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 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
510const 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
519fn vui(bits: &mut Bits<'_>, chroma_format: u32) -> Option<Vui> {
522 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)?; }
555 if bits.flag()? {
556 bits.skip(3)?; 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()?; 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
583fn 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
597fn hevc_sps(nal: &[u8]) -> Option<SequenceFacts> {
600 let payload = unescape(nal.get(2..)?);
601 let mut bits = Bits::new(&payload);
602 bits.skip(4)?; let sub_layers = bits.read(3)?; bits.skip(1)?; 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()?; let chroma_format = bits.ue()?;
619 if chroma_format == 3 {
620 bits.skip(1)?; }
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
649fn 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()?; bits.ue()?; bits.ue()?; }
658 for _ in 0..6 {
659 bits.ue()?;
661 }
662 if bits.flag()? && bits.flag()? {
663 skip_hevc_scaling_lists(bits)?;
664 }
665 bits.skip(2)?; if bits.flag()? {
667 bits.skip(8)?; bits.ue()?; bits.ue()?; bits.skip(1)?; }
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)?; bits.skip(1)?; }
678 }
679 bits.skip(2)?; if !bits.flag()? {
681 return Some(Vui::default());
682 }
683 vui(bits, chroma_format)
684}
685
686fn 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()?; }
696 for _ in 0..coefficients {
697 bits.se()?; }
699 } else {
700 bits.ue()?; }
702 }
703 }
704 Some(())
705}
706
707fn 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)?; bits.ue()?; 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()?; bits.skip(1)?; }
738 pictures
739 };
740 delta_pocs.push(pictures);
741 }
742 Some(())
743}
744
745#[derive(Clone, Copy, Debug, Eq, PartialEq)]
748pub struct Vp9Format {
749 pub profile: u8,
751 pub bit_depth: u8,
753 pub subsampling: (bool, bool),
755 pub color_space: u8,
757 pub full_range: bool,
759 pub width: u32,
761 pub height: u32,
763}
764
765impl Vp9Format {
766 #[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 let chroma = match self.subsampling {
807 (true, true) => 1,
808 (true, false) => 2,
809 (false, _) => 3,
810 };
811 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#[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)?; }
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
932struct 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 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 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 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 let mut single = ALPHA_VPS;
1013 single[3] &= 0x0f;
1014 assert_eq!(hevc_layers(&start_coded(&single)), Some(HevcLayers::Single));
1015 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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}