use crate::{CodecProfile, Error, ErrorKind, Result};
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AvcConfigurationRecord {
pub profile_idc: u8,
pub constraint_flags: u8,
pub level_idc: u8,
pub length_size: usize,
pub sequence_parameter_sets: Vec<Vec<u8>>,
pub picture_parameter_sets: Vec<Vec<u8>>,
pub chroma_format_idc: u8,
pub bit_depth_luma: u8,
pub bit_depth_chroma: u8,
}
const NAL_SPS: u8 = 7;
const NAL_PPS: u8 = 8;
impl AvcConfigurationRecord {
pub fn parse(decoder_config: &[u8]) -> Result<Self> {
let payload = avcc_payload(decoder_config)?;
if payload.len() < 7 {
return Err(malformed("avcC configuration is too short"));
}
if payload[0] != 1 {
return Err(malformed("avcC configurationVersion is not 1"));
}
let profile_idc = payload[1];
let constraint_flags = payload[2];
let level_idc = payload[3];
let length_size = usize::from(payload[4] & 0b11) + 1;
if length_size == 3 {
return Err(malformed("avcC NAL unit length size of 3 bytes is invalid"));
}
let mut cursor = 5;
let sps_count = usize::from(payload[cursor] & 0b1_1111);
cursor += 1;
let sequence_parameter_sets = read_sets(payload, &mut cursor, sps_count, NAL_SPS)?;
let pps_count = usize::from(
*payload
.get(cursor)
.ok_or_else(|| malformed("avcC configuration ends before its PPS count"))?,
);
cursor += 1;
let picture_parameter_sets = read_sets(payload, &mut cursor, pps_count, NAL_PPS)?;
let first_sps = sequence_parameter_sets
.first()
.ok_or_else(|| malformed("avcC configuration does not contain an SPS"))?;
if picture_parameter_sets.is_empty() {
return Err(malformed("avcC configuration does not contain a PPS"));
}
let sps = SpsSummary::parse(first_sps)?;
Ok(Self {
profile_idc,
constraint_flags,
level_idc,
length_size,
sequence_parameter_sets,
picture_parameter_sets,
chroma_format_idc: sps.chroma_format_idc,
bit_depth_luma: sps.bit_depth_luma,
bit_depth_chroma: sps.bit_depth_chroma,
})
}
pub fn codec_string(&self) -> String {
format!(
"avc1.{:02X}{:02X}{:02X}",
self.profile_idc, self.constraint_flags, self.level_idc
)
}
pub fn codec_profile(&self) -> Result<CodecProfile> {
match self.profile_idc {
66 => Ok(CodecProfile::H264Baseline),
77 => Ok(CodecProfile::H264Main),
100 => Ok(CodecProfile::H264High),
other => Err(Error::new(
ErrorKind::Unsupported,
format!(
"H.264 profile_idc {other} is unsupported; only Baseline (66), Main (77) and High (100) are"
),
)),
}
}
pub fn is_8bit_420(&self) -> bool {
self.chroma_format_idc == 1 && self.bit_depth_luma == 8 && self.bit_depth_chroma == 8
}
}
fn avcc_payload(decoder_config: &[u8]) -> Result<&[u8]> {
if decoder_config.len() >= 8 && &decoder_config[4..8] == b"avcC" {
let declared = u32::from_be_bytes(decoder_config[..4].try_into().expect("four bytes"));
if usize::try_from(declared).ok() != Some(decoder_config.len()) {
return Err(malformed(
"avcC box size does not match its configuration bytes",
));
}
return Ok(&decoder_config[8..]);
}
if decoder_config.first() == Some(&1) {
return Ok(decoder_config);
}
Err(malformed("H.264 configuration is not an avcC record"))
}
fn read_sets(
payload: &[u8],
cursor: &mut usize,
count: usize,
nal_type: u8,
) -> Result<Vec<Vec<u8>>> {
let mut sets = Vec::with_capacity(count);
for _ in 0..count {
let length = payload
.get(*cursor..*cursor + 2)
.ok_or_else(|| malformed("avcC parameter set length is truncated"))?;
let length = usize::from(u16::from_be_bytes([length[0], length[1]]));
*cursor += 2;
let unit = payload
.get(*cursor..*cursor + length)
.ok_or_else(|| malformed("avcC parameter set is truncated"))?;
*cursor += length;
if unit.first().map(|header| header & 0x1f) != Some(nal_type) {
return Err(malformed(if nal_type == NAL_SPS {
"avcC SPS entry is not a sequence parameter set"
} else {
"avcC PPS entry is not a picture parameter set"
}));
}
sets.push(unit.to_vec());
}
Ok(sets)
}
struct SpsSummary {
chroma_format_idc: u8,
bit_depth_luma: u8,
bit_depth_chroma: u8,
}
impl SpsSummary {
fn parse(unit: &[u8]) -> Result<Self> {
let rbsp = unescape(unit.get(1..).unwrap_or_default());
let mut bits = BitReader::new(&rbsp);
let profile_idc = bits.read_bits(8)? as u8;
bits.read_bits(16)?; bits.read_ue()?; if matches!(
profile_idc,
100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135
) {
let chroma_format_idc = bits.read_ue()?;
if chroma_format_idc > 3 {
return Err(malformed("H.264 SPS chroma_format_idc is out of range"));
}
if chroma_format_idc == 3 {
bits.read_bits(1)?; }
let luma = bits.read_ue()?;
let chroma = bits.read_ue()?;
if luma > 6 || chroma > 6 {
return Err(malformed("H.264 SPS bit depth is out of range"));
}
return Ok(Self {
chroma_format_idc: chroma_format_idc as u8,
bit_depth_luma: luma as u8 + 8,
bit_depth_chroma: chroma as u8 + 8,
});
}
Ok(Self {
chroma_format_idc: 1,
bit_depth_luma: 8,
bit_depth_chroma: 8,
})
}
}
fn unescape(escaped: &[u8]) -> Vec<u8> {
let mut output = 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 };
output.push(byte);
}
output
}
struct BitReader<'a> {
data: &'a [u8],
position: usize,
}
impl<'a> BitReader<'a> {
fn new(data: &'a [u8]) -> Self {
Self { data, position: 0 }
}
fn read_bit(&mut self) -> Result<u32> {
let byte = self
.data
.get(self.position / 8)
.ok_or_else(|| malformed("H.264 SPS is truncated"))?;
let bit = (byte >> (7 - self.position % 8)) & 1;
self.position += 1;
Ok(u32::from(bit))
}
fn read_bits(&mut self, count: u32) -> Result<u32> {
let mut value = 0;
for _ in 0..count {
value = (value << 1) | self.read_bit()?;
}
Ok(value)
}
fn read_ue(&mut self) -> Result<u32> {
let mut leading_zeros = 0;
while self.read_bit()? == 0 {
leading_zeros += 1;
if leading_zeros > 31 {
return Err(malformed("H.264 SPS Exp-Golomb code is too long"));
}
}
Ok((1u32 << leading_zeros) - 1 + self.read_bits(leading_zeros)?)
}
}
fn malformed(message: impl Into<String>) -> Error {
Error::new(ErrorKind::MalformedMedia, message)
}
#[cfg(test)]
mod tests {
use super::*;
const HIGH_SPS: &[u8] = &[
0x67, 0x64, 0x00, 0x0c, 0xac, 0xd9, 0x41, 0x01, 0x3f, 0xbf, 0xfc, 0x00, 0x8c, 0x00, 0x91,
0xa8, 0x28, 0x28, 0x32, 0x00, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x03, 0x00, 0x60, 0x1e,
0x28, 0x53, 0x2c,
];
const PPS: &[u8] = &[0x68, 0xe9, 0x38, 0x44, 0xb2, 0x2c];
fn record(profile: u8, sps: &[&[u8]], pps: &[&[u8]]) -> Vec<u8> {
let mut payload = vec![1, profile, 0x00, 0x0c, 0xff, 0xe0 | sps.len() as u8];
for set in sps {
payload.extend_from_slice(&(set.len() as u16).to_be_bytes());
payload.extend_from_slice(set);
}
payload.push(pps.len() as u8);
for set in pps {
payload.extend_from_slice(&(set.len() as u16).to_be_bytes());
payload.extend_from_slice(set);
}
let mut boxed = ((payload.len() + 8) as u32).to_be_bytes().to_vec();
boxed.extend_from_slice(b"avcC");
boxed.extend_from_slice(&payload);
boxed
}
enum Field {
Bits(u32, u32),
Ue(u32),
}
use Field::{Bits, Ue};
fn sps(fields: &[Field]) -> Vec<u8> {
let mut bits = Vec::new();
let mut push = |value: u32, width: u32| {
for shift in (0..width).rev() {
bits.push((value >> shift) & 1 == 1);
}
};
for field in fields {
match *field {
Bits(value, width) => push(value, width),
Ue(value) => {
let coded = value + 1;
let width = 32 - coded.leading_zeros();
push(0, width - 1);
push(coded, width);
}
}
}
bits.push(true);
let mut unit = vec![0x67];
unit.extend(bits.chunks(8).map(|chunk| {
chunk.iter().enumerate().fold(0u8, |byte, (index, &bit)| {
byte | (u8::from(bit) << (7 - index))
})
}));
unit
}
#[test]
fn parses_a_high_profile_box_and_its_bare_payload() {
let boxed = record(100, &[HIGH_SPS], &[PPS]);
let parsed = AvcConfigurationRecord::parse(&boxed).unwrap();
assert_eq!(parsed.profile_idc, 100);
assert_eq!(parsed.level_idc, 12);
assert_eq!(parsed.length_size, 4);
assert_eq!(parsed.sequence_parameter_sets, [HIGH_SPS.to_vec()]);
assert_eq!(parsed.picture_parameter_sets, [PPS.to_vec()]);
assert!(parsed.is_8bit_420());
assert_eq!(parsed.codec_string(), "avc1.64000C");
assert_eq!(parsed.codec_profile().unwrap(), CodecProfile::H264High);
assert_eq!(AvcConfigurationRecord::parse(&boxed[8..]).unwrap(), parsed);
}
#[test]
fn maps_baseline_and_main_and_refuses_other_profiles() {
let baseline = sps(&[Bits(66, 8), Bits(0xc0, 8), Bits(30, 8), Ue(0)]);
let mut boxed = record(66, &[&baseline], &[PPS]);
boxed[10] = 0xc0;
boxed[11] = 30;
let parsed = AvcConfigurationRecord::parse(&boxed).unwrap();
assert_eq!(parsed.codec_profile().unwrap(), CodecProfile::H264Baseline);
assert!(parsed.is_8bit_420());
assert_eq!(parsed.codec_string(), "avc1.42C01E");
let parsed = AvcConfigurationRecord::parse(&record(77, &[&baseline], &[PPS])).unwrap();
assert_eq!(parsed.codec_profile().unwrap(), CodecProfile::H264Main);
let error = AvcConfigurationRecord::parse(&record(88, &[&baseline], &[PPS]))
.unwrap()
.codec_profile()
.unwrap_err();
assert_eq!(error.kind(), ErrorKind::Unsupported);
}
#[test]
fn reads_high_10_and_4_4_4_formats_from_the_sps() {
let high10 = sps(&[Bits(110, 8), Bits(0, 16), Ue(0), Ue(1), Ue(2), Ue(2)]);
let parsed = AvcConfigurationRecord::parse(&record(110, &[&high10], &[PPS])).unwrap();
assert_eq!(
(
parsed.chroma_format_idc,
parsed.bit_depth_luma,
parsed.bit_depth_chroma
),
(1, 10, 10)
);
assert!(!parsed.is_8bit_420());
assert_eq!(
parsed.codec_profile().unwrap_err().kind(),
ErrorKind::Unsupported
);
let high444 = sps(&[
Bits(244, 8),
Bits(0, 16),
Ue(0),
Ue(3),
Bits(0, 1),
Ue(0),
Ue(0),
]);
let parsed = AvcConfigurationRecord::parse(&record(244, &[&high444], &[PPS])).unwrap();
assert_eq!(parsed.chroma_format_idc, 3);
assert_eq!((parsed.bit_depth_luma, parsed.bit_depth_chroma), (8, 8));
assert!(!parsed.is_8bit_420());
}
#[test]
fn rejects_malformed_records() {
let good = record(100, &[HIGH_SPS], &[PPS]);
for (name, bytes) in [
("empty", Vec::new()),
("not avcC", vec![2, 100, 0, 30, 0xff, 0xe1]),
("truncated", good[..good.len() - 2].to_vec()),
("box size mismatch", {
let mut bytes = good.clone();
bytes[3] = bytes[3].wrapping_add(1);
bytes
}),
("no SPS", record(100, &[], &[PPS])),
("no PPS", record(100, &[HIGH_SPS], &[])),
("SPS slot holds a PPS", record(100, &[PPS], &[PPS])),
("length size 3", {
let mut bytes = good.clone();
bytes[12] = 0xfe;
bytes
}),
] {
let error = AvcConfigurationRecord::parse(&bytes)
.err()
.unwrap_or_else(|| panic!("{name} must be rejected"));
assert_eq!(error.kind(), ErrorKind::MalformedMedia, "{name}");
}
}
#[test]
fn unescapes_emulation_prevention_bytes() {
assert_eq!(unescape(&[0, 0, 3, 1, 0, 0, 3, 0]), [0, 0, 1, 0, 0, 0]);
assert_eq!(unescape(&[0, 3, 0, 0, 3]), [0, 3, 0, 0]);
}
}