qualia_core_db/medical/dicom_codecs/jpegls/
mod.rs1mod bitstream;
4mod context;
5mod headers;
6#[cfg(test)]
7mod tests;
8
9pub use headers::{
10 JpegLsError, JpegLsFrameInfo, JpegLsLimits, TS_JPEGLS_LOSSLESS, TS_JPEGLS_NEAR_LOSSLESS,
11};
12
13use super::encapsulated::{parse_encapsulated_part10, EncapLimits};
14use bitstream::LsBitReader;
15use context::ContextModel;
16use headers::{derive_coding, parse_jpegls_frame};
17
18pub fn decode_jpegls_codestream_into(
22 codestream: &[u8],
23 expected_width: u16,
24 expected_height: u16,
25 expected_components: u16,
26 expected_bits_allocated: u16,
27 expected_bits_stored: u16,
28 lossless_only: bool,
29 output: &mut [u8],
30) -> Result<u8, JpegLsError> {
31 let parsed = parse_jpegls_frame(codestream)?;
32 if parsed.width != expected_width || parsed.height != expected_height {
33 return Err(JpegLsError::DimensionMismatch);
34 }
35 if parsed.comp_count as u16 != expected_components {
36 return Err(JpegLsError::CorruptStream("component count mismatch"));
37 }
38 if parsed.precision as u16 != expected_bits_stored {
39 return Err(JpegLsError::BitPrecisionMismatch);
40 }
41 let bytes_per_sample = if expected_bits_allocated <= 8 { 1usize } else { 2usize };
42 let w = parsed.width as usize;
43 let h = parsed.height as usize;
44 let nc = parsed.comp_count as usize;
45 let need = w
46 .checked_mul(h)
47 .and_then(|n| n.checked_mul(nc))
48 .and_then(|n| n.checked_mul(bytes_per_sample))
49 .ok_or(JpegLsError::Overflow)?;
50 if output.len() < need {
51 return Err(JpegLsError::OutputTooSmall);
52 }
53
54 let mut planes = Vec::new();
55 planes
56 .try_reserve_exact(nc)
57 .map_err(|_| JpegLsError::ByteLimit)?;
58 for _ in 0..nc {
59 let mut p = Vec::new();
60 p.try_reserve_exact(w * h).map_err(|_| JpegLsError::ByteLimit)?;
61 p.resize(w * h, 0i32);
62 planes.push(p);
63 }
64 let mut decoded_mask = 0u8;
65 let mut near_max = 0u8;
66
67 for scan in &parsed.scans {
68 if lossless_only && scan.near != 0 {
69 return Err(JpegLsError::LosslessModeViolation);
70 }
71 near_max = near_max.max(scan.near);
72 for &ci in &scan.comp_indices {
73 if (decoded_mask & (1u8 << ci)) != 0 {
74 return Err(JpegLsError::CorruptStream("duplicate component decoded across scans"));
75 }
76 decoded_mask |= 1u8 << ci;
77 }
78 let coding = derive_coding(parsed.precision, scan.near, scan.preset)?;
79 let mut model = ContextModel::new(coding);
80 let mut reader = LsBitReader::new(scan.entropy_and_tail);
81 let mut rst_idx = 0u8;
82 match scan.ilv {
83 0 => {
84 let ci = scan.comp_indices[0];
85 let mut prev = vec![0i32; w + 2];
86 let mut curr = vec![0i32; w + 2];
87 let mut run_index = 0usize;
88 for y in 0..h {
89 if scan.restart_interval > 0 && y > 0 && (y % scan.restart_interval as usize) == 0 {
90 reader.consume_restart(rst_idx)?;
91 rst_idx = rst_idx.wrapping_add(1);
92 model.reset_state();
93 prev.fill(0);
94 run_index = 0;
95 }
96 model.decode_line(&mut reader, &mut prev, &mut curr, w, &mut run_index)?;
97 planes[ci][y * w..(y + 1) * w].copy_from_slice(&curr[1..=w]);
98 std::mem::swap(&mut prev, &mut curr);
99 }
100 }
101 1 => {
102 let snc = scan.comp_indices.len();
103 let mut prev: Vec<Vec<i32>> = (0..snc).map(|_| vec![0i32; w + 2]).collect();
104 let mut curr: Vec<Vec<i32>> = (0..snc).map(|_| vec![0i32; w + 2]).collect();
105 let mut run_index = vec![0usize; snc];
106 for y in 0..h {
107 if scan.restart_interval > 0 && y > 0 && (y % scan.restart_interval as usize) == 0 {
108 reader.consume_restart(rst_idx)?;
109 rst_idx = rst_idx.wrapping_add(1);
110 model.reset_state();
111 for p in &mut prev { p.fill(0); }
112 run_index.fill(0);
113 }
114 for (si, &ci) in scan.comp_indices.iter().enumerate() {
115 model.decode_line(&mut reader, &mut prev[si], &mut curr[si], w, &mut run_index[si])?;
116 planes[ci][y * w..(y + 1) * w].copy_from_slice(&curr[si][1..=w]);
117 std::mem::swap(&mut prev[si], &mut curr[si]);
118 }
119 }
120 }
121 2 => {
122 let snc = scan.comp_indices.len();
123 let mut prev: Vec<Vec<i32>> = (0..snc).map(|_| vec![0i32; w + 2]).collect();
124 let mut curr: Vec<Vec<i32>> = (0..snc).map(|_| vec![0i32; w + 2]).collect();
125 let mut run_index = 0usize;
126 for y in 0..h {
127 if scan.restart_interval > 0 && y > 0 && (y % scan.restart_interval as usize) == 0 {
128 reader.consume_restart(rst_idx)?;
129 rst_idx = rst_idx.wrapping_add(1);
130 model.reset_state();
131 for p in &mut prev { p.fill(0); }
132 run_index = 0;
133 }
134 model.decode_sample_interleaved_line(&mut reader, &mut prev, &mut curr, w, &mut run_index)?;
135 for (si, &ci) in scan.comp_indices.iter().enumerate() {
136 planes[ci][y * w..(y + 1) * w].copy_from_slice(&curr[si][1..=w]);
137 std::mem::swap(&mut prev[si], &mut curr[si]);
138 }
139 }
140 }
141 _ => return Err(JpegLsError::CorruptStream("invalid ILV")),
142 }
143 }
144
145 let expected_mask = (1u8 << nc) - 1;
146 if decoded_mask != expected_mask {
147 return Err(JpegLsError::CorruptStream("missing JPEG-LS scan for frame component"));
148 }
149
150 if bytes_per_sample == 1 {
152 for px in 0..w * h {
153 for c in 0..nc {
154 output[px * nc + c] = planes[c][px] as u8;
155 }
156 }
157 } else {
158 for px in 0..w * h {
159 for c in 0..nc {
160 let le = (planes[c][px] as u16).to_le_bytes();
161 let dst = (px * nc + c) * 2;
162 output[dst] = le[0];
163 output[dst + 1] = le[1];
164 }
165 }
166 }
167 Ok(near_max)
168}
169
170pub fn decode_jpegls_part10_into<'a>(
173 part10_bytes: &'a [u8],
174 output: &mut [u8],
175 limits: JpegLsLimits,
176) -> Result<JpegLsFrameInfo<'a>, JpegLsError> {
177 let encap = parse_encapsulated_part10(
178 part10_bytes,
179 &[TS_JPEGLS_LOSSLESS, TS_JPEGLS_NEAR_LOSSLESS],
180 EncapLimits {
181 max_part10_bytes: limits.max_part10_bytes,
182 max_decoded_bytes: limits.max_decoded_bytes,
183 max_compressed_bytes: limits.max_compressed_bytes,
184 max_frames: limits.max_frames,
185 max_fragments: limits.max_fragments,
186 max_width: limits.max_width,
187 max_height: limits.max_height,
188 max_elements: 8192,
189 },
190 )?;
191 if !matches!(encap.samples_per_pixel, 1 | 3) {
192 return Err(JpegLsError::Unsupported("JPEG-LS SamplesPerPixel must be 1 or 3"));
193 }
194 if encap.samples_per_pixel == 1 {
195 if !matches!(encap.photometric, "MONOCHROME1" | "MONOCHROME2") || encap.planar_configuration.is_some() {
196 return Err(JpegLsError::Unsupported("monochrome JPEG-LS requires MONOCHROME1/2 without PlanarConfiguration"));
197 }
198 } else if !matches!(encap.photometric, "RGB" | "YBR_RCT" | "YBR_ICT") || encap.planar_configuration.is_some_and(|p| p != 0) {
199 return Err(JpegLsError::Unsupported("color JPEG-LS requires RGB/YBR PlanarConfiguration 0"));
200 }
201 if !matches!(encap.bits_allocated, 8 | 16) || !(2..=16).contains(&encap.bits_stored) || encap.bits_stored > encap.bits_allocated {
202 return Err(JpegLsError::BitPrecisionMismatch);
203 }
204 let bps = (encap.bits_allocated / 8) as usize;
205 let frame_bytes = (encap.rows as usize)
206 .checked_mul(encap.columns as usize)
207 .and_then(|v| v.checked_mul(encap.samples_per_pixel as usize))
208 .and_then(|v| v.checked_mul(bps))
209 .ok_or(JpegLsError::Overflow)?;
210 let total_bytes = frame_bytes.checked_mul(encap.frames as usize).ok_or(JpegLsError::Overflow)?;
211 if total_bytes > limits.max_decoded_bytes {
212 return Err(JpegLsError::ByteLimit);
213 }
214 if output.len() < total_bytes {
215 return Err(JpegLsError::OutputTooSmall);
216 }
217
218 let mut staged = Vec::new();
219 staged.try_reserve_exact(total_bytes).map_err(|_| JpegLsError::ByteLimit)?;
220 staged.resize(total_bytes, 0u8);
221 let lossless_only = encap.transfer_syntax_uid == TS_JPEGLS_LOSSLESS;
222 let mut near_max = 0u8;
223
224 for f in 0..encap.frames as usize {
225 let frag_bytes = encap.frame_bytes(f, limits.max_compressed_bytes)?;
226 let dst = &mut staged[f * frame_bytes..(f + 1) * frame_bytes];
227 let near = decode_jpegls_codestream_into(
228 frag_bytes.as_ref(),
229 encap.columns,
230 encap.rows,
231 encap.samples_per_pixel,
232 encap.bits_allocated,
233 encap.bits_stored,
234 lossless_only,
235 dst,
236 )?;
237 near_max = near_max.max(near);
238 }
239
240 output[..total_bytes].copy_from_slice(&staged);
241 Ok(JpegLsFrameInfo {
242 source_blake3: encap.source_blake3,
243 transfer_syntax_uid: encap.transfer_syntax_uid,
244 rows: encap.rows,
245 columns: encap.columns,
246 frames: encap.frames,
247 samples_per_pixel: encap.samples_per_pixel,
248 bits_allocated: encap.bits_allocated,
249 bits_stored: encap.bits_stored,
250 signed: encap.pixel_representation == 1,
251 source_photometric: encap.photometric,
252 near_max,
253 bytes: total_bytes,
254 })
255}