#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NalType {
IdrWRadl,
Vps,
Sps,
Pps,
}
impl NalType {
fn nal_unit_type(self) -> u8 {
match self {
NalType::IdrWRadl => 19,
NalType::Vps => 32,
NalType::Sps => 33,
NalType::Pps => 34,
}
}
}
pub fn write_annexb_nal(out: &mut Vec<u8>, nal_type: NalType, rbsp: &[u8]) {
out.extend_from_slice(&[0, 0, 0, 1]);
let nuh_layer_id = 0u8;
let nuh_temporal_id_plus1 = 1u8;
let header = [
(nal_type.nal_unit_type() << 1) | (nuh_layer_id >> 5),
(nuh_layer_id << 5) | nuh_temporal_id_plus1,
];
let mut zeros = 0usize;
for &b in header.iter().chain(rbsp.iter()) {
if zeros >= 2 && b <= 0x03 {
out.push(0x03);
zeros = 0;
}
out.push(b);
zeros = if b == 0 { zeros + 1 } else { 0 };
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn header_bytes_for_sps() {
let mut out = Vec::new();
write_annexb_nal(&mut out, NalType::Sps, &[]);
assert_eq!(out, vec![0, 0, 0, 1, 33 << 1, 1]);
}
#[test]
fn emulation_prevention_inserted() {
let mut out = Vec::new();
write_annexb_nal(
&mut out,
NalType::Sps,
&[
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x02, 0x00, 0x00, 0x03,
],
);
let rbsp_out = &out[6..];
assert_eq!(
rbsp_out,
&[
0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x03, 0x02, 0x00, 0x00, 0x03, 0x03, ]
);
}
#[test]
fn no_false_positive_epb() {
let mut out = Vec::new();
write_annexb_nal(&mut out, NalType::Sps, &[0x00, 0x00, 0x04]);
let rbsp_out = &out[6..];
assert_eq!(rbsp_out, &[0x00, 0x00, 0x04]);
}
}