1use crate::codestream::MainHeader;
5use crate::{Error, Result};
6
7#[derive(Debug, Clone, PartialEq, Eq)]
10pub struct Image {
11 pub width: u32,
13 pub height: u32,
15 pub bit_depth: u8,
17 pub signed: bool,
19 pub samples: Vec<i32>,
21}
22
23impl Image {
24 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
35pub(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 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 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 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 let h = header(2, 2, 8, false);
174 let img = assemble(&h, vec![0, -128, 127, 200]).unwrap();
175 assert_eq!(img.samples, vec![128, 0, 255, 255]);
178 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 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 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 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 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 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); 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 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 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}