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