use super::header::Jp2Header;
use super::metadata::ColorSpace;
use crate::{Error, Result};
const ENUMERATED: u8 = 1;
const RESTRICTED_ICC: u8 = 2;
pub(crate) fn check_bpcc(header: &Jp2Header<'_>) -> Result<()> {
for (at, child) in header.children.iter().enumerate() {
if &child.kind != b"bpcc" {
continue;
}
let before_ihdr = at < header.ihdr_at;
let components = if before_ihdr {
0
} else {
usize::from(header.ihdr.components)
};
if child.payload.len() != components {
return Err(Error::FileFormat(format!(
"a `bpcc` box holds {} bytes; it needs one per component ({components}{})",
child.payload.len(),
if before_ihdr {
", as `ihdr` has not been read yet"
} else {
""
}
)));
}
}
Ok(())
}
pub(crate) fn read(header: &Jp2Header<'_>) -> Result<ColorSpace> {
let mut first = None;
for payload in header.colr() {
if payload.len() < 3 {
return Err(Error::FileFormat(format!(
"a `colr` box holds {} bytes; it needs at least 3 (`METH`, `PREC`, `APPROX`)",
payload.len()
)));
}
if first.is_none() {
first = parse_usable(payload)?;
}
}
Ok(first.unwrap_or(ColorSpace::Unknown))
}
pub(super) fn parse_usable(payload: &[u8]) -> Result<Option<ColorSpace>> {
let method = payload[0];
let rest = &payload[3..];
match method {
ENUMERATED => {
let Some(&[a, b, c, d]) = rest.first_chunk::<4>() else {
return Err(Error::FileFormat(format!(
"a `colr` box with `METH` 1 holds {} bytes; it needs 7 for the \
enumerated color space",
payload.len()
)));
};
Ok(Some(match u32::from_be_bytes([a, b, c, d]) {
16 => ColorSpace::Srgb,
17 => ColorSpace::Grayscale,
18 => ColorSpace::Sycc,
other => ColorSpace::Enumerated(other),
}))
}
RESTRICTED_ICC => {
if rest.is_empty() {
return Err(Error::FileFormat(
"a `colr` box with `METH` 2 holds no ICC profile".into(),
));
}
Ok(Some(ColorSpace::RestrictedIcc(rest.to_vec())))
}
_ => Ok(None),
}
}