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