use bytes::{Bytes, BytesMut};
use shared::error::{Error, Result};
use std::io::Read;
use super::H26xReader;
#[cfg(test)]
#[path = "sample_reader_bound_test.rs"]
mod sample_reader_bound_test;
const ANNEXB_START_CODE: [u8; 4] = [0x00, 0x00, 0x00, 0x01];
pub const MAX_ACCESS_UNIT_NALS: usize = 4096;
pub const MAX_ACCESS_UNIT_BYTES: usize = 32 * 1024 * 1024;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct H26xSample {
pub data: Bytes,
pub timed: bool,
}
pub struct H26xSampleReader<R: Read> {
reader: H26xReader<R>,
is_hevc: bool,
pending: Vec<BytesMut>,
pending_has_vcl: bool,
pending_bytes: usize,
}
impl<R: Read> H26xSampleReader<R> {
pub fn new(reader: R, capacity: usize, is_hevc: bool) -> Self {
Self {
reader: H26xReader::new(reader, capacity, is_hevc),
is_hevc,
pending: vec![],
pending_has_vcl: false,
pending_bytes: 0,
}
}
pub fn next_sample(&mut self) -> Result<H26xSample> {
loop {
let nal = match self.reader.next_nal() {
Ok(nal) => nal,
Err(Error::ErrIoEOF) if !self.pending.is_empty() => {
return Ok(self.take_access_unit());
}
Err(err) => return Err(err),
};
let data = nal.data();
if data.is_empty() {
continue;
}
let vcl = is_vcl(self.is_hevc, data);
if self.pending_has_vcl && starts_access_unit(self.is_hevc, data) {
let sample = self.take_access_unit();
self.pending_bytes = data.len();
self.pending.push(data.clone());
self.pending_has_vcl = vcl;
return Ok(sample);
}
if self.pending.len() >= MAX_ACCESS_UNIT_NALS
|| self.pending_bytes.saturating_add(data.len()) > MAX_ACCESS_UNIT_BYTES
{
self.pending.clear();
self.pending_has_vcl = false;
self.pending_bytes = 0;
return Err(Error::ErrBufferFull);
}
self.pending_bytes += data.len();
self.pending.push(data.clone());
self.pending_has_vcl |= vcl;
}
}
fn take_access_unit(&mut self) -> H26xSample {
let timed = self.pending_has_vcl;
self.pending_has_vcl = false;
self.pending_bytes = 0;
H26xSample {
data: build_access_unit(&mut self.pending),
timed,
}
}
}
fn is_vcl(is_hevc: bool, nal: &[u8]) -> bool {
if is_hevc {
(nal[0] >> 1) & 0x3f <= 31
} else {
(1..=5).contains(&(nal[0] & 0x1f))
}
}
fn starts_access_unit(is_hevc: bool, nal: &[u8]) -> bool {
if is_hevc {
let unit_type = (nal[0] >> 1) & 0x3f;
match unit_type {
32..=35 | 39 | 41..=44 | 48..=55 => true,
0..=31 => nal.get(2).is_some_and(|b| b & 0x80 != 0),
_ => false,
}
} else {
let unit_type = nal[0] & 0x1f;
match unit_type {
6..=9 | 14..=18 => true,
1 | 2 | 5 => nal.get(1).is_some_and(|b| b & 0x80 != 0),
_ => false,
}
}
}
fn build_access_unit(nals: &mut Vec<BytesMut>) -> Bytes {
let total_len = nals
.iter()
.map(|nal| ANNEXB_START_CODE.len() + nal.len())
.sum::<usize>();
let mut access_unit = BytesMut::with_capacity(total_len);
for nal in nals.drain(..) {
access_unit.extend_from_slice(&ANNEXB_START_CODE);
access_unit.extend_from_slice(&nal);
}
access_unit.freeze()
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
const SC: [u8; 4] = [0x00, 0x00, 0x00, 0x01];
fn annex_b(nals: &[&[u8]]) -> Vec<u8> {
let mut out = vec![];
for nal in nals {
out.extend_from_slice(&SC);
out.extend_from_slice(nal);
}
out
}
#[test]
fn h265_sample_reader_groups_parameter_sets_with_following_vcl() -> Result<()> {
let nals: [&[u8]; 4] = [
&[0x40, 0x01, 0x01],
&[0x42, 0x01, 0x02],
&[0x44, 0x01, 0x03],
&[0x28, 0x01, 0xaa],
];
let mut reader = H26xSampleReader::new(Cursor::new(annex_b(&nals)), 1024, true);
let sample = reader.next_sample()?;
assert!(sample.timed);
assert_eq!(sample.data, Bytes::from(annex_b(&nals)));
assert!(matches!(reader.next_sample(), Err(Error::ErrIoEOF)));
Ok(())
}
#[test]
fn h264_sample_reader_returns_whole_access_units() -> Result<()> {
let sps: &[u8] = &[0x67, 0x42, 0x00, 0x1f];
let pps: &[u8] = &[0x68, 0xce, 0x06, 0xe2];
let idr1: &[u8] = &[0x65, 0x88, 0x84, 0x21];
let idr2: &[u8] = &[0x65, 0x40, 0x84, 0x21];
let p1: &[u8] = &[0x41, 0x9a, 0x02, 0x03];
let stream = annex_b(&[sps, pps, idr1, idr2, p1]);
let mut reader = H26xSampleReader::new(Cursor::new(stream), 1024, false);
let first = reader.next_sample()?;
assert!(first.timed);
assert_eq!(first.data, Bytes::from(annex_b(&[sps, pps, idr1, idr2])));
let second = reader.next_sample()?;
assert!(second.timed);
assert_eq!(second.data, Bytes::from(annex_b(&[p1])));
assert!(matches!(reader.next_sample(), Err(Error::ErrIoEOF)));
Ok(())
}
#[test]
fn parameter_sets_alone_are_untimed() -> Result<()> {
let sps: &[u8] = &[0x67, 0x42, 0x00, 0x1f];
let pps: &[u8] = &[0x68, 0xce, 0x06, 0xe2];
let mut reader = H26xSampleReader::new(Cursor::new(annex_b(&[sps, pps])), 1024, false);
let sample = reader.next_sample()?;
assert!(!sample.timed);
assert_eq!(sample.data, Bytes::from(annex_b(&[sps, pps])));
Ok(())
}
#[test]
fn h264_slices_of_one_picture_advance_time_once() -> Result<()> {
let idr1: &[u8] = &[0x65, 0x88, 0x84]; let idr2: &[u8] = &[0x65, 0x40, 0x84]; let p1: &[u8] = &[0x41, 0x9a, 0x02]; let p2: &[u8] = &[0x41, 0x20, 0x02]; let stream = annex_b(&[idr1, idr2, p1, p2]);
let mut reader = H26xSampleReader::new(Cursor::new(stream), 1024, false);
let first = reader.next_sample()?;
assert!(first.timed);
assert_eq!(first.data, Bytes::from(annex_b(&[idr1, idr2])));
let second = reader.next_sample()?;
assert!(second.timed);
assert_eq!(second.data, Bytes::from(annex_b(&[p1, p2])));
assert!(matches!(reader.next_sample(), Err(Error::ErrIoEOF)));
Ok(())
}
}