Skip to main content

rust_j2k/
image.rs

1//! Decoder output: the image area on the reference grid, and one integer
2//! component per SIZ component, 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::dwt::Samples;
9use crate::{Error, 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. A sub-sampled component covers
16/// that same area with fewer samples, so its own
17/// [`Component::width`]/[`Component::height`] can be smaller. With unit
18/// sub-sampling — the common case — they are equal.
19///
20/// Components are in SIZ order and are independent: no inter-component (color)
21/// transform is applied here.
22///
23/// The struct is `#[non_exhaustive]`: [`decode`](crate::decode) is the normal
24/// producer, and later metadata (a JP2 wrapper's colour description, say) can
25/// then land as new fields without a breaking change. To build one by hand —
26/// an expected image in a test harness, for instance — use [`Image::new`].
27#[derive(Debug, Clone, PartialEq, Eq)]
28#[non_exhaustive]
29pub struct Image {
30    /// Reference-grid image area width, in reference-grid points.
31    pub width: u32,
32    /// Reference-grid image area height, in reference-grid points.
33    pub height: u32,
34    /// One entry per SIZ component, in SIZ order. Never empty in decoder
35    /// output.
36    pub components: Vec<Component>,
37}
38
39/// One decoded component: its own sample grid, its declared depth and sign, and
40/// the sub-sampling that maps it onto the image's reference grid.
41///
42/// `samples` is row-major, `width * height` entries, each already
43/// DC-level-shifted and clamped to the declared depth.
44///
45/// `#[non_exhaustive]`, like [`Image`]; build one by hand with
46/// [`Component::new`].
47#[derive(Debug, Clone, PartialEq, Eq)]
48#[non_exhaustive]
49pub struct Component {
50    /// Component width in samples.
51    pub width: u32,
52    /// Component height in samples.
53    pub height: u32,
54    /// Bits per sample as declared in SIZ `Ssiz` (1..=32).
55    pub bit_depth: u8,
56    /// Whether samples are signed (SIZ component sign bit).
57    pub signed: bool,
58    /// Horizontal sub-sampling factor (SIZ `XRsiz`); `1` means unit sampling.
59    pub x_sampling: u8,
60    /// Vertical sub-sampling factor (SIZ `YRsiz`); `1` means unit sampling.
61    pub y_sampling: u8,
62    /// `width * height` samples, row-major.
63    pub samples: Vec<i32>,
64}
65
66impl Image {
67    /// Package `components` with the reference-grid image area they are
68    /// registered against. The values are stored as given; only
69    /// [`decode`](crate::decode) vouches for their consistency.
70    #[must_use]
71    pub fn new(width: u32, height: u32, components: Vec<Component>) -> Self {
72        Self {
73            width,
74            height,
75            components,
76        }
77    }
78
79    /// The component at `index` in SIZ order, or `None` if out of range.
80    pub fn component(&self, index: usize) -> Option<&Component> {
81        self.components.get(index)
82    }
83}
84
85impl Component {
86    /// Package a component's samples with their geometry and interpretation.
87    /// The values are stored as given; only [`decode`](crate::decode) vouches
88    /// for their consistency.
89    #[must_use]
90    pub fn new(
91        width: u32,
92        height: u32,
93        bit_depth: u8,
94        signed: bool,
95        x_sampling: u8,
96        y_sampling: u8,
97        samples: Vec<i32>,
98    ) -> Self {
99        Self {
100            width,
101            height,
102            bit_depth,
103            signed,
104            x_sampling,
105            y_sampling,
106            samples,
107        }
108    }
109
110    /// Sample at `(x, y)` on this component's own grid, or `None` if out of bounds.
111    pub fn sample(&self, x: u32, y: u32) -> Option<i32> {
112        if x >= self.width || y >= self.height {
113            return None;
114        }
115        self.samples
116            .get((y as usize) * (self.width as usize) + x as usize)
117            .copied()
118    }
119}
120
121/// The per-component sample planes a tiled decode reconstructs into: one plane
122/// per SIZ component, sized to that component's whole grid, which each tile
123/// writes its own rectangle of.
124///
125/// Tiles are decoded independently — their own coordinate frame, their own
126/// header, their own wavelet pyramid — and the canvas is where they meet again.
127/// A tile-component's reconstructed raster is placed at the tile's offset on the
128/// component grid; the tiles partition that grid exactly, so every sample is
129/// written once. Nothing is blended and no tile overlaps another: the wavelet
130/// transform is applied per tile, which is why a tiled encode can show seams,
131/// and reproducing them is correct.
132pub(crate) struct Canvas {
133    planes: Vec<Samples>,
134    /// Each component's whole grid at the decode's reduction — the rectangle a
135    /// tile's placement is measured against.
136    rects: Vec<Rect>,
137}
138
139impl Canvas {
140    /// Allocate one zeroed plane per component, at the reduced size
141    /// [`assemble`] will expect.
142    ///
143    /// A plane's arithmetic follows its component's wavelet — 5/3 reconstructs
144    /// exact integers, 9/7 reals — which is why `parse` rejects a codestream
145    /// whose tiles disagree about a component's wavelet: it would ask one plane
146    /// to hold both.
147    pub(crate) fn new(header: &MainHeader, reduction: u8) -> Result<Self> {
148        let siz = &header.siz;
149        let (mut planes, mut rects) = (Vec::new(), Vec::new());
150        for index in 0..siz.components.len() {
151            let (width, height) = siz
152                .component_extent_at(index, reduction)
153                .ok_or_else(|| Error::Inconsistent(format!("SIZ declares no component {index}")))?;
154            let count = (width as usize) * (height as usize);
155            planes.push(match header.components[index].coding.transform {
156                Transform::Reversible53 => Samples::Reversible(vec![0; count]),
157                Transform::Irreversible97 => Samples::Irreversible(vec![0.0; count]),
158            });
159            rects.push(
160                siz.component_rect(index)
161                    .ok_or_else(|| {
162                        Error::Inconsistent(format!("SIZ declares no component {index}"))
163                    })?
164                    .reduced(reduction),
165            );
166        }
167        Ok(Canvas { planes, rects })
168    }
169
170    /// Write one tile-component's reconstructed raster into its component's
171    /// plane. `rect` is the tile-component's rectangle on the component grid, at
172    /// the same reduction the canvas was built at.
173    pub(crate) fn place(&mut self, index: usize, rect: Rect, samples: Samples) -> Result<()> {
174        let (plane, canvas) = self
175            .planes
176            .get_mut(index)
177            .zip(self.rects.get(index))
178            .ok_or_else(|| Error::Inconsistent(format!("no canvas plane for component {index}")))?;
179        if samples.len() as u64 != rect.area() {
180            return Err(Error::Inconsistent(format!(
181                "component {index} of a tile reconstructed {} samples but its {}x{} rectangle \
182                 holds {}",
183                samples.len(),
184                rect.width(),
185                rect.height(),
186                rect.area(),
187            )));
188        }
189        // The tile grid partitions the canvas, so this only fails on a header
190        // whose SIZ tiling and whose decoded geometry disagree.
191        if rect.x0 < canvas.x0 || rect.y0 < canvas.y0 || rect.x1 > canvas.x1 || rect.y1 > canvas.y1
192        {
193            return Err(Error::Inconsistent(format!(
194                "a tile's component {index} rectangle {rect:?} falls outside the canvas {canvas:?}",
195            )));
196        }
197        let (left, top) = (
198            (rect.x0 - canvas.x0) as usize,
199            (rect.y0 - canvas.y0) as usize,
200        );
201        let stride = canvas.width() as usize;
202        match (plane, samples) {
203            (Samples::Reversible(dst), Samples::Reversible(src)) => {
204                blit(dst, stride, &src, rect.width() as usize, left, top);
205            }
206            (Samples::Irreversible(dst), Samples::Irreversible(src)) => {
207                blit(dst, stride, &src, rect.width() as usize, left, top);
208            }
209            _ => {
210                return Err(Error::Inconsistent(format!(
211                    "a tile reconstructed component {index} on the other wavelet's arithmetic"
212                )));
213            }
214        }
215        Ok(())
216    }
217
218    /// The finished planes, in SIZ component order, ready for [`assemble`].
219    pub(crate) fn into_planes(self) -> Vec<Samples> {
220        self.planes
221    }
222}
223
224/// Copy a `src_width`-wide raster into `dst` (a `stride`-wide raster) with its
225/// top-left at `(left, top)`. The caller has already checked that it fits.
226fn blit<T: Copy>(
227    dst: &mut [T],
228    stride: usize,
229    src: &[T],
230    src_width: usize,
231    left: usize,
232    top: usize,
233) {
234    if src_width == 0 {
235        return;
236    }
237    for (row, line) in src.chunks_exact(src_width).enumerate() {
238        let start = (top + row) * stride + left;
239        dst[start..start + src_width].copy_from_slice(line);
240    }
241}
242
243/// Final stage: apply the inverse DC level shift, clamp to the component depth,
244/// and package the reconstructed samples with their geometry.
245///
246/// The component geometry follows the SIZ reference-grid equations (ISO/IEC
247/// 15444-1 §B.2): for sub-sampling factors `XRsiz`/`YRsiz`,
248///
249/// ```text
250/// width  = ceil(Xsiz / XRsiz) - ceil(XOsiz / XRsiz)
251/// height = ceil(Ysiz / YRsiz) - ceil(YOsiz / YRsiz)
252/// ```
253///
254/// which reduces to the image area `Xsiz - XOsiz` by `Ysiz - YOsiz` under unit
255/// sub-sampling. The image area itself is carried on the [`Image`].
256///
257/// The inverse DC level shift (§G.1.2) adds `2^(depth-1)` back to *unsigned*
258/// components (the encoder subtracted it before the forward transform); signed
259/// components are left as-is. Samples are then clamped to the declared depth
260/// and sign before being packed row-major into a [`Component`].
261///
262/// `samples` carries one reconstructed sample vector per SIZ component, in SIZ
263/// order — [`Canvas::into_planes`] output. Each is level-shifted and clamped
264/// on its own component's depth and sign, then packed with that component's
265/// geometry.
266pub(crate) fn assemble(header: &MainHeader, samples: Vec<Samples>, reduction: u8) -> Result<Image> {
267    let siz = &header.siz;
268    if samples.len() != siz.components.len() {
269        return Err(Error::Inconsistent(format!(
270            "decoded {} components but SIZ declares {}",
271            samples.len(),
272            siz.components.len(),
273        )));
274    }
275    if samples.is_empty() {
276        return Err(Error::Inconsistent("SIZ declares no components".into()));
277    }
278
279    let components = samples
280        .into_iter()
281        .enumerate()
282        .map(|(index, component_samples)| {
283            assemble_component(siz, index, component_samples, reduction)
284        })
285        .collect::<Result<Vec<_>>>()?;
286
287    // At a reduction the image area shrinks with its components, by the same
288    // halve-and-round-up per dropped level.
289    let (image_width, image_height) = siz.image_extent_at(reduction);
290    Ok(Image {
291        width: image_width,
292        height: image_height,
293        components,
294    })
295}
296
297/// Round to the nearest integer, level-shift, clamp, and package one
298/// component's reconstructed samples.
299///
300/// This is the *only* place the irreversible path rounds. It happens after the
301/// inverse colour transform, matching `opj_tcd_dc_level_shift_decode`, which
302/// calls `opj_lrintf` and then adds the DC level shift and clamps:
303///
304/// ```c
305/// OPJ_INT64 l_value_int = (OPJ_INT64)opj_lrintf(l_value);
306/// *l_dest = opj_int64_clamp(l_value_int + l_tccp->m_dc_level_shift, l_min, l_max);
307/// ```
308///
309/// `opj_lrintf` is `lrintf` on GCC and Clang — the build that produced the
310/// committed oracles — and `lrintf` rounds under the default floating-point
311/// mode, which is ties-to-even. Its MSVC arms (`cvtss2si`, `fistp`) round
312/// ties-to-even too. Rust's `f32::round` rounds ties *away from zero*, so `2.5`
313/// would become `3` where the oracle gives `2`; `round_ties_even` agrees.
314///
315/// OpenJPEG tried the away-from-zero form and reverted it, leaving the evidence
316/// in `opj_includes.h`:
317///
318/// ```c
319/// /* commented out line breaks many tests */
320/// /* return (long)((f>0.0f) ? (f + 0.5f):(f -0.5f)); */
321/// ```
322fn assemble_component(
323    siz: &Siz,
324    index: usize,
325    samples: Samples,
326    reduction: u8,
327) -> Result<Component> {
328    let comp = siz
329        .components
330        .get(index)
331        .ok_or_else(|| Error::Inconsistent(format!("SIZ declares no component {index}")))?;
332
333    let depth = comp.bit_depth;
334    // The standard allows 1..=38 (Table A-11) and `decode_siz` enforces it;
335    // this defensive restatement keeps the shift arithmetic below well-defined
336    // for callers that assemble a header by hand. Legal depths whose range
337    // does not fit the i32 sample container (33..=38, and unsigned 32) fall
338    // through to the container check, which rejects them as Unsupported.
339    if !(1..=38).contains(&depth) {
340        return Err(Error::Marker(format!(
341            "component {index} bit depth {depth} outside the standard's range 1..=38"
342        )));
343    }
344    if comp.x_sampling == 0 || comp.y_sampling == 0 {
345        return Err(Error::Marker(format!(
346            "component {index} sub-sampling factor is zero"
347        )));
348    }
349
350    // Safe now that the zero-factor case above is excluded.
351    let (width, height) = siz
352        .component_extent_at(index, reduction)
353        .ok_or_else(|| Error::Inconsistent(format!("SIZ declares no component {index}")))?;
354
355    let expected = (width as usize) * (height as usize);
356    if samples.len() != expected {
357        return Err(Error::Inconsistent(format!(
358            "component {index} decoded {} samples but its geometry is {width}x{height} = {expected}",
359            samples.len()
360        )));
361    }
362
363    // The irreversible path arrives unrounded. `as i32` saturates, so a value
364    // outside the container cannot wrap before the clamp below sees it.
365    let samples: Vec<i32> = match samples {
366        Samples::Reversible(values) => values,
367        Samples::Irreversible(values) => values
368            .into_iter()
369            .map(|v| v.round_ties_even() as i32)
370            .collect(),
371    };
372
373    // Level-shift offset and the clamp bounds, all in i64 so the `1 << 31`
374    // signed-32-bit case and the unsigned `2^depth - 1` upper bound cannot
375    // overflow during the computation.
376    let (shift, lo, hi): (i64, i64, i64) = if comp.signed {
377        (0, -(1i64 << (depth - 1)), (1i64 << (depth - 1)) - 1)
378    } else {
379        (1i64 << (depth - 1), 0, (1i64 << depth) - 1)
380    };
381
382    // The output container is `i32`; reject depths whose clamp range cannot be
383    // represented (e.g. unsigned 32-bit, whose max is `2^32 - 1`). Checked once
384    // so the per-sample cast below is always exact.
385    if hi > i32::MAX as i64 || lo < i32::MIN as i64 {
386        return Err(Error::Unsupported(format!(
387            "component {index} depth {depth} ({}) exceeds the i32 sample container",
388            if comp.signed { "signed" } else { "unsigned" }
389        )));
390    }
391
392    let shifted: Vec<i32> = samples
393        .into_iter()
394        .map(|v| (v as i64 + shift).clamp(lo, hi) as i32)
395        .collect();
396
397    Ok(Component {
398        width,
399        height,
400        bit_depth: depth,
401        signed: comp.signed,
402        x_sampling: comp.x_sampling,
403        y_sampling: comp.y_sampling,
404        samples: shifted,
405    })
406}
407
408#[cfg(test)]
409mod tests {
410    use super::*;
411    use crate::codestream::markers::{
412        Cod, Progression, Qcd, QuantStyle, Siz, SizComponent, Transform,
413    };
414
415    /// A minimal single-component header: an image of `x_size` by `y_size` at the
416    /// origin with unit sub-sampling. Only the SIZ fields `assemble` reads
417    /// matter; COD/QCD are filler. Tests tweak offsets/sampling on the result.
418    fn header(x_size: u32, y_size: u32, bit_depth: u8, signed: bool) -> MainHeader {
419        MainHeader::new(
420            Siz {
421                x_size,
422                y_size,
423                x_offset: 0,
424                y_offset: 0,
425                tile_width: x_size,
426                tile_height: y_size,
427                tile_x_offset: 0,
428                tile_y_offset: 0,
429                components: vec![SizComponent {
430                    bit_depth,
431                    signed,
432                    x_sampling: 1,
433                    y_sampling: 1,
434                }],
435            },
436            Cod {
437                progression: Progression::Lrcp,
438                layers: 1,
439                decomposition_levels: 0,
440                code_block_width: 4,
441                code_block_height: 4,
442                code_block_style: 0,
443                use_sop: false,
444                use_eph: false,
445                multiple_component_transform: false,
446                transform: Transform::Reversible53,
447                precinct_sizes: vec![],
448            },
449            Qcd {
450                style: QuantStyle::None,
451                guard_bits: 1,
452                steps: vec![],
453            },
454        )
455    }
456
457    /// Assemble a single-component image: most of these tests predate the
458    /// component axis and care only about level shift, clamping, and geometry.
459    fn assemble1(header: &MainHeader, samples: Vec<i32>) -> Result<Image> {
460        assemble(header, vec![Samples::Reversible(samples)], 0)
461    }
462
463    /// The single component `assemble` produces, for tests that only care about
464    /// the samples and not the enclosing image area.
465    fn only(img: &Image) -> &Component {
466        assert_eq!(img.components.len(), 1, "assemble emits one component");
467        img.component(0).unwrap()
468    }
469
470    #[test]
471    fn unsigned_adds_level_shift_and_clamps() {
472        // 8-bit unsigned: shift = 128, clamp to [0, 255].
473        let h = header(2, 2, 8, false);
474        let img = assemble1(&h, vec![0, -128, 127, 200]).unwrap();
475        // 0 -> 128 (mid), -128 -> 0 (low edge), 127 -> 255 (high edge),
476        // 200 -> 328 clamps to 255.
477        assert_eq!(only(&img).samples, vec![128, 0, 255, 255]);
478        // And the low edge under-shoot also clamps.
479        let img = assemble1(&header(1, 1, 8, false), vec![-200]).unwrap();
480        assert_eq!(only(&img).samples, vec![0]);
481    }
482
483    #[test]
484    fn signed_is_unshifted_and_clamps() {
485        // 8-bit signed: no shift, clamp to [-128, 127].
486        let h = header(2, 2, 8, true);
487        let img = assemble1(&h, vec![0, 50, 200, -200]).unwrap();
488        assert_eq!(only(&img).samples, vec![0, 50, 127, -128]);
489    }
490
491    #[test]
492    fn wider_depths_round_trip_edges() {
493        // 12-bit unsigned: shift = 2048, clamp to [0, 4095].
494        let img = assemble1(&header(1, 4, 12, false), vec![-2048, 0, 2047, 9999]).unwrap();
495        assert_eq!(only(&img).samples, vec![0, 2048, 4095, 4095]);
496        // 16-bit signed: clamp to [-32768, 32767], no shift.
497        let img = assemble1(&header(1, 3, 16, true), vec![-40000, 12345, 40000]).unwrap();
498        assert_eq!(only(&img).samples, vec![-32768, 12345, 32767]);
499    }
500
501    #[test]
502    fn geometry_uses_siz_image_area() {
503        let mut h = header(6, 5, 8, false);
504        h.siz.x_offset = 2;
505        h.siz.y_offset = 1;
506        // width = 6 - 2 = 4, height = 5 - 1 = 4.
507        let img = assemble1(&h, vec![0; 16]).unwrap();
508        assert_eq!((img.width, img.height), (4, 4));
509        let c = only(&img);
510        assert_eq!((c.width, c.height), (4, 4));
511        assert_eq!(c.bit_depth, 8);
512        assert!(!c.signed);
513        assert_eq!(c.sample(3, 3), Some(128));
514        assert_eq!(c.sample(4, 0), None);
515    }
516
517    #[test]
518    fn geometry_honours_sub_sampling() {
519        let mut h = header(8, 8, 8, false);
520        h.siz.components[0].x_sampling = 2;
521        h.siz.components[0].y_sampling = 2;
522        let img = assemble1(&h, vec![0; 16]).unwrap();
523        // The image area stays on the reference grid ...
524        assert_eq!((img.width, img.height), (8, 8));
525        // ... while the component carries ceil(8/2) - ceil(0/2) = 4 per axis.
526        let c = only(&img);
527        assert_eq!((c.width, c.height), (4, 4));
528        assert_eq!((c.x_sampling, c.y_sampling), (2, 2));
529    }
530
531    /// The irreversible path rounds once, here, and rounds ties to even —
532    /// matching `opj_lrintf` under the default floating-point mode. Rust's
533    /// `f32::round` rounds ties away from zero and would disagree at every
534    /// half-integer.
535    #[test]
536    fn irreversible_samples_round_ties_to_even() {
537        // 8-bit signed: no level shift, clamp to [-128, 127].
538        let h = header(5, 1, 8, true);
539        let img = assemble(
540            &h,
541            vec![Samples::Irreversible(vec![0.5, 1.5, 2.5, -0.5, -2.5])],
542            0,
543        )
544        .unwrap();
545        assert_eq!(only(&img).samples, vec![0, 2, 2, 0, -2]);
546
547        // Away-from-zero would have given [1, 2, 3, -1, -3].
548        let away: Vec<i32> = [0.5f32, 1.5, 2.5, -0.5, -2.5]
549            .iter()
550            .map(|v| v.round() as i32)
551            .collect();
552        assert_ne!(away, only(&img).samples);
553    }
554
555    /// A reconstructed value outside the `i32` container saturates rather than
556    /// wrapping, before the depth clamp sees it.
557    #[test]
558    fn irreversible_samples_saturate_into_the_container() {
559        let h = header(2, 1, 16, true);
560        let img = assemble(&h, vec![Samples::Irreversible(vec![1e30, -1e30])], 0).unwrap();
561        assert_eq!(only(&img).samples, vec![32767, -32768]);
562    }
563
564    #[test]
565    fn sample_count_mismatch_is_inconsistent() {
566        let h = header(4, 4, 8, false); // expects 16 samples
567        let err = assemble1(&h, vec![0; 15]).unwrap_err();
568        assert!(matches!(err, Error::Inconsistent(_)), "got {err:?}");
569    }
570
571    #[test]
572    fn depth_beyond_i32_container_is_unsupported() {
573        // Unsigned 32-bit's upper bound (2^32 - 1) cannot fit in i32, and the
574        // standard-legal 33..=38 depths (Table A-11) exceed it either way —
575        // legal-but-undecodable, so Unsupported rather than Marker.
576        for (depth, signed) in [(32, false), (33, false), (33, true), (38, true)] {
577            let h = header(1, 1, depth, signed);
578            let err = assemble1(&h, vec![0]).unwrap_err();
579            assert!(matches!(err, Error::Unsupported(_)), "{depth} got {err:?}");
580        }
581        // Signed 32-bit fits exactly and is accepted.
582        let img = assemble1(&header(1, 1, 32, true), vec![i32::MIN]).unwrap();
583        assert_eq!(only(&img).samples, vec![i32::MIN]);
584    }
585
586    #[test]
587    fn bad_depth_is_rejected() {
588        // 0 and 39+ are illegal encodings (Table A-11), not missing features.
589        for depth in [0, 39] {
590            let h = header(1, 1, depth, false);
591            assert!(matches!(assemble1(&h, vec![0]), Err(Error::Marker(_))));
592        }
593    }
594}