use alpha2_media::{ChromaLocation, ColorMetadata, SampleAspectRatio};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ParameterSetCodec {
H264,
Hevc,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct CropWindow {
pub coded_width: u32,
pub coded_height: u32,
pub left: u32,
pub right: u32,
pub top: u32,
pub bottom: u32,
}
impl CropWindow {
#[must_use]
pub fn visible(&self) -> Option<alpha2_media::Rect> {
let width = self
.coded_width
.checked_sub(self.left)?
.checked_sub(self.right)?;
let height = self
.coded_height
.checked_sub(self.top)?
.checked_sub(self.bottom)?;
(width > 0 && height > 0).then_some(alpha2_media::Rect {
x: self.left,
y: self.top,
width,
height,
})
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct Vui {
pub sample_aspect_ratio: Option<SampleAspectRatio>,
pub color: Option<ColorMetadata>,
pub signal: Option<VideoSignal>,
pub chroma_location: Option<ChromaLocation>,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct VideoSignal {
pub full_range: bool,
pub description: Option<[u8; 3]>,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct SequenceFacts {
pub crop: CropWindow,
pub chroma_format: u32,
pub bit_depth_luma: u32,
pub bit_depth_chroma: u32,
pub vui: Vui,
}
impl SequenceFacts {
#[must_use]
pub fn chroma_location(&self) -> Option<ChromaLocation> {
self.vui
.chroma_location
.or((self.chroma_format == 1).then_some(ChromaLocation::Left))
}
}
#[must_use]
pub fn sequence_facts(codec: ParameterSetCodec, extradata: &[u8]) -> Option<SequenceFacts> {
let hevc = codec == ParameterSetCodec::Hevc;
let nal = *sequence_parameter_sets(hevc, extradata).first()?;
if hevc { hevc_sps(nal) } else { h264_sps(nal) }
}
#[must_use]
pub fn length_prefixed_units(annex_b: &[u8]) -> Vec<u8> {
let units = annex_b_units(annex_b);
let mut out = Vec::with_capacity(annex_b.len() + units.len());
for unit in units {
out.extend_from_slice(&u32::try_from(unit.len()).unwrap_or(u32::MAX).to_be_bytes());
out.extend_from_slice(unit);
}
out
}
#[must_use]
pub fn avc_decoder_config(annex_b: &[u8]) -> Option<Vec<u8>> {
let units = annex_b_units(annex_b);
let of_type = |kind: u8| -> Vec<&[u8]> {
units
.iter()
.copied()
.filter(|unit| unit[0] & 0x1f == kind)
.collect()
};
let (sps, pps) = (of_type(7), of_type(8));
let first = *sps.first()?;
if pps.is_empty() || first.len() < 4 {
return None;
}
let facts = h264_sps(first)?;
let mut record = vec![1, first[1], first[2], first[3], 0xff];
record.push(0xe0 | u8::try_from(sps.len()).ok().filter(|count| *count < 32)?);
for unit in &sps {
record.extend_from_slice(&u16::try_from(unit.len()).ok()?.to_be_bytes());
record.extend_from_slice(unit);
}
record.push(u8::try_from(pps.len()).ok()?);
for unit in &pps {
record.extend_from_slice(&u16::try_from(unit.len()).ok()?.to_be_bytes());
record.extend_from_slice(unit);
}
if matches!(first[1], 100 | 110 | 122 | 144) {
record.push(0xfc | u8::try_from(facts.chroma_format & 3).ok()?);
record.push(0xf8 | u8::try_from(facts.bit_depth_luma.checked_sub(8)? & 7).ok()?);
record.push(0xf8 | u8::try_from(facts.bit_depth_chroma.checked_sub(8)? & 7).ok()?);
record.push(0);
}
Some(record)
}
#[must_use]
pub fn hevc_decoder_config(annex_b: &[u8]) -> Option<Vec<u8>> {
let units = annex_b_units(annex_b);
let kind = |unit: &[u8]| (unit[0] >> 1) & 0x3f;
let sps = *units
.iter()
.find(|unit| unit.len() > 2 && kind(unit) == 33)?;
let facts = hevc_sps(sps)?;
let payload = unescape(sps.get(2..)?);
let general = payload.get(1..13)?;
let sub_layers = (payload[0] >> 1) & 7;
let nested = payload[0] & 1;
let mut record = vec![1];
record.extend_from_slice(general);
record.extend_from_slice(&[0xf0, 0x00, 0xfc]); record.push(0xfc | u8::try_from(facts.chroma_format & 3).ok()?);
record.push(0xf8 | u8::try_from(facts.bit_depth_luma.checked_sub(8)? & 7).ok()?);
record.push(0xf8 | u8::try_from(facts.bit_depth_chroma.checked_sub(8)? & 7).ok()?);
record.extend_from_slice(&[0, 0]); record.push(((sub_layers + 1) << 3) | (nested << 2) | 3);
let arrays = [32, 33, 34]
.into_iter()
.map(|wanted| {
units
.iter()
.copied()
.filter(|unit| unit.len() > 2 && kind(unit) == wanted)
.collect::<Vec<_>>()
})
.filter(|array| !array.is_empty())
.collect::<Vec<_>>();
record.push(u8::try_from(arrays.len()).ok()?);
for array in arrays {
record.push(0x80 | kind(array[0]));
record.extend_from_slice(&u16::try_from(array.len()).ok()?.to_be_bytes());
for unit in array {
record.extend_from_slice(&u16::try_from(unit.len()).ok()?.to_be_bytes());
record.extend_from_slice(unit);
}
}
Some(record)
}
fn crop_windows(codec: ParameterSetCodec, extradata: &[u8]) -> Option<Vec<CropWindow>> {
let hevc = codec == ParameterSetCodec::Hevc;
sequence_parameter_sets(hevc, extradata)
.into_iter()
.map(|nal| if hevc { hevc_sps(nal) } else { h264_sps(nal) }.map(|facts| facts.crop))
.collect()
}
#[must_use]
pub fn crop_window(codec: ParameterSetCodec, extradata: &[u8]) -> Option<CropWindow> {
crop_windows(codec, extradata)?.first().copied()
}
#[must_use]
pub fn leading_crop(codec: ParameterSetCodec, extradata: &[u8]) -> Option<(u32, u32)> {
let crops = crop_windows(codec, extradata)?;
let first = *crops.first()?;
let leading = crops
.into_iter()
.find(|crop| crop.left > 0 || crop.top > 0)
.unwrap_or(first);
Some((leading.left, leading.top))
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum HevcLayers {
Single,
AuxiliaryAlpha,
Extra,
}
#[must_use]
pub fn hevc_layers(extradata: &[u8]) -> Option<HevcLayers> {
let units = match extradata {
[1, ..] => hvcc_units(extradata),
_ => annex_b_units(extradata),
};
let vps = units
.into_iter()
.find(|nal| matches!(nal, [first, ..] if (first >> 1) & 0x3f == 32))?;
let payload = unescape(vps.get(2..)?);
let mut bits = Bits::new(&payload);
bits.skip(4)?; let base_internal = bits.flag()?;
bits.skip(1)?; let max_layers = bits.read(6)?; if max_layers == 0 {
return Some(HevcLayers::Single);
}
Some(vps_auxiliary_layer(&mut bits, base_internal).unwrap_or(HevcLayers::Extra))
}
fn vps_auxiliary_layer(bits: &mut Bits<'_>, base_internal: bool) -> Option<HevcLayers> {
let sub_layers = bits.read(3)?; bits.skip(1 + 16)?; skip_profile_tier_level(bits, true, sub_layers)?;
let ordering_for_all = bits.flag()?; for _ in if ordering_for_all { 0 } else { sub_layers }..=sub_layers {
bits.ue()?; bits.ue()?; bits.ue()?; }
let max_layer_id = bits.read(6)?; let layer_sets = bits.ue()?; bits.skip(
usize::try_from(layer_sets)
.ok()?
.checked_mul(max_layer_id as usize + 1)?,
)?;
if bits.flag()? {
return None;
}
if !bits.flag()? {
return Some(HevcLayers::Extra);
}
while !bits.at.is_multiple_of(8) {
bits.skip(1)?; }
if base_internal {
skip_profile_tier_level(bits, false, sub_layers)?;
}
bits.skip(1)?; let mask = bits.read(16)?; Some(if mask & (1 << (15 - 3)) != 0 {
HevcLayers::AuxiliaryAlpha
} else {
HevcLayers::Extra
})
}
fn skip_profile_tier_level(
bits: &mut Bits<'_>,
profile_present: bool,
sub_layers: u32,
) -> Option<()> {
bits.skip(if profile_present { 88 } else { 0 } + 8)?;
let mut present = Vec::new();
for _ in 0..sub_layers {
present.push((bits.flag()?, bits.flag()?));
}
if sub_layers > 0 {
bits.skip(2 * (8 - sub_layers as usize))?;
}
for (profile, level) in present {
bits.skip(if profile { 88 } else { 0 } + if level { 8 } else { 0 })?;
}
Some(())
}
fn sequence_parameter_sets(hevc: bool, extradata: &[u8]) -> Vec<&[u8]> {
let is_sps = |nal: &[u8]| match (hevc, nal) {
(false, [header, ..]) => header & 0x1f == 7,
(true, [first, second, ..]) => {
(first >> 1) & 0x3f == 33 && (first & 1) == 0 && second >> 3 == 0
}
_ => false,
};
let units = match (hevc, extradata) {
(false, [1, ..]) => avcc_units(extradata),
(true, [1, ..]) => hvcc_units(extradata),
_ => annex_b_units(extradata),
};
units.into_iter().filter(|nal| is_sps(nal)).collect()
}
fn avcc_units(data: &[u8]) -> Vec<&[u8]> {
let mut units = Vec::new();
let Some(&count) = data.get(5) else {
return units;
};
let mut at = 6;
for _ in 0..(count & 0x1f) {
let Some((nal, next)) = length_prefixed(data, at) else {
return units;
};
units.push(nal);
at = next;
}
let Some(&count) = data.get(at) else {
return units;
};
at += 1;
for _ in 0..count {
let Some((nal, next)) = length_prefixed(data, at) else {
break;
};
units.push(nal);
at = next;
}
units
}
fn hvcc_units(data: &[u8]) -> Vec<&[u8]> {
let mut units = Vec::new();
let Some(&arrays) = data.get(22) else {
return units;
};
let mut at = 23;
for _ in 0..arrays {
let Some(count) = data.get(at + 1..at + 3) else {
break;
};
let count = u16::from_be_bytes([count[0], count[1]]);
at += 3;
for _ in 0..count {
let Some((nal, next)) = length_prefixed(data, at) else {
return units;
};
units.push(nal);
at = next;
}
}
units
}
fn length_prefixed(data: &[u8], at: usize) -> Option<(&[u8], usize)> {
let length = data.get(at..at + 2)?;
let end = at + 2 + usize::from(u16::from_be_bytes([length[0], length[1]]));
Some((data.get(at + 2..end)?, end))
}
fn annex_b_units(data: &[u8]) -> Vec<&[u8]> {
let starts = (0..data.len().saturating_sub(2))
.filter(|&at| data[at..at + 3] == [0, 0, 1])
.map(|at| at + 3)
.collect::<Vec<_>>();
starts
.iter()
.enumerate()
.map(|(index, &start)| {
let end = starts.get(index + 1).map_or(data.len(), |next| next - 3);
let mut unit = &data[start..end.max(start)];
while let [rest @ .., 0] = unit {
unit = rest;
}
unit
})
.filter(|unit| !unit.is_empty())
.collect()
}
fn h264_sps(nal: &[u8]) -> Option<SequenceFacts> {
let payload = unescape(nal.get(1..)?);
let mut bits = Bits::new(&payload);
let profile = bits.read(8)?;
bits.skip(16)?; bits.ue()?; let (mut chroma_format, mut bit_depth_luma, mut bit_depth_chroma) = (1, 8, 8);
if matches!(
profile,
100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135
) {
chroma_format = bits.ue()?;
if chroma_format == 3 {
bits.skip(1)?; }
bit_depth_luma = bits.ue()?.saturating_add(8);
bit_depth_chroma = bits.ue()?.saturating_add(8);
bits.skip(1)?; if bits.flag()? {
for list in 0..if chroma_format == 3 { 12 } else { 8 } {
if bits.flag()? {
skip_scaling_list(&mut bits, if list < 6 { 16 } else { 64 })?;
}
}
}
}
bits.ue()?; match bits.ue()? {
0 => {
bits.ue()?; }
1 => {
bits.skip(1)?; bits.se()?; bits.se()?; for _ in 0..bits.ue()?.min(255) {
bits.se()?; }
}
_ => {}
}
bits.ue()?; bits.skip(1)?; let width_in_mbs = bits.ue()?.saturating_add(1);
let height_in_map_units = bits.ue()?.saturating_add(1);
let frame_mbs_only = bits.flag()?;
let coded_width = width_in_mbs.saturating_mul(16);
let coded_height = height_in_map_units
.saturating_mul(16)
.saturating_mul(if frame_mbs_only { 1 } else { 2 });
if !frame_mbs_only {
bits.skip(1)?; }
bits.skip(1)?; let mut crop = CropWindow {
coded_width,
coded_height,
..CropWindow::default()
};
if bits.flag()? {
let (left, right, top, bottom) = (bits.ue()?, bits.ue()?, bits.ue()?, bits.ue()?);
let (unit_x, unit_y) = crop_units(chroma_format);
let unit_y = unit_y * if frame_mbs_only { 1 } else { 2 };
crop.left = left.saturating_mul(unit_x);
crop.right = right.saturating_mul(unit_x);
crop.top = top.saturating_mul(unit_y);
crop.bottom = bottom.saturating_mul(unit_y);
}
let vui = bits
.flag()
.filter(|present| *present)
.and_then(|_| vui(&mut bits, chroma_format))
.unwrap_or_default();
Some(SequenceFacts {
crop,
chroma_format,
bit_depth_luma,
bit_depth_chroma,
vui,
})
}
const fn crop_units(chroma_format: u32) -> (u32, u32) {
match chroma_format {
1 => (2, 2),
2 => (2, 1),
_ => (1, 1),
}
}
fn vui(bits: &mut Bits<'_>, chroma_format: u32) -> Option<Vui> {
const RATIOS: [(u32, u32); 16] = [
(1, 1),
(12, 11),
(10, 11),
(16, 11),
(40, 33),
(24, 11),
(20, 11),
(32, 11),
(80, 33),
(18, 11),
(15, 11),
(64, 33),
(160, 99),
(4, 3),
(3, 2),
(2, 1),
];
let mut vui = Vui::default();
if bits.flag()? {
let ratio = match bits.read(8)? {
255 => Some((bits.read(16)?, bits.read(16)?)),
idc @ 1..=16 => RATIOS.get(idc as usize - 1).copied(),
_ => None,
};
vui.sample_aspect_ratio = ratio
.filter(|(num, den)| *num > 0 && *den > 0)
.map(|(num, den)| SampleAspectRatio { num, den });
}
if bits.flag()? {
bits.skip(1)?; }
if bits.flag()? {
bits.skip(3)?; let full = bits.flag()?;
let code = |value: u32| u8::try_from(value).unwrap_or(2);
let description = if bits.flag()? {
Some([
code(bits.read(8)?),
code(bits.read(8)?),
code(bits.read(8)?),
])
} else {
None
};
let [primaries, transfer, matrix] = description.unwrap_or([2, 2, 2]);
vui.color = ColorMetadata::from_h273(primaries, transfer, matrix, Some(full));
vui.signal = Some(VideoSignal {
full_range: full,
description,
});
}
if bits.flag()? {
let top = bits.ue()?;
bits.ue()?; if chroma_format == 1 {
vui.chroma_location = Some(match top {
0 => ChromaLocation::Left,
1 => ChromaLocation::Center,
2 => ChromaLocation::TopLeft,
_ => ChromaLocation::Unspecified,
});
}
}
Some(vui)
}
fn skip_scaling_list(bits: &mut Bits<'_>, size: usize) -> Option<()> {
let (mut last, mut next) = (8_i64, 8_i64);
for _ in 0..size {
if next != 0 {
next = (last + bits.se()? + 256).rem_euclid(256);
}
if next != 0 {
last = next;
}
}
Some(())
}
fn hevc_sps(nal: &[u8]) -> Option<SequenceFacts> {
let payload = unescape(nal.get(2..)?);
let mut bits = Bits::new(&payload);
bits.skip(4)?; let sub_layers = bits.read(3)?; bits.skip(1)?; bits.skip(96)?;
let mut present = Vec::new();
for _ in 0..sub_layers {
present.push((bits.flag()?, bits.flag()?));
}
if sub_layers > 0 {
bits.skip(2 * (8 - sub_layers as usize))?;
}
for (profile, level) in present {
bits.skip(if profile { 88 } else { 0 } + if level { 8 } else { 0 })?;
}
bits.ue()?; let chroma_format = bits.ue()?;
if chroma_format == 3 {
bits.skip(1)?; }
let coded_width = bits.ue()?;
let coded_height = bits.ue()?;
let mut crop = CropWindow {
coded_width,
coded_height,
..CropWindow::default()
};
if bits.flag()? {
let (left, right, top, bottom) = (bits.ue()?, bits.ue()?, bits.ue()?, bits.ue()?);
let (unit_x, unit_y) = crop_units(chroma_format);
crop.left = left.saturating_mul(unit_x);
crop.right = right.saturating_mul(unit_x);
crop.top = top.saturating_mul(unit_y);
crop.bottom = bottom.saturating_mul(unit_y);
}
let bit_depth_luma = bits.ue()?.saturating_add(8);
let bit_depth_chroma = bits.ue()?.saturating_add(8);
let vui = hevc_vui(&mut bits, sub_layers, chroma_format).unwrap_or_default();
Some(SequenceFacts {
crop,
chroma_format,
bit_depth_luma,
bit_depth_chroma,
vui,
})
}
fn hevc_vui(bits: &mut Bits<'_>, sub_layers: u32, chroma_format: u32) -> Option<Vui> {
let poc_lsb_bits = bits.ue()?.checked_add(4)?;
let first = if bits.flag()? { 0 } else { sub_layers };
for _ in first..=sub_layers {
bits.ue()?; bits.ue()?; bits.ue()?; }
for _ in 0..6 {
bits.ue()?;
}
if bits.flag()? && bits.flag()? {
skip_hevc_scaling_lists(bits)?;
}
bits.skip(2)?; if bits.flag()? {
bits.skip(8)?; bits.ue()?; bits.ue()?; bits.skip(1)?; }
skip_short_term_ref_pic_sets(bits)?;
if bits.flag()? {
for _ in 0..bits.ue()?.min(32) {
bits.skip(poc_lsb_bits as usize)?; bits.skip(1)?; }
}
bits.skip(2)?; if !bits.flag()? {
return Some(Vui::default());
}
vui(bits, chroma_format)
}
fn skip_hevc_scaling_lists(bits: &mut Bits<'_>) -> Option<()> {
for size in 0..4_u32 {
let step = if size == 3 { 3 } else { 1 };
for _ in (0..6).step_by(step) {
if bits.flag()? {
let coefficients = 64.min(1 << (4 + (size << 1)));
if size > 1 {
bits.se()?; }
for _ in 0..coefficients {
bits.se()?; }
} else {
bits.ue()?; }
}
}
Some(())
}
fn skip_short_term_ref_pic_sets(bits: &mut Bits<'_>) -> Option<()> {
let count = bits.ue()?;
if count > 64 {
return None;
}
let mut delta_pocs: Vec<u32> = Vec::with_capacity(count as usize);
for index in 0..count {
let predicted = index != 0 && bits.flag()?;
let pictures = if predicted {
bits.skip(1)?; bits.ue()?; let reference = *delta_pocs.last()?;
let mut pictures = 0;
for _ in 0..=reference {
let used = bits.flag()?;
if used || bits.flag()? {
pictures += 1;
}
}
pictures
} else {
let negative = bits.ue()?;
let positive = bits.ue()?;
let pictures = negative
.checked_add(positive)
.filter(|total| *total <= 32)?;
for _ in 0..pictures {
bits.ue()?; bits.skip(1)?; }
pictures
};
delta_pocs.push(pictures);
}
Some(())
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Vp9Format {
pub profile: u8,
pub bit_depth: u8,
pub subsampling: (bool, bool),
pub color_space: u8,
pub full_range: bool,
pub width: u32,
pub height: u32,
}
impl Vp9Format {
#[must_use]
pub fn vpcc_record(&self, color: Option<ColorMetadata>) -> [u8; 12] {
use alpha2_media::{ColorMatrix, ColorPrimaries, TransferFunction};
let (primaries, transfer, matrix) = match color {
Some(color) => (
match color.primaries {
ColorPrimaries::Bt601 => 6,
ColorPrimaries::Bt709 => 1,
ColorPrimaries::Bt2020 => 9,
ColorPrimaries::DisplayP3 => 12,
},
match color.transfer {
TransferFunction::Bt709 => 1,
TransferFunction::Srgb => 13,
TransferFunction::Pq => 16,
TransferFunction::Hlg => 18,
},
match color.matrix {
ColorMatrix::Bt601 => 6,
ColorMatrix::Bt709 => 1,
ColorMatrix::Bt2020Ncl => 9,
ColorMatrix::Rgb => 0,
},
),
None => (
2,
2,
match self.color_space {
1 | 3 => 6,
2 => 1,
4 => 7,
5 => 9,
7 => 0,
_ => 2,
},
),
};
let chroma = match self.subsampling {
(true, true) => 1,
(true, false) => 2,
(false, _) => 3,
};
let samples = u64::from(self.width) * u64::from(self.height);
let level = [
(36_864, 10),
(73_728, 11),
(122_880, 20),
(245_760, 21),
(552_960, 30),
(983_040, 31),
(2_228_224, 40),
(8_912_896, 50),
(35_651_584, 60),
]
.iter()
.find(|(size, _)| samples <= *size)
.map_or(62, |(_, level)| *level);
[
1,
0,
0,
0,
self.profile,
level,
(self.bit_depth << 4) | (chroma << 1) | u8::from(self.full_range),
primaries,
transfer,
matrix,
0,
0,
]
}
}
#[must_use]
pub fn vp9_format(frame: &[u8]) -> Option<Vp9Format> {
const SYNC_CODE: u32 = 0x49_83_42;
const CS_RGB: u8 = 7;
let mut bits = Bits::new(frame);
if bits.read(2)? != 2 {
return None;
}
let low = bits.read(1)?;
let profile = u8::try_from((bits.read(1)? << 1) | low).ok()?;
if profile == 3 {
bits.skip(1)?;
}
if bits.flag()? {
return None;
}
let key_frame = !bits.flag()?;
let show_frame = bits.flag()?;
let error_resilient = bits.flag()?;
let mut format = Vp9Format {
profile,
bit_depth: 8,
subsampling: (true, true),
color_space: 1,
full_range: false,
width: 0,
height: 0,
};
let intra_only = if key_frame {
false
} else {
let intra_only = !show_frame && bits.flag()?;
if !error_resilient {
bits.skip(2)?;
}
if !intra_only {
return None;
}
true
};
if bits.read(24)? != SYNC_CODE {
return None;
}
if !intra_only || profile > 0 {
if profile >= 2 {
format.bit_depth = if bits.flag()? { 12 } else { 10 };
}
format.color_space = u8::try_from(bits.read(3)?).ok()?;
let four_four_four = profile == 1 || profile == 3;
if format.color_space == CS_RGB {
format.full_range = true;
if four_four_four {
format.subsampling = (false, false);
bits.skip(1)?;
}
} else {
format.full_range = bits.flag()?;
if four_four_four {
format.subsampling = (bits.flag()?, bits.flag()?);
bits.skip(1)?;
}
}
}
if intra_only {
bits.skip(8)?; }
format.width = bits.read(16)? + 1;
format.height = bits.read(16)? + 1;
Some(format)
}
fn unescape(escaped: &[u8]) -> Vec<u8> {
let mut payload = Vec::with_capacity(escaped.len());
let mut zeros = 0;
for &byte in escaped {
if zeros >= 2 && byte == 3 {
zeros = 0;
continue;
}
zeros = if byte == 0 { zeros + 1 } else { 0 };
payload.push(byte);
}
payload
}
struct Bits<'a> {
data: &'a [u8],
at: usize,
}
impl<'a> Bits<'a> {
const fn new(data: &'a [u8]) -> Self {
Self { data, at: 0 }
}
fn flag(&mut self) -> Option<bool> {
let byte = *self.data.get(self.at / 8)?;
let bit = (byte >> (7 - self.at % 8)) & 1;
self.at += 1;
Some(bit == 1)
}
fn read(&mut self, count: u32) -> Option<u32> {
(0..count).try_fold(0, |value, _| Some((value << 1) | u32::from(self.flag()?)))
}
fn skip(&mut self, count: usize) -> Option<()> {
let end = self.at.checked_add(count)?;
(end <= self.data.len() * 8).then(|| self.at = end)
}
fn ue(&mut self) -> Option<u32> {
let mut zeros = 0;
while !self.flag()? {
zeros += 1;
if zeros > 31 {
return None;
}
}
Some((1_u32 << zeros) - 1 + self.read(zeros)?)
}
fn se(&mut self) -> Option<i64> {
let code = i64::from(self.ue()?);
Some(if code % 2 == 1 {
(code + 1) / 2
} else {
-(code / 2)
})
}
}
#[cfg(test)]
mod tests {
use super::{
HevcLayers, ParameterSetCodec, Vp9Format, avc_decoder_config, crop_window,
hevc_decoder_config, hevc_layers, leading_crop, length_prefixed_units, sequence_facts,
vp9_format,
};
use alpha2_media::ColorMetadata;
const ALPHA_VPS: [u8; 41] = [
0x40, 0x01, 0x0c, 0x11, 0xff, 0xff, 0x01, 0x60, 0x00, 0x00, 0x03, 0x00, 0xb0, 0x00, 0x00,
0x03, 0x00, 0x00, 0x03, 0x00, 0x1e, 0x17, 0x06, 0xff, 0x1e, 0x08, 0x00, 0x08, 0x30, 0x28,
0x53, 0x80, 0x50, 0x00, 0x30, 0x50, 0x0c, 0x23, 0xf1, 0x7a, 0x40,
];
fn start_coded(nal: &[u8]) -> Vec<u8> {
let mut data = vec![0, 0, 0, 1];
data.extend_from_slice(nal);
data
}
#[test]
fn hevc_alpha_is_detected_from_its_vps() {
assert_eq!(
hevc_layers(&start_coded(&ALPHA_VPS)),
Some(HevcLayers::AuxiliaryAlpha)
);
let mut single = ALPHA_VPS;
single[3] &= 0x0f;
assert_eq!(hevc_layers(&start_coded(&single)), Some(HevcLayers::Single));
let mut views = ALPHA_VPS;
views[25] = 0x20;
assert_eq!(hevc_layers(&start_coded(&views)), Some(HevcLayers::Extra));
assert_eq!(hevc_layers(&[1, 2, 3]), None);
}
fn h264_sps(window: &[u8]) -> Vec<u8> {
let mut sps = vec![0x67, 0x64, 0x00, 0x0a, 0xac, 0xd9, 0x42, 0x0d];
sps.extend_from_slice(window);
sps.extend_from_slice(&[
0x16, 0xa0, 0x20, 0x20, 0x28, 0x00, 0x00, 0x03, 0x00, 0x08, 0x00, 0x00, 0x03, 0x01,
0xe0, 0x78, 0x91, 0x2c, 0xb0,
]);
sps
}
fn hevc_sps(window: &[u8]) -> Vec<u8> {
let mut sps = vec![
0x42, 0x01, 0x01, 0x01, 0x60, 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00,
0x00, 0x03, 0x00, 0x1e, 0xa0, 0x20, 0x83,
];
sps.extend_from_slice(window);
sps.extend_from_slice(&[
0x59, 0x59, 0xae, 0x4c, 0xaf, 0x01, 0x69, 0x6c, 0x20, 0x00, 0x00, 0x03, 0x00, 0x20,
0x00, 0x00, 0x03, 0x03, 0xc1,
]);
sps
}
fn avcc(sps: &[u8]) -> Vec<u8> {
let mut data = vec![1, 0x64, 0x00, 0x0a, 0xff, 0xe1];
data.extend_from_slice(&u16::try_from(sps.len()).unwrap().to_be_bytes());
data.extend_from_slice(sps);
data.extend_from_slice(&[1, 0, 4, 0x68, 0xeb, 0xe3, 0xcb]);
data
}
fn hvcc(sps: &[u8]) -> Vec<u8> {
let mut data = vec![1];
data.extend_from_slice(&[0; 21]);
data.extend_from_slice(&[2, 32, 0, 1, 0, 2, 0x40, 0x01, 33, 0, 1]);
data.extend_from_slice(&u16::try_from(sps.len()).unwrap().to_be_bytes());
data.extend_from_slice(sps);
data
}
fn annex_b(sps: &[u8]) -> Vec<u8> {
let mut data = vec![0, 0, 0, 1];
data.extend_from_slice(sps);
data.extend_from_slice(&[0, 0, 1, 0x68, 0xeb, 0xe3, 0xcb]);
data
}
#[test]
fn an_h264_sps_reports_the_columns_and_rows_it_crops_on_the_left_and_top() {
for (window, expected) in [
(&[0xb0][..], (0, 0)),
(&[0xcb, 0xf0], (8, 0)),
(&[0xf2, 0xf0], (0, 8)),
(&[0xe5, 0xf0], (0, 0)),
(&[0xf9, 0x30], (0, 0)),
] {
let sps = h264_sps(window);
for extradata in [avcc(&sps), annex_b(&sps)] {
assert_eq!(
leading_crop(ParameterSetCodec::H264, &extradata),
Some(expected),
"{window:02x?}"
);
}
}
}
#[test]
fn an_hevc_sps_reports_the_columns_and_rows_its_window_takes_on_the_left_and_top() {
for (window, expected) in [
(&[0x16][..], (0, 0)),
(&[0x19, 0x7e], (8, 0)),
(&[0x1e, 0x5e], (0, 8)),
(&[0x1c, 0xbe], (0, 0)),
(&[0x1f, 0x2e], (0, 0)),
] {
let sps = hevc_sps(window);
for extradata in [hvcc(&sps), annex_b(&sps)] {
assert_eq!(
leading_crop(ParameterSetCodec::Hevc, &extradata),
Some(expected),
"{window:02x?}"
);
}
}
}
#[test]
fn the_whole_crop_window_is_read_from_the_corpus() {
let corpus = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/corpus");
for (name, expected) in [
("h264-bt709-crop-left.mp4", (8, 0, 0, 0)),
("h264-bt709-crop-bottom.mp4", (0, 0, 0, 6)),
("h264-padded.mp4", (0, 0, 0, 12)),
("hevc-padded.mp4", (0, 0, 0, 4)),
] {
let file = std::fs::read(corpus.join(name)).expect(name);
let hevc = name.starts_with("hevc");
let tag: &[u8] = if hevc { b"hvcC" } else { b"avcC" };
let at = file
.windows(4)
.position(|window| window == tag)
.expect("decoder configuration");
let size = u32::from_be_bytes(file[at - 4..at].try_into().expect("size")) as usize;
let record = &file[at + 4..at - 4 + size];
let codec = if hevc {
ParameterSetCodec::Hevc
} else {
ParameterSetCodec::H264
};
let crop = crop_window(codec, record).expect(name);
assert_eq!(
(crop.left, crop.right, crop.top, crop.bottom),
expected,
"{name}"
);
let visible = crop.visible().expect("a visible area");
let probed = match name {
"h264-bt709-crop-left.mp4" => (120, 96),
"h264-bt709-crop-bottom.mp4" => (128, 90),
_ => (320, 180),
};
assert_eq!((visible.width, visible.height), probed, "{name}");
}
}
#[test]
fn the_vui_aspect_color_and_chroma_siting_are_read_from_the_corpus() {
use alpha2_media::{ChromaLocation, ColorMetadata, SampleAspectRatio};
let corpus = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/corpus");
let hlg = ColorMetadata::from_h273(9, 18, 9, Some(false));
let bt709 = ColorMetadata::from_h273(1, 1, 1, Some(false));
let range_only = ColorMetadata::from_h273(2, 2, 2, Some(false));
let facts_of = |name: &str| {
let file = std::fs::read(corpus.join(name)).expect(name);
let hevc = name.starts_with("hevc");
let tag: &[u8] = if hevc { b"hvcC" } else { b"avcC" };
let at = file
.windows(4)
.position(|window| window == tag)
.expect("decoder configuration");
let size = u32::from_be_bytes(file[at - 4..at].try_into().expect("size")) as usize;
let codec = if hevc {
ParameterSetCodec::Hevc
} else {
ParameterSetCodec::H264
};
sequence_facts(codec, &file[at + 4..at - 4 + size]).expect(name)
};
for (name, ratio, color, chroma) in [
(
"h264-bt709-vui-sar.mp4",
(4, 3),
bt709,
ChromaLocation::Left,
),
(
"hevc-topleft.mp4",
(1, 1),
range_only,
ChromaLocation::TopLeft,
),
("hevc-hvc1.mp4", (1, 1), range_only, ChromaLocation::TopLeft),
("hdr-hlg.mp4", (1, 1), hlg, ChromaLocation::Left),
("hevc-padded.mp4", (1, 1), bt709, ChromaLocation::Left),
("h264-high10.mp4", (1, 1), None, ChromaLocation::Left),
] {
let facts = facts_of(name);
let (num, den) = ratio;
assert_eq!(
facts
.vui
.sample_aspect_ratio
.unwrap_or(SampleAspectRatio { num: 1, den: 1 }),
SampleAspectRatio { num, den },
"{name}"
);
assert_eq!(facts.vui.color, color, "{name}");
assert_eq!(facts.chroma_location(), Some(chroma), "{name}");
}
for (name, description) in [
("h264-bt709-transcode.mp4", Some([1, 1, 1])),
("h264-bt709-transcode-vui-bt601.mp4", Some([6, 6, 6])),
] {
assert_eq!(
facts_of(name).vui.signal,
Some(super::VideoSignal {
full_range: false,
description
}),
"{name}"
);
}
assert_eq!(facts_of("h264-high10.mp4").vui.signal, None);
}
fn record(name: &str, tag: &[u8]) -> Vec<u8> {
let corpus = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/corpus");
let file = std::fs::read(corpus.join(name)).expect(name);
let at = file
.windows(4)
.position(|window| window == tag)
.expect("decoder configuration");
let size = u32::from_be_bytes(file[at - 4..at].try_into().expect("size")) as usize;
file[at + 4..at - 4 + size].to_vec()
}
fn annex_b_of(units: &[&[u8]]) -> Vec<u8> {
units
.iter()
.flat_map(|unit| [&[0, 0, 0, 1][..], unit].concat())
.collect()
}
#[test]
fn decoder_configurations_are_rebuilt_from_annex_b_parameter_sets() {
let avcc = record("h264-bt709-copy.mp4", b"avcC");
let units = super::avcc_units(&avcc);
let built = avc_decoder_config(&annex_b_of(&units)).expect("avcC");
assert_eq!(built, avcc);
let hvcc = record("hevc-hvc1.mp4", b"hvcC");
let built = hevc_decoder_config(&annex_b_of(&super::hvcc_units(&hvcc))).expect("hvcC");
assert_eq!(built[..13], hvcc[..13]);
assert_eq!(built[16..19], hvcc[16..19]);
assert_eq!(built[21] & 0x3f, hvcc[21] & 0x3f);
let parameter_sets = |record: &[u8]| {
super::hvcc_units(record)
.into_iter()
.filter(|unit| matches!((unit[0] >> 1) & 0x3f, 32..=34))
.map(<[u8]>::to_vec)
.collect::<Vec<_>>()
};
assert_eq!(parameter_sets(&built), parameter_sets(&hvcc));
assert_eq!(built[22], 3);
assert_eq!(
length_prefixed_units(&[0, 0, 0, 1, 0x65, 9, 0, 0, 1, 0x41, 7]),
[0, 0, 0, 2, 0x65, 9, 0, 0, 0, 2, 0x41, 7]
);
}
#[test]
fn a_description_without_a_readable_sps_reports_nothing() {
assert_eq!(leading_crop(ParameterSetCodec::H264, &[]), None);
let mut truncated = h264_sps(&[0xcb, 0xf0]);
truncated.truncate(9);
assert_eq!(
leading_crop(ParameterSetCodec::H264, &avcc(&truncated)),
None
);
}
fn packed(bits: &str) -> Vec<u8> {
let bits = bits.bytes().filter(|bit| *bit != b' ').collect::<Vec<_>>();
bits.chunks(8)
.map(|chunk| {
(0..8).fold(0_u8, |byte, at| {
(byte << 1) | u8::from(chunk.get(at) == Some(&b'1'))
})
})
.collect()
}
const VP9_SYNC: &str = "01001001 10000011 01000010";
const SIZE_128X96: &str = "00000000 01111111 00000000 01011111";
fn vp9(profile: u8, bit_depth: u8, subsampling: (bool, bool), color_space: u8) -> Vp9Format {
Vp9Format {
profile,
bit_depth,
subsampling,
color_space,
full_range: color_space == 7,
width: 128,
height: 96,
}
}
#[test]
fn vp9_keyframes_declare_their_format() {
let corpus = vp9_format(&[0x82, 0x49, 0x83, 0x42, 0x00, 0x07, 0xf0, 0x05, 0xf6]);
assert_eq!(corpus, Some(vp9(0, 8, (true, true), 0)));
let color = vp9_format(&[0x82, 0x49, 0x83, 0x42, 0x40, 0x0f, 0xf0, 0x03, 0xf6]);
assert_eq!(
color,
Some(Vp9Format {
color_space: 2,
width: 256,
height: 64,
..vp9(0, 8, (true, true), 2)
})
);
assert_eq!(
vp9_format(&packed(&format!(
"10 0 1 0 0 1 0 {VP9_SYNC} 0 101 1 {SIZE_128X96}"
))),
Some(Vp9Format {
full_range: true,
..vp9(2, 10, (true, true), 5)
})
);
assert_eq!(
vp9_format(&packed(&format!(
"10 0 1 0 0 1 0 {VP9_SYNC} 1 010 0 {SIZE_128X96}"
))),
Some(vp9(2, 12, (true, true), 2))
);
assert_eq!(
vp9_format(&packed(&format!(
"10 1 0 0 0 1 0 {VP9_SYNC} 010 0 1 0 0 {SIZE_128X96}"
))),
Some(vp9(1, 8, (true, false), 2))
);
assert_eq!(
vp9_format(&packed(&format!(
"10 1 1 0 0 0 1 0 {VP9_SYNC} 1 111 0 {SIZE_128X96}"
))),
Some(vp9(3, 12, (false, false), 7))
);
}
#[test]
fn vp9_intra_only_frames_declare_their_format() {
assert_eq!(
vp9_format(&packed(&format!(
"10 0 1 0 1 0 0 1 00 {VP9_SYNC} 0 010 0 11111111 {SIZE_128X96}"
))),
Some(vp9(2, 10, (true, true), 2))
);
assert_eq!(
vp9_format(&packed(&format!(
"10 0 0 0 1 0 0 1 00 {VP9_SYNC} 11111111 {SIZE_128X96}"
))),
Some(vp9(0, 8, (true, true), 1))
);
}
#[test]
fn vp9_frames_without_a_color_config_declare_nothing() {
assert_eq!(vp9_format(&[0x86, 0x00, 0x00, 0x00]), None);
assert_eq!(vp9_format(&[0x88]), None);
assert_eq!(
vp9_format(&[0x82, 0x49, 0x83, 0x43, 0x00, 0x07, 0xf0, 0x05]),
None
);
assert_eq!(
vp9_format(&[0x42, 0x49, 0x83, 0x42, 0x00, 0x07, 0xf0, 0x05]),
None
);
assert_eq!(vp9_format(&[0x92, 0x49]), None);
assert_eq!(vp9_format(&[0x82, 0x49, 0x83, 0x42, 0x00]), None);
assert_eq!(vp9_format(&[]), None);
}
#[test]
fn a_vp9_format_makes_the_vpcc_body_videotoolbox_reads() {
let hd = Vp9Format {
width: 1920,
height: 1080,
..vp9(0, 8, (true, true), 2)
};
assert_eq!(
hd.vpcc_record(Some(ColorMetadata::EXPORT)),
[1, 0, 0, 0, 0, 40, 0x82, 1, 1, 1, 0, 0]
);
assert_eq!(
vp9(0, 8, (true, true), 2).vpcc_record(None),
[1, 0, 0, 0, 0, 10, 0x82, 2, 2, 1, 0, 0]
);
let full = Vp9Format {
full_range: true,
..vp9(2, 10, (true, true), 0)
};
assert_eq!(
full.vpcc_record(None),
[1, 0, 0, 0, 2, 10, 0xa3, 2, 2, 2, 0, 0]
);
assert_eq!(vp9(1, 8, (true, false), 1).vpcc_record(None)[6], 0x84);
assert_eq!(
vp9(3, 12, (false, false), 7).vpcc_record(None)[4..10],
[3, 10, 0xc7, 2, 2, 0]
);
}
}