rust_j2k/image.rs
1//! Decoder output: the image area on the reference grid, and one integer
2//! component per output channel, each in raster order on its own sample grid,
3//! plus the metadata a caller needs to interpret the samples (bit depth,
4//! signedness, sub-sampling).
5
6use crate::codestream::MainHeader;
7use crate::codestream::markers::{Rect, Siz, Transform};
8use crate::pipeline::Samples;
9use crate::{DecodeReport, Error, Jp2Metadata, Result};
10
11/// A decoded image: the image area on the reference grid, plus its components.
12///
13/// [`width`](Self::width) and [`height`](Self::height) describe the *reference
14/// grid* image area (`Xsiz - XOsiz` by `Ysiz - YOsiz`), which is the coordinate
15/// space the components are registered against. Under a resolution reduction
16/// of `r` levels they are that area at the reduced resolution:
17/// `ceil(Xsiz / 2^r) - ceil(XOsiz / 2^r)` by the same in y. A sub-sampled component covers
18/// that same area with fewer samples, so its own
19/// [`Component::width`]/[`Component::height`] can be smaller. With unit
20/// sub-sampling, the common case, they are equal.
21///
22/// Components are in output-channel order. For a raw codestream that is SIZ
23/// order; a JP2 file's palette, channel definitions and sRGB option can change
24/// the channels (see [`components`](Self::components)). The codestream's
25/// inter-component (color) transform, and a JP2 file's palette and channel
26/// definitions, are part of decoding (unless
27/// [`raw_channels`](crate::DecodeOptions::raw_channels) is set); no color
28/// conversion is applied unless the caller asks for sRGB output.
29///
30/// The struct is `#[non_exhaustive]`, so fields can be added without a
31/// breaking change, and [`decode`](crate::decode) is the normal producer. To
32/// build one by hand, such as an expected image in a test harness, use
33/// [`Image::new`].
34#[derive(Debug, Clone, PartialEq, Eq)]
35#[non_exhaustive]
36pub struct Image {
37 /// The image area's width: reference-grid points, or points of the
38 /// reduced grid under a resolution reduction.
39 pub width: u32,
40 /// The image area's height, as [`width`](Self::width).
41 pub height: u32,
42 /// One entry per output channel. For a raw codestream, and for a JP2 file
43 /// with no palette, no channel definitions and as-coded output, that is one
44 /// per SIZ component, in SIZ order. A palette makes one channel per
45 /// palette column, channel definitions put the color channels in color
46 /// order, and sRGB output can change the count (a monochrome profile can
47 /// give three). Never empty in decoder output.
48 pub components: Vec<Component>,
49 /// What the JP2 wrapper said about the samples: their color space and
50 /// what each channel is. `None` for a raw codestream.
51 pub jp2: Option<Jp2Metadata>,
52 /// What the decode left out. A strict decode (the default) gives the
53 /// complete report, [`DecodeReport::default`]; with
54 /// [`strict`](crate::DecodeOptions::strict) off it lists what was missing
55 /// or skipped. `Image`'s `PartialEq` compares the report too, so two
56 /// images with the same samples and different reports are not equal.
57 pub report: DecodeReport,
58}
59
60/// One decoded component: its own sample grid, its declared depth and sign, and
61/// the sub-sampling that maps it onto the image's reference grid.
62///
63/// `samples` is row-major, `width * height` entries, each already
64/// DC-level-shifted and clamped to the declared depth.
65///
66/// A channel made by a JP2 palette (`pclr`) is different: its depth and sign
67/// come from the palette's `Bi` (for a direct channel `i`, from column `i`),
68/// and its samples are the palette entries as stored (for a direct channel,
69/// the component's samples). Its samples can fall outside the range that depth
70/// and sign declare, as in OpenJPEG.
71///
72/// `#[non_exhaustive]`, like [`Image`]; build one by hand with
73/// [`Component::new`].
74#[derive(Debug, Clone, PartialEq, Eq)]
75#[non_exhaustive]
76pub struct Component {
77 /// Component width in samples.
78 pub width: u32,
79 /// Component height in samples.
80 pub height: u32,
81 /// Bits per sample as declared in SIZ `Ssiz`, or by the palette for a
82 /// palette channel: 1 to 31 for unsigned samples, 1 to 32 for signed ones
83 /// (the `i32` container holds both).
84 ///
85 /// Except in a palette channel (see [`Component`]), unsigned samples run
86 /// from 0 to `2^bit_depth - 1`; signed samples from
87 /// `-2^(bit_depth - 1)` to `2^(bit_depth - 1) - 1`. To map a signed
88 /// sample to an unsigned one, add `2^(bit_depth - 1)` (do it in `i64`,
89 /// since the sum overflows `i32` at 32 bits).
90 pub bit_depth: u8,
91 /// Whether samples are signed (SIZ component sign bit, or the palette's).
92 pub signed: bool,
93 /// Horizontal sub-sampling factor (SIZ `XRsiz`); `1` means no
94 /// sub-sampling.
95 pub x_sampling: u8,
96 /// Vertical sub-sampling factor (SIZ `YRsiz`); `1` means no
97 /// sub-sampling.
98 pub y_sampling: u8,
99 /// `width * height` samples, row-major.
100 pub samples: Vec<i32>,
101}
102
103impl Image {
104 /// Package `components` with the reference-grid image area they are
105 /// registered against, and no JP2 metadata ([`jp2`](Self::jp2) is `None`).
106 /// The values are stored as given; only [`decode`](crate::decode) vouches
107 /// for their consistency.
108 #[must_use]
109 pub fn new(width: u32, height: u32, components: Vec<Component>) -> Self {
110 Self {
111 width,
112 height,
113 components,
114 jp2: None,
115 report: DecodeReport::default(),
116 }
117 }
118
119 /// The component at `index` in [`components`](Self::components) order,
120 /// or `None` if out of range.
121 pub fn component(&self, index: usize) -> Option<&Component> {
122 self.components.get(index)
123 }
124}
125
126impl Component {
127 /// Package a component's samples with their geometry and interpretation.
128 /// The values are stored as given; only [`decode`](crate::decode) vouches
129 /// for their consistency.
130 #[must_use]
131 pub fn new(
132 width: u32,
133 height: u32,
134 bit_depth: u8,
135 signed: bool,
136 x_sampling: u8,
137 y_sampling: u8,
138 samples: Vec<i32>,
139 ) -> Self {
140 Self {
141 width,
142 height,
143 bit_depth,
144 signed,
145 x_sampling,
146 y_sampling,
147 samples,
148 }
149 }
150
151 /// Sample at `(x, y)` on this component's own grid, or `None` if out of bounds.
152 pub fn sample(&self, x: u32, y: u32) -> Option<i32> {
153 if x >= self.width || y >= self.height {
154 return None;
155 }
156 self.samples
157 .get((y as usize) * (self.width as usize) + x as usize)
158 .copied()
159 }
160}
161
162/// The per-component sample planes a tiled decode reconstructs into: one plane
163/// per SIZ component, sized to that component's whole grid, which each tile
164/// writes its own rectangle of.
165///
166/// Tiles are decoded independently — their own coordinate frame, their own
167/// header, their own wavelet pyramid — and the canvas is where they meet again.
168/// A tile-component's reconstructed raster is placed at the tile's offset on the
169/// component grid; the tiles partition that grid exactly, so every sample is
170/// written once. Nothing is blended and no tile overlaps another: the wavelet
171/// transform is applied per tile, which is why a tiled encode can show seams,
172/// and reproducing them is correct.
173///
174/// A plane is allocated when its first tile arrives. A tile that covers the
175/// whole plane, as the only tile of an image does, becomes the plane: its
176/// raster is moved in rather than copied, so the decode never holds two
177/// image-sized buffers for one component.
178pub(crate) struct Canvas {
179 planes: Vec<Option<Samples>>,
180 /// Each component's whole grid at the decode's reduction — the rectangle a
181 /// tile's placement is measured against.
182 rects: Vec<Rect>,
183 /// Each component's wavelet, which fixes its plane's arithmetic.
184 transforms: Vec<Transform>,
185}
186
187impl Canvas {
188 /// Record each component's grid at the reduced size [`assemble`] will
189 /// expect, and its wavelet.
190 ///
191 /// A plane's arithmetic follows its component's wavelet — 5/3 reconstructs
192 /// exact integers, 9/7 reals — which is why `parse` rejects a codestream
193 /// whose tiles disagree about a component's wavelet: it would ask one plane
194 /// to hold both.
195 pub(crate) fn new(header: &MainHeader, reduction: u8) -> Result<Self> {
196 let siz = &header.siz;
197 let count = siz.components.len();
198 let (mut rects, mut transforms) = (Vec::with_capacity(count), Vec::with_capacity(count));
199 for index in 0..count {
200 rects.push(
201 siz.component_rect(index)
202 .ok_or_else(|| {
203 Error::Inconsistent(format!("`SIZ` declares no component {index}"))
204 })?
205 .reduced(reduction),
206 );
207 transforms.push(
208 header
209 .components
210 .get(index)
211 .ok_or_else(|| {
212 Error::Inconsistent(format!("no coding parameters for component {index}"))
213 })?
214 .coding
215 .transform,
216 );
217 }
218 Ok(Canvas {
219 planes: (0..count).map(|_| None).collect(),
220 rects,
221 transforms,
222 })
223 }
224
225 /// Write one tile-component's reconstructed raster into its component's
226 /// plane. `rect` is the tile-component's rectangle on the component grid, at
227 /// the same reduction the canvas was built at.
228 pub(crate) fn place(&mut self, index: usize, rect: Rect, samples: Samples) -> Result<()> {
229 let ((plane, canvas), transform) = self
230 .planes
231 .get_mut(index)
232 .zip(self.rects.get(index))
233 .zip(self.transforms.get(index))
234 .ok_or_else(|| Error::Inconsistent(format!("no canvas plane for component {index}")))?;
235 if samples.len() as u64 != rect.area() {
236 return Err(Error::Inconsistent(format!(
237 "component {index} of a tile reconstructed {} samples but its {}x{} rectangle \
238 holds {}",
239 samples.len(),
240 rect.width(),
241 rect.height(),
242 rect.area(),
243 )));
244 }
245 // The tile grid partitions the canvas, so this only fails on a header
246 // whose SIZ tiling and whose decoded geometry disagree.
247 if rect.x0 < canvas.x0 || rect.y0 < canvas.y0 || rect.x1 > canvas.x1 || rect.y1 > canvas.y1
248 {
249 return Err(Error::Inconsistent(format!(
250 "a tile's component {index} rectangle {rect:?} falls outside the canvas {canvas:?}",
251 )));
252 }
253 if !matches!(
254 (transform, &samples),
255 (Transform::Reversible53, Samples::Reversible(_))
256 | (Transform::Irreversible97, Samples::Irreversible(_))
257 ) {
258 return Err(Error::Inconsistent(format!(
259 "a tile reconstructed component {index} on the other wavelet's arithmetic"
260 )));
261 }
262 // A tile that covers the whole plane writes every sample of it, so its
263 // raster is the plane.
264 if rect == *canvas {
265 *plane = Some(samples);
266 return Ok(());
267 }
268 let plane = plane.get_or_insert_with(|| zeroed(*transform, canvas.area() as usize));
269 let (left, top) = (
270 (rect.x0 - canvas.x0) as usize,
271 (rect.y0 - canvas.y0) as usize,
272 );
273 let stride = canvas.width() as usize;
274 match (plane, samples) {
275 (Samples::Reversible(dst), Samples::Reversible(src)) => {
276 blit(dst, stride, &src, rect.width() as usize, left, top);
277 }
278 (Samples::Irreversible(dst), Samples::Irreversible(src)) => {
279 blit(dst, stride, &src, rect.width() as usize, left, top);
280 }
281 _ => {
282 return Err(Error::Inconsistent(format!(
283 "a tile reconstructed component {index} on the other wavelet's arithmetic"
284 )));
285 }
286 }
287 Ok(())
288 }
289
290 /// The finished planes, in SIZ component order, ready for [`assemble`]. A
291 /// plane no tile reached is all zeros.
292 pub(crate) fn into_planes(self) -> Vec<Samples> {
293 self.planes
294 .into_iter()
295 .zip(self.rects)
296 .zip(self.transforms)
297 .map(|((plane, rect), transform)| {
298 plane.unwrap_or_else(|| zeroed(transform, rect.area() as usize))
299 })
300 .collect()
301 }
302}
303
304/// A zeroed plane of `count` samples on `transform`'s arithmetic.
305fn zeroed(transform: Transform, count: usize) -> Samples {
306 match transform {
307 Transform::Reversible53 => Samples::Reversible(vec![0; count]),
308 Transform::Irreversible97 => Samples::Irreversible(vec![0.0; count]),
309 }
310}
311
312/// Copy a `src_width`-wide raster into `dst` (a `stride`-wide raster) with its
313/// top-left at `(left, top)`. The caller has already checked that it fits.
314pub(crate) fn blit<T: Copy>(
315 dst: &mut [T],
316 stride: usize,
317 src: &[T],
318 src_width: usize,
319 left: usize,
320 top: usize,
321) {
322 if src_width == 0 {
323 return;
324 }
325 for (row, line) in src.chunks_exact(src_width).enumerate() {
326 let start = (top + row) * stride + left;
327 dst[start..start + src_width].copy_from_slice(line);
328 }
329}
330
331/// Final stage: apply the inverse DC level shift, clamp to the component depth,
332/// and package the reconstructed samples with their geometry.
333///
334/// The component geometry follows the SIZ reference-grid equations (ISO/IEC
335/// 15444-1 §B.2): for sub-sampling factors `XRsiz`/`YRsiz`,
336///
337/// ```text
338/// width = ceil(Xsiz / XRsiz) - ceil(XOsiz / XRsiz)
339/// height = ceil(Ysiz / YRsiz) - ceil(YOsiz / YRsiz)
340/// ```
341///
342/// which reduces to the image area `Xsiz - XOsiz` by `Ysiz - YOsiz` under unit
343/// sub-sampling. The image area itself is carried on the [`Image`].
344///
345/// The inverse DC level shift (§G.1.2) adds `2^(depth-1)` back to *unsigned*
346/// components (the encoder subtracted it before the forward transform); signed
347/// components are left as-is. Samples are then clamped to the declared depth
348/// and sign before being packed row-major into a [`Component`].
349///
350/// `samples` carries one reconstructed sample vector per SIZ component, in SIZ
351/// order — [`Canvas::into_planes`] output. Each is level-shifted and clamped
352/// on its own component's depth and sign, then packed with that component's
353/// geometry.
354pub(crate) fn assemble(header: &MainHeader, samples: Vec<Samples>, reduction: u8) -> Result<Image> {
355 let siz = &header.siz;
356 if samples.len() != siz.components.len() {
357 return Err(Error::Inconsistent(format!(
358 "decoded {} components but `SIZ` declares {}",
359 samples.len(),
360 siz.components.len(),
361 )));
362 }
363 if samples.is_empty() {
364 return Err(Error::Inconsistent("`SIZ` declares no components".into()));
365 }
366
367 let components = samples
368 .into_iter()
369 .enumerate()
370 .map(|(index, component_samples)| {
371 assemble_component(siz, index, component_samples, reduction)
372 })
373 .collect::<Result<Vec<_>>>()?;
374
375 // At a reduction the image area shrinks with its components, by the same
376 // halve-and-round-up per dropped level.
377 let (image_width, image_height) = siz.image_extent_at(reduction);
378 Ok(Image::new(image_width, image_height, components))
379}
380
381/// Set tile `tile`'s samples to 0 in every component of `image`, a decode at
382/// `reduction`: what a tile no tile-part of reached gives, after the DC level
383/// shift, as `opj_decompress -allow-partial` writes it.
384pub(crate) fn zero_tile(image: &mut Image, siz: &Siz, tile: u32, reduction: u8) {
385 for (comp, component) in image.components.iter_mut().enumerate() {
386 let (Some(rect), Some(canvas)) = (
387 siz.tile_component_rect(tile, comp),
388 siz.component_rect(comp),
389 ) else {
390 continue;
391 };
392 let (rect, canvas) = (rect.reduced(reduction), canvas.reduced(reduction));
393 let width = component.width as usize;
394 let x0 = rect.x0.saturating_sub(canvas.x0) as usize;
395 let x1 = (rect.x1.saturating_sub(canvas.x0) as usize).min(width);
396 for y in rect.y0..rect.y1 {
397 let row = y.saturating_sub(canvas.y0) as usize;
398 if let Some(line) = component
399 .samples
400 .get_mut(row * width + x0..row * width + x1)
401 {
402 line.fill(0);
403 }
404 }
405 }
406}
407
408/// Round to the nearest integer, level-shift, clamp, and package one
409/// component's reconstructed samples.
410///
411/// This is the *only* place the irreversible path rounds. It happens after the
412/// inverse color transform, matching `opj_tcd_dc_level_shift_decode`, which
413/// calls `opj_lrintf` and then adds the DC level shift and clamps:
414///
415/// ```c
416/// OPJ_INT64 l_value_int = (OPJ_INT64)opj_lrintf(l_value);
417/// *l_dest = opj_int64_clamp(l_value_int + l_tccp->m_dc_level_shift, l_min, l_max);
418/// ```
419///
420/// `opj_lrintf` is `lrintf` on GCC and Clang — the build that produced the
421/// committed oracles — and `lrintf` rounds under the default floating-point
422/// mode, which is ties-to-even. Its MSVC arms (`cvtss2si`, `fistp`) round
423/// ties-to-even too. Rust's `f32::round` rounds ties *away from zero*, so `2.5`
424/// would become `3` where the oracle gives `2`; `round_ties_even` agrees.
425///
426/// OpenJPEG tried the away-from-zero form and reverted it, leaving the evidence
427/// in `opj_includes.h`:
428///
429/// ```c
430/// /* commented out line breaks many tests */
431/// /* return (long)((f>0.0f) ? (f + 0.5f):(f -0.5f)); */
432/// ```
433fn assemble_component(
434 siz: &Siz,
435 index: usize,
436 samples: Samples,
437 reduction: u8,
438) -> Result<Component> {
439 let comp = siz
440 .components
441 .get(index)
442 .ok_or_else(|| Error::Inconsistent(format!("`SIZ` declares no component {index}")))?;
443
444 let depth = comp.bit_depth;
445 // The standard allows 1..=38 (Table A-11) and `decode_siz` enforces it;
446 // this defensive restatement keeps the shift arithmetic below well-defined
447 // for callers that assemble a header by hand. Legal depths whose range
448 // does not fit the i32 sample container (33..=38, and unsigned 32) fall
449 // through to the container check, which rejects them as Unsupported.
450 if !(1..=38).contains(&depth) {
451 return Err(Error::Marker(format!(
452 "component {index} has bit depth {depth}, outside the standard's range of 1 to 38"
453 )));
454 }
455 if comp.x_sampling == 0 || comp.y_sampling == 0 {
456 return Err(Error::Marker(format!(
457 "component {index} sub-sampling factor is zero"
458 )));
459 }
460
461 // Safe now that the zero-factor case above is excluded.
462 let (width, height) = siz
463 .component_extent_at(index, reduction)
464 .ok_or_else(|| Error::Inconsistent(format!("`SIZ` declares no component {index}")))?;
465
466 let expected = (width as usize) * (height as usize);
467 if samples.len() != expected {
468 return Err(Error::Inconsistent(format!(
469 "component {index} decoded {} samples but its geometry is {width}x{height} = {expected}",
470 samples.len()
471 )));
472 }
473
474 // Level-shift offset and the clamp bounds, all in i64 so the `1 << 31`
475 // signed-32-bit case and the unsigned `2^depth - 1` upper bound cannot
476 // overflow during the computation.
477 let (shift, lo, hi): (i64, i64, i64) = if comp.signed {
478 (0, -(1i64 << (depth - 1)), (1i64 << (depth - 1)) - 1)
479 } else {
480 (1i64 << (depth - 1), 0, (1i64 << depth) - 1)
481 };
482
483 // The output container is `i32`; reject depths whose clamp range cannot be
484 // represented (e.g. unsigned 32-bit, whose max is `2^32 - 1`). Checked once
485 // so the per-sample cast below is always exact.
486 if hi > i32::MAX as i64 || lo < i32::MIN as i64 {
487 return Err(Error::Unsupported(format!(
488 "component {index} depth {depth} ({}) exceeds the i32 sample container",
489 if comp.signed { "signed" } else { "unsigned" }
490 )));
491 }
492
493 let shifted: Vec<i32> = match samples {
494 Samples::Reversible(values) => values
495 .into_iter()
496 .map(|v| (v as i64 + shift).clamp(lo, hi) as i32)
497 .collect(),
498 // The irreversible path arrives unrounded.
499 Samples::Irreversible(values) => round_shift_clamp(values, depth, shift, lo, hi),
500 };
501
502 Ok(Component {
503 width,
504 height,
505 bit_depth: depth,
506 signed: comp.signed,
507 x_sampling: comp.x_sampling,
508 y_sampling: comp.y_sampling,
509 samples: shifted,
510 })
511}
512
513/// `1.5 * 2^23`. For `-2^22 <= x < 2^22`, `x + ROUND_MAGIC` lies in
514/// `[2^23, 2^24]`, where consecutive `f32` values are exactly 1 apart (2^24
515/// itself is reached only by rounding up from just below it, and its bit
516/// pattern still follows on by one), so the addition itself rounds `x` to an
517/// integer, ties to even under the default rounding mode, and that integer is
518/// the sum's bit pattern minus `ROUND_MAGIC`'s. [`round_shift_clamp`] clamps
519/// first, so `x` is at most `2^22 - 1` there.
520const ROUND_MAGIC: f32 = 12_582_912.0;
521
522/// The deepest component [`round_shift_clamp`] rounds with [`ROUND_MAGIC`].
523/// Before the level shift, a `depth`-bit component's range is
524/// `[-2^(depth-1), 2^(depth-1) - 1]` whatever its sign, which stays inside
525/// `±2^22` up to 23 bits. Deeper components take the `round_ties_even` path.
526const MAGIC_MAX_DEPTH: u8 = 23;
527
528/// Round each irreversible sample to the nearest integer, ties to even, then
529/// add the level shift `shift` and clamp to `lo..=hi`, in one pass.
530///
531/// This gives exactly what `(v.round_ties_even() as i32 as i64 + shift)
532/// .clamp(lo, hi)` gives, including NaN to `shift` and the infinities to the
533/// clamp ends, without a `rintf` call per sample: baseline x86-64 has no
534/// rounding instruction, so `round_ties_even` is a libm call there. The clamp
535/// moves ahead of the rounding, in `f32` before the shift; that is the same
536/// result because the bounds are integers and rounding is monotonic.
537fn round_shift_clamp(values: Vec<f32>, depth: u8, shift: i64, lo: i64, hi: i64) -> Vec<i32> {
538 if depth > MAGIC_MAX_DEPTH {
539 // `as i32` saturates, so a value outside the container cannot wrap
540 // before the clamp sees it.
541 return values
542 .into_iter()
543 .map(|v| (v.round_ties_even() as i32 as i64 + shift).clamp(lo, hi) as i32)
544 .collect();
545 }
546 // Exact: both bounds are at most 2^22 in magnitude here.
547 let low = (lo - shift) as f32;
548 let high = (hi - shift) as f32;
549 let shift = shift as i32;
550 let magic = ROUND_MAGIC.to_bits() as i32;
551 values
552 .into_iter()
553 .map(|v| {
554 // NaN becomes 0, as `NaN as i32` did on the general path.
555 let v = if v.is_nan() { 0.0 } else { v };
556 let v = if v < low {
557 low
558 } else if v > high {
559 high
560 } else {
561 v
562 };
563 (v + ROUND_MAGIC).to_bits() as i32 - magic + shift
564 })
565 .collect()
566}
567
568#[cfg(test)]
569mod tests {
570 use super::*;
571 use crate::codestream::markers::{
572 Cod, Progression, Qcd, QuantStyle, Siz, SizComponent, Transform,
573 };
574
575 /// A minimal single-component header: an image of `x_size` by `y_size` at the
576 /// origin with unit sub-sampling. Only the SIZ fields `assemble` reads
577 /// matter; COD/QCD are filler. Tests tweak offsets/sampling on the result.
578 fn header(x_size: u32, y_size: u32, bit_depth: u8, signed: bool) -> MainHeader {
579 MainHeader::new(
580 Siz {
581 x_size,
582 y_size,
583 x_offset: 0,
584 y_offset: 0,
585 tile_width: x_size,
586 tile_height: y_size,
587 tile_x_offset: 0,
588 tile_y_offset: 0,
589 components: vec![SizComponent {
590 bit_depth,
591 signed,
592 x_sampling: 1,
593 y_sampling: 1,
594 }],
595 },
596 Cod {
597 progression: Progression::Lrcp,
598 layers: 1,
599 decomposition_levels: 0,
600 code_block_width: 4,
601 code_block_height: 4,
602 code_block_style: 0,
603 use_sop: false,
604 use_eph: false,
605 multiple_component_transform: false,
606 transform: Transform::Reversible53,
607 precinct_sizes: vec![],
608 },
609 Qcd {
610 style: QuantStyle::None,
611 guard_bits: 1,
612 steps: vec![],
613 },
614 )
615 }
616
617 /// Assemble a single-component image: most of these tests predate the
618 /// component axis and care only about level shift, clamping, and geometry.
619 fn assemble1(header: &MainHeader, samples: Vec<i32>) -> Result<Image> {
620 assemble(header, vec![Samples::Reversible(samples)], 0)
621 }
622
623 /// The single component `assemble` produces, for tests that only care about
624 /// the samples and not the enclosing image area.
625 fn only(img: &Image) -> &Component {
626 assert_eq!(img.components.len(), 1, "assemble emits one component");
627 img.component(0).unwrap()
628 }
629
630 #[test]
631 fn unsigned_adds_level_shift_and_clamps() {
632 // 8-bit unsigned: shift = 128, clamp to [0, 255].
633 let h = header(2, 2, 8, false);
634 let img = assemble1(&h, vec![0, -128, 127, 200]).unwrap();
635 // 0 -> 128 (mid), -128 -> 0 (low edge), 127 -> 255 (high edge),
636 // 200 -> 328 clamps to 255.
637 assert_eq!(only(&img).samples, vec![128, 0, 255, 255]);
638 // And the low edge under-shoot also clamps.
639 let img = assemble1(&header(1, 1, 8, false), vec![-200]).unwrap();
640 assert_eq!(only(&img).samples, vec![0]);
641 }
642
643 #[test]
644 fn signed_is_unshifted_and_clamps() {
645 // 8-bit signed: no shift, clamp to [-128, 127].
646 let h = header(2, 2, 8, true);
647 let img = assemble1(&h, vec![0, 50, 200, -200]).unwrap();
648 assert_eq!(only(&img).samples, vec![0, 50, 127, -128]);
649 }
650
651 #[test]
652 fn wider_depths_round_trip_edges() {
653 // 12-bit unsigned: shift = 2048, clamp to [0, 4095].
654 let img = assemble1(&header(1, 4, 12, false), vec![-2048, 0, 2047, 9999]).unwrap();
655 assert_eq!(only(&img).samples, vec![0, 2048, 4095, 4095]);
656 // 16-bit signed: clamp to [-32768, 32767], no shift.
657 let img = assemble1(&header(1, 3, 16, true), vec![-40000, 12345, 40000]).unwrap();
658 assert_eq!(only(&img).samples, vec![-32768, 12345, 32767]);
659 }
660
661 #[test]
662 fn geometry_uses_siz_image_area() {
663 let mut h = header(6, 5, 8, false);
664 h.siz.x_offset = 2;
665 h.siz.y_offset = 1;
666 // width = 6 - 2 = 4, height = 5 - 1 = 4.
667 let img = assemble1(&h, vec![0; 16]).unwrap();
668 assert_eq!((img.width, img.height), (4, 4));
669 let c = only(&img);
670 assert_eq!((c.width, c.height), (4, 4));
671 assert_eq!(c.bit_depth, 8);
672 assert!(!c.signed);
673 assert_eq!(c.sample(3, 3), Some(128));
674 assert_eq!(c.sample(4, 0), None);
675 }
676
677 #[test]
678 fn geometry_honors_sub_sampling() {
679 let mut h = header(8, 8, 8, false);
680 h.siz.components[0].x_sampling = 2;
681 h.siz.components[0].y_sampling = 2;
682 let img = assemble1(&h, vec![0; 16]).unwrap();
683 // The image area stays on the reference grid ...
684 assert_eq!((img.width, img.height), (8, 8));
685 // ... while the component carries ceil(8/2) - ceil(0/2) = 4 per axis.
686 let c = only(&img);
687 assert_eq!((c.width, c.height), (4, 4));
688 assert_eq!((c.x_sampling, c.y_sampling), (2, 2));
689 }
690
691 /// The irreversible path rounds once, here, and rounds ties to even —
692 /// matching `opj_lrintf` under the default floating-point mode. Rust's
693 /// `f32::round` rounds ties away from zero and would disagree at every
694 /// half-integer.
695 #[test]
696 fn irreversible_samples_round_ties_to_even() {
697 // 8-bit signed: no level shift, clamp to [-128, 127].
698 let h = header(5, 1, 8, true);
699 let img = assemble(
700 &h,
701 vec![Samples::Irreversible(vec![0.5, 1.5, 2.5, -0.5, -2.5])],
702 0,
703 )
704 .unwrap();
705 assert_eq!(only(&img).samples, vec![0, 2, 2, 0, -2]);
706
707 // Away-from-zero would have given [1, 2, 3, -1, -3].
708 let away: Vec<i32> = [0.5f32, 1.5, 2.5, -0.5, -2.5]
709 .iter()
710 .map(|v| v.round() as i32)
711 .collect();
712 assert_ne!(away, only(&img).samples);
713 }
714
715 /// A reconstructed value outside the `i32` container saturates rather than
716 /// wrapping, before the depth clamp sees it.
717 #[test]
718 fn irreversible_samples_saturate_into_the_container() {
719 let h = header(2, 1, 16, true);
720 let img = assemble(&h, vec![Samples::Irreversible(vec![1e30, -1e30])], 0).unwrap();
721 assert_eq!(only(&img).samples, vec![32767, -32768]);
722 }
723
724 /// What [`round_shift_clamp`] must equal: round ties to even, saturate into
725 /// `i32`, shift, clamp.
726 fn reference(v: f32, shift: i64, lo: i64, hi: i64) -> i32 {
727 (v.round_ties_even() as i32 as i64 + shift).clamp(lo, hi) as i32
728 }
729
730 /// The level shift and clamp bounds `assemble_component` derives.
731 fn bounds(depth: u8, signed: bool) -> (i64, i64, i64) {
732 if signed {
733 (0, -(1i64 << (depth - 1)), (1i64 << (depth - 1)) - 1)
734 } else {
735 (1i64 << (depth - 1), 0, (1i64 << depth) - 1)
736 }
737 }
738
739 /// Check `values` through [`round_shift_clamp`] against [`reference`].
740 fn check_against_reference(values: Vec<f32>, depth: u8, signed: bool) {
741 let (shift, lo, hi) = bounds(depth, signed);
742 let got = round_shift_clamp(values.clone(), depth, shift, lo, hi);
743 for (v, g) in values.iter().zip(got) {
744 assert_eq!(
745 g,
746 reference(*v, shift, lo, hi),
747 "depth {depth} signed {signed} input {v:e} (bits {:#010x})",
748 v.to_bits()
749 );
750 }
751 }
752
753 /// The `f32` values within `ulps` steps of `x` on either side, `x` included.
754 fn window(x: f32, ulps: u32, out: &mut Vec<f32>) {
755 let (mut up, mut down) = (x, x);
756 out.push(x);
757 for _ in 0..ulps {
758 up = up.next_up();
759 down = down.next_down();
760 out.push(up);
761 out.push(down);
762 }
763 }
764
765 /// Values every depth must handle: zeros, NaNs, infinities, extremes, and
766 /// the neighborhoods of 2^22, 2^23 and 2^24 where `ROUND_MAGIC` stops
767 /// being exact.
768 fn special_values() -> Vec<f32> {
769 let mut v = vec![
770 0.0,
771 -0.0,
772 f32::NAN,
773 -f32::NAN,
774 f32::from_bits(0x7fc0_0001),
775 f32::from_bits(0xffbf_ffff),
776 f32::INFINITY,
777 f32::NEG_INFINITY,
778 f32::MAX,
779 f32::MIN,
780 f32::MIN_POSITIVE,
781 -f32::MIN_POSITIVE,
782 f32::from_bits(1),
783 -f32::from_bits(1),
784 1e30,
785 -1e30,
786 2147483648.0,
787 -2147483648.0,
788 4294967296.0,
789 ];
790 for p in [21, 22, 23, 24, 25] {
791 let x = (1u32 << p) as f32;
792 for x in [x, -x, x + 0.5, -x - 0.5, x - 0.5, -x + 0.5] {
793 window(x, 8, &mut v);
794 }
795 }
796 v
797 }
798
799 /// Ties to even, the level shift and the clamp, bit for bit against
800 /// `round_ties_even`, over every half-integer in and around each depth's
801 /// range (with neighbors), every `f32` near the clamp ends and zero, and
802 /// the special values.
803 #[test]
804 fn round_shift_clamp_matches_round_ties_even() {
805 // 1..=16 run the ROUND_MAGIC path at every width used in practice; 22
806 // and 23 are its deepest; 24 and 32 are the fallback.
807 let depths = (1..=16).chain([22, 23, 24, 32]);
808 for depth in depths {
809 for signed in [false, true] {
810 if !signed && depth == 32 {
811 continue; // Rejected before rounding: exceeds i32.
812 }
813 let (shift, lo, hi) = bounds(depth, signed);
814 let (low, high) = (lo - shift, hi - shift);
815 let mut values = special_values();
816 if depth <= 16 {
817 // Every half-integer and integer across the range and two
818 // past each end, with two f32 steps either side.
819 for n in (2 * (low - 2))..=(2 * (high + 2)) {
820 window(n as f32 / 2.0, 2, &mut values);
821 }
822 }
823 // Every f32 within 256 steps of each half-integer near the
824 // clamp ends and near zero.
825 for center in [low, high, 0] {
826 for n in (2 * (center - 4))..=(2 * (center + 4)) {
827 window(n as f32 / 2.0, 256, &mut values);
828 }
829 }
830 check_against_reference(values, depth, signed);
831 }
832 }
833 }
834
835 /// Spot checks through `assemble`, so a wrong result shows as a sample.
836 #[test]
837 fn irreversible_ties_and_specials_through_assemble() {
838 // 8-bit unsigned: shift 128, clamp [0, 255]; 127.5 rounds to 128 and
839 // clamps to 255, -128.5 rounds to -128 (even) and lands on 0.
840 let h = header(8, 1, 8, false);
841 let values = vec![
842 -0.0,
843 126.5,
844 127.5,
845 -127.5,
846 -128.5,
847 f32::NAN,
848 f32::INFINITY,
849 f32::NEG_INFINITY,
850 ];
851 let img = assemble(&h, vec![Samples::Irreversible(values)], 0).unwrap();
852 assert_eq!(only(&img).samples, vec![128, 254, 255, 0, 0, 128, 255, 0]);
853 // 24-bit signed takes the fallback: 2^23 - 1.5 rounds to 2^23 - 2,
854 // and 2^23 - 0.5 is not an f32, so its neighbor 2^23 - 1 is exact.
855 let h = header(3, 1, 24, true);
856 let values = vec![8_388_606.5, -8_388_607.5, 1e9];
857 let img = assemble(&h, vec![Samples::Irreversible(values)], 0).unwrap();
858 assert_eq!(only(&img).samples, vec![8_388_606, -8_388_608, 8_388_607]);
859 }
860
861 /// Every one of the 2^32 `f32` bit patterns, at each depth 1..=16 and 23,
862 /// signed and unsigned. Run with
863 /// `cargo test --release -- --ignored every_f32`.
864 #[test]
865 #[ignore = "slow: about 30 CPU-minutes on a release build, spread over all cores"]
866 fn round_shift_clamp_matches_round_ties_even_on_every_f32() {
867 const CHUNK: u32 = 1 << 20;
868 let depths: Vec<u8> = (1..=16).chain([23]).collect();
869 let threads = std::thread::available_parallelism().map_or(4, |n| n.get());
870 std::thread::scope(|scope| {
871 for t in 0..threads {
872 let depths = &depths;
873 scope.spawn(move || {
874 let mut chunk = t as u64;
875 while chunk < (1u64 << 32) / CHUNK as u64 {
876 let start = chunk as u32 * CHUNK;
877 let values: Vec<f32> =
878 (start..=start + (CHUNK - 1)).map(f32::from_bits).collect();
879 for &depth in depths {
880 for signed in [false, true] {
881 let (shift, lo, hi) = bounds(depth, signed);
882 let got = round_shift_clamp(values.clone(), depth, shift, lo, hi);
883 for (v, g) in values.iter().zip(got) {
884 assert_eq!(
885 g,
886 reference(*v, shift, lo, hi),
887 "depth {depth} signed {signed} bits {:#010x}",
888 v.to_bits()
889 );
890 }
891 }
892 }
893 chunk += threads as u64;
894 }
895 });
896 }
897 });
898 }
899
900 #[test]
901 fn sample_count_mismatch_is_inconsistent() {
902 let h = header(4, 4, 8, false); // expects 16 samples
903 let err = assemble1(&h, vec![0; 15]).unwrap_err();
904 assert!(matches!(err, Error::Inconsistent(_)), "got {err:?}");
905 }
906
907 #[test]
908 fn depth_beyond_i32_container_is_unsupported() {
909 // Unsigned 32-bit's upper bound (2^32 - 1) cannot fit in i32, and the
910 // standard-legal 33..=38 depths (Table A-11) exceed it either way —
911 // legal-but-undecodable, so Unsupported rather than Marker.
912 for (depth, signed) in [(32, false), (33, false), (33, true), (38, true)] {
913 let h = header(1, 1, depth, signed);
914 let err = assemble1(&h, vec![0]).unwrap_err();
915 assert!(matches!(err, Error::Unsupported(_)), "{depth} got {err:?}");
916 }
917 // Signed 32-bit fits exactly and is accepted.
918 let img = assemble1(&header(1, 1, 32, true), vec![i32::MIN]).unwrap();
919 assert_eq!(only(&img).samples, vec![i32::MIN]);
920 }
921
922 #[test]
923 fn bad_depth_is_rejected() {
924 // 0 and 39+ are illegal encodings (Table A-11), not missing features.
925 for depth in [0, 39] {
926 let h = header(1, 1, depth, false);
927 assert!(matches!(assemble1(&h, vec![0]), Err(Error::Marker(_))));
928 }
929 }
930
931 fn rect(x0: u32, y0: u32, x1: u32, y1: u32) -> Rect {
932 Rect { x0, y0, x1, y1 }
933 }
934
935 #[test]
936 fn a_tile_covering_the_canvas_is_moved_in() {
937 let h = header(4, 2, 8, false);
938 let mut canvas = Canvas::new(&h, 0).unwrap();
939 let samples = vec![1, 2, 3, 4, 5, 6, 7, 8];
940 let at = samples.as_ptr();
941 canvas
942 .place(0, rect(0, 0, 4, 2), Samples::Reversible(samples))
943 .unwrap();
944 match canvas.into_planes().as_slice() {
945 [Samples::Reversible(plane)] => {
946 assert_eq!(plane, &[1, 2, 3, 4, 5, 6, 7, 8]);
947 assert_eq!(plane.as_ptr(), at, "the tile's buffer is the plane");
948 }
949 other => panic!("expected one reversible plane, got {other:?}"),
950 }
951 }
952
953 #[test]
954 fn partial_tiles_are_copied_into_one_plane() {
955 let h = header(4, 2, 8, false);
956 let mut canvas = Canvas::new(&h, 0).unwrap();
957 canvas
958 .place(0, rect(2, 0, 4, 2), Samples::Reversible(vec![3, 4, 7, 8]))
959 .unwrap();
960 canvas
961 .place(0, rect(0, 0, 2, 2), Samples::Reversible(vec![1, 2, 5, 6]))
962 .unwrap();
963 match canvas.into_planes().as_slice() {
964 [Samples::Reversible(plane)] => assert_eq!(plane, &[1, 2, 3, 4, 5, 6, 7, 8]),
965 other => panic!("expected one reversible plane, got {other:?}"),
966 }
967 }
968
969 #[test]
970 fn a_plane_no_tile_reached_is_zeros() {
971 let mut h = header(2, 1, 8, false);
972 h.components[0].coding.transform = Transform::Irreversible97;
973 match Canvas::new(&h, 0).unwrap().into_planes().as_slice() {
974 [Samples::Irreversible(plane)] => assert_eq!(plane, &[0.0, 0.0]),
975 other => panic!("expected one irreversible plane, got {other:?}"),
976 }
977 }
978
979 #[test]
980 fn a_tile_on_the_other_wavelet_is_inconsistent() {
981 let h = header(2, 2, 8, false);
982 for area in [rect(0, 0, 2, 2), rect(0, 0, 1, 2)] {
983 let mut canvas = Canvas::new(&h, 0).unwrap();
984 let samples = Samples::Irreversible(vec![0.0; area.area() as usize]);
985 let err = canvas.place(0, area, samples).unwrap_err();
986 assert!(
987 matches!(err, Error::Inconsistent(_)),
988 "{area:?} got {err:?}"
989 );
990 }
991 }
992}