#[cfg(test)]
mod h264_test;
#[cfg(test)]
mod interleaved_test;
#[cfg(test)]
mod packetization_mode_test;
#[cfg(test)]
mod rfc6184_test;
use crate::packetizer::{Depacketizer, Payloader};
use shared::error::{Error, Result};
use bytes::{BufMut, Bytes, BytesMut};
use std::time::{Duration, Instant};
pub const STAPA_NALU_TYPE: u8 = 24;
pub const STAPB_NALU_TYPE: u8 = 25;
pub const MTAP16_NALU_TYPE: u8 = 26;
pub const MTAP24_NALU_TYPE: u8 = 27;
pub const FUA_NALU_TYPE: u8 = 28;
pub const FUB_NALU_TYPE: u8 = 29;
pub const IDR_NALU_TYPE: u8 = 5;
pub const SEI_NALU_TYPE: u8 = 6;
pub const SPS_NALU_TYPE: u8 = 7;
pub const PPS_NALU_TYPE: u8 = 8;
pub const AUD_NALU_TYPE: u8 = 9;
pub const FILLER_NALU_TYPE: u8 = 12;
pub const FUA_HEADER_SIZE: usize = 2;
pub const FUB_HEADER_SIZE: usize = 4;
pub const MAX_FUA_NALU_SIZE: usize = 4 * 1024 * 1024;
pub const STAPA_HEADER_SIZE: usize = 1;
pub const STAPB_HEADER_SIZE: usize = 3;
pub const MTAP_HEADER_SIZE: usize = 3;
pub const STAPA_NALU_LENGTH_SIZE: usize = 2;
pub const NALU_TYPE_BITMASK: u8 = 0x1F;
pub const NALU_REF_IDC_BITMASK: u8 = 0x60;
pub const NALU_FORBIDDEN_BITMASK: u8 = 0x80;
pub const FU_START_BITMASK: u8 = 0x80;
pub const FU_END_BITMASK: u8 = 0x40;
pub const OUTPUT_STAP_AHEADER: u8 = 0x78;
pub static ANNEXB_NALUSTART_CODE: Bytes = Bytes::from_static(&[0x00, 0x00, 0x00, 0x01]);
const MAX_HELD_PARAMETER_SETS: usize = 64;
const MAX_HELD_PARAMETER_SET_BYTES: usize = 1024 * 1024;
pub(crate) fn annex_b_nal_units(payload: &Bytes) -> Vec<Bytes> {
fn next_start_code(data: &[u8], start: usize) -> Option<(usize, usize)> {
let at = start + memchr::memmem::find(&data[start..], &[0, 0, 1])?;
let first_zero = data[start..at]
.iter()
.rposition(|&b| b != 0)
.map_or(start, |nonzero| start + nonzero + 1);
Some((first_zero, at + 3 - first_zero))
}
let mut nalus = vec![];
let Some((mut code_start, mut code_len)) = next_start_code(payload, 0) else {
nalus.push(payload.clone());
return nalus;
};
loop {
let nalu_start = code_start + code_len;
match next_start_code(payload, nalu_start) {
Some((next_start, next_len)) => {
nalus.push(payload.slice(nalu_start..next_start));
code_start = next_start;
code_len = next_len;
}
None => {
nalus.push(payload.slice(nalu_start..));
return nalus;
}
}
}
}
fn is_nal_unit_type(nalu_type: u8) -> bool {
(1..=23).contains(&nalu_type)
}
fn is_vcl_type(nalu_type: u8) -> bool {
(1..=5).contains(&nalu_type)
}
fn aggregation_header(packet_type: u8, nalus: &[Bytes]) -> u8 {
let mut forbidden = 0;
let mut ref_idc = 0;
for nalu in nalus {
if let Some(&header) = nalu.first() {
forbidden |= header & NALU_FORBIDDEN_BITMASK;
ref_idc = ref_idc.max(header & NALU_REF_IDC_BITMASK);
}
}
forbidden | ref_idc | packet_type
}
fn check_aggregated(nalus: &[&Bytes]) -> Result<()> {
if nalus.is_empty() {
return Err(Error::Other(
"an H.264 aggregation packet holds at least one NAL unit".to_owned(),
));
}
for nalu in nalus {
let Some(&header) = nalu.first() else {
return Err(Error::ErrShortPacket);
};
if !is_nal_unit_type(header & NALU_TYPE_BITMASK) {
return Err(Error::NaluTypeIsNotHandled(header & NALU_TYPE_BITMASK));
}
if nalu.len() > u16::MAX as usize {
return Err(Error::NaluTooLarge(nalu.len()));
}
}
Ok(())
}
pub fn stap_a(nalus: &[Bytes]) -> Result<Bytes> {
check_aggregated(&nalus.iter().collect::<Vec<_>>())?;
let mut out = BytesMut::with_capacity(
STAPA_HEADER_SIZE + nalus.iter().map(|nalu| 2 + nalu.len()).sum::<usize>(),
);
out.put_u8(aggregation_header(STAPA_NALU_TYPE, nalus));
for nalu in nalus {
out.put_u16(nalu.len() as u16);
out.put(&**nalu);
}
Ok(out.freeze())
}
pub fn stap_b(don: u16, nalus: &[Bytes]) -> Result<Bytes> {
check_aggregated(&nalus.iter().collect::<Vec<_>>())?;
let mut out = BytesMut::with_capacity(
STAPB_HEADER_SIZE + nalus.iter().map(|nalu| 2 + nalu.len()).sum::<usize>(),
);
out.put_u8(aggregation_header(STAPB_NALU_TYPE, nalus));
out.put_u16(don);
for nalu in nalus {
out.put_u16(nalu.len() as u16);
out.put(&**nalu);
}
Ok(out.freeze())
}
pub fn don_diff(m: u16, n: u16) -> i32 {
let (m, n) = (i32::from(m), i32::from(n));
if m == n {
0
} else if m < n && n - m < 32768 {
n - m
} else if m > n && m - n >= 32768 {
65536 - m + n
} else if m < n {
-(m + 65536 - n)
} else {
-(m - n)
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum MtapKind {
Mtap16,
Mtap24,
}
impl MtapKind {
fn nalu_type(self) -> u8 {
match self {
MtapKind::Mtap16 => MTAP16_NALU_TYPE,
MtapKind::Mtap24 => MTAP24_NALU_TYPE,
}
}
fn offset_size(self) -> usize {
match self {
MtapKind::Mtap16 => 2,
MtapKind::Mtap24 => 3,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MtapUnit {
pub don: u16,
pub timestamp: u32,
pub nalu: Bytes,
}
pub fn mtap(kind: MtapKind, units: &[MtapUnit]) -> Result<(Bytes, u32)> {
check_aggregated(&units.iter().map(|unit| &unit.nalu).collect::<Vec<_>>())?;
let mut don_base = units[0].don;
let mut timestamp = units[0].timestamp;
for unit in units {
if don_diff(don_base, unit.don) < 0 {
don_base = unit.don;
}
if (unit.timestamp.wrapping_sub(timestamp) as i32) < 0 {
timestamp = unit.timestamp;
}
}
let mut ordered: Vec<&MtapUnit> = units.iter().collect();
ordered.sort_by_key(|unit| don_diff(don_base, unit.don));
let units = ordered;
let nalus: Vec<Bytes> = units.iter().map(|unit| unit.nalu.clone()).collect();
let mut out = BytesMut::with_capacity(
MTAP_HEADER_SIZE
+ units
.iter()
.map(|unit| 3 + kind.offset_size() + unit.nalu.len())
.sum::<usize>(),
);
out.put_u8(aggregation_header(kind.nalu_type(), &nalus));
out.put_u16(don_base);
for unit in units {
let dond = u8::try_from(don_diff(don_base, unit.don)).map_err(|_| {
Error::Other(format!(
"MTAP: DON {} is more than 255 after the DON base {don_base}",
unit.don
))
})?;
let offset = unit.timestamp.wrapping_sub(timestamp);
if offset >> (8 * kind.offset_size()) != 0 {
return Err(Error::Other(format!(
"MTAP: a timestamp offset of {offset} does not fit {} bits",
8 * kind.offset_size()
)));
}
out.put_u16(unit.nalu.len() as u16);
out.put_u8(dond);
match kind {
MtapKind::Mtap16 => out.put_u16(offset as u16),
MtapKind::Mtap24 => {
out.put_u8((offset >> 16) as u8);
out.put_u16(offset as u16);
}
}
out.put(&*unit.nalu);
}
Ok((out.freeze(), timestamp))
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
enum PacketizationMode {
SingleNalUnit,
#[default]
NonInterleaved,
Interleaved,
}
#[derive(Default, Debug, Clone)]
pub struct H264Payloader {
held_parameter_sets: Vec<Bytes>,
mode: PacketizationMode,
next_don: u16,
}
impl H264Payloader {
pub fn with_packetization_mode(packetization_mode: u8) -> Self {
Self::try_with_packetization_mode(packetization_mode).unwrap_or_default()
}
pub fn try_with_packetization_mode(packetization_mode: u8) -> Result<Self> {
let mode = match packetization_mode {
0 => PacketizationMode::SingleNalUnit,
1 => PacketizationMode::NonInterleaved,
2 => PacketizationMode::Interleaved,
other => {
return Err(Error::Other(format!(
"H.264 packetization-mode is 0, 1 or 2, not {other}"
)));
}
};
Ok(Self {
mode,
..Default::default()
})
}
pub fn with_initial_don(mut self, don: u16) -> Self {
self.next_don = don;
self
}
fn is_sent(nalu: &Bytes) -> bool {
nalu.first().is_some_and(|&header| {
let nalu_type = header & NALU_TYPE_BITMASK;
is_nal_unit_type(nalu_type)
&& nalu_type != AUD_NALU_TYPE
&& nalu_type != FILLER_NALU_TYPE
})
}
fn emit_single_nal_unit(nalu: &Bytes, mtu: usize, payloads: &mut Vec<Bytes>) -> Result<()> {
if !Self::is_sent(nalu) {
return Ok(());
}
if nalu.len() > mtu {
return Err(Error::Other(format!(
"H.264 packetization-mode=0: a {}-byte NAL unit does not fit the {mtu}-byte MTU",
nalu.len()
)));
}
payloads.push(nalu.clone());
Ok(())
}
fn emit_single_or_fragment(nalu: &Bytes, mtu: usize, payloads: &mut Vec<Bytes>) {
if nalu.is_empty() {
return;
}
if nalu.len() <= mtu {
payloads.push(nalu.clone());
return;
}
let Some(max_fragment_size) = mtu.checked_sub(FUA_HEADER_SIZE).filter(|&size| size > 0)
else {
return;
};
let indicator = (nalu[0] & (NALU_FORBIDDEN_BITMASK | NALU_REF_IDC_BITMASK)) | FUA_NALU_TYPE;
let nalu_type = nalu[0] & NALU_TYPE_BITMASK;
let data = &nalu[1..];
let last = data.len().div_ceil(max_fragment_size) - 1;
for (i, fragment) in data.chunks(max_fragment_size).enumerate() {
let mut out = BytesMut::with_capacity(FUA_HEADER_SIZE + fragment.len());
out.put_u8(indicator);
let mut fu_header = nalu_type;
if i == 0 {
fu_header |= FU_START_BITMASK;
} else if i == last {
fu_header |= FU_END_BITMASK;
}
out.put_u8(fu_header);
out.put(fragment);
payloads.push(out.freeze());
}
}
fn emit_fu_b(nalu: &Bytes, don: u16, mtu: usize, payloads: &mut Vec<Bytes>) {
let (Some(first_size), Some(next_size)) = (
mtu.checked_sub(FUB_HEADER_SIZE).filter(|&size| size > 0),
mtu.checked_sub(FUA_HEADER_SIZE).filter(|&size| size > 0),
) else {
return;
};
let flags = nalu[0] & (NALU_FORBIDDEN_BITMASK | NALU_REF_IDC_BITMASK);
let nalu_type = nalu[0] & NALU_TYPE_BITMASK;
let data = &nalu[1..];
let first_len = if data.len() <= first_size {
data.len().div_ceil(2)
} else {
first_size
};
let (first, rest) = data.split_at(first_len);
let mut out = BytesMut::with_capacity(FUB_HEADER_SIZE + first.len());
out.put_u8(flags | FUB_NALU_TYPE);
out.put_u8(FU_START_BITMASK | nalu_type);
out.put_u16(don);
out.put(first);
payloads.push(out.freeze());
let fragments = rest.len().div_ceil(next_size).max(1);
for i in 0..fragments {
let fragment = &rest[i * next_size..rest.len().min((i + 1) * next_size)];
let mut out = BytesMut::with_capacity(FUA_HEADER_SIZE + fragment.len());
out.put_u8(flags | FUA_NALU_TYPE);
out.put_u8(if i == fragments - 1 {
FU_END_BITMASK | nalu_type
} else {
nalu_type
});
out.put(fragment);
payloads.push(out.freeze());
}
}
fn payload_non_interleaved(
&mut self,
nalus: Vec<Bytes>,
mtu: usize,
payloads: &mut Vec<Bytes>,
) {
let nalus: Vec<Bytes> = nalus.into_iter().filter(Self::is_sent).collect();
if nalus.is_empty() {
return;
}
let only_parameter_sets = nalus.iter().all(|nalu| {
let nalu_type = nalu[0] & NALU_TYPE_BITMASK;
nalu_type == SPS_NALU_TYPE || nalu_type == PPS_NALU_TYPE
});
let held_bytes: usize = self
.held_parameter_sets
.iter()
.chain(&nalus)
.map(Bytes::len)
.sum();
if only_parameter_sets
&& self.held_parameter_sets.len() + nalus.len() <= MAX_HELD_PARAMETER_SETS
&& held_bytes <= MAX_HELD_PARAMETER_SET_BYTES
{
self.held_parameter_sets.extend(nalus);
return;
}
fn flush(pending: &mut Vec<Bytes>, payloads: &mut Vec<Bytes>) {
match pending.len() {
0 => {}
1 => payloads.extend(pending.pop()),
_ => {
let mut out = BytesMut::with_capacity(
STAPA_HEADER_SIZE
+ pending.iter().map(|nalu| 2 + nalu.len()).sum::<usize>(),
);
out.put_u8(aggregation_header(STAPA_NALU_TYPE, pending));
for nalu in pending.drain(..) {
out.put_u16(nalu.len() as u16);
out.put(nalu);
}
payloads.push(out.freeze());
}
}
}
let mut pending: Vec<Bytes> = vec![];
let mut pending_size = STAPA_HEADER_SIZE;
let held = std::mem::take(&mut self.held_parameter_sets);
for nalu in held.into_iter().chain(nalus) {
let unit_size = STAPA_NALU_LENGTH_SIZE + nalu.len();
let aggregated = !is_vcl_type(nalu[0] & NALU_TYPE_BITMASK)
&& nalu.len() <= u16::MAX as usize
&& STAPA_HEADER_SIZE + unit_size <= mtu;
if aggregated {
if pending_size + unit_size > mtu {
flush(&mut pending, payloads);
pending_size = STAPA_HEADER_SIZE;
}
pending_size += unit_size;
pending.push(nalu);
} else {
flush(&mut pending, payloads);
pending_size = STAPA_HEADER_SIZE;
Self::emit_single_or_fragment(&nalu, mtu, payloads);
}
}
flush(&mut pending, payloads);
}
fn payload_interleaved(&mut self, nalus: Vec<Bytes>, mtu: usize, payloads: &mut Vec<Bytes>) {
fn flush(don: u16, pending: &mut Vec<Bytes>, payloads: &mut Vec<Bytes>) {
if pending.is_empty() {
return;
}
let mut out = BytesMut::with_capacity(
STAPB_HEADER_SIZE + pending.iter().map(|nalu| 2 + nalu.len()).sum::<usize>(),
);
out.put_u8(aggregation_header(STAPB_NALU_TYPE, pending));
out.put_u16(don);
for nalu in pending.drain(..) {
out.put_u16(nalu.len() as u16);
out.put(nalu);
}
payloads.push(out.freeze());
}
let mut pending: Vec<Bytes> = vec![];
let mut pending_don = self.next_don;
let mut pending_size = STAPB_HEADER_SIZE;
for nalu in nalus.into_iter().filter(Self::is_sent) {
let don = self.next_don;
self.next_don = self.next_don.wrapping_add(1);
let unit_size = STAPA_NALU_LENGTH_SIZE + nalu.len();
if nalu.len() <= u16::MAX as usize && STAPB_HEADER_SIZE + unit_size <= mtu {
if pending_size + unit_size > mtu {
flush(pending_don, &mut pending, payloads);
pending_size = STAPB_HEADER_SIZE;
}
if pending.is_empty() {
pending_don = don;
}
pending_size += unit_size;
pending.push(nalu);
} else {
flush(pending_don, &mut pending, payloads);
pending_size = STAPB_HEADER_SIZE;
Self::emit_fu_b(&nalu, don, mtu, payloads);
}
}
flush(pending_don, &mut pending, payloads);
}
}
impl Payloader for H264Payloader {
fn payload(&mut self, mtu: usize, payload: &Bytes) -> Result<Vec<Bytes>> {
if payload.is_empty() || mtu == 0 {
return Ok(vec![]);
}
let nalus = annex_b_nal_units(payload);
let mut payloads = vec![];
match self.mode {
PacketizationMode::SingleNalUnit => {
for nalu in &nalus {
Self::emit_single_nal_unit(nalu, mtu, &mut payloads)?;
}
}
PacketizationMode::NonInterleaved => {
self.payload_non_interleaved(nalus, mtu, &mut payloads)
}
PacketizationMode::Interleaved => self.payload_interleaved(nalus, mtu, &mut payloads),
}
Ok(payloads)
}
fn clone_to(&self) -> Box<dyn Payloader> {
Box::new(self.clone())
}
}
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct H264NalUnit {
pub data: Bytes,
pub don: Option<u16>,
pub timestamp_offset: Option<u32>,
}
impl H264NalUnit {
fn plain(data: Bytes) -> Self {
H264NalUnit {
data,
don: None,
timestamp_offset: None,
}
}
pub fn nalu_type(&self) -> u8 {
self.data.first().map_or(0, |b| b & NALU_TYPE_BITMASK)
}
}
pub const MAX_DEINTERLEAVING_NAL_UNITS: usize = 4096;
pub const MAX_DEINTERLEAVING_BYTES: usize = 32 * 1024 * 1024;
#[derive(PartialEq, Eq, Debug, Clone)]
struct BufferedNalUnit {
unit: H264NalUnit,
don: u16,
abs_don: i64,
}
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct H264DeinterleavingBuffer {
vcl_capacity: usize,
max_don_diff: Option<i32>,
previous_don: Option<u16>,
units: Vec<BufferedNalUnit>,
last_received: Option<(u16, i64)>,
bytes: usize,
init_buf_time: Option<Duration>,
first_arrival: Option<Instant>,
initial_buffering_over: bool,
literal_pdon: bool,
}
impl H264DeinterleavingBuffer {
pub fn new(sprop_interleaving_depth: u16, sprop_max_don_diff: Option<u16>) -> Self {
H264DeinterleavingBuffer {
vcl_capacity: usize::from(sprop_interleaving_depth) + 1,
max_don_diff: sprop_max_don_diff.map(i32::from),
previous_don: None,
units: Vec::new(),
last_received: None,
bytes: 0,
init_buf_time: None,
first_arrival: None,
initial_buffering_over: false,
literal_pdon: false,
}
}
pub fn with_literal_pdon(mut self, literal: bool) -> Self {
self.literal_pdon = literal;
self
}
pub fn with_init_buf_time(mut self, sprop_init_buf_time: u32) -> Self {
self.init_buf_time = Some(Duration::from_micros(
u64::from(sprop_init_buf_time) * 1_000_000 / 90_000,
));
self
}
pub fn push_at(&mut self, now: Instant, unit: H264NalUnit) -> Vec<H264NalUnit> {
if unit.don.is_some() {
self.first_arrival.get_or_insert(now);
}
self.push(unit)
}
pub fn is_initial_buffering(&self, now: Instant) -> bool {
if self.initial_buffering_over {
return false;
}
match (self.init_buf_time, self.first_arrival) {
(Some(wait), Some(first)) => now.saturating_duration_since(first) < wait,
_ => true,
}
}
pub fn len(&self) -> usize {
self.units.len()
}
pub fn is_empty(&self) -> bool {
self.units.is_empty()
}
fn distance(&self, don: u16) -> u32 {
let previous_don = self.previous_don.unwrap_or_else(|| {
if self.literal_pdon {
return 0;
}
self.units
.iter()
.min_by_key(|buffered| buffered.abs_don)
.map_or(0, |earliest| earliest.don.wrapping_sub(1))
});
if don > previous_don {
u32::from(don - previous_don)
} else {
65535 - u32::from(previous_don) + u32::from(don) + 1
}
}
fn vcl_count(&self) -> usize {
self.units
.iter()
.filter(|buffered| is_vcl_type(buffered.unit.nalu_type()))
.count()
}
fn take_next(&mut self) -> BufferedNalUnit {
let index = (0..self.units.len())
.min_by_key(|&i| self.distance(self.units[i].don))
.unwrap_or(0);
let buffered = self.units.remove(index);
self.bytes -= buffered.unit.data.len();
buffered
}
pub fn push(&mut self, unit: H264NalUnit) -> Vec<H264NalUnit> {
let Some(don) = unit.don else {
return vec![unit];
};
let abs_don = match self.last_received {
Some((last_don, last_abs)) => last_abs + i64::from(don_diff(last_don, don)),
None => i64::from(don),
};
self.last_received = Some((don, abs_don));
self.bytes += unit.data.len();
self.units.push(BufferedNalUnit { unit, don, abs_don });
let mut out = vec![];
let mut last_out = None;
if self.vcl_count() >= self.vcl_capacity {
self.initial_buffering_over = true;
}
while self.vcl_count() >= self.vcl_capacity {
let buffered = self.take_next();
last_out = Some(buffered.don);
out.push(buffered.unit);
}
if let Some(max_don_diff) = self.max_don_diff {
let greatest = self.units.iter().map(|b| b.abs_don).max().unwrap_or(0);
loop {
let due = self
.units
.iter()
.any(|b| greatest - b.abs_don > i64::from(max_don_diff));
if !due {
break;
}
self.initial_buffering_over = true;
let index = (0..self.units.len())
.filter(|&i| greatest - self.units[i].abs_don > i64::from(max_don_diff))
.min_by_key(|&i| self.distance(self.units[i].don))
.unwrap_or(0);
let buffered = self.units.remove(index);
self.bytes -= buffered.unit.data.len();
last_out = Some(buffered.don);
out.push(buffered.unit);
}
}
while self.units.len() > MAX_DEINTERLEAVING_NAL_UNITS
|| self.bytes > MAX_DEINTERLEAVING_BYTES
{
let buffered = self.take_next();
last_out = Some(buffered.don);
out.push(buffered.unit);
}
if last_out.is_some() {
self.previous_don = last_out;
}
out
}
pub fn flush(&mut self) -> Vec<H264NalUnit> {
let mut buffered: Vec<(u32, BufferedNalUnit)> = self
.units
.iter()
.map(|b| (self.distance(b.don), b.clone()))
.collect();
self.units.clear();
self.bytes = 0;
buffered.sort_by_key(|(distance, _)| *distance);
let buffered: Vec<BufferedNalUnit> = buffered.into_iter().map(|(_, b)| b).collect();
if let Some(last) = buffered.last() {
self.previous_don = Some(last.don);
}
buffered.into_iter().map(|b| b.unit).collect()
}
}
#[derive(PartialEq, Eq, Debug, Default, Clone)]
pub struct H264Packet {
pub is_avc: bool,
fua_buffer: Option<BytesMut>,
fu_don: Option<u16>,
last_sequence_number: Option<u16>,
deinterleaving: Option<H264DeinterleavingBuffer>,
}
impl H264Packet {
pub fn with_deinterleaving(mut self, buffer: H264DeinterleavingBuffer) -> Self {
self.deinterleaving = Some(buffer);
self
}
pub fn flush_deinterleaving(&mut self) -> Bytes {
let units = self
.deinterleaving
.as_mut()
.map(H264DeinterleavingBuffer::flush)
.unwrap_or_default();
self.format(&units)
}
pub fn depacketize_with_sequence_number(
&mut self,
sequence_number: u16,
packet: &Bytes,
) -> Result<Bytes> {
if let Some(last) = self.last_sequence_number
&& sequence_number != last.wrapping_add(1)
{
self.fua_buffer = None;
self.fu_don = None;
}
self.last_sequence_number = Some(sequence_number);
self.depacketize(packet)
}
pub fn nal_units(&mut self, packet: &Bytes) -> Result<Vec<H264NalUnit>> {
let Some(&b0) = packet.first() else {
return Err(Error::ErrShortPacket);
};
let nalu_type = b0 & NALU_TYPE_BITMASK;
match nalu_type {
1..=23 => Ok(vec![H264NalUnit::plain(packet.clone())]),
STAPA_NALU_TYPE | STAPB_NALU_TYPE => {
let mut curr_offset = STAPA_HEADER_SIZE;
let mut don = if nalu_type == STAPB_NALU_TYPE {
if packet.len() < STAPB_HEADER_SIZE {
return Err(Error::ErrShortPacket);
}
curr_offset = STAPB_HEADER_SIZE;
Some(u16::from_be_bytes([packet[1], packet[2]]))
} else {
None
};
if curr_offset >= packet.len() {
return Err(Error::ErrShortPacket);
}
let mut units = vec![];
while curr_offset < packet.len() {
if packet.len() - curr_offset < STAPA_NALU_LENGTH_SIZE {
return Err(Error::ErrShortPacket);
}
let nalu_size =
((packet[curr_offset] as usize) << 8) | packet[curr_offset + 1] as usize;
curr_offset += STAPA_NALU_LENGTH_SIZE;
if packet.len() < curr_offset + nalu_size {
return Err(Error::StapASizeLargerThanBuffer(
nalu_size,
packet.len() - curr_offset,
));
}
let data = packet.slice(curr_offset..curr_offset + nalu_size);
curr_offset += nalu_size;
let unit_don = don;
don = don.map(|don| don.wrapping_add(1));
if data
.first()
.is_some_and(|b| is_nal_unit_type(b & NALU_TYPE_BITMASK))
{
units.push(H264NalUnit {
data,
don: unit_don,
timestamp_offset: None,
});
}
}
Ok(units)
}
MTAP16_NALU_TYPE | MTAP24_NALU_TYPE => {
let offset_size = if nalu_type == MTAP16_NALU_TYPE { 2 } else { 3 };
if packet.len() <= MTAP_HEADER_SIZE {
return Err(Error::ErrShortPacket);
}
let don_base = u16::from_be_bytes([packet[1], packet[2]]);
let mut curr_offset = MTAP_HEADER_SIZE;
let mut units = vec![];
while curr_offset < packet.len() {
let unit_header = STAPA_NALU_LENGTH_SIZE + 1 + offset_size;
if packet.len() - curr_offset < unit_header {
return Err(Error::ErrShortPacket);
}
let nalu_size =
((packet[curr_offset] as usize) << 8) | packet[curr_offset + 1] as usize;
let dond = packet[curr_offset + 2];
let timestamp_offset = packet[curr_offset + 3..curr_offset + unit_header]
.iter()
.fold(0u32, |offset, &b| (offset << 8) | u32::from(b));
curr_offset += unit_header;
if packet.len() < curr_offset + nalu_size {
return Err(Error::StapASizeLargerThanBuffer(
nalu_size,
packet.len() - curr_offset,
));
}
let data = packet.slice(curr_offset..curr_offset + nalu_size);
curr_offset += nalu_size;
if data
.first()
.is_some_and(|b| is_nal_unit_type(b & NALU_TYPE_BITMASK))
{
units.push(H264NalUnit {
data,
don: Some(don_base.wrapping_add(u16::from(dond))),
timestamp_offset: Some(timestamp_offset),
});
}
}
Ok(units)
}
FUA_NALU_TYPE | FUB_NALU_TYPE => {
if packet.len() < FUA_HEADER_SIZE {
return Err(Error::ErrShortPacket);
}
let b1 = packet[1];
let fragmented_nalu_type = b1 & NALU_TYPE_BITMASK;
let start = b1 & FU_START_BITMASK != 0;
let mut header_size = FUA_HEADER_SIZE;
if nalu_type == FUB_NALU_TYPE {
if !start || packet.len() < FUB_HEADER_SIZE {
self.fua_buffer = None;
self.fu_don = None;
return Err(Error::ErrShortPacket);
}
header_size = FUB_HEADER_SIZE;
}
if start {
if is_nal_unit_type(fragmented_nalu_type) {
self.fua_buffer = Some(BytesMut::new());
self.fu_don = (nalu_type == FUB_NALU_TYPE)
.then(|| u16::from_be_bytes([packet[2], packet[3]]));
} else {
self.fua_buffer = None;
self.fu_don = None;
}
}
let Some(fua_buffer) = &mut self.fua_buffer else {
return Ok(vec![]);
};
let fragment = &packet[header_size..];
if fua_buffer.len() + fragment.len() > MAX_FUA_NALU_SIZE {
self.fua_buffer = None;
self.fu_don = None;
return Err(Error::ErrShortPacket);
}
fua_buffer.put(fragment);
if b1 & FU_END_BITMASK == 0 {
return Ok(vec![]);
}
let mut data = BytesMut::with_capacity(1 + fua_buffer.len());
data.put_u8(
(b0 & (NALU_FORBIDDEN_BITMASK | NALU_REF_IDC_BITMASK)) | fragmented_nalu_type,
);
if let Some(fua_buffer) = self.fua_buffer.take() {
data.put(fua_buffer);
}
Ok(vec![H264NalUnit {
data: data.freeze(),
don: self.fu_don.take(),
timestamp_offset: None,
}])
}
_ => Ok(vec![]),
}
}
fn format(&self, units: &[H264NalUnit]) -> Bytes {
let mut payload =
BytesMut::with_capacity(units.iter().map(|unit| 4 + unit.data.len()).sum());
for unit in units {
if self.is_avc {
payload.put_u32(unit.data.len() as u32);
} else {
payload.put(&*ANNEXB_NALUSTART_CODE);
}
payload.put(&*unit.data);
}
payload.freeze()
}
}
impl Depacketizer for H264Packet {
fn depacketize(&mut self, packet: &Bytes) -> Result<Bytes> {
let mut units = self.nal_units(packet)?;
if let Some(buffer) = &mut self.deinterleaving {
units = units
.into_iter()
.flat_map(|unit| buffer.push(unit))
.collect();
}
Ok(self.format(&units))
}
fn is_partition_head(&self, payload: &Bytes) -> bool {
let Some(&b0) = payload.first() else {
return false;
};
if b0 & NALU_TYPE_BITMASK == FUA_NALU_TYPE || b0 & NALU_TYPE_BITMASK == FUB_NALU_TYPE {
payload
.get(1)
.is_some_and(|fu_header| fu_header & FU_START_BITMASK != 0)
} else {
true
}
}
fn is_partition_tail(&self, marker: bool, _payload: &Bytes) -> bool {
marker
}
fn has_key_frames(&self) -> bool {
true
}
fn is_key_frame_start(&self, payload: &Bytes) -> bool {
fn first_idr_slice(unit: &[u8]) -> bool {
unit.first()
.is_some_and(|header| header & NALU_TYPE_BITMASK == IDR_NALU_TYPE)
&& unit.get(1).is_some_and(|slice| slice & 0x80 != 0)
}
let Some(&b0) = payload.first() else {
return false;
};
match b0 & NALU_TYPE_BITMASK {
IDR_NALU_TYPE => first_idr_slice(payload),
kind @ (FUA_NALU_TYPE | FUB_NALU_TYPE) => {
let data = if kind == FUA_NALU_TYPE {
FUA_HEADER_SIZE
} else {
FUB_HEADER_SIZE
};
payload.get(1).is_some_and(|fu_header| {
fu_header & FU_START_BITMASK != 0
&& fu_header & NALU_TYPE_BITMASK == IDR_NALU_TYPE
}) && payload.get(data).is_some_and(|slice| slice & 0x80 != 0)
}
kind @ (STAPA_NALU_TYPE | STAPB_NALU_TYPE) => {
let mut offset = if kind == STAPA_NALU_TYPE {
STAPA_HEADER_SIZE
} else {
STAPB_HEADER_SIZE
};
while let Some(size) = payload.get(offset..offset + STAPA_NALU_LENGTH_SIZE) {
let size = usize::from(u16::from_be_bytes([size[0], size[1]]));
offset += STAPA_NALU_LENGTH_SIZE;
let Some(unit) = payload.get(offset..offset + size) else {
return false;
};
if first_idr_slice(unit) {
return true;
}
match unit.first().map(|header| header & NALU_TYPE_BITMASK) {
Some(SEI_NALU_TYPE | SPS_NALU_TYPE | PPS_NALU_TYPE | AUD_NALU_TYPE) => {}
_ => return false,
}
offset += size;
}
false
}
_ => false,
}
}
}