Skip to main content

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