use alloc::vec::Vec;
use crate::boxes::{BoxHeader, BoxIter};
use crate::error::{Error, Result};
#[derive(Debug, Clone, Copy)]
pub struct Association {
pub index: u16,
pub essential: bool,
}
#[derive(Debug, Clone)]
pub struct Properties<'a> {
pub boxes: Vec<BoxHeader<'a>>,
pub assoc: Vec<(u32, Vec<Association>)>,
}
impl<'a> Properties<'a> {
pub fn empty() -> Self {
Properties {
boxes: Vec::new(),
assoc: Vec::new(),
}
}
pub fn associations(&self, item: u32) -> &[Association] {
for (id, list) in &self.assoc {
if *id == item {
return list;
}
}
&[]
}
pub fn resolve(&self, a: Association) -> Option<&BoxHeader<'a>> {
if a.index == 0 {
return None;
}
self.boxes.get(usize::from(a.index) - 1)
}
pub fn find(&self, item: u32, code: &[u8; 4]) -> Option<&BoxHeader<'a>> {
self.associations(item)
.iter()
.filter_map(|a| self.resolve(*a))
.find(|b| b.is(code))
}
pub fn find_all(
&self,
item: u32,
code: &'static [u8; 4],
) -> impl Iterator<Item = &BoxHeader<'a>> {
self.associations(item)
.iter()
.filter_map(|a| self.resolve(*a))
.filter(move |b| b.is(code))
}
pub fn unknown_essential(&self, item: u32) -> Option<[u8; 4]> {
const KNOWN: [&[u8; 4]; 9] = [
b"hvcC", b"ispe", b"pixi", b"colr", b"irot", b"imir", b"clap", b"auxC", b"pasp",
];
for a in self.associations(item) {
if !a.essential {
continue;
}
let Some(b) = self.resolve(*a) else { continue };
if !KNOWN.iter().any(|k| b.is(k)) {
return Some(b.boxtype);
}
}
None
}
}
pub fn parse<'a>(b: &BoxHeader<'a>) -> Result<Properties<'a>> {
let mut boxes = Vec::new();
let mut assoc: Vec<(u32, Vec<Association>)> = Vec::new();
for child in b.children() {
let child = child?;
if child.is(b"ipco") {
for p in child.children() {
boxes.push(p?);
}
} else if child.is(b"ipma") {
parse_ipma(&child, &mut assoc)?;
}
}
Ok(Properties { boxes, assoc })
}
fn parse_ipma(b: &BoxHeader<'_>, out: &mut Vec<(u32, Vec<Association>)>) -> Result<()> {
let (version, flags, mut r) = b.full_box("ipma")?;
let wide_index = flags & 1 != 0;
let entry_count = r.u32("ipma entry count")?;
if entry_count as usize > r.remaining() / 3 + 1 {
return Err(Error::Malformed("ipma declares more entries than can fit"));
}
for _ in 0..entry_count {
let item = if version < 1 {
u32::from(r.u16("ipma item id")?)
} else {
r.u32("ipma item id")?
};
let count = r.u8("ipma association count")?;
let mut list = Vec::with_capacity(usize::from(count));
for _ in 0..count {
let (essential, index) = if wide_index {
let w = r.u16("ipma association")?;
(w & 0x8000 != 0, w & 0x7fff)
} else {
let w = r.u8("ipma association")?;
(w & 0x80 != 0, u16::from(w & 0x7f))
};
list.push(Association { index, essential });
}
match out.iter_mut().find(|(id, _)| *id == item) {
Some((_, existing)) => existing.extend_from_slice(&list),
None => out.push((item, list)),
}
}
Ok(())
}
pub fn ipco_boxes(data: &[u8]) -> BoxIter<'_> {
BoxIter::new(data)
}