use crate::bitstream::emulation_prevention;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum NalUnitType {
TrailN = 0,
TrailR = 1,
IdrWRadl = 19,
IdrNLp = 20,
CraNut = 21,
Vps = 32,
Sps = 33,
Pps = 34,
Aud = 35,
PrefixSei = 39,
}
impl NalUnitType {
pub fn code(self) -> u8 {
self as u8
}
pub fn is_irap(self) -> bool {
matches!(
self,
NalUnitType::IdrWRadl | NalUnitType::IdrNLp | NalUnitType::CraNut
)
}
}
pub const START_CODE: [u8; 4] = [0x00, 0x00, 0x00, 0x01];
pub fn nal_unit(nal_type: NalUnitType, layer_id: u8, temporal_id: u8, rbsp: &[u8]) -> Vec<u8> {
let t = nal_type.code() & 0x3F;
let layer = layer_id & 0x3F;
let tid1 = (temporal_id & 0x07) + 1;
let b0 = (t << 1) | (layer >> 5);
let b1 = ((layer & 0x1F) << 3) | tid1;
let ebsp = emulation_prevention(rbsp);
let mut out = Vec::with_capacity(2 + ebsp.len());
out.push(b0);
out.push(b1);
out.extend_from_slice(&ebsp);
out
}
pub fn nal_unit_base(nal_type: NalUnitType, rbsp: &[u8]) -> Vec<u8> {
nal_unit(nal_type, 0, 0, rbsp)
}
pub fn push_annexb(out: &mut Vec<u8>, nal: &[u8]) {
out.extend_from_slice(&START_CODE);
out.extend_from_slice(nal);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn header_bytes_base_layer() {
let nal = nal_unit_base(NalUnitType::Vps, &[0xAA]);
assert_eq!(nal[0], 0x40, "nal_unit_type 32 in bits 1..7");
assert_eq!(nal[1], 0x01, "layer 0, temporal_id_plus1 = 1");
assert_eq!(&nal[2..], &[0xAA]);
assert_eq!(nal_unit_base(NalUnitType::Sps, &[])[0], 0x42);
assert_eq!(nal_unit_base(NalUnitType::Pps, &[])[0], 0x44);
}
#[test]
fn payload_gets_emulation_prevention() {
let nal = nal_unit_base(NalUnitType::Pps, &[0x00, 0x00, 0x01, 0xFF]);
assert_eq!(&nal[2..], &[0x00, 0x00, 0x03, 0x01, 0xFF]);
}
#[test]
fn irap_classification() {
assert!(NalUnitType::IdrWRadl.is_irap());
assert!(NalUnitType::CraNut.is_irap());
assert!(!NalUnitType::TrailR.is_irap());
assert!(!NalUnitType::Vps.is_irap());
}
#[test]
fn annexb_prefixes_start_code() {
let mut stream = Vec::new();
push_annexb(&mut stream, &[0x42, 0x01, 0x99]);
assert_eq!(stream, vec![0x00, 0x00, 0x00, 0x01, 0x42, 0x01, 0x99]);
}
}