Skip to main content

rust_j2k/
image.rs

1//! Decoder output: one integer component in raster order, plus the metadata a
2//! caller needs to interpret the samples (bit depth + signedness).
3
4use crate::codestream::MainHeader;
5use crate::{Error, Result};
6
7/// A decoded single-component image. `samples` is row-major, `width * height`
8/// entries, each already DC-level-shifted and clamped to the declared depth.
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub struct Image {
11    /// Image width in samples.
12    pub width: u32,
13    /// Image height in samples.
14    pub height: u32,
15    /// Bits per sample as declared in SIZ (1..=32 for the GRIB2 subset).
16    pub bit_depth: u8,
17    /// Whether samples are signed (SIZ component sign bit).
18    pub signed: bool,
19    /// `width * height` samples, row-major.
20    pub samples: Vec<i32>,
21}
22
23impl Image {
24    /// Sample at `(x, y)`, or `None` if out of bounds.
25    pub fn sample(&self, x: u32, y: u32) -> Option<i32> {
26        if x >= self.width || y >= self.height {
27            return None;
28        }
29        self.samples
30            .get((y as usize) * (self.width as usize) + x as usize)
31            .copied()
32    }
33}
34
35/// Final stage: apply the inverse DC level shift, clamp to the component depth,
36/// and package the reconstructed samples with their geometry.
37///
38/// The component geometry follows the SIZ reference-grid equations (ISO/IEC
39/// 15444-1 §B.2): for sub-sampling factors `XRsiz`/`YRsiz`,
40///
41/// ```text
42/// width  = ceil(Xsiz / XRsiz) - ceil(XOsiz / XRsiz)
43/// height = ceil(Ysiz / YRsiz) - ceil(YOsiz / YRsiz)
44/// ```
45///
46/// which reduces to `Xsiz - XOsiz` by `Ysiz - YOsiz` for the unit-sampling
47/// single-component GRIB2 case.
48///
49/// The inverse DC level shift (§G.1.2) adds `2^(depth-1)` back to *unsigned*
50/// components (the encoder subtracted it before the forward transform); signed
51/// components are left as-is. Samples are then clamped to the declared depth
52/// and sign before being packed row-major into the [`Image`].
53pub(crate) fn assemble(header: &MainHeader, samples: Vec<i32>) -> Result<Image> {
54    let siz = &header.siz;
55    let comp = siz
56        .components
57        .first()
58        .ok_or_else(|| Error::Inconsistent("SIZ declares no components".into()))?;
59
60    let depth = comp.bit_depth;
61    if !(1..=32).contains(&depth) {
62        return Err(Error::Marker(format!(
63            "component bit depth {depth} outside the supported range 1..=32"
64        )));
65    }
66    if comp.x_sampling == 0 || comp.y_sampling == 0 {
67        return Err(Error::Marker(
68            "component sub-sampling factor is zero".into(),
69        ));
70    }
71
72    let xr = comp.x_sampling as u32;
73    let yr = comp.y_sampling as u32;
74    let width = siz
75        .x_size
76        .div_ceil(xr)
77        .saturating_sub(siz.x_offset.div_ceil(xr));
78    let height = siz
79        .y_size
80        .div_ceil(yr)
81        .saturating_sub(siz.y_offset.div_ceil(yr));
82
83    let expected = (width as usize) * (height as usize);
84    if samples.len() != expected {
85        return Err(Error::Inconsistent(format!(
86            "decoded {} samples but SIZ geometry is {width}x{height} = {expected}",
87            samples.len()
88        )));
89    }
90
91    // Level-shift offset and the clamp bounds, all in i64 so the `1 << 31`
92    // signed-32-bit case and the unsigned `2^depth - 1` upper bound cannot
93    // overflow during the computation.
94    let (shift, lo, hi): (i64, i64, i64) = if comp.signed {
95        (0, -(1i64 << (depth - 1)), (1i64 << (depth - 1)) - 1)
96    } else {
97        (1i64 << (depth - 1), 0, (1i64 << depth) - 1)
98    };
99
100    // The output container is `i32`; reject depths whose clamp range cannot be
101    // represented (e.g. unsigned 32-bit, whose max is `2^32 - 1`). Checked once
102    // so the per-sample cast below is always exact.
103    if hi > i32::MAX as i64 || lo < i32::MIN as i64 {
104        return Err(Error::Unsupported(format!(
105            "component depth {depth} ({}) exceeds the i32 sample container",
106            if comp.signed { "signed" } else { "unsigned" }
107        )));
108    }
109
110    let shifted: Vec<i32> = samples
111        .into_iter()
112        .map(|v| (v as i64 + shift).clamp(lo, hi) as i32)
113        .collect();
114
115    Ok(Image {
116        width,
117        height,
118        bit_depth: depth,
119        signed: comp.signed,
120        samples: shifted,
121    })
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127    use crate::codestream::markers::{
128        Cod, Progression, Qcd, QuantStyle, Siz, SizComponent, Transform,
129    };
130
131    /// A minimal single-component header: an image of `x_size` by `y_size` at the
132    /// origin with unit sub-sampling. Only the SIZ fields `assemble` reads
133    /// matter; COD/QCD are filler. Tests tweak offsets/sampling on the result.
134    fn header(x_size: u32, y_size: u32, bit_depth: u8, signed: bool) -> MainHeader {
135        MainHeader {
136            siz: Siz {
137                x_size,
138                y_size,
139                x_offset: 0,
140                y_offset: 0,
141                tile_width: x_size,
142                tile_height: y_size,
143                tile_x_offset: 0,
144                tile_y_offset: 0,
145                components: vec![SizComponent {
146                    bit_depth,
147                    signed,
148                    x_sampling: 1,
149                    y_sampling: 1,
150                }],
151            },
152            cod: Cod {
153                progression: Progression::Lrcp,
154                layers: 1,
155                decomposition_levels: 0,
156                code_block_width: 4,
157                code_block_height: 4,
158                code_block_style: 0,
159                transform: Transform::Reversible53,
160                precinct_sizes: vec![],
161            },
162            qcd: Qcd {
163                style: QuantStyle::None,
164                guard_bits: 1,
165                steps: vec![],
166            },
167        }
168    }
169
170    #[test]
171    fn unsigned_adds_level_shift_and_clamps() {
172        // 8-bit unsigned: shift = 128, clamp to [0, 255].
173        let h = header(2, 2, 8, false);
174        let img = assemble(&h, vec![0, -128, 127, 200]).unwrap();
175        // 0 -> 128 (mid), -128 -> 0 (low edge), 127 -> 255 (high edge),
176        // 200 -> 328 clamps to 255.
177        assert_eq!(img.samples, vec![128, 0, 255, 255]);
178        // And the low edge under-shoot also clamps.
179        let img = assemble(&header(1, 1, 8, false), vec![-200]).unwrap();
180        assert_eq!(img.samples, vec![0]);
181    }
182
183    #[test]
184    fn signed_is_unshifted_and_clamps() {
185        // 8-bit signed: no shift, clamp to [-128, 127].
186        let h = header(2, 2, 8, true);
187        let img = assemble(&h, vec![0, 50, 200, -200]).unwrap();
188        assert_eq!(img.samples, vec![0, 50, 127, -128]);
189    }
190
191    #[test]
192    fn wider_depths_round_trip_edges() {
193        // 12-bit unsigned: shift = 2048, clamp to [0, 4095].
194        let img = assemble(&header(1, 4, 12, false), vec![-2048, 0, 2047, 9999]).unwrap();
195        assert_eq!(img.samples, vec![0, 2048, 4095, 4095]);
196        // 16-bit signed: clamp to [-32768, 32767], no shift.
197        let img = assemble(&header(1, 3, 16, true), vec![-40000, 12345, 40000]).unwrap();
198        assert_eq!(img.samples, vec![-32768, 12345, 32767]);
199    }
200
201    #[test]
202    fn geometry_uses_siz_image_area() {
203        let mut h = header(6, 5, 8, false);
204        h.siz.x_offset = 2;
205        h.siz.y_offset = 1;
206        // width = 6 - 2 = 4, height = 5 - 1 = 4.
207        let img = assemble(&h, vec![0; 16]).unwrap();
208        assert_eq!((img.width, img.height), (4, 4));
209        assert_eq!(img.bit_depth, 8);
210        assert!(!img.signed);
211        assert_eq!(img.sample(3, 3), Some(128));
212        assert_eq!(img.sample(4, 0), None);
213    }
214
215    #[test]
216    fn geometry_honours_sub_sampling() {
217        let mut h = header(8, 8, 8, false);
218        h.siz.components[0].x_sampling = 2;
219        h.siz.components[0].y_sampling = 2;
220        // ceil(8/2) - ceil(0/2) = 4 in each axis.
221        let img = assemble(&h, vec![0; 16]).unwrap();
222        assert_eq!((img.width, img.height), (4, 4));
223    }
224
225    #[test]
226    fn sample_count_mismatch_is_inconsistent() {
227        let h = header(4, 4, 8, false); // expects 16 samples
228        let err = assemble(&h, vec![0; 15]).unwrap_err();
229        assert!(matches!(err, Error::Inconsistent(_)), "got {err:?}");
230    }
231
232    #[test]
233    fn depth_beyond_i32_container_is_unsupported() {
234        // Unsigned 32-bit's upper bound (2^32 - 1) cannot fit in i32.
235        let h = header(1, 1, 32, false);
236        let err = assemble(&h, vec![0]).unwrap_err();
237        assert!(matches!(err, Error::Unsupported(_)), "got {err:?}");
238        // Signed 32-bit fits exactly and is accepted.
239        let img = assemble(&header(1, 1, 32, true), vec![i32::MIN]).unwrap();
240        assert_eq!(img.samples, vec![i32::MIN]);
241    }
242
243    #[test]
244    fn bad_depth_is_rejected() {
245        let h = header(1, 1, 0, false);
246        assert!(matches!(assemble(&h, vec![0]), Err(Error::Marker(_))));
247    }
248}