Skip to main content

qualia_core_db/medical/dicom_codecs/
jpeg.rs

1//! Bounded DICOM encapsulated JPEG Baseline (.50) & Extended (.51) decoder.
2//! All framing, dimensions, color/subsampling and budgets are verified before
3//! touching the caller output buffer.
4use super::PixelError;
5use crate::medical::dicom_dataset::{DatasetError, ElementKind, Part10Dataset, WorkBudget};
6use jpeg_decoder::{CodingProcess, ColorTransform, Decoder, Error as DecoderError, PixelFormat};
7use std::io::{self, Read};
8
9pub const TS_JPEG_BASELINE: &str = "1.2.840.10008.1.2.4.50";
10pub const TS_JPEG_EXTENDED: &str = "1.2.840.10008.1.2.4.51";
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum JpegError {
14    Dataset(DatasetError),
15    Pixel(PixelError),
16    Unsupported(&'static str),
17    OutputTooSmall,
18    ByteLimit,
19    FrameLimit,
20    FragmentLimit,
21    DimensionLimit,
22    Overflow,
23    FragmentCount,
24    BasicOffsetTable,
25    CorruptStream(&'static str),
26    DimensionMismatch,
27    ColorOrSubsamplingMismatch,
28    BitPrecisionMismatch,
29}
30impl From<DatasetError> for JpegError { fn from(e: DatasetError) -> Self { Self::Dataset(e) } }
31impl From<PixelError> for JpegError { fn from(e: PixelError) -> Self { Self::Pixel(e) } }
32impl std::fmt::Display for JpegError {
33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "DICOM JPEG: {self:?}") }
34}
35impl std::error::Error for JpegError {}
36
37#[derive(Clone, Copy, Debug)]
38pub struct JpegLimits {
39    pub max_decoded_bytes: usize,
40    pub max_compressed_bytes: usize,
41    pub max_frames: u32,
42    pub max_fragments: usize,
43    pub max_width: u16,
44    pub max_height: u16,
45}
46impl Default for JpegLimits {
47    fn default() -> Self {
48        Self {
49            max_decoded_bytes: 256 * 1024 * 1024, max_compressed_bytes: 64 * 1024 * 1024,
50            max_frames: 4096, max_fragments: 16384, max_width: 16384, max_height: 16384,
51        }
52    }
53}
54
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56pub enum JpegColorFormat {
57    Gray8,
58    Rgb24,
59    /// 12-bit monochrome (`0..=4095`) packed into little-endian `u16` (`2` bytes/sample).
60    Gray12,
61    /// 12-bit 3-channel RGB (`0..=4095` per channel) packed into little-endian `u16` (`6` bytes/pixel).
62    Rgb36,
63}
64
65#[derive(Clone, Copy, Debug, PartialEq, Eq)]
66pub struct JpegDecodedInfo<'a> {
67    pub source_blake3: [u8; 32],
68    pub transfer_syntax_uid: &'a str,
69    pub rows: u16,
70    pub columns: u16,
71    pub frames: u32,
72    pub samples_per_pixel: u16,
73    pub bits_stored: u16,
74    pub source_photometric: &'a str,
75    pub output_format: JpegColorFormat,
76    pub bytes: usize,
77}
78
79struct FragmentChainReader<'a, 'b> {
80    fragments: &'b [&'a [u8]],
81    frag_idx: usize,
82    offset: usize,
83}
84impl<'a, 'b> FragmentChainReader<'a, 'b> {
85    fn new(fragments: &'b [&'a [u8]]) -> Self {
86        Self { fragments, frag_idx: 0, offset: 0 }
87    }
88}
89impl Read for FragmentChainReader<'_, '_> {
90    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
91        while self.frag_idx < self.fragments.len() {
92            let frag = self.fragments[self.frag_idx];
93            if self.offset < frag.len() {
94                let n = buf.len().min(frag.len() - self.offset);
95                buf[..n].copy_from_slice(&frag[self.offset..self.offset + n]);
96                self.offset += n;
97                return Ok(n);
98            }
99            self.frag_idx += 1;
100            self.offset = 0;
101        }
102        Ok(0)
103    }
104}
105
106fn read_u8_stream<R: Read>(r: &mut R) -> Result<u8, JpegError> {
107    let mut b = [0u8; 1];
108    r.read_exact(&mut b).map_err(|_| JpegError::CorruptStream("truncated JPEG header"))?;
109    Ok(b[0])
110}
111
112fn read_u16_be_stream<R: Read>(r: &mut R) -> Result<u16, JpegError> {
113    let mut b = [0u8; 2];
114    r.read_exact(&mut b).map_err(|_| JpegError::CorruptStream("truncated JPEG marker length"))?;
115    Ok(u16::from_be_bytes(b))
116}
117
118fn skip_exact<R: Read>(r: &mut R, mut remaining: usize) -> Result<(), JpegError> {
119    let mut scratch = [0u8; 256];
120    while remaining > 0 {
121        let step = remaining.min(scratch.len());
122        r.read_exact(&mut scratch[..step]).map_err(|_| JpegError::CorruptStream("truncated JPEG marker payload"))?;
123        remaining -= step;
124    }
125    Ok(())
126}
127
128fn bot_entry(bot: &[u8], index: usize) -> Result<u32, JpegError> {
129    let start = index.checked_mul(4).ok_or(JpegError::Overflow)?;
130    let end = start.checked_add(4).ok_or(JpegError::Overflow)?;
131    let b = bot.get(start..end).ok_or(JpegError::BasicOffsetTable)?;
132    Ok(u32::from_le_bytes(b.try_into().map_err(|_| JpegError::BasicOffsetTable)?))
133}
134
135fn inspect_jpeg_sof(
136    fragments: &[&[u8]],
137    ts_uid: &str,
138    rows: u16,
139    cols: u16,
140    spp: u16,
141    bs: u16,
142    photometric: &str,
143) -> Result<(), JpegError> {
144    let mut r = FragmentChainReader::new(fragments);
145    if read_u8_stream(&mut r)? != 0xFF || read_u8_stream(&mut r)? != 0xD8 {
146        return Err(JpegError::CorruptStream("missing JPEG SOI marker"));
147    }
148    loop {
149        let mut b = read_u8_stream(&mut r)?;
150        while b != 0xFF {
151            b = read_u8_stream(&mut r)?;
152        }
153        let mut marker = read_u8_stream(&mut r)?;
154        while marker == 0xFF {
155            marker = read_u8_stream(&mut r)?;
156        }
157        if marker == 0x00 || marker == 0x01 || (0xD0..=0xD8).contains(&marker) {
158            continue;
159        }
160        if marker == 0xD9 || marker == 0xDA {
161            return Err(JpegError::CorruptStream("JPEG stream missing SOF marker"));
162        }
163        let seg_len = read_u16_be_stream(&mut r)? as usize;
164        if seg_len < 2 {
165            return Err(JpegError::CorruptStream("invalid JPEG marker length"));
166        }
167        let payload_len = seg_len - 2;
168        if matches!(marker, 0xC0..=0xC3 | 0xC5..=0xC7 | 0xC9..=0xCB | 0xCD..=0xCF | 0xF7) {
169            if marker == 0xC1 && ts_uid == TS_JPEG_BASELINE {
170                return Err(JpegError::Unsupported("JPEG Baseline (.50) rejects Extended SOF1"));
171            }
172            if !matches!(marker, 0xC0 | 0xC1) {
173                return Err(JpegError::Unsupported("JPEG process outside Baseline SOF0 / Extended SOF1"));
174            }
175            if payload_len < 6 || payload_len > 18 {
176                return Err(JpegError::CorruptStream("invalid SOF length"));
177            }
178            let mut sof = [0u8; 18];
179            r.read_exact(&mut sof[..payload_len]).map_err(|_| JpegError::CorruptStream("truncated SOF marker"))?;
180            let precision = sof[0];
181            let expected_prec = if bs == 12 { 12 } else { 8 };
182            if precision == 12 && ts_uid == TS_JPEG_BASELINE {
183                return Err(JpegError::Unsupported("JPEG Baseline (.50) rejects 12-bit precision"));
184            }
185            if precision != expected_prec {
186                return Err(JpegError::BitPrecisionMismatch);
187            }
188            if precision == 12 && marker != 0xC1 {
189                return Err(JpegError::Unsupported("12-bit JPEG requires SOF1 Extended Sequential"));
190            }
191            let h = u16::from_be_bytes([sof[1], sof[2]]);
192            let w = u16::from_be_bytes([sof[3], sof[4]]);
193            if h != rows || w != cols {
194                return Err(JpegError::DimensionMismatch);
195            }
196            let nf = sof[5];
197            if nf as u16 != spp || payload_len != 6 + 3 * nf as usize {
198                return Err(JpegError::ColorOrSubsamplingMismatch);
199            }
200            let mut hv = [(0u8, 0u8); 3];
201            for i in 0..nf as usize {
202                let s = sof[6 + i * 3 + 1];
203                let (hs, vs) = (s >> 4, s & 0x0F);
204                if !(1..=4).contains(&hs) || !(1..=4).contains(&vs) {
205                    return Err(JpegError::CorruptStream("invalid SOF sampling factor"));
206                }
207                hv[i] = (hs, vs);
208            }
209            match photometric {
210                "MONOCHROME1" | "MONOCHROME2" if nf == 1 => {}
211                "RGB" | "YBR_FULL" if nf == 3 && hv == [(1, 1); 3] => {}
212                "YBR_FULL_422" if nf == 3 && hv == [(2, 1), (1, 1), (1, 1)] => {}
213                _ => return Err(JpegError::ColorOrSubsamplingMismatch),
214            }
215            return Ok(());
216        }
217        skip_exact(&mut r, payload_len)?;
218    }
219}
220
221fn map_decoder_err(err: DecoderError) -> JpegError {
222    match err {
223        DecoderError::Unsupported(_) => JpegError::Unsupported("unsupported JPEG feature in jpeg-decoder"),
224        DecoderError::Format(_) | DecoderError::Io(_) | DecoderError::Internal(_) => {
225            JpegError::CorruptStream("JPEG entropy decode failed")
226        }
227    }
228}
229
230fn validate_metadata<'a>(
231    ds: &Part10Dataset<'a>,
232    limits: JpegLimits,
233    w: &mut WorkBudget,
234) -> Result<(u16, u16, u32, u16, u16, &'a str, usize, usize), JpegError> {
235    let ts_uid = ds.transfer_syntax_uid();
236    if !matches!(ts_uid, TS_JPEG_BASELINE | TS_JPEG_EXTENDED) {
237        return Err(JpegError::Unsupported("requires JPEG Baseline (.50) or Extended (.51) transfer syntax"));
238    }
239    for tag in [0x7fe00008, 0x7fe00009, 0x7fe00001, 0x7fe00002] {
240        if ds.find(None, tag, w)?.is_some() {
241            return Err(JpegError::Unsupported("float pixel data or Extended Offset Table unsupported"));
242        }
243    }
244    let req = |tag, w: &mut WorkBudget| -> Result<u16, JpegError> {
245        ds.unsigned_short(tag, w).map_err(JpegError::from)?.ok_or_else(|| JpegError::Pixel(PixelError::Missing(tag)))
246    };
247    let (rows, cols) = (req(0x00280010, w)?, req(0x00280011, w)?);
248    if rows == 0 || cols == 0 {
249        return Err(PixelError::Invalid(0x00280010).into());
250    }
251    if cols > limits.max_width || rows > limits.max_height {
252        return Err(JpegError::DimensionLimit);
253    }
254    let spp = req(0x00280002, w)?;
255    if !matches!(spp, 1 | 3) {
256        return Err(JpegError::Unsupported("SamplesPerPixel must be 1 or 3"));
257    }
258    let photometric = ds.text(None, 0x00280004, *b"CS", w)?.ok_or(PixelError::Missing(0x00280004))?;
259    let planar = ds.unsigned_short(0x00280006, w)?;
260    if spp == 1 {
261        if !matches!(photometric, "MONOCHROME1" | "MONOCHROME2") {
262            return Err(JpegError::ColorOrSubsamplingMismatch);
263        }
264        if planar.is_some() {
265            return Err(JpegError::Unsupported("monochrome JPEG requires absent PlanarConfiguration"));
266        }
267    } else {
268        if !matches!(photometric, "RGB" | "YBR_FULL" | "YBR_FULL_422") {
269            return Err(JpegError::ColorOrSubsamplingMismatch);
270        }
271        if planar.is_some_and(|p| p != 0) {
272            return Err(JpegError::Unsupported("planar RGB JPEG unsupported"));
273        }
274    }
275    let (ba, bs, hb, rep) = (req(0x00280100, w)?, req(0x00280101, w)?, req(0x00280102, w)?, req(0x00280103, w)?);
276    if rep != 0 {
277        return Err(JpegError::BitPrecisionMismatch);
278    }
279    let is_8bit = ba == 8 && bs == 8 && hb == 7;
280    let is_12bit = ts_uid == TS_JPEG_EXTENDED && ba == 16 && bs == 12 && hb == 11;
281    if !is_8bit && !is_12bit {
282        return Err(JpegError::BitPrecisionMismatch);
283    }
284    let frames = ds.frame_count(w)?;
285    if frames == 0 || frames > limits.max_frames {
286        return Err(JpegError::FrameLimit);
287    }
288    let sample_bytes = if is_12bit { 2usize } else { 1usize };
289    let frame_bytes = (rows as usize)
290        .checked_mul(cols as usize)
291        .and_then(|v| v.checked_mul(spp as usize))
292        .and_then(|v| v.checked_mul(sample_bytes))
293        .ok_or(JpegError::Overflow)?;
294    let total_bytes = frame_bytes.checked_mul(frames as usize).ok_or(JpegError::Overflow)?;
295    if total_bytes > limits.max_decoded_bytes {
296        return Err(JpegError::ByteLimit);
297    }
298    Ok((rows, cols, frames, spp, bs, photometric, frame_bytes, total_bytes))
299}
300
301fn collect_frame_ranges<'a>(
302    ds: &Part10Dataset<'a>,
303    frames: u32,
304    limits: JpegLimits,
305    w: &mut WorkBudget,
306) -> Result<(Vec<&'a [u8]>, Vec<(usize, usize)>), JpegError> {
307    let id = ds.find(None, 0x7fe00010, w)?.ok_or(PixelError::Missing(0x7fe00010))?;
308    let elem = ds.element(id)?;
309    if elem.kind != ElementKind::EncapsulatedPixels || elem.vr != Some(*b"OB") {
310        return Err(PixelError::Invalid(0x7fe00010).into());
311    }
312    let mut items = ds.sequence_items(id, w)?;
313    let bot_id = items.next().ok_or(JpegError::FragmentCount)?;
314    let bot = ds.item_bytes(bot_id)?;
315    let bot_len = (frames as usize).checked_mul(4).ok_or(JpegError::Overflow)?;
316    if !bot.is_empty() && (bot.len() != bot_len || bot_entry(bot, 0)? != 0) {
317        return Err(JpegError::BasicOffsetTable);
318    }
319    let (mut frag_count, mut compressed, mut offset, mut next_frame) = (0usize, 0usize, 0usize, 0usize);
320    for item in items {
321        frag_count = frag_count.checked_add(1).ok_or(JpegError::Overflow)?;
322        if frag_count > limits.max_fragments {
323            return Err(JpegError::FragmentLimit);
324        }
325        let bytes = ds.item_bytes(item)?;
326        compressed = compressed.checked_add(bytes.len()).ok_or(JpegError::Overflow)?;
327        if compressed > limits.max_compressed_bytes {
328            return Err(JpegError::ByteLimit);
329        }
330        if !bot.is_empty() && next_frame < frames as usize {
331            let expected = bot_entry(bot, next_frame)? as usize;
332            if offset == expected {
333                next_frame += 1;
334            } else if offset > expected {
335                return Err(JpegError::BasicOffsetTable);
336            }
337        }
338        offset = offset.checked_add(8).and_then(|n| n.checked_add(bytes.len())).ok_or(JpegError::Overflow)?;
339    }
340    if frag_count == 0 || (!bot.is_empty() && next_frame != frames as usize) {
341        return Err(if frag_count == 0 { JpegError::FragmentCount } else { JpegError::BasicOffsetTable });
342    }
343    if bot.is_empty() && frames > 1 && frag_count != frames as usize {
344        return Err(JpegError::BasicOffsetTable);
345    }
346    let mut frags = Vec::new();
347    frags.try_reserve_exact(frag_count).map_err(|_| JpegError::ByteLimit)?;
348    let mut ranges = Vec::new();
349    ranges.try_reserve_exact(frames as usize).map_err(|_| JpegError::FrameLimit)?;
350    let mut starts = Vec::new();
351    if !bot.is_empty() {
352        starts.try_reserve_exact(frames as usize).map_err(|_| JpegError::FrameLimit)?;
353    }
354    let mut items2 = ds.sequence_items(id, w)?;
355    items2.next();
356    let (mut cur_offset, mut f_idx) = (0usize, 0usize);
357    for (idx, item) in items2.enumerate() {
358        let bytes = ds.item_bytes(item)?;
359        if !bot.is_empty() && f_idx < frames as usize && cur_offset == bot_entry(bot, f_idx)? as usize {
360            starts.push(idx);
361            f_idx += 1;
362        }
363        cur_offset += 8 + bytes.len();
364        frags.push(bytes);
365    }
366    if !bot.is_empty() {
367        for i in 0..frames as usize {
368            let end = if i + 1 < frames as usize { starts[i + 1] } else { frags.len() };
369            if starts[i] >= end {
370                return Err(JpegError::FragmentCount);
371            }
372            ranges.push((starts[i], end));
373        }
374    } else if frames == 1 {
375        ranges.push((0, frags.len()));
376    } else {
377        for i in 0..frames as usize {
378            ranges.push((i, i + 1));
379        }
380    }
381    Ok((frags, ranges))
382}
383
384/// Decode encapsulated DICOM JPEG Baseline (.50) or Extended (.51) frames into
385/// `output`, verifying dimensions, coding process, sampling and pixel format
386/// across all frames before writing a single byte to `output`.
387pub fn decode_jpeg_into<'a>(
388    ds: &Part10Dataset<'a>,
389    output: &mut [u8],
390    limits: JpegLimits,
391    w: &mut WorkBudget,
392) -> Result<JpegDecodedInfo<'a>, JpegError> {
393    let (rows, cols, frames, spp, bs, photometric, frame_bytes, total_bytes) = validate_metadata(ds, limits, w)?;
394    if output.len() < total_bytes {
395        return Err(JpegError::OutputTooSmall);
396    }
397    let (frags, ranges) = collect_frame_ranges(ds, frames, limits, w)?;
398    let mut staged = Vec::new();
399    staged.try_reserve_exact(total_bytes).map_err(|_| JpegError::ByteLimit)?;
400    staged.resize(total_bytes, 0);
401    let ts_uid = ds.transfer_syntax_uid();
402    let expected_pf = if spp == 1 { PixelFormat::L8 } else { PixelFormat::RGB24 };
403    for (frame_idx, (start, end)) in ranges.into_iter().enumerate() {
404        let slice = &frags[start..end];
405        inspect_jpeg_sof(slice, ts_uid, rows, cols, spp, bs, photometric)?;
406        let pixels = if bs == 12 {
407            super::jpeg_12bit::decode_jpeg_12bit_frame(slice, rows, cols, spp, photometric)?
408        } else {
409            let mut decoder = Decoder::new(FragmentChainReader::new(slice));
410            decoder.set_max_decoding_buffer_size(frame_bytes);
411            decoder.read_info().map_err(map_decoder_err)?;
412            let info = decoder.info().ok_or(JpegError::CorruptStream("missing JPEG frame info"))?;
413            if info.width != cols || info.height != rows { return Err(JpegError::DimensionMismatch); }
414            if info.coding_process != CodingProcess::DctSequential { return Err(JpegError::Unsupported("non-sequential JPEG process")); }
415            if info.pixel_format != expected_pf { return Err(JpegError::ColorOrSubsamplingMismatch); }
416            decoder.set_color_transform(match photometric {
417                "MONOCHROME1" | "MONOCHROME2" => ColorTransform::Grayscale,
418                "RGB" => ColorTransform::RGB,
419                _ => ColorTransform::YCbCr,
420            });
421            decoder.decode().map_err(map_decoder_err)?
422        };
423        if pixels.len() != frame_bytes {
424            return Err(JpegError::DimensionMismatch);
425        }
426        let dst = frame_idx * frame_bytes;
427        staged[dst..dst + frame_bytes].copy_from_slice(&pixels);
428    }
429    output[..total_bytes].copy_from_slice(&staged);
430    Ok(JpegDecodedInfo {
431        source_blake3: ds.source_blake3(), transfer_syntax_uid: ts_uid, rows, columns: cols, frames,
432        samples_per_pixel: spp, bits_stored: bs, source_photometric: photometric,
433        output_format: match (spp, bs) {
434            (1, 12) => JpegColorFormat::Gray12,
435            (1, _) => JpegColorFormat::Gray8,
436            (_, 12) => JpegColorFormat::Rgb36,
437            _ => JpegColorFormat::Rgb24,
438        },
439        bytes: total_bytes,
440    })
441}