mod after;
mod boxes;
mod channels;
mod color;
mod header;
mod lcms;
mod math;
mod math_data;
mod metadata;
mod palette;
mod resolution;
mod rreq;
mod srgb;
mod uuid_info;
#[cfg(test)]
mod color_tests;
#[cfg(test)]
mod math_tests;
#[cfg(test)]
mod srgb_tests;
#[cfg(test)]
mod tests;
pub(crate) use after::check as check_after_codestream;
pub use metadata::{
Association, ChannelDefinition, ChannelDefinitionEntry, ChannelType, ColorSpace,
ColorSpecification, FileType, ImageHeader, IprBox, Jp2Metadata, Ratio, ReaderRequirements, Res,
Resolution, StandardFeature, UuidBox, UuidInfo, VendorFeature, XmlBox,
};
pub use palette::{ChannelMapping, MappingKind, Palette, PaletteColumn};
use crate::codestream::markers::Siz;
use crate::{Component, ComponentInfo, Error, Result, WorkLimit};
use after::End;
use boxes::{Boxes, Jp2Box, walk_after_codestream};
use channels::ChannelPlan;
use header::{Jp2Header, check_file_type};
use palette::PalettePlan;
pub(crate) use srgb::SrgbPlan;
pub(crate) const SIGNATURE: [u8; 12] = [
0x00, 0x00, 0x00, 0x0C, b'j', b'P', b' ', b' ', 0x0D, 0x0A, 0x87, 0x0A,
];
pub(crate) fn looks_like_jp2(bytes: &[u8]) -> bool {
bytes.get(4..8) == Some(&SIGNATURE[4..8])
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Jp2File<'a> {
pub(crate) file_type: FileType,
pub(crate) header: Jp2Header<'a>,
pub(crate) color: ColorSpace,
pub(crate) codestream: &'a [u8],
pub(crate) other: Vec<Jp2Box<'a>>,
pub(crate) after_codestream: Vec<Jp2Box<'a>>,
pub(crate) after_box: Vec<Jp2Box<'a>>,
pub(crate) after_read: bool,
pub(crate) after_fault: Option<Error>,
}
pub(crate) fn parse<'a>(bytes: &'a [u8], packet_work: &WorkLimit) -> Result<Jp2File<'a>> {
if !bytes.starts_with(&SIGNATURE) {
return Err(Error::FileFormat(
"the file must open with the 12-byte JP2 signature box (`jP ` holding \
0D 0A 87 0A)"
.into(),
));
}
let mut boxes = Boxes::top_level(bytes, SIGNATURE.len());
let file_type = match boxes.next().transpose()? {
Some(ftyp) if &ftyp.kind == b"ftyp" => check_file_type(&ftyp)?,
Some(other) => {
return Err(Error::FileFormat(format!(
"the `ftyp` box must follow the signature, not `{}`",
other.name()
)));
}
None => {
return Err(Error::FileFormat(
"the file ends after the signature box".into(),
));
}
};
let mut header: Option<Jp2Header<'_>> = None;
let mut other = Vec::new();
let mut open_ended = false;
while let Some(item) = boxes.next() {
let item = item?;
open_ended = boxes.last_was_open_ended();
match &item.kind {
b"jp2h" => {
header = Some(match header {
None => Jp2Header::parse(item.payload)?,
Some(first) => first.merge(item.payload)?,
});
}
b"jp2c" => {
let Some(header) = header else {
return Err(Error::FileFormat(
"the file has no `jp2h` header box before its `jp2c` codestream box".into(),
));
};
color::check_bpcc(&header)?;
let color = color::read(&header)?;
let (codestream, rest, after_read) =
locate_codestream(bytes, item.payload, boxes.rest(), packet_work);
let after = walk_after_codestream(rest);
let past_box = boxes.rest();
let after_box = if past_box.len() < rest.len() {
walk_after_codestream(past_box).boxes
} else {
after.boxes.clone()
};
return Ok(Jp2File {
file_type,
header,
color,
codestream,
other,
after_codestream: after.boxes,
after_box,
after_read,
after_fault: after.fault,
});
}
_ => {
let taken = header
.as_mut()
.is_some_and(|header| header.add_misplaced(item));
if !taken {
other.push(item);
}
}
}
}
let missing = match header {
None => "the file has no `jp2h` header box and no `jp2c` codestream box",
Some(_) => "the file has no `jp2c` codestream box",
};
Err(Error::FileFormat(if open_ended {
format!("{missing}: a box of length 0 (to the end of the file) swallowed the rest")
} else {
missing.into()
}))
}
fn locate_codestream<'a>(
file: &'a [u8],
payload: &'a [u8],
rest: &'a [u8],
packet_work: &WorkLimit,
) -> (&'a [u8], &'a [u8], bool) {
let tail = file
.len()
.checked_sub(rest.len() + payload.len())
.and_then(|start| file.get(start..));
let Some(tail) = tail else {
return (payload, rest, false);
};
match after::codestream_end(tail) {
End::At(end) => (&tail[..end], &tail[end..], true),
End::OpenLastPart(_) if payload.ends_with(&[0xFF, 0xD9]) => (payload, rest, false),
End::OpenLastPart(tile)
if matches!(after::codestream_end(payload), End::OpenLastPart(_)) =>
{
match tail.get(..payload.len() + 2) {
Some(cut) if packets_end_at(cut, tile, packet_work) => (cut, rest, false),
_ => (tail, &[], false),
}
}
End::OpenLastPart(_) => (tail, &[], false),
End::Unknown => (payload, rest, false),
}
}
const PROBE_GEOMETRY: usize = 1 << 14;
const PROBE_TILES: usize = 1 << 12;
const PROBE_COMPONENTS: usize = 1 << 10;
const PROBE_VISITS_MIN: u64 = 1 << 22;
const PROBE_VISITS_PER_BYTE: u64 = 8;
fn probe_visits(bytes: u64) -> u64 {
PROBE_VISITS_MIN.max(bytes.saturating_mul(PROBE_VISITS_PER_BYTE))
}
fn packets_end_at(codestream: &[u8], tile: u16, packet_work: &WorkLimit) -> bool {
probe_packets(codestream, tile, packet_work).0
}
fn probe_packets(codestream: &[u8], tile: u16, packet_work: &WorkLimit) -> (bool, u64) {
let Ok(parsed) = crate::codestream::parse_header(codestream) else {
return (false, 0);
};
let siz = &parsed.header.siz;
let tiles = siz.num_tiles() as usize;
if tiles > PROBE_TILES
|| siz.components.len() > PROBE_COMPONENTS
|| tiles.saturating_mul(14) > codestream.len()
{
return (false, 0);
}
let Ok(cs) = crate::codestream::split_tiles(codestream, parsed) else {
return (false, 0);
};
let index = usize::from(tile);
let (Some(data), Ok(header)) = (cs.tiles.get(index), cs.tile_header(index)) else {
return (false, 0);
};
let bytes = (data.data.len() + data.packed_headers.len()) as u64;
let visits = packet_work.apply(probe_visits(bytes));
let mut budget = crate::tier2::Budget {
precincts: PROBE_GEOMETRY,
blocks: PROBE_GEOMETRY,
visits,
poc_bitmap: crate::tier2::decode_visits(crate::tile_bytes(&cs)),
poc_set: false,
poc_coverage: false,
reduction: 0,
refusal: None,
};
let ends = crate::tier2::decode_packets_within(&header, data, &mut budget).is_ok();
(ends, visits - budget.visits)
}
pub(crate) fn check_against_siz(header: &Jp2Header<'_>, siz: &Siz) -> Result<()> {
let ihdr = &header.ihdr;
let (width, height) = siz.image_extent_at(0);
if (ihdr.width, ihdr.height) != (width, height) {
return Err(Error::FileFormat(format!(
"`ihdr` declares a {}x{} image but the codestream's `SIZ` declares {width}x{height}",
ihdr.width, ihdr.height
)));
}
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ChannelPlans {
palette: PalettePlan,
channels: ChannelPlan,
}
impl ChannelPlans {
pub(crate) fn plan(
header: &Jp2Header<'_>,
siz: &Siz,
reduction: u8,
cap: u64,
raw_channels: bool,
) -> Result<Self> {
let palette = palette::plan(header, siz, reduction, cap, raw_channels)?;
let count = palette.output_channels(siz, reduction).len();
let channels = channels::plan(header, count, raw_channels)?;
Ok(ChannelPlans { palette, channels })
}
pub(crate) fn outputs(&self, siz: &Siz, reduction: u8) -> Result<Vec<ComponentInfo>> {
self.channels
.apply(self.palette.output_channels(siz, reduction))
}
pub(crate) fn apply(&self, components: Vec<Component>) -> Result<Vec<Component>> {
self.channels.apply(self.palette.apply(components)?)
}
}
pub(crate) fn metadata(file: &Jp2File<'_>, plans: &ChannelPlans, siz: &Siz) -> Result<Jp2Metadata> {
let passed = passthrough(file);
let ihdr = &file.header.ihdr;
let mut metadata = Jp2Metadata {
color: file.color.clone(),
channels: color_channels(plans.outputs(siz, 0)?.len(), &file.color)?,
palette_applied: false,
palette: None,
channel_mapping: None,
channel_definitions: channels::definitions(&file.header),
resolution: resolution::read(&file.header),
xml: passed.xml,
uuid: passed.uuid,
ipr: passed.ipr,
uuid_info: passed.uuid_info,
image_header: ImageHeader {
compression: ihdr.compression,
unknown_color_space: ihdr.unknown_colorspace,
ipr_flag: ihdr.ipr,
},
color_specifications: color_specifications(&file.header),
file_type: file.file_type.clone(),
reader_requirements: passed.reader_requirements,
};
plans.palette.describe(&mut metadata);
plans.channels.describe(&mut metadata);
Ok(metadata)
}
#[derive(Default)]
struct Passthrough {
xml: Vec<XmlBox>,
uuid: Vec<UuidBox>,
ipr: Vec<IprBox>,
uuid_info: Vec<UuidInfo>,
reader_requirements: Option<ReaderRequirements>,
}
fn passthrough(file: &Jp2File<'_>) -> Passthrough {
let mut out = Passthrough::default();
let mut rreq_seen = false;
for item in file.other.iter().chain(&file.after_box) {
match &item.kind {
b"xml " => out.xml.push(XmlBox {
payload: item.payload.to_vec(),
}),
b"uuid" => {
if let Some((id, payload)) = item.payload.split_first_chunk::<16>() {
out.uuid.push(UuidBox {
id: *id,
payload: payload.to_vec(),
});
}
}
b"jp2i" => out.ipr.push(IprBox {
payload: item.payload.to_vec(),
}),
b"uinf" => out.uuid_info.extend(uuid_info::parse(item.payload)),
b"rreq" if !rreq_seen => {
rreq_seen = true;
out.reader_requirements = rreq::parse(item.payload);
}
_ => {}
}
}
out
}
fn color_specifications(header: &Jp2Header<'_>) -> Vec<ColorSpecification> {
header
.colr()
.into_iter()
.filter_map(|body| {
let (&[method, precedence, approximation], payload) = body.split_first_chunk()?;
Some(ColorSpecification {
method,
precedence,
approximation,
payload: payload.to_vec(),
})
})
.collect()
}
fn color_count(color: &ColorSpace) -> Option<usize> {
match color {
ColorSpace::Grayscale => Some(1),
ColorSpace::Srgb | ColorSpace::Sycc => Some(3),
ColorSpace::Enumerated(value) => match value {
0 | 15 => Some(1),
1 | 3 | 4 | 9 | 11 | 14 | 19..=24 => Some(3),
12 | 13 => Some(4),
_ => None,
},
ColorSpace::RestrictedIcc(profile) => {
match profile.get(16..20)? {
b"GRAY" => Some(1),
b"RGB " | b"YCbr" | b"Lab " | b"Luv " | b"XYZ " | b"Yxy " | b"HSV " | b"HLS "
| b"CMY " => Some(3),
b"CMYK" => Some(4),
[d @ (b'2'..=b'9' | b'A'..=b'F'), b'C', b'L', b'R'] => {
char::from(*d).to_digit(16).map(|n| n as usize)
}
_ => None,
}
}
ColorSpace::Unknown => None,
}
}
fn color_channels(count: usize, color: &ColorSpace) -> Result<Vec<ChannelDefinition>> {
let colors = color_count(color).unwrap_or(count);
(0..count)
.map(|i| {
if i >= colors {
return Ok(ChannelDefinition {
kind: ChannelType::Unspecified,
association: Association::None,
});
}
let color = u16::try_from(i + 1).map_err(|_| {
Error::Inconsistent(format!("{count} channels exceed the `u16` color index"))
})?;
Ok(ChannelDefinition {
kind: ChannelType::Color,
association: Association::Color(color),
})
})
.collect()
}
pub(crate) fn plan_srgb(
metadata: &Jp2Metadata,
plans: &ChannelPlans,
siz: &Siz,
reduction: u8,
cap: u64,
) -> Result<SrgbPlan> {
srgb::plan(
&metadata.color,
&metadata.channels,
&plans.outputs(siz, reduction)?,
siz,
reduction,
cap,
)
}