use super::header::Jp2Header;
use super::metadata::{
Association, ChannelDefinition, ChannelDefinitionEntry, ChannelType, Jp2Metadata,
};
use crate::{Error, Result};
const ENTRY_BYTES: usize = 6;
const APPLICATION_DEFINED: u16 = 3;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Entry {
channel: u16,
kind: u16,
association: u16,
jph: bool,
}
impl Entry {
fn target(self) -> Option<usize> {
match (self.kind, self.association) {
(0, 1..=65534) => Some(usize::from(self.association) - 1),
_ => None,
}
}
fn application_defined(self) -> bool {
self.jph && self.kind == APPLICATION_DEFINED
}
fn definition(self) -> ChannelDefinition {
ChannelDefinition {
kind: match self.kind {
_ if self.application_defined() => ChannelType::ApplicationDefined,
0 => ChannelType::Color,
1 => ChannelType::Opacity,
2 => ChannelType::PremultipliedOpacity,
65535 => ChannelType::Unspecified,
other => ChannelType::Other(other),
},
association: match self.association {
n if self.application_defined() => Association::ApplicationDefined(n),
0 => Association::WholeImage,
65535 => Association::None,
n => Association::Color(n),
},
}
}
}
fn parse(payload: &[u8], jph: bool) -> Result<Vec<Entry>> {
let &[n0, n1, ref body @ ..] = payload else {
return Err(Error::file_format(format!(
"the `cdef` box holds {} bytes, fewer than its 2-byte count",
payload.len()
)));
};
let count = u16::from_be_bytes([n0, n1]);
if count == 0 {
return Err(Error::file_format(
"the `cdef` box declares 0 channel definitions",
));
}
let needed = usize::from(count)
.checked_mul(ENTRY_BYTES)
.ok_or_else(|| Error::file_format("the `cdef` box's size overflows"))?;
let Some(entries) = body.get(..needed) else {
return Err(Error::file_format(format!(
"the `cdef` box declares {count} channel definitions ({needed} bytes) but holds {}",
body.len()
)));
};
Ok(entries
.chunks_exact(ENTRY_BYTES)
.map(|e| Entry {
channel: u16::from_be_bytes([e[0], e[1]]),
kind: u16::from_be_bytes([e[2], e[3]]),
association: u16::from_be_bytes([e[4], e[5]]),
jph,
})
.collect())
}
pub(super) fn definitions(
header: &Jp2Header<'_>,
jph: bool,
) -> Option<Vec<ChannelDefinitionEntry>> {
let payload = header.cdef().first().copied()?;
let entries = parse(payload, jph).ok()?;
Some(
entries
.into_iter()
.map(|e| ChannelDefinitionEntry {
channel: e.channel,
definition: e.definition(),
})
.collect(),
)
}
pub(super) fn check_layout(payload: &[u8]) -> Result<()> {
parse(payload, false).map(|_| ())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ChannelPlan {
None,
Apply {
order: Vec<usize>,
definitions: Vec<ChannelDefinition>,
},
}
pub(crate) fn plan(
header: &Jp2Header<'_>,
channels: usize,
raw_channels: bool,
jph: bool,
) -> Result<ChannelPlan> {
let boxes = header.cdef();
if boxes.len() > 1 {
return Err(Error::file_format("the file has more than one `cdef` box"));
}
let Some(payload) = boxes.first() else {
return Ok(ChannelPlan::None);
};
let entries = parse(payload, jph)?;
if raw_channels {
return Ok(ChannelPlan::None);
}
check(&entries, channels)?;
Ok(place(&entries, channels))
}
fn check(entries: &[Entry], channels: usize) -> Result<()> {
for (i, entry) in entries.iter().enumerate() {
if usize::from(entry.channel) >= channels {
return Err(Error::file_format(format!(
"`cdef` entry {i} describes channel {}, but the file has {channels}",
entry.channel
)));
}
if !entry.application_defined()
&& !matches!(entry.association, 0 | 65535)
&& usize::from(entry.association) > channels
{
return Err(Error::file_format(format!(
"`cdef` entry {i} associates channel {} with color {}, but the file has \
{channels} channels",
entry.channel, entry.association
)));
}
}
let mut named = vec![false; channels];
for entry in entries {
if let Some(slot) = named.get_mut(usize::from(entry.channel)) {
*slot = true;
}
}
if let Some(missing) = named.iter().position(|&n| !n) {
return Err(Error::file_format(format!(
"the `cdef` box does not define channel {missing}; it must define every channel"
)));
}
Ok(())
}
fn place(entries: &[Entry], channels: usize) -> ChannelPlan {
let mut order: Vec<usize> = (0..channels).collect();
let mut position: Vec<usize> = (0..channels).collect();
let mut labels = vec![
ChannelDefinition {
kind: ChannelType::Unspecified,
association: Association::None,
};
channels
];
for entry in entries {
let channel = usize::from(entry.channel);
labels[channel] = entry.definition();
let Some(target) = entry.target() else {
continue;
};
let from = position[channel];
if from != target {
let displaced = order[target];
order.swap(from, target);
position[channel] = target;
position[displaced] = from;
}
}
let definitions = order.iter().map(|&c| labels[c]).collect();
ChannelPlan::Apply { order, definitions }
}
impl ChannelPlan {
pub(crate) fn apply<T>(&self, components: Vec<T>) -> Result<Vec<T>> {
let ChannelPlan::Apply { order, .. } = self else {
return Ok(components);
};
if order.len() != components.len() {
return Err(Error::inconsistent(format!(
"the `cdef` plan covers {} channels but {} were decoded",
order.len(),
components.len()
)));
}
let mut slots: Vec<Option<T>> = components.into_iter().map(Some).collect();
order
.iter()
.map(|&from| {
slots.get_mut(from).and_then(Option::take).ok_or_else(|| {
Error::inconsistent(format!("`cdef` places channel {from} twice"))
})
})
.collect()
}
pub(crate) fn describe(&self, metadata: &mut Jp2Metadata) {
if let ChannelPlan::Apply { definitions, .. } = self {
metadata.channels.clone_from(definitions);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Component;
fn entries(triples: &[(u16, u16, u16)]) -> Vec<Entry> {
triples
.iter()
.map(|&(channel, kind, association)| Entry {
channel,
kind,
association,
jph: true,
})
.collect()
}
fn order(triples: &[(u16, u16, u16)], channels: usize) -> Vec<usize> {
let orders: Vec<Vec<usize>> = [true, false]
.into_iter()
.map(|jph| {
let entries: Vec<Entry> = entries(triples)
.into_iter()
.map(|entry| Entry { jph, ..entry })
.collect();
check(&entries, channels).expect("valid entries");
match place(&entries, channels) {
ChannelPlan::Apply { order, .. } => order,
ChannelPlan::None => unreachable!(),
}
})
.collect();
assert_eq!(orders[0], orders[1], "{triples:?}");
orders[0].clone()
}
#[test]
fn a_typ_3_asoc_past_the_last_channel_is_checked_outside_jph() {
let jph = entries(&[(0, 0, 1), (1, 0, 2), (2, 3, 18284)]);
check(&jph, 3).expect("a JPH file");
let jp2: Vec<Entry> = jph
.into_iter()
.map(|entry| Entry {
jph: false,
..entry
})
.collect();
let err = check(&jp2, 3).unwrap_err();
assert!(matches!(err, Error::FileFormat(_)), "{err:?}");
}
#[test]
fn placement_follows_openjpeg() {
type Case = (&'static [(u16, u16, u16)], [usize; 3]);
let cases: &[Case] = &[
(&[(0, 0, 1), (1, 0, 2), (2, 0, 3)], [0, 1, 2]),
(&[(0, 0, 3), (1, 0, 2), (2, 0, 1)], [2, 1, 0]),
(&[(2, 0, 1), (1, 0, 2), (0, 0, 3)], [2, 1, 0]),
(&[(0, 0, 2), (1, 0, 3), (2, 0, 1)], [2, 0, 1]),
(&[(0, 0, 2), (1, 0, 2), (2, 0, 3)], [0, 1, 2]),
(&[(1, 1, 0), (0, 0, 2), (2, 0, 3)], [1, 0, 2]),
(&[(0, 1, 3), (1, 0, 2), (2, 0, 1)], [2, 1, 0]),
(&[(0, 0, 0), (1, 0, 65535), (2, 0, 3)], [0, 1, 2]),
(&[(0, 7, 1), (1, 0, 2), (2, 0, 3)], [0, 1, 2]),
(&[(0, 3, 3), (1, 3, 1), (2, 3, 2)], [0, 1, 2]),
(&[(0, 3, 2), (1, 3, 1), (2, 0, 3)], [0, 1, 2]),
(
&[(0, 65535, 65535), (1, 65535, 65535), (2, 65535, 65535)],
[0, 1, 2],
),
(&[(0, 0, 1), (1, 0, 2), (2, 0, 3), (2, 1, 0)], [0, 1, 2]),
];
for (triples, want) in cases {
assert_eq!(order(triples, 3), want, "{triples:?}");
}
}
#[test]
fn an_opacity_channel_pushed_along_keeps_its_label() {
let entries = entries(&[(0, 1, 0), (1, 0, 1), (2, 0, 2), (3, 0, 3)]);
check(&entries, 4).unwrap();
let ChannelPlan::Apply { order, definitions } = place(&entries, 4) else {
unreachable!()
};
assert_eq!(order, [1, 2, 3, 0]);
let color = |n| ChannelDefinition {
kind: ChannelType::Color,
association: Association::Color(n),
};
assert_eq!(
definitions,
[
color(1),
color(2),
color(3),
ChannelDefinition {
kind: ChannelType::Opacity,
association: Association::WholeImage,
},
]
);
}
#[test]
fn the_last_entry_naming_a_channel_labels_it() {
let entries = entries(&[(0, 0, 1), (0, 2, 0)]);
let ChannelPlan::Apply { definitions, .. } = place(&entries, 1) else {
unreachable!()
};
assert_eq!(definitions[0].kind, ChannelType::PremultipliedOpacity);
assert_eq!(definitions[0].association, Association::WholeImage);
}
#[test]
fn types_and_associations_map_to_their_variants() {
let label = |kind, association| {
Entry {
channel: 0,
kind,
association,
jph: true,
}
.definition()
};
assert_eq!(label(0, 2).kind, ChannelType::Color);
assert_eq!(label(1, 0).kind, ChannelType::Opacity);
assert_eq!(label(2, 0).kind, ChannelType::PremultipliedOpacity);
assert_eq!(label(65535, 0).kind, ChannelType::Unspecified);
assert_eq!(label(3, 0).kind, ChannelType::ApplicationDefined);
assert_eq!(label(4, 0).kind, ChannelType::Other(4));
assert_eq!(label(65534, 0).kind, ChannelType::Other(65534));
assert_eq!(label(0, 0).association, Association::WholeImage);
assert_eq!(label(0, 65535).association, Association::None);
assert_eq!(label(0, 7).association, Association::Color(7));
for asoc in [0, 1, 18284, 65535] {
assert_eq!(
label(3, asoc).association,
Association::ApplicationDefined(asoc)
);
}
assert_eq!(label(4, 7).association, Association::Color(7));
let reserved = Entry {
channel: 0,
kind: 3,
association: 7,
jph: false,
}
.definition();
assert_eq!(reserved.kind, ChannelType::Other(3));
assert_eq!(reserved.association, Association::Color(7));
}
#[test]
fn apply_moves_each_channel_once() {
let plan = ChannelPlan::Apply {
order: vec![2, 0, 1],
definitions: vec![],
};
let plane = |v| Component::new(1, 1, 8, false, 1, 1, vec![v]);
let out = plan.apply(vec![plane(10), plane(11), plane(12)]).unwrap();
let samples: Vec<i32> = out.iter().map(|c| c.samples[0]).collect();
assert_eq!(samples, [12, 10, 11]);
assert!(matches!(
plan.apply(vec![plane(10), plane(11)]),
Err(Error::Inconsistent(_))
));
}
#[test]
fn parse_reads_entries_and_ignores_trailing_bytes() {
let payload = [0, 1, 0, 2, 0, 1, 0, 0, 0xFF, 0xFF];
assert_eq!(parse(&payload, true).unwrap(), entries(&[(2, 1, 0)]));
}
}