use super::header::Jp2Header;
use super::metadata::{Association, ChannelDefinition, ChannelType, Jp2Metadata};
use crate::codestream::markers::Siz;
use crate::samples;
use crate::{Component, ComponentInfo, Error, Result};
const MAX_ENTRIES: u16 = 1024;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct PaletteColumn {
pub bit_depth: u8,
pub signed: bool,
}
impl PaletteColumn {
fn entry_bytes(&self) -> usize {
usize::from(self.bit_depth).div_ceil(8).min(4)
}
fn fits_i32(&self) -> bool {
if self.signed {
self.bit_depth <= 32
} else {
self.bit_depth <= 31
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Palette {
entries: u16,
columns: Vec<PaletteColumn>,
values: Vec<i32>,
}
impl Palette {
pub(super) fn parse(payload: &[u8]) -> Result<Self> {
let &[ne0, ne1, npc, ref rest @ ..] = payload else {
return Err(Error::file_format(format!(
"the `pclr` box holds {} bytes, fewer than its 3-byte header",
payload.len()
)));
};
let entries = u16::from_be_bytes([ne0, ne1]);
if !(1..=MAX_ENTRIES).contains(&entries) {
return Err(Error::file_format(format!(
"the `pclr` box declares {entries} entries; a palette holds 1 to {MAX_ENTRIES}"
)));
}
if npc == 0 {
return Err(Error::file_format(
"the `pclr` box declares 0 palette columns",
));
}
let Some((bi, table)) = rest.split_at_checked(usize::from(npc)) else {
return Err(Error::file_format(format!(
"the `pclr` box declares {npc} columns but ends inside their `Bi` bytes"
)));
};
let columns: Vec<PaletteColumn> = bi
.iter()
.map(|&b| PaletteColumn {
bit_depth: (b & 0x7F) + 1,
signed: b & 0x80 != 0,
})
.collect();
let row_bytes: usize = columns.iter().map(|c| c.entry_bytes()).sum();
let needed = row_bytes
.checked_mul(usize::from(entries))
.ok_or_else(|| Error::file_format("the `pclr` box's entry table size overflows"))?;
if table.len() < needed {
return Err(Error::file_format(format!(
"the `pclr` box's {entries} x {npc} entries need {needed} bytes but it holds {}",
table.len()
)));
}
let mut values = Vec::with_capacity(usize::from(entries) * columns.len());
let mut at = 0;
for _ in 0..entries {
for column in &columns {
let width = column.entry_bytes();
let bytes = table
.get(at..at + width)
.ok_or_else(|| Error::inconsistent("palette entry past its table"))?;
at += width;
values.push(entry_value(bytes));
}
}
Ok(Palette {
entries,
columns,
values,
})
}
#[must_use]
pub fn columns(&self) -> &[PaletteColumn] {
&self.columns
}
#[must_use]
pub fn entry_count(&self) -> usize {
usize::from(self.entries)
}
#[must_use]
pub fn entry(&self, index: usize) -> Option<&[i32]> {
let width = self.columns.len();
if index >= self.entry_count() {
return None;
}
self.values.get(index * width..(index + 1) * width)
}
fn lookup(&self, index: i32, column: usize) -> i32 {
let top = i32::from(self.entries) - 1;
let row = index.clamp(0, top) as usize;
self.values[row * self.columns.len() + column]
}
}
fn entry_value(bytes: &[u8]) -> i32 {
let value = bytes.iter().fold(0u32, |acc, &b| (acc << 8) | u32::from(b));
value as i32
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ChannelMapping {
pub component: u16,
pub kind: MappingKind,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum MappingKind {
Direct,
Palette {
column: u8,
},
Reserved {
mtyp: u8,
pcol: u8,
},
}
fn public_source(source: Source) -> ChannelMapping {
match source {
Source::Direct { component } => ChannelMapping {
component,
kind: MappingKind::Direct,
},
Source::Palette { component, column } => ChannelMapping {
component,
kind: MappingKind::Palette { column },
},
}
}
fn public_mapping(entries: &[(u16, u8, u8)]) -> Vec<ChannelMapping> {
entries
.iter()
.map(|&(component, mtyp, pcol)| ChannelMapping {
component,
kind: match mtyp {
0 => MappingKind::Direct,
1 => MappingKind::Palette { column: pcol },
mtyp => MappingKind::Reserved { mtyp, pcol },
},
})
.collect()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Source {
Direct { component: u16 },
Palette { component: u16, column: u8 },
}
impl Source {
fn component(self) -> u16 {
match self {
Source::Direct { component } | Source::Palette { component, .. } => component,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct PlannedChannel {
pub(crate) source: Source,
pub(crate) bit_depth: u8,
pub(crate) signed: bool,
pub(crate) x_sampling: u8,
pub(crate) y_sampling: u8,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum PalettePlan {
None,
Skipped {
index_components: Vec<bool>,
palette: Palette,
mapping: Vec<ChannelMapping>,
},
Apply {
palette: Palette,
channels: Vec<PlannedChannel>,
},
}
pub(crate) fn plan(
header: &Jp2Header<'_>,
siz: &Siz,
reduction: u8,
cap: u64,
raw_channels: bool,
) -> Result<PalettePlan> {
let (pclrs, cmaps) = (header.pclr(), header.cmap());
if pclrs.len() > 1 {
return Err(Error::file_format("the file has more than one `pclr` box"));
}
if cmaps.len() > 1 {
return Err(Error::file_format("the file has more than one `cmap` box"));
}
let Some(pclr) = pclrs.first() else {
if cmaps.is_empty() {
return Ok(PalettePlan::None);
}
return Err(Error::file_format(
"the file has a `cmap` box but no `pclr` box",
));
};
if cmap_before_pclr(header) {
return Err(Error::file_format(
"the `cmap` box comes before the `pclr` box it maps",
));
}
let palette = Palette::parse(pclr)?;
let Some(cmap) = cmaps.first() else {
return Ok(PalettePlan::None);
};
let entries = parse_cmap(cmap, palette.columns.len())?;
if raw_channels {
let mut index_components = vec![false; siz.components.len()];
for &(component, mtyp, _) in &entries {
if let (1, Some(slot)) = (mtyp, index_components.get_mut(usize::from(component))) {
*slot = true;
}
}
let mapping = match map_channels(&entries, palette.columns.len(), siz.components.len()) {
Ok(sources) => sources.into_iter().map(public_source).collect(),
Err(_) => public_mapping(&entries),
};
return Ok(PalettePlan::Skipped {
index_components,
palette,
mapping,
});
}
let sources = map_channels(&entries, palette.columns.len(), siz.components.len())?;
let channels: Vec<PlannedChannel> = sources
.into_iter()
.enumerate()
.map(|(i, source)| plan_channel(i, source, &palette, siz))
.collect::<Result<_>>()?;
check_budget(&channels, siz, reduction, cap)?;
Ok(PalettePlan::Apply { palette, channels })
}
fn cmap_before_pclr(header: &Jp2Header<'_>) -> bool {
let position = |kind: &[u8; 4]| header.children.iter().position(|c| &c.kind == kind);
match (position(b"cmap"), position(b"pclr")) {
(Some(cmap), Some(pclr)) => cmap < pclr,
_ => false,
}
}
fn parse_cmap(payload: &[u8], count: usize) -> Result<Vec<(u16, u8, u8)>> {
let needed = count * 4;
let Some(body) = payload.get(..needed) else {
return Err(Error::file_format(format!(
"the `cmap` box holds {} bytes; mapping {count} palette columns needs {needed}",
payload.len()
)));
};
Ok(body
.chunks_exact(4)
.map(|e| (u16::from_be_bytes([e[0], e[1]]), e[2], e[3]))
.collect())
}
fn map_channels(
entries: &[(u16, u8, u8)],
columns: usize,
components: usize,
) -> Result<Vec<Source>> {
let mut used = vec![false; columns];
for (i, &(component, mtyp, pcol)) in entries.iter().enumerate() {
if usize::from(component) >= components {
return Err(Error::file_format(format!(
"`cmap` channel {i} maps component {component}, but the codestream has {components}"
)));
}
let column = usize::from(pcol);
if mtyp > 1 {
return Err(Error::file_format(format!(
"`cmap` channel {i} has mapping type {mtyp}; only 0 (direct) and 1 (palette) exist"
)));
}
if column >= columns {
return Err(Error::file_format(format!(
"`cmap` channel {i} names palette column {pcol}, but the palette has {columns}"
)));
}
if mtyp == 1 && used[column] {
return Err(Error::file_format(format!(
"`cmap` maps palette column {pcol} twice"
)));
}
if mtyp == 0 && pcol != 0 {
return Err(Error::file_format(format!(
"`cmap` channel {i} uses component {component} directly but names palette \
column {pcol}; a direct channel's `PCOL` must be 0"
)));
}
used[column] = true;
}
for (i, &(_, mtyp, _)) in entries.iter().enumerate() {
if mtyp != 0 && !used[i] {
return Err(Error::file_format(format!(
"`cmap` channel {i} is a palette channel but palette column {i} is not mapped"
)));
}
}
for (i, &(_, mtyp, pcol)) in entries.iter().enumerate() {
if mtyp == 1 && usize::from(pcol) != i {
return Err(Error::unsupported(format!(
"`cmap` channel {i} looks up palette column {pcol}; only channel i from \
column i is decoded"
)));
}
}
let correct = components == 1 && used.contains(&false);
entries
.iter()
.enumerate()
.map(|(i, &(component, mtyp, pcol))| {
Ok(if correct {
let column = u8::try_from(i).map_err(|_| {
Error::inconsistent(format!("palette column {i} exceeds `NPC`"))
})?;
Source::Palette { component, column }
} else if mtyp == 0 {
Source::Direct { component }
} else {
Source::Palette {
component,
column: pcol,
}
})
})
.collect()
}
fn plan_channel(i: usize, source: Source, palette: &Palette, siz: &Siz) -> Result<PlannedChannel> {
let label = match source {
Source::Direct { .. } => i,
Source::Palette { column, .. } => usize::from(column),
};
let column = palette
.columns
.get(label)
.ok_or_else(|| Error::inconsistent(format!("no palette column {label}")))?;
if !column.fits_i32() {
return Err(Error::unsupported(format!(
"palette channel {i} has depth {} ({}), which exceeds the i32 sample container",
column.bit_depth,
if column.signed { "signed" } else { "unsigned" }
)));
}
let component = siz
.components
.get(usize::from(source.component()))
.ok_or_else(|| Error::inconsistent("`cmap` component past `SIZ`"))?;
Ok(PlannedChannel {
source,
bit_depth: column.bit_depth,
signed: column.signed,
x_sampling: component.x_sampling,
y_sampling: component.y_sampling,
})
}
fn check_budget(channels: &[PlannedChannel], siz: &Siz, reduction: u8, cap: u64) -> Result<()> {
let mut total: u64 = 0;
for channel in channels {
let index = usize::from(channel.source.component());
let (width, height) = siz
.component_extent_at(index, reduction)
.ok_or_else(|| Error::inconsistent(format!("`SIZ` declares no component {index}")))?;
total = total.saturating_add(u64::from(width) * u64::from(height));
}
if total > cap {
let what = format!(
"palette expansion to {} channels{}",
channels.len(),
samples::at(reduction)
);
return Err(samples::over(&what, total, cap));
}
Ok(())
}
impl PalettePlan {
pub(crate) fn output_channels(&self, siz: &Siz, reduction: u8) -> Vec<ComponentInfo> {
match self {
PalettePlan::Apply { channels, .. } => channels
.iter()
.map(|c| {
ComponentInfo::on_grid(
siz,
c.bit_depth,
c.signed,
c.x_sampling,
c.y_sampling,
reduction,
)
})
.collect(),
PalettePlan::None | PalettePlan::Skipped { .. } => {
ComponentInfo::of_siz(siz, reduction)
}
}
}
pub(crate) fn apply(&self, mut components: Vec<Component>) -> Result<Vec<Component>> {
let PalettePlan::Apply { palette, channels } = self else {
return Ok(components);
};
let mut reads_left = vec![0usize; components.len()];
for channel in channels {
let index = usize::from(channel.source.component());
let slot = reads_left.get_mut(index).ok_or_else(|| {
Error::inconsistent(format!(
"`cmap` names component {index}, which was not decoded"
))
})?;
*slot += 1;
}
let mut out = Vec::with_capacity(channels.len());
for channel in channels {
let index = usize::from(channel.source.component());
reads_left[index] -= 1;
let from = &mut components[index];
let samples = match channel.source {
Source::Direct { .. } if reads_left[index] == 0 => {
std::mem::take(&mut from.samples)
}
Source::Direct { .. } => from.samples.clone(),
Source::Palette { column, .. } => from
.samples
.iter()
.map(|&k| palette.lookup(k, usize::from(column)))
.collect(),
};
out.push(Component::new(
from.width,
from.height,
channel.bit_depth,
channel.signed,
channel.x_sampling,
channel.y_sampling,
samples,
));
}
Ok(out)
}
pub(crate) fn describe(&self, metadata: &mut Jp2Metadata) {
metadata.palette_applied = matches!(self, PalettePlan::Apply { .. });
match self {
PalettePlan::None => {}
PalettePlan::Apply { palette, channels } => {
metadata.palette = Some(palette.clone());
metadata.channel_mapping =
Some(channels.iter().map(|c| public_source(c.source)).collect());
}
PalettePlan::Skipped {
palette, mapping, ..
} => {
metadata.palette = Some(palette.clone());
metadata.channel_mapping = Some(mapping.clone());
}
}
if let PalettePlan::Skipped {
index_components, ..
} = self
{
for (channel, &index) in metadata.channels.iter_mut().zip(index_components) {
if index {
*channel = ChannelDefinition {
kind: ChannelType::Unspecified,
association: Association::None,
};
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::codestream::markers::SizComponent;
fn pclr(entries: u16, bi: &[u8], table: &[u8]) -> Vec<u8> {
let mut out = entries.to_be_bytes().to_vec();
out.push(u8::try_from(bi.len()).unwrap());
out.extend_from_slice(bi);
out.extend_from_slice(table);
out
}
#[test]
fn entries_are_read_at_their_byte_widths() {
let palette =
Palette::parse(&pclr(2, &[7, 11, 0], &[1, 0x0A, 0xBC, 1, 2, 0x0F, 0xFF, 0])).unwrap();
assert_eq!(palette.values, [1, 0xABC, 1, 2, 0xFFF, 0]);
assert_eq!(
palette.columns,
[
PaletteColumn {
bit_depth: 8,
signed: false
},
PaletteColumn {
bit_depth: 12,
signed: false
},
PaletteColumn {
bit_depth: 1,
signed: false
},
]
);
}
#[test]
fn a_deep_column_is_read_at_a_four_byte_stride() {
let palette = Palette::parse(&pclr(2, &[37], &[0, 0, 0, 7, 0xFF, 0xFF, 0xFF, 0xFF]))
.expect("4 bytes per entry is enough");
assert_eq!(palette.values, [7, -1]);
assert!(matches!(
Palette::parse(&pclr(2, &[37], &[0; 7])),
Err(Error::FileFormat(_))
));
}
#[test]
fn entries_are_unsigned_and_unmasked_as_in_openjpeg() {
let palette = Palette::parse(&pclr(1, &[0x8B, 11], &[0x0F, 0xFF, 0xF0, 0x00])).unwrap();
assert!(palette.columns[0].signed);
assert_eq!(palette.values, [4095, 0xF000]);
}
#[test]
fn indices_clamp_to_the_palette() {
let palette = Palette::parse(&pclr(3, &[7], &[10, 20, 30])).unwrap();
let looked: Vec<i32> = [-5, 0, 1, 2, 3, 1000, i32::MIN, i32::MAX]
.iter()
.map(|&k| palette.lookup(k, 0))
.collect();
assert_eq!(looked, [10, 10, 20, 30, 30, 30, 10, 30]);
}
fn siz(width: u32, height: u32) -> Siz {
Siz {
x_size: width,
y_size: height,
x_offset: 0,
y_offset: 0,
tile_width: width,
tile_height: height,
tile_x_offset: 0,
tile_y_offset: 0,
components: vec![SizComponent {
bit_depth: 8,
signed: false,
x_sampling: 1,
y_sampling: 1,
}],
}
}
#[test]
fn the_expansion_is_held_to_the_sample_budget() {
let channel = |column| PlannedChannel {
source: Source::Palette {
component: 0,
column,
},
bit_depth: 8,
signed: false,
x_sampling: 1,
y_sampling: 1,
};
let channels: Vec<PlannedChannel> = (0..=254).map(channel).collect();
let siz = siz(600, 500);
assert!(matches!(
check_budget(&channels, &siz, 0, 1 << 26),
Err(Error::Limit(_))
));
assert!(check_budget(&channels, &siz, 1, 1 << 26).is_ok());
assert!(check_budget(&channels[..200], &siz, 0, 1 << 26).is_ok());
}
#[test]
fn a_direct_channel_moves_or_copies_its_plane() {
let palette = Palette::parse(&pclr(2, &[7, 7], &[10, 20, 30, 40])).unwrap();
let direct = PlannedChannel {
source: Source::Direct { component: 0 },
bit_depth: 8,
signed: false,
x_sampling: 1,
y_sampling: 1,
};
let lookup = PlannedChannel {
source: Source::Palette {
component: 0,
column: 1,
},
..direct
};
let index = Component::new(2, 1, 8, false, 1, 1, vec![0, 1]);
for channels in [
vec![direct, lookup],
vec![lookup, direct],
vec![direct, direct],
] {
let plan = PalettePlan::Apply {
palette: palette.clone(),
channels: channels.clone(),
};
let out = plan.apply(vec![index.clone()]).unwrap();
for (channel, got) in channels.iter().zip(&out) {
let want = match channel.source {
Source::Direct { .. } => vec![0, 1],
Source::Palette { .. } => vec![20, 40],
};
assert_eq!(got.samples, want, "{channels:?}");
}
}
}
#[test]
fn entries_are_big_endian_and_cast_to_i32() {
assert_eq!(entry_value(&[0x01, 0x02, 0x03, 0x04]), 0x0102_0304);
assert_eq!(entry_value(&[0xFF, 0xFF, 0xFF, 0xFF]), -1);
assert_eq!(entry_value(&[0x0A, 0xBC]), 0xABC);
}
}