use bytes::Bytes;
use crate::{DemuxError, FourCc};
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct RawBox {
pub kind: FourCc,
pub header: usize,
pub bytes: Bytes,
}
impl RawBox {
pub fn payload(&self) -> &[u8] {
&self.bytes[self.header..]
}
}
pub(crate) fn children(data: &Bytes) -> Vec<RawBox> {
let mut found = Vec::new();
let mut at = 0_usize;
while data.len().saturating_sub(at) >= 8 {
let size = u64::from(u32::from_be_bytes([
data[at],
data[at + 1],
data[at + 2],
data[at + 3],
]));
let kind = FourCc([data[at + 4], data[at + 5], data[at + 6], data[at + 7]]);
let remaining = (data.len() - at) as u64;
let (size, header) = match size {
0 => (remaining, 8),
1 if remaining >= 16 => {
let mut wide = [0; 8];
wide.copy_from_slice(&data[at + 8..at + 16]);
(u64::from_be_bytes(wide), 16)
}
1 => break,
size => (size, 8),
};
if size < header as u64 {
break;
}
let size = usize::try_from(size.min(remaining)).unwrap_or(data.len() - at);
found.push(RawBox {
kind,
header,
bytes: data.slice(at..at + size),
});
at += size;
}
found
}
pub(crate) fn find<'a>(boxes: &'a [RawBox], kind: &[u8]) -> Option<&'a RawBox> {
boxes.iter().find(|child| child.kind.0 == kind)
}
fn truncated(what: &str) -> DemuxError {
DemuxError::Invalid(format!("the {what} box is truncated"))
}
pub(crate) struct Reader<'a> {
data: &'a [u8],
at: usize,
what: &'static str,
}
impl<'a> Reader<'a> {
pub fn new(data: &'a [u8], what: &'static str) -> Self {
Self { data, at: 0, what }
}
pub fn remaining(&self) -> usize {
self.data.len() - self.at
}
pub fn position(&self) -> usize {
self.at
}
pub fn rest(&self) -> &'a [u8] {
&self.data[self.at..]
}
pub fn bytes(&mut self, count: usize) -> Result<&'a [u8], DemuxError> {
let end = self
.at
.checked_add(count)
.filter(|end| *end <= self.data.len())
.ok_or_else(|| truncated(self.what))?;
let bytes = &self.data[self.at..end];
self.at = end;
Ok(bytes)
}
pub fn skip(&mut self, count: usize) -> Result<(), DemuxError> {
self.bytes(count).map(|_| ())
}
fn array<const N: usize>(&mut self) -> Result<[u8; N], DemuxError> {
let mut out = [0; N];
out.copy_from_slice(self.bytes(N)?);
Ok(out)
}
pub fn u8(&mut self) -> Result<u8, DemuxError> {
Ok(self.array::<1>()?[0])
}
pub fn u16(&mut self) -> Result<u16, DemuxError> {
Ok(u16::from_be_bytes(self.array()?))
}
pub fn u32(&mut self) -> Result<u32, DemuxError> {
Ok(u32::from_be_bytes(self.array()?))
}
pub fn i32(&mut self) -> Result<i32, DemuxError> {
Ok(i32::from_be_bytes(self.array()?))
}
pub fn u64(&mut self) -> Result<u64, DemuxError> {
Ok(u64::from_be_bytes(self.array()?))
}
pub fn i64(&mut self) -> Result<i64, DemuxError> {
Ok(i64::from_be_bytes(self.array()?))
}
pub fn fourcc(&mut self) -> Result<FourCc, DemuxError> {
Ok(FourCc(self.array()?))
}
pub fn version_flags(&mut self) -> Result<(u8, u32), DemuxError> {
let [version, flags @ ..] = self.array::<4>()?;
Ok((
version,
u32::from_be_bytes([0, flags[0], flags[1], flags[2]]),
))
}
}