use super::Jp2File;
use super::boxes::{Boxes, Jp2Box};
use super::{channels, color, palette};
use crate::codestream::markers::marker::{EOC, SOC, SOT};
use crate::{Error, Result};
const MIN_TILE_PART: u32 = 14;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum End {
At(usize),
OpenLastPart(u16),
Unknown,
}
pub(crate) fn codestream_end(bytes: &[u8]) -> End {
let marker = |at: usize| {
bytes
.get(at..at.checked_add(2)?)
.map(|b| u16::from_be_bytes([b[0], b[1]]))
};
if marker(0) != Some(SOC) {
return End::Unknown;
}
let mut at = 2usize;
loop {
match marker(at) {
Some(SOT) => break,
Some(code) if code >> 8 == 0xFF => {
let Some(length) = marker(at + 2).filter(|&length| length >= 2) else {
return End::Unknown;
};
at += 2 + usize::from(length);
}
_ => return End::Unknown,
}
}
loop {
let Some(&[p0, p1, p2, p3]) = at.checked_add(6).and_then(|from| bytes.get(from..from + 4))
else {
return End::Unknown;
};
let psot = u32::from_be_bytes([p0, p1, p2, p3]);
if psot == 0 {
let isot = u16::from_be_bytes([bytes[at + 4], bytes[at + 5]]);
return End::OpenLastPart(isot);
}
if psot < MIN_TILE_PART {
return End::Unknown;
}
let Some(end) = usize::try_from(psot)
.ok()
.and_then(|psot| at.checked_add(psot))
else {
return End::Unknown;
};
match marker(end) {
Some(EOC) => return End::At(end + 2),
Some(SOT) => at = end,
_ => return End::Unknown,
}
}
}
struct State {
components: usize,
has_color: bool,
palette: Option<usize>,
mapped: bool,
channel_definitions: bool,
}
impl State {
fn after_decode(file: &Jp2File<'_>, raw_channels: bool) -> Self {
let header = &file.header;
let mapped = !header.cmap().is_empty();
let palette = header
.pclr()
.first()
.and_then(|pclr| pclr.get(2))
.filter(|_| mapped || raw_channels)
.map(|&npc| usize::from(npc));
State {
components: usize::from(header.ihdr.components),
has_color: header
.colr()
.iter()
.any(|colr| matches!(colr.first(), Some(1 | 2))),
mapped: palette.is_some() && mapped,
palette,
channel_definitions: raw_channels && !header.cdef().is_empty(),
}
}
fn read(&mut self, item: &Jp2Box<'_>) -> Result<()> {
let payload = item.payload;
match &item.kind {
b"colr" => {
if payload.len() < 3 {
return Err(fault(format!(
"a `colr` box holds {} bytes; it needs at least 3",
payload.len()
)));
}
if !self.has_color {
self.has_color = color::parse_usable(payload).map_err(context)?.is_some();
}
}
b"bpcc" => {
if payload.len() != self.components {
return Err(fault(format!(
"a `bpcc` box holds {} bytes; it needs one per component ({})",
payload.len(),
self.components
)));
}
}
b"pclr" => {
if self.palette.is_some() {
return Err(fault("the file has a second `pclr` box"));
}
let columns = palette::Palette::parse(payload)
.map_err(context)?
.columns()
.len();
self.palette = Some(columns);
self.mapped = false;
}
b"cmap" => {
let Some(columns) = self.palette else {
return Err(fault(
"the file has a `cmap` box with no `pclr` box before it",
));
};
if self.mapped {
return Err(fault("the file has a second `cmap` box"));
}
if payload.len() < columns * 4 {
return Err(fault(format!(
"the `cmap` box holds {} bytes; mapping {columns} palette columns needs {}",
payload.len(),
columns * 4
)));
}
self.mapped = true;
}
b"cdef" => {
if self.channel_definitions {
return Err(fault("the file has a second `cdef` box"));
}
channels::check_layout(payload).map_err(context)?;
self.channel_definitions = true;
}
_ => {}
}
Ok(())
}
}
fn fault(message: impl core::fmt::Display) -> Error {
Error::file_format(format!("after the codestream, {message}"))
}
fn context(error: Error) -> Error {
match error {
Error::FileFormat(message) => fault(message),
other => other,
}
}
pub(crate) fn check(file: &Jp2File<'_>, raw_channels: bool) -> Result<()> {
if !file.after_read {
return Ok(());
}
let mut state = State::after_decode(file, raw_channels);
for item in &file.after_codestream {
match &item.kind {
b"jP " => {
return Err(fault(
"the file has a signature box, which must be the first box",
));
}
b"ftyp" => {
return Err(fault(
"the file has an `ftyp` box, which must be the second box",
));
}
b"ihdr" => {}
b"jp2h" => {
let mut has_ihdr = false;
for child in Boxes::children(item.payload, "a `jp2h` box after the codestream") {
let child = child?;
if &child.kind == b"ihdr" {
has_ihdr = true;
} else {
state.read(&child)?;
}
}
if !has_ihdr {
return Err(fault("a `jp2h` box has no `ihdr` box"));
}
}
_ => state.read(item)?,
}
}
match &file.after_fault {
Some(error) => Err(error.clone()),
None => Ok(()),
}
}