use super::boxes::{Boxes, Jp2Box, type_name};
use super::metadata::FileType;
use crate::{Error, Result};
const JP2_BRAND: [u8; 4] = *b"jp2 ";
pub(crate) fn check_file_type(ftyp: &Jp2Box<'_>) -> Result<FileType> {
let payload = ftyp.payload;
if payload.len() < 8 || !payload.len().is_multiple_of(4) {
return Err(Error::FileFormat(format!(
"the `ftyp` box holds {} bytes; it needs a brand, a version, and whole \
4-byte compatibility codes",
payload.len()
)));
}
let brand = [payload[0], payload[1], payload[2], payload[3]];
let minor_version = u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]);
let compatibility: Vec<[u8; 4]> = payload[8..]
.chunks_exact(4)
.map(|code| [code[0], code[1], code[2], code[3]])
.collect();
let compatible = brand == JP2_BRAND || compatibility.contains(&JP2_BRAND);
if !compatible {
return Err(Error::Unsupported(format!(
"file brand `{}` without `jp2 ` compatibility (a JPX, JPM or MJ2 file that \
does not claim to be readable as JP2)",
type_name(brand)
)));
}
Ok(FileType {
brand,
minor_version,
compatibility,
})
}
const MAX_COMPONENTS: u16 = 16384;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Ihdr {
pub(crate) height: u32,
pub(crate) width: u32,
pub(crate) components: u16,
pub(crate) bits_per_component: u8,
pub(crate) compression: u8,
pub(crate) unknown_colorspace: u8,
pub(crate) ipr: u8,
}
impl Ihdr {
fn parse(payload: &[u8]) -> Result<Self> {
let &[h0, h1, h2, h3, w0, w1, w2, w3, n0, n1, bpc, c, unk_c, ipr] = payload else {
return Err(Error::FileFormat(format!(
"the `ihdr` box holds {} bytes, not 14",
payload.len()
)));
};
let (height, width) = (
u32::from_be_bytes([h0, h1, h2, h3]),
u32::from_be_bytes([w0, w1, w2, w3]),
);
let components = u16::from_be_bytes([n0, n1]);
if height == 0 || width == 0 || components == 0 {
return Err(Error::FileFormat(format!(
"the `ihdr` box declares a {width}x{height} image of {components} components; \
none may be 0"
)));
}
if components > MAX_COMPONENTS {
return Err(Error::FileFormat(format!(
"the `ihdr` box declares {components} components; a file holds at most \
{MAX_COMPONENTS}"
)));
}
Ok(Ihdr {
height,
width,
components,
bits_per_component: bpc,
compression: c,
unknown_colorspace: unk_c,
ipr,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Jp2Header<'a> {
pub(crate) ihdr: Ihdr,
pub(crate) ihdr_at: usize,
pub(crate) children: Vec<Jp2Box<'a>>,
}
impl<'a> Jp2Header<'a> {
pub(crate) fn parse(payload: &'a [u8]) -> Result<Self> {
Self::read(payload, None)
}
pub(crate) fn merge(self, payload: &'a [u8]) -> Result<Self> {
Self::read(payload, Some(self))
}
pub(crate) fn add_misplaced(&mut self, item: Jp2Box<'a>) -> bool {
match &item.kind {
b"ihdr" => true,
b"bpcc" | b"colr" | b"pclr" | b"cmap" | b"cdef" => {
self.children.push(item);
true
}
_ => false,
}
}
fn read(payload: &'a [u8], previous: Option<Self>) -> Result<Self> {
let mut known = previous
.as_ref()
.map(|header| (header.ihdr, header.ihdr_at));
let mut has_ihdr = false;
let mut children = previous.map(|header| header.children).unwrap_or_default();
for child in Boxes::children(payload, "the `jp2h` box") {
let child = child?;
if &child.kind == b"ihdr" {
has_ihdr = true;
if known.is_none() {
known = Some((Ihdr::parse(child.payload)?, children.len()));
}
} else {
children.push(child);
}
}
match known {
Some((ihdr, ihdr_at)) if has_ihdr => Ok(Jp2Header {
ihdr,
ihdr_at,
children,
}),
_ => Err(Error::FileFormat("a `jp2h` box has no `ihdr` box".into())),
}
}
fn payloads(&self, kind: &[u8; 4]) -> Vec<&'a [u8]> {
self.children
.iter()
.filter(|child| &child.kind == kind)
.map(|child| child.payload)
.collect()
}
pub(crate) fn colr(&self) -> Vec<&'a [u8]> {
self.payloads(b"colr")
}
pub(crate) fn pclr(&self) -> Vec<&'a [u8]> {
self.payloads(b"pclr")
}
pub(crate) fn cmap(&self) -> Vec<&'a [u8]> {
self.payloads(b"cmap")
}
pub(crate) fn cdef(&self) -> Vec<&'a [u8]> {
self.payloads(b"cdef")
}
#[cfg(test)]
pub(crate) fn bpcc(&self) -> Vec<&'a [u8]> {
self.payloads(b"bpcc")
}
pub(crate) fn res(&self) -> Vec<&'a [u8]> {
self.payloads(b"res ")
}
#[cfg(test)]
pub(crate) fn unknown(&self) -> Vec<&Jp2Box<'a>> {
self.children
.iter()
.filter(|child| {
!matches!(
&child.kind,
b"bpcc" | b"colr" | b"pclr" | b"cmap" | b"cdef" | b"res "
)
})
.collect()
}
}