#![deny(unsafe_code)]
#![warn(missing_docs)]
mod codestream;
mod decode;
mod dwt;
mod error;
mod jp2;
mod kernels;
mod mq;
mod t1;
mod tagtree;
mod tile;
pub use error::{JpxError, JpxResult};
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Limits {
pub max_samples: u64,
pub max_components: u32,
pub max_structures: u64,
}
impl Default for Limits {
fn default() -> Self {
Limits {
max_samples: 1 << 28,
max_components: 1024,
max_structures: 1 << 22,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct DecodeOptions {
pub reduce: u8,
pub allow_truncated: bool,
pub apply_palette: bool,
pub limits: Limits,
}
impl Default for DecodeOptions {
fn default() -> Self {
DecodeOptions {
reduce: 0,
allow_truncated: false,
apply_palette: true,
limits: Limits::default(),
}
}
}
impl DecodeOptions {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_reduce(mut self, reduce: u8) -> Self {
self.reduce = reduce;
self
}
#[must_use]
pub fn with_allow_truncated(mut self, allow: bool) -> Self {
self.allow_truncated = allow;
self
}
#[must_use]
pub fn with_limits(mut self, limits: Limits) -> Self {
self.limits = limits;
self
}
#[must_use]
pub fn with_apply_palette(mut self, apply: bool) -> Self {
self.apply_palette = apply;
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ColorSpace {
Unspecified,
Bilevel,
Grey,
Srgb,
Sycc,
ESycc,
ESrgb,
RommRgb,
Cmy,
Cmyk,
Ycck,
CieLab,
Icc,
Other(u32),
}
impl ColorSpace {
fn from_enum(v: u32) -> Self {
match v {
0 | 15 => Self::Bilevel,
11 => Self::Cmy,
12 => Self::Cmyk,
13 => Self::Ycck,
14 => Self::CieLab,
16 => Self::Srgb,
17 => Self::Grey,
18 => Self::Sycc,
20 => Self::ESrgb,
21 => Self::RommRgb,
24 => Self::ESycc,
v => Self::Other(v),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ChannelRole {
Color,
Opacity,
PremultipliedOpacity,
Unspecified,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Component {
pub bits: u8,
pub signed: bool,
pub role: ChannelRole,
pub width: u32,
pub height: u32,
pub dx: u32,
pub dy: u32,
pub data: Vec<i32>,
x0: u32,
y0: u32,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Jpx {
pub width: u32,
pub height: u32,
pub components: Vec<Component>,
pub color: ColorSpace,
pub icc: Option<Vec<u8>>,
pub has_alpha: bool,
pub truncated: bool,
x0: u32,
y0: u32,
}
impl Jpx {
#[must_use]
pub fn alpha(&self) -> Option<&Component> {
self.components.iter().find(|c| {
matches!(
c.role,
ChannelRole::Opacity | ChannelRole::PremultipliedOpacity
)
})
}
pub fn colors(&self) -> impl Iterator<Item = &Component> {
self.components
.iter()
.filter(|c| c.role == ChannelRole::Color)
}
#[must_use]
pub fn upsampled(&self, i: usize) -> Option<std::borrow::Cow<'_, [i32]>> {
let c = self.components.get(i)?;
if (c.width, c.height) == (self.width, self.height) {
return Some(std::borrow::Cow::Borrowed(&c.data));
}
if c.data.is_empty() {
return None;
}
let index = |v: u32, origin: u32, step: u32, first: u32, n: u32| {
(((u64::from(origin) + u64::from(v)) / u64::from(step))
.saturating_sub(first.into())
.min(u64::from(n) - 1)) as usize
};
let columns: Vec<usize> = (0..self.width)
.map(|x| index(x, self.x0, c.dx, c.x0, c.width))
.collect();
let mut out = Vec::new();
out.try_reserve_exact(self.width as usize * self.height as usize)
.ok()?;
for y in 0..self.height {
let row = index(y, self.y0, c.dy, c.y0, c.height) * c.width as usize;
let row = &c.data[row..row + c.width as usize];
out.extend(columns.iter().map(|&x| row[x]));
}
Some(std::borrow::Cow::Owned(out))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct ComponentInfo {
pub bits: u8,
pub signed: bool,
pub dx: u32,
pub dy: u32,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Info {
pub width: u32,
pub height: u32,
pub components: Vec<ComponentInfo>,
pub color: ColorSpace,
pub icc: Option<Vec<u8>>,
pub has_alpha: bool,
pub has_palette: bool,
pub tiles: u32,
pub layers: u32,
pub max_reduce: u8,
pub reversible: bool,
}
pub fn info(data: &[u8]) -> JpxResult<Info> {
let container = jp2::parse(data)?;
let (siz, params) = codestream::parse_main(container.codestream, &Limits::default())?;
let mut max_reduce = 32;
let mut reversible = true;
for c in 0..siz.comps.len() {
let coding = params.coding(c)?;
max_reduce = max_reduce.min(coding.levels);
reversible &= coding.reversible;
}
Ok(Info {
width: siz.x1 - siz.x0,
height: siz.y1 - siz.y0,
components: siz
.comps
.iter()
.map(|c| ComponentInfo {
bits: c.bits,
signed: c.signed,
dx: c.dx,
dy: c.dy,
})
.collect(),
color: first_color(&container),
icc: container.icc.map(<[u8]>::to_vec),
has_alpha: container.cdef.iter().any(|d| matches!(d.1, 1 | 2)),
has_palette: container.palette.is_some(),
tiles: siz.tiles_x * siz.tiles_y,
layers: params.layers,
max_reduce,
reversible,
})
}
fn first_color(c: &jp2::Container) -> ColorSpace {
c.colors.first().copied().unwrap_or(ColorSpace::Unspecified)
}
pub fn decode_jpx(data: &[u8]) -> JpxResult<Jpx> {
decode_jpx_with(data, &DecodeOptions::default())
}
pub fn decode_jpx_with(data: &[u8], options: &DecodeOptions) -> JpxResult<Jpx> {
let container = jp2::parse(data)?;
let decoded = decode::decode(container.codestream, options)?;
let siz = &decoded.siz;
let reduce = u32::from(options.reduce);
let mut components = Vec::with_capacity(siz.comps.len());
for (c, (k, data)) in siz.comps.iter().zip(decoded.samples).enumerate() {
let r = siz.comp_rect(c, reduce);
components.push(Component {
bits: k.bits,
signed: k.signed,
role: ChannelRole::Color,
width: r[2].saturating_sub(r[0]),
height: r[3].saturating_sub(r[1]),
dx: k.dx,
dy: k.dy,
data,
x0: r[0],
y0: r[1],
});
}
if options.apply_palette {
if let Some(p) = &container.palette {
let default: Vec<_> = (0..p.columns.len()).map(|i| (0, 1, i as u8)).collect();
let cmap = if container.cmap.is_empty() {
&default
} else {
&container.cmap
};
components = jp2::apply_palette(components, p, cmap, options.limits.max_samples)?;
}
}
apply_cdef(&mut components, &container.cdef);
let has_alpha = components.iter().any(|c| {
matches!(
c.role,
ChannelRole::Opacity | ChannelRole::PremultipliedOpacity
)
});
let grid = [siz.x0, siz.y0, siz.x1, siz.y1].map(|v| codestream::ceil_shift(v, reduce));
Ok(Jpx {
width: grid[2].saturating_sub(grid[0]),
height: grid[3].saturating_sub(grid[1]),
components,
color: first_color(&container),
icc: container.icc.map(<[u8]>::to_vec),
has_alpha,
truncated: decoded.truncated,
x0: grid[0],
y0: grid[1],
})
}
fn apply_cdef(components: &mut Vec<Component>, cdef: &[(u16, u16, u16)]) {
if cdef.is_empty() {
return;
}
let mut order = vec![u32::MAX; components.len()];
for &(channel, kind, association) in cdef {
let Some(c) = components.get_mut(usize::from(channel)) else {
continue;
};
c.role = match kind {
0 => ChannelRole::Color,
1 => ChannelRole::Opacity,
2 => ChannelRole::PremultipliedOpacity,
_ => ChannelRole::Unspecified,
};
if kind == 0 {
order[usize::from(channel)] = u32::from(association);
}
}
let mut tagged: Vec<(u32, Component)> = order.into_iter().zip(components.drain(..)).collect();
tagged.sort_by_key(|t| t.0);
components.extend(tagged.into_iter().map(|t| t.1));
}