use crate::codestream::MainHeader;
use crate::codestream::markers::{Rect, Siz, Transform};
use crate::pipeline::Samples;
use crate::{DecodeReport, Error, Jp2Metadata, Result};
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Image {
pub width: u32,
pub height: u32,
pub components: Vec<Component>,
pub jp2: Option<Jp2Metadata>,
pub report: DecodeReport,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Component {
pub width: u32,
pub height: u32,
pub bit_depth: u8,
pub signed: bool,
pub x_sampling: u8,
pub y_sampling: u8,
pub samples: Vec<i32>,
}
impl Image {
#[must_use]
pub fn new(width: u32, height: u32, components: Vec<Component>) -> Self {
Self {
width,
height,
components,
jp2: None,
report: DecodeReport::default(),
}
}
pub fn component(&self, index: usize) -> Option<&Component> {
self.components.get(index)
}
}
impl Component {
#[must_use]
pub fn new(
width: u32,
height: u32,
bit_depth: u8,
signed: bool,
x_sampling: u8,
y_sampling: u8,
samples: Vec<i32>,
) -> Self {
Self {
width,
height,
bit_depth,
signed,
x_sampling,
y_sampling,
samples,
}
}
pub fn sample(&self, x: u32, y: u32) -> Option<i32> {
if x >= self.width || y >= self.height {
return None;
}
self.samples
.get((y as usize) * (self.width as usize) + x as usize)
.copied()
}
}
pub(crate) struct Canvas {
planes: Vec<Option<Samples>>,
rects: Vec<Rect>,
transforms: Vec<Transform>,
kept: Vec<bool>,
order: Vec<usize>,
windowed: bool,
}
impl Canvas {
pub(crate) fn bytes(&self) -> u64 {
self.rects
.iter()
.zip(&self.kept)
.filter(|(_, kept)| **kept)
.map(|(rect, _)| rect.area().saturating_mul(4))
.fold(0, u64::saturating_add)
}
#[cfg(test)]
pub(crate) fn new(header: &MainHeader, reduction: u8) -> Result<Self> {
let order: Vec<usize> = (0..header.siz.components.len()).collect();
Self::over(header, &header.siz, reduction, &order)
}
pub(crate) fn over(
header: &MainHeader,
area: &Siz,
reduction: u8,
order: &[usize],
) -> Result<Self> {
let count = area.components.len();
let (mut rects, mut transforms) = (Vec::with_capacity(count), Vec::with_capacity(count));
let mut kept = vec![false; count];
for &index in order {
let slot = kept.get_mut(index).ok_or_else(|| {
Error::inconsistent(format!("`SIZ` declares no component {index}"))
})?;
*slot = true;
}
for index in 0..count {
rects.push(
area.component_rect(index)
.ok_or_else(|| {
Error::inconsistent(format!("`SIZ` declares no component {index}"))
})?
.reduced(reduction),
);
transforms.push(
header
.components
.get(index)
.ok_or_else(|| {
Error::inconsistent(format!("no coding parameters for component {index}"))
})?
.coding
.transform,
);
}
Ok(Canvas {
planes: (0..count).map(|_| None).collect(),
rects,
transforms,
kept,
order: order.to_vec(),
windowed: area.image_rect() != header.siz.image_rect(),
})
}
pub(crate) fn keeps(&self, index: usize) -> bool {
self.kept.get(index).copied().unwrap_or(false)
}
pub(crate) fn place(&mut self, index: usize, rect: Rect, samples: Samples) -> Result<()> {
let ((plane, canvas), transform) = self
.planes
.get_mut(index)
.zip(self.rects.get(index))
.zip(self.transforms.get(index))
.ok_or_else(|| Error::inconsistent(format!("no canvas plane for component {index}")))?;
if samples.len() as u64 != rect.area() {
return Err(Error::inconsistent(format!(
"component {index} of a tile reconstructed {} samples but its {}x{} rectangle \
holds {}",
samples.len(),
rect.width(),
rect.height(),
rect.area(),
)));
}
if !matches!(
(transform, &samples),
(Transform::Reversible53, Samples::Reversible(_))
| (Transform::Irreversible97, Samples::Irreversible(_))
) {
return Err(Error::inconsistent(format!(
"a tile reconstructed component {index} on the other wavelet's arithmetic"
)));
}
if !self.kept.get(index).copied().unwrap_or(false) {
return Ok(());
}
if rect == *canvas {
*plane = Some(samples);
return Ok(());
}
let clip = rect.intersect(canvas);
if !self.windowed && clip != rect {
return Err(Error::inconsistent(format!(
"a tile's component {index} rectangle {rect:?} falls outside the canvas {canvas:?}",
)));
}
if clip.is_empty() {
return Ok(());
}
let plane = plane.get_or_insert_with(|| zeroed(*transform, canvas.area() as usize));
let copy = Crop {
dst_stride: canvas.width() as usize,
src_stride: rect.width() as usize,
width: clip.width() as usize,
height: clip.height() as usize,
src: ((clip.x0 - rect.x0) as usize, (clip.y0 - rect.y0) as usize),
dst: (
(clip.x0 - canvas.x0) as usize,
(clip.y0 - canvas.y0) as usize,
),
};
match (plane, samples) {
(Samples::Reversible(dst), Samples::Reversible(src)) => copy.run(dst, &src),
(Samples::Irreversible(dst), Samples::Irreversible(src)) => copy.run(dst, &src),
_ => {
return Err(Error::inconsistent(format!(
"a tile reconstructed component {index} on the other wavelet's arithmetic"
)));
}
}
Ok(())
}
pub(crate) fn into_planes(mut self) -> Vec<Samples> {
let mut out = Vec::with_capacity(self.order.len());
for &index in &self.order {
let plane = self.planes[index].take().unwrap_or_else(|| {
zeroed(self.transforms[index], self.rects[index].area() as usize)
});
out.push(plane);
}
out
}
}
struct Crop {
dst_stride: usize,
src_stride: usize,
width: usize,
height: usize,
src: (usize, usize),
dst: (usize, usize),
}
impl Crop {
fn run<T: Copy>(&self, dst: &mut [T], src: &[T]) {
for row in 0..self.height {
let from = (self.src.1 + row) * self.src_stride + self.src.0;
let to = (self.dst.1 + row) * self.dst_stride + self.dst.0;
dst[to..to + self.width].copy_from_slice(&src[from..from + self.width]);
}
}
}
fn zeroed(transform: Transform, count: usize) -> Samples {
match transform {
Transform::Reversible53 => Samples::Reversible(vec![0; count]),
Transform::Irreversible97 => Samples::Irreversible(vec![0.0; count]),
}
}
pub(crate) fn blit<T: Copy>(
dst: &mut [T],
stride: usize,
src: &[T],
src_width: usize,
left: usize,
top: usize,
) {
if src_width == 0 {
return;
}
for (row, line) in src.chunks_exact(src_width).enumerate() {
let start = (top + row) * stride + left;
dst[start..start + src_width].copy_from_slice(line);
}
}
#[cfg(test)]
pub(crate) fn assemble(header: &MainHeader, samples: Vec<Samples>, reduction: u8) -> Result<Image> {
let order: Vec<usize> = (0..header.siz.components.len()).collect();
assemble_over(&header.siz, samples, &order, reduction)
}
pub(crate) fn assemble_over(
area: &Siz,
samples: Vec<Samples>,
order: &[usize],
reduction: u8,
) -> Result<Image> {
if samples.len() != order.len() {
return Err(Error::inconsistent(format!(
"decoded {} components but the decode returns {}",
samples.len(),
order.len(),
)));
}
if samples.is_empty() {
return Err(Error::inconsistent("`SIZ` declares no components"));
}
let components = samples
.into_iter()
.zip(order)
.map(|(component_samples, &index)| {
assemble_component(area, index, component_samples, reduction)
})
.collect::<Result<Vec<_>>>()?;
let (image_width, image_height) = area.image_extent_at(reduction);
Ok(Image::new(image_width, image_height, components))
}
pub(crate) fn zero_tile(
image: &mut Image,
siz: &Siz,
area: &Siz,
order: &[usize],
tile: u32,
reduction: u8,
) {
for (component, &comp) in image.components.iter_mut().zip(order) {
let (Some(rect), Some(canvas)) = (
siz.tile_component_rect(tile, comp),
area.component_rect(comp),
) else {
continue;
};
let canvas = canvas.reduced(reduction);
let clip = rect.reduced(reduction).intersect(&canvas);
if clip.is_empty() {
continue;
}
let width = component.width as usize;
let x0 = (clip.x0 - canvas.x0) as usize;
let x1 = (clip.x1 - canvas.x0) as usize;
for y in clip.y0..clip.y1 {
let row = (y - canvas.y0) as usize;
if let Some(line) = component
.samples
.get_mut(row * width + x0..row * width + x1)
{
line.fill(0);
}
}
}
}
fn assemble_component(
siz: &Siz,
index: usize,
samples: Samples,
reduction: u8,
) -> Result<Component> {
let comp = siz
.components
.get(index)
.ok_or_else(|| Error::inconsistent(format!("`SIZ` declares no component {index}")))?;
let depth = comp.bit_depth;
if !(1..=38).contains(&depth) {
return Err(Error::marker(format!(
"component {index} has bit depth {depth}, outside the standard's range of 1 to 38"
)));
}
if comp.x_sampling == 0 || comp.y_sampling == 0 {
return Err(Error::marker(format!(
"component {index} sub-sampling factor is zero"
)));
}
let (width, height) = siz
.component_extent_at(index, reduction)
.ok_or_else(|| Error::inconsistent(format!("`SIZ` declares no component {index}")))?;
let expected = (width as usize) * (height as usize);
if samples.len() != expected {
return Err(Error::inconsistent(format!(
"component {index} decoded {} samples but its geometry is {width}x{height} = {expected}",
samples.len()
)));
}
let (shift, lo, hi): (i64, i64, i64) = if comp.signed {
(0, -(1i64 << (depth - 1)), (1i64 << (depth - 1)) - 1)
} else {
(1i64 << (depth - 1), 0, (1i64 << depth) - 1)
};
if hi > i32::MAX as i64 || lo < i32::MIN as i64 {
return Err(Error::unsupported(format!(
"component {index} depth {depth} ({}) exceeds the i32 sample container",
if comp.signed { "signed" } else { "unsigned" }
)));
}
let shifted: Vec<i32> = match samples {
Samples::Reversible(values) => values
.into_iter()
.map(|v| (v as i64 + shift).clamp(lo, hi) as i32)
.collect(),
Samples::Irreversible(values) => round_shift_clamp(values, depth, shift, lo, hi),
};
Ok(Component {
width,
height,
bit_depth: depth,
signed: comp.signed,
x_sampling: comp.x_sampling,
y_sampling: comp.y_sampling,
samples: shifted,
})
}
const ROUND_MAGIC: f32 = 12_582_912.0;
const MAGIC_MAX_DEPTH: u8 = 23;
fn round_shift_clamp(values: Vec<f32>, depth: u8, shift: i64, lo: i64, hi: i64) -> Vec<i32> {
if depth > MAGIC_MAX_DEPTH {
return values
.into_iter()
.map(|v| (v.round_ties_even() as i32 as i64 + shift).clamp(lo, hi) as i32)
.collect();
}
let low = (lo - shift) as f32;
let high = (hi - shift) as f32;
let shift = shift as i32;
let magic = ROUND_MAGIC.to_bits() as i32;
values
.into_iter()
.map(|v| {
let v = if v.is_nan() { 0.0 } else { v };
let v = if v < low {
low
} else if v > high {
high
} else {
v
};
(v + ROUND_MAGIC).to_bits() as i32 - magic + shift
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::codestream::markers::{Qcd, QuantStyle, Transform};
fn header(x_size: u32, y_size: u32, bit_depth: u8, signed: bool) -> MainHeader {
let qcd = Qcd {
style: QuantStyle::None,
guard_bits: 1,
steps: vec![],
};
MainHeader::single_component(
(x_size, y_size),
(bit_depth, signed),
(0, Transform::Reversible53),
qcd,
)
}
fn assemble1(header: &MainHeader, samples: Vec<i32>) -> Result<Image> {
assemble(header, vec![Samples::Reversible(samples)], 0)
}
fn only(img: &Image) -> &Component {
assert_eq!(img.components.len(), 1, "assemble emits one component");
img.component(0).unwrap()
}
#[test]
fn unsigned_adds_level_shift_and_clamps() {
let h = header(2, 2, 8, false);
let img = assemble1(&h, vec![0, -128, 127, 200]).unwrap();
assert_eq!(only(&img).samples, vec![128, 0, 255, 255]);
let img = assemble1(&header(1, 1, 8, false), vec![-200]).unwrap();
assert_eq!(only(&img).samples, vec![0]);
}
#[test]
fn signed_is_unshifted_and_clamps() {
let h = header(2, 2, 8, true);
let img = assemble1(&h, vec![0, 50, 200, -200]).unwrap();
assert_eq!(only(&img).samples, vec![0, 50, 127, -128]);
}
#[test]
fn wider_depths_round_trip_edges() {
let img = assemble1(&header(1, 4, 12, false), vec![-2048, 0, 2047, 9999]).unwrap();
assert_eq!(only(&img).samples, vec![0, 2048, 4095, 4095]);
let img = assemble1(&header(1, 3, 16, true), vec![-40000, 12345, 40000]).unwrap();
assert_eq!(only(&img).samples, vec![-32768, 12345, 32767]);
}
#[test]
fn geometry_uses_siz_image_area() {
let mut h = header(6, 5, 8, false);
h.siz.x_offset = 2;
h.siz.y_offset = 1;
let img = assemble1(&h, vec![0; 16]).unwrap();
assert_eq!((img.width, img.height), (4, 4));
let c = only(&img);
assert_eq!((c.width, c.height), (4, 4));
assert_eq!(c.bit_depth, 8);
assert!(!c.signed);
assert_eq!(c.sample(3, 3), Some(128));
assert_eq!(c.sample(4, 0), None);
}
#[test]
fn geometry_honors_sub_sampling() {
let mut h = header(8, 8, 8, false);
h.siz.components[0].x_sampling = 2;
h.siz.components[0].y_sampling = 2;
let img = assemble1(&h, vec![0; 16]).unwrap();
assert_eq!((img.width, img.height), (8, 8));
let c = only(&img);
assert_eq!((c.width, c.height), (4, 4));
assert_eq!((c.x_sampling, c.y_sampling), (2, 2));
}
#[test]
fn irreversible_samples_round_ties_to_even() {
let h = header(5, 1, 8, true);
let img = assemble(
&h,
vec![Samples::Irreversible(vec![0.5, 1.5, 2.5, -0.5, -2.5])],
0,
)
.unwrap();
assert_eq!(only(&img).samples, vec![0, 2, 2, 0, -2]);
let away: Vec<i32> = [0.5f32, 1.5, 2.5, -0.5, -2.5]
.iter()
.map(|v| v.round() as i32)
.collect();
assert_ne!(away, only(&img).samples);
}
#[test]
fn irreversible_samples_saturate_into_the_container() {
let h = header(2, 1, 16, true);
let img = assemble(&h, vec![Samples::Irreversible(vec![1e30, -1e30])], 0).unwrap();
assert_eq!(only(&img).samples, vec![32767, -32768]);
}
fn reference(v: f32, shift: i64, lo: i64, hi: i64) -> i32 {
(v.round_ties_even() as i32 as i64 + shift).clamp(lo, hi) as i32
}
fn bounds(depth: u8, signed: bool) -> (i64, i64, i64) {
if signed {
(0, -(1i64 << (depth - 1)), (1i64 << (depth - 1)) - 1)
} else {
(1i64 << (depth - 1), 0, (1i64 << depth) - 1)
}
}
fn check_against_reference(values: Vec<f32>, depth: u8, signed: bool) {
let (shift, lo, hi) = bounds(depth, signed);
let got = round_shift_clamp(values.clone(), depth, shift, lo, hi);
for (v, g) in values.iter().zip(got) {
assert_eq!(
g,
reference(*v, shift, lo, hi),
"depth {depth} signed {signed} input {v:e} (bits {:#010x})",
v.to_bits()
);
}
}
fn window(x: f32, ulps: u32, out: &mut Vec<f32>) {
let (mut up, mut down) = (x, x);
out.push(x);
for _ in 0..ulps {
up = up.next_up();
down = down.next_down();
out.push(up);
out.push(down);
}
}
fn special_values() -> Vec<f32> {
let mut v = vec![
0.0,
-0.0,
f32::NAN,
-f32::NAN,
f32::from_bits(0x7fc0_0001),
f32::from_bits(0xffbf_ffff),
f32::INFINITY,
f32::NEG_INFINITY,
f32::MAX,
f32::MIN,
f32::MIN_POSITIVE,
-f32::MIN_POSITIVE,
f32::from_bits(1),
-f32::from_bits(1),
1e30,
-1e30,
2147483648.0,
-2147483648.0,
4294967296.0,
];
for p in [21, 22, 23, 24, 25] {
let x = (1u32 << p) as f32;
for x in [x, -x, x + 0.5, -x - 0.5, x - 0.5, -x + 0.5] {
window(x, 8, &mut v);
}
}
v
}
#[test]
fn round_shift_clamp_matches_round_ties_even() {
let depths = (1..=16).chain([22, 23, 24, 32]);
for depth in depths {
for signed in [false, true] {
if !signed && depth == 32 {
continue; }
let (shift, lo, hi) = bounds(depth, signed);
let (low, high) = (lo - shift, hi - shift);
let mut values = special_values();
if depth <= 16 {
for n in (2 * (low - 2))..=(2 * (high + 2)) {
window(n as f32 / 2.0, 2, &mut values);
}
}
for center in [low, high, 0] {
for n in (2 * (center - 4))..=(2 * (center + 4)) {
window(n as f32 / 2.0, 256, &mut values);
}
}
check_against_reference(values, depth, signed);
}
}
}
#[test]
fn irreversible_ties_and_specials_through_assemble() {
let h = header(8, 1, 8, false);
let values = vec![
-0.0,
126.5,
127.5,
-127.5,
-128.5,
f32::NAN,
f32::INFINITY,
f32::NEG_INFINITY,
];
let img = assemble(&h, vec![Samples::Irreversible(values)], 0).unwrap();
assert_eq!(only(&img).samples, vec![128, 254, 255, 0, 0, 128, 255, 0]);
let h = header(3, 1, 24, true);
let values = vec![8_388_606.5, -8_388_607.5, 1e9];
let img = assemble(&h, vec![Samples::Irreversible(values)], 0).unwrap();
assert_eq!(only(&img).samples, vec![8_388_606, -8_388_608, 8_388_607]);
}
#[test]
#[ignore = "slow: about 30 CPU-minutes on a release build, spread over all cores"]
fn round_shift_clamp_matches_round_ties_even_on_every_f32() {
const CHUNK: u32 = 1 << 20;
let depths: Vec<u8> = (1..=16).chain([23]).collect();
let threads = std::thread::available_parallelism().map_or(4, |n| n.get());
std::thread::scope(|scope| {
for t in 0..threads {
let depths = &depths;
scope.spawn(move || {
let mut chunk = t as u64;
while chunk < (1u64 << 32) / CHUNK as u64 {
let start = chunk as u32 * CHUNK;
let values: Vec<f32> =
(start..=start + (CHUNK - 1)).map(f32::from_bits).collect();
for &depth in depths {
for signed in [false, true] {
let (shift, lo, hi) = bounds(depth, signed);
let got = round_shift_clamp(values.clone(), depth, shift, lo, hi);
for (v, g) in values.iter().zip(got) {
assert_eq!(
g,
reference(*v, shift, lo, hi),
"depth {depth} signed {signed} bits {:#010x}",
v.to_bits()
);
}
}
}
chunk += threads as u64;
}
});
}
});
}
#[test]
fn sample_count_mismatch_is_inconsistent() {
let h = header(4, 4, 8, false); let err = assemble1(&h, vec![0; 15]).unwrap_err();
assert!(matches!(err, Error::Inconsistent(_)), "got {err:?}");
}
#[test]
fn depth_beyond_i32_container_is_unsupported() {
for (depth, signed) in [(32, false), (33, false), (33, true), (38, true)] {
let h = header(1, 1, depth, signed);
let err = assemble1(&h, vec![0]).unwrap_err();
assert!(matches!(err, Error::Unsupported(_)), "{depth} got {err:?}");
}
let img = assemble1(&header(1, 1, 32, true), vec![i32::MIN]).unwrap();
assert_eq!(only(&img).samples, vec![i32::MIN]);
}
#[test]
fn bad_depth_is_rejected() {
for depth in [0, 39] {
let h = header(1, 1, depth, false);
assert!(matches!(assemble1(&h, vec![0]), Err(Error::Marker(_))));
}
}
fn rect(x0: u32, y0: u32, x1: u32, y1: u32) -> Rect {
Rect { x0, y0, x1, y1 }
}
#[test]
fn a_tile_covering_the_canvas_is_moved_in() {
let h = header(4, 2, 8, false);
let mut canvas = Canvas::new(&h, 0).unwrap();
let samples = vec![1, 2, 3, 4, 5, 6, 7, 8];
let at = samples.as_ptr();
canvas
.place(0, rect(0, 0, 4, 2), Samples::Reversible(samples))
.unwrap();
match canvas.into_planes().as_slice() {
[Samples::Reversible(plane)] => {
assert_eq!(plane, &[1, 2, 3, 4, 5, 6, 7, 8]);
assert_eq!(plane.as_ptr(), at, "the tile's buffer is the plane");
}
other => panic!("expected one reversible plane, got {other:?}"),
}
}
#[test]
fn partial_tiles_are_copied_into_one_plane() {
let h = header(4, 2, 8, false);
let mut canvas = Canvas::new(&h, 0).unwrap();
canvas
.place(0, rect(2, 0, 4, 2), Samples::Reversible(vec![3, 4, 7, 8]))
.unwrap();
canvas
.place(0, rect(0, 0, 2, 2), Samples::Reversible(vec![1, 2, 5, 6]))
.unwrap();
match canvas.into_planes().as_slice() {
[Samples::Reversible(plane)] => assert_eq!(plane, &[1, 2, 3, 4, 5, 6, 7, 8]),
other => panic!("expected one reversible plane, got {other:?}"),
}
}
#[test]
fn a_plane_no_tile_reached_is_zeros() {
let mut h = header(2, 1, 8, false);
h.components[0].coding.transform = Transform::Irreversible97;
match Canvas::new(&h, 0).unwrap().into_planes().as_slice() {
[Samples::Irreversible(plane)] => assert_eq!(plane, &[0.0, 0.0]),
other => panic!("expected one irreversible plane, got {other:?}"),
}
}
#[test]
fn a_tile_on_the_other_wavelet_is_inconsistent() {
let h = header(2, 2, 8, false);
for area in [rect(0, 0, 2, 2), rect(0, 0, 1, 2)] {
let mut canvas = Canvas::new(&h, 0).unwrap();
let samples = Samples::Irreversible(vec![0.0; area.area() as usize]);
let err = canvas.place(0, area, samples).unwrap_err();
assert!(
matches!(err, Error::Inconsistent(_)),
"{area:?} got {err:?}"
);
}
}
#[test]
fn a_tile_past_the_canvas_is_inconsistent_without_a_window() {
let h = header(4, 2, 8, false);
let mut canvas = Canvas::new(&h, 0).unwrap();
let err = canvas
.place(0, rect(2, 0, 6, 2), Samples::Reversible(vec![0; 8]))
.unwrap_err();
assert!(matches!(err, Error::Inconsistent(_)), "got {err:?}");
let mut area = h.siz.clone();
area.x_offset = 2;
let mut canvas = Canvas::over(&h, &area, 0, &[0]).unwrap();
canvas
.place(
0,
rect(0, 0, 4, 2),
Samples::Reversible(vec![1, 2, 3, 4, 5, 6, 7, 8]),
)
.unwrap();
match canvas.into_planes().as_slice() {
[Samples::Reversible(plane)] => assert_eq!(plane, &[3, 4, 7, 8]),
other => panic!("expected one reversible plane, got {other:?}"),
}
}
}