use crate::{Error, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Jp2Box<'a> {
pub(crate) kind: [u8; 4],
pub(crate) payload: &'a [u8],
}
impl Jp2Box<'_> {
pub(crate) fn name(&self) -> String {
type_name(self.kind)
}
}
pub(crate) fn type_name(kind: [u8; 4]) -> String {
kind.iter()
.flat_map(|&b| std::ascii::escape_default(b))
.map(char::from)
.collect()
}
pub(crate) struct Boxes<'a> {
data: &'a [u8],
pos: usize,
open_ended: bool,
parent: &'static str,
done: bool,
last_open_ended: bool,
}
impl<'a> Boxes<'a> {
pub(crate) fn top_level(file: &'a [u8], start: usize) -> Self {
Boxes {
data: file,
pos: start,
open_ended: true,
parent: "the file",
done: false,
last_open_ended: false,
}
}
pub(crate) fn children(payload: &'a [u8], parent: &'static str) -> Self {
Boxes {
data: payload,
pos: 0,
open_ended: false,
parent,
done: false,
last_open_ended: false,
}
}
pub(crate) fn rest(&self) -> &'a [u8] {
self.data.get(self.pos..).unwrap_or_default()
}
pub(crate) fn last_was_open_ended(&self) -> bool {
self.last_open_ended
}
fn read(&mut self) -> Result<Jp2Box<'a>> {
let rest = self.data.get(self.pos..).unwrap_or_default();
let (lbox, kind) = match rest {
[a, b, c, d, t0, t1, t2, t3, ..] => {
(u32::from_be_bytes([*a, *b, *c, *d]), [*t0, *t1, *t2, *t3])
}
_ => {
return Err(Error::FileFormat(format!(
"a box header needs 8 bytes but {} remain in {}",
rest.len(),
self.parent
)));
}
};
let name = type_name(kind);
self.last_open_ended = lbox == 0;
let codestream = self.open_ended && &kind == b"jp2c";
let (length, header): (u64, usize) = match lbox {
0 if self.open_ended => (rest.len() as u64, 8),
0 => {
return Err(Error::FileFormat(format!(
"box `{name}` in {} has length 0 (to the end of the file), which only the \
last box of the file may use",
self.parent
)));
}
1 => {
let Some(xl) = rest.get(8..16) else {
return Err(Error::FileFormat(format!(
"box `{name}` has a 64-bit length but its `XLBox` field is truncated"
)));
};
let mut be = [0u8; 8];
be.copy_from_slice(xl);
let xlbox = u64::from_be_bytes(be);
match xlbox {
0..16 if codestream => (rest.len() as u64, 16),
0..16 => {
return Err(Error::FileFormat(format!(
"box `{name}` has `XLBox` {xlbox}, shorter than its 16-byte header"
)));
}
_ => (xlbox, 16),
}
}
2..=7 if codestream => (rest.len() as u64, 8),
2..=7 => {
return Err(Error::FileFormat(format!(
"box `{name}` has length {lbox}, shorter than its 8-byte header"
)));
}
n => (u64::from(n), 8),
};
let length = if codestream {
length.min(rest.len() as u64)
} else {
length
};
if length > rest.len() as u64 {
return Err(Error::FileFormat(format!(
"box `{name}` is {length} bytes but only {} remain in {}",
rest.len(),
self.parent
)));
}
let length = length as usize;
let payload = rest.get(header..length).ok_or_else(|| {
Error::Inconsistent(format!("box `{name}` bounds checked but not sliceable"))
})?;
self.pos = self
.pos
.checked_add(length)
.ok_or_else(|| Error::Inconsistent("box offset overflow".into()))?;
Ok(Jp2Box { kind, payload })
}
}
impl<'a> Iterator for Boxes<'a> {
type Item = Result<Jp2Box<'a>>;
fn next(&mut self) -> Option<Self::Item> {
if self.done || self.pos >= self.data.len() {
return None;
}
let item = self.read();
self.done = item.is_err();
Some(item)
}
}
pub(crate) const READ_BY_OPENJPEG: [&[u8; 4]; 9] = [
b"jP ", b"ftyp", b"jp2h", b"ihdr", b"colr", b"bpcc", b"pclr", b"cmap", b"cdef",
];
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct AfterCodestream<'a> {
pub(crate) boxes: Vec<Jp2Box<'a>>,
pub(crate) fault: Option<Error>,
}
pub(crate) fn walk_after_codestream(mut rest: &[u8]) -> AfterCodestream<'_> {
let mut boxes = Vec::new();
let fault = loop {
let [a, b, c, d, t0, t1, t2, t3, ..] = *rest else {
break None;
};
let lbox = u32::from_be_bytes([a, b, c, d]);
let kind = [t0, t1, t2, t3];
let (length, header) = match lbox {
0 => match u32::try_from(rest.len()) {
Ok(length) => (length, 8),
Err(_) => break None,
},
1 => match rest.get(8..16) {
Some(&[0, 0, 0, 0, l0, l1, l2, l3]) => (u32::from_be_bytes([l0, l1, l2, l3]), 16),
_ => break None,
},
n => (n, 8),
};
if &kind == b"jp2c" {
break None;
}
if (length as usize) < header {
let field = if lbox == 1 { "`XLBox`" } else { "length" };
break Some(Error::FileFormat(format!(
"box `{}` after the codestream has {field} {length}, shorter than its \
{header}-byte header",
type_name(kind)
)));
}
let Some(payload) = rest.get(header..length as usize) else {
if READ_BY_OPENJPEG.contains(&&kind) {
break Some(Error::FileFormat(format!(
"box `{}` after the codestream is {length} bytes but only {} remain in \
the file",
type_name(kind),
rest.len()
)));
}
break None;
};
boxes.push(Jp2Box { kind, payload });
rest = rest.get(length as usize..).unwrap_or_default();
};
AfterCodestream { boxes, fault }
}