use crate::error::{Error, Result};
use crate::reader::Reader;
pub const MAX_BOX_SIZE: u64 = 1 << 30;
#[derive(Debug, Clone, Copy)]
pub struct BoxHeader<'a> {
pub boxtype: [u8; 4],
pub payload: &'a [u8],
pub uuid: Option<[u8; 16]>,
pub offset: usize,
}
impl<'a> BoxHeader<'a> {
pub fn is(&self, code: &[u8; 4]) -> bool {
&self.boxtype == code
}
pub fn reader(&self) -> Reader<'a> {
Reader::new(self.payload)
}
pub fn children(&self) -> BoxIter<'a> {
BoxIter::new(self.payload)
}
pub fn full_box(&self, what: &'static str) -> Result<(u8, u32, Reader<'a>)> {
let mut r = self.reader();
let (version, flags) = r.full_box(what)?;
Ok((version, flags, r))
}
}
#[derive(Debug, Clone)]
pub struct BoxIter<'a> {
data: &'a [u8],
pos: usize,
done: bool,
}
impl<'a> BoxIter<'a> {
pub const fn new(data: &'a [u8]) -> Self {
BoxIter {
data,
pos: 0,
done: false,
}
}
pub fn find(self, code: &[u8; 4]) -> Result<Option<BoxHeader<'a>>> {
for b in self {
let b = b?;
if b.is(code) {
return Ok(Some(b));
}
}
Ok(None)
}
pub fn require(self, code: &[u8; 4], name: &'static str) -> Result<BoxHeader<'a>> {
self.find(code)?.ok_or(Error::MissingBox(name))
}
fn next_box(&mut self) -> Result<Option<BoxHeader<'a>>> {
if self.pos >= self.data.len() {
return Ok(None);
}
let start = self.pos;
let mut r = Reader::new(&self.data[start..]);
let size32 = r.u32("box size")?;
let boxtype = r.fourcc("box type")?;
let total: u64 = match size32 {
1 => r.u64("box largesize")?,
0 => (self.data.len() - start) as u64,
n => u64::from(n),
};
let uuid = if boxtype == *b"uuid" {
let b = r.take(16, "uuid")?;
let mut u = [0u8; 16];
u.copy_from_slice(b);
Some(u)
} else {
None
};
let header_len = r.position();
if total < header_len as u64 {
return Err(Error::Malformed("box size is smaller than its own header"));
}
if total > MAX_BOX_SIZE {
return Err(Error::BoxTooLarge {
boxtype,
size: total,
});
}
let total = total as usize;
let end = start
.checked_add(total)
.ok_or(Error::Truncated("box body"))?;
if end > self.data.len() {
return Err(Error::Truncated("box body"));
}
let payload = &self.data[start + header_len..end];
self.pos = end;
Ok(Some(BoxHeader {
boxtype,
payload,
uuid,
offset: start,
}))
}
}
impl<'a> Iterator for BoxIter<'a> {
type Item = Result<BoxHeader<'a>>;
fn next(&mut self) -> Option<Self::Item> {
if self.done {
return None;
}
match self.next_box() {
Ok(Some(b)) => Some(Ok(b)),
Ok(None) => {
self.done = true;
None
}
Err(e) => {
self.done = true;
Some(Err(e))
}
}
}
}