Skip to main content

qualia_core_db/medical/dicom_codecs/jxl/
mod.rs

1//! ISO/IEC 18181-1 / 18181-2 JPEG-XL decoder for DICOM Transfer Syntaxes
2//! `1.2.840.10008.1.2.4.110` (JPEG XL Lossless),
3//! `1.2.840.10008.1.2.4.111` (JPEG XL JPEG Recompression), and
4//! `1.2.840.10008.1.2.4.112` (JPEG XL).
5mod color;
6mod container;
7mod entropy;
8mod entropy_tables;
9mod headers;
10pub mod jbrd_reconstruct;
11mod modular;
12mod modular_transforms;
13mod vardct;
14#[cfg(test)]
15mod tests;
16#[cfg(test)]
17mod jxl_jbrd_tests;
18
19pub use container::{
20    extract_jbrd_payload, JxlEncoding, JxlError, JxlFrameType, JxlImageHeader, JxlLimits,
21    JxlTransferFunction, TS_JXL, TS_JXL_JPEG_RECOMPRESSION, TS_JXL_LOSSLESS,
22};
23pub use jbrd_reconstruct::{
24    encode_jbrd_box_from_jpeg, reconstruct_jpeg_from_jbrd, reconstruct_jpeg_from_jxl_container,
25    JbrdExtractedCoeffs,
26};
27
28use super::encapsulated::{parse_encapsulated_part10, EncapLimits};
29use color::pack_jxl_planes_into_output;
30use container::unwrap_jxl_container;
31use entropy::JxlBitReader;
32use headers::{parse_frame_header, parse_image_header};
33use modular::decode_modular_frame_planes;
34use vardct::decode_vardct_frame_planes;
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub struct JxlFrameInfo<'a> {
38    pub source_blake3: [u8; 32],
39    pub transfer_syntax_uid: &'a str,
40    pub rows: u16,
41    pub columns: u16,
42    pub frames: u32,
43    pub samples_per_pixel: u16,
44    pub bits_allocated: u16,
45    pub bits_stored: u16,
46    pub signed: bool,
47    pub source_photometric: &'a str,
48    pub encoding: JxlEncoding,
49    pub has_jbrd_box: bool,
50    pub bytes: usize,
51}
52
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54pub struct JxlDecodedCodestream {
55    pub encoding: JxlEncoding,
56    pub has_jbrd_box: bool,
57}
58
59/// Decode one bare `FF 0A` codestream OR ISOBMFF `JXL ` container into `output`
60/// (`bits_allocated = 8 | 16`). Fails closed leaving `output` untouched on any error.
61pub fn decode_jxl_codestream_into(
62    bytes: &[u8],
63    expected_width: u16,
64    expected_height: u16,
65    expected_nc: u16,
66    expected_ba: u16,
67    expected_bs: u16,
68    lossless_only: bool,
69    limits: JxlLimits,
70    output: &mut [u8],
71) -> Result<JxlDecodedCodestream, JxlError> {
72    let unwrapped = unwrap_jxl_container(bytes, limits.max_compressed_bytes)?;
73    let cs = unwrapped.codestream.as_ref();
74    let mut br = JxlBitReader::new(cs);
75    let hdr = parse_image_header(&mut br, limits)?;
76    if hdr.width != expected_width as u32 || hdr.height != expected_height as u32 {
77        return Err(JxlError::DimensionMismatch);
78    }
79    let cs_nc = if hdr.is_gray { 1 } else { 3 } + hdr.num_extra_channels;
80    if cs_nc != expected_nc {
81        return Err(JxlError::CorruptStream("JXL component count mismatch"));
82    }
83    if hdr.bits_per_sample as u16 != expected_bs || expected_bs > expected_ba || !matches!(expected_ba, 8 | 16) {
84        return Err(JxlError::BitPrecisionMismatch);
85    }
86    if hdr.floating_point {
87        return Err(JxlError::Unsupported("floating-point JXL pixel depth unsupported for integer PixelData"));
88    }
89    let fh = parse_frame_header(&mut br, &hdr)?;
90    if lossless_only && fh.encoding != JxlEncoding::Modular {
91        return Err(JxlError::LosslessModeViolation);
92    }
93    if fh.frame_type != JxlFrameType::Regular {
94        return Err(JxlError::Unsupported("non-regular JXL frame type unsupported"));
95    }
96    let bps = if expected_ba <= 8 { 1usize } else { 2usize };
97    let need = (hdr.width as usize)
98        .checked_mul(hdr.height as usize)
99        .and_then(|v| v.checked_mul(expected_nc as usize))
100        .and_then(|v| v.checked_mul(bps))
101        .ok_or(JxlError::Overflow)?;
102    if need > limits.max_decoded_bytes {
103        return Err(JxlError::ByteLimit);
104    }
105    if output.len() < need {
106        return Err(JxlError::OutputTooSmall);
107    }
108
109    br.skip_pad_to_byte()?;
110    let byte_offset = br.bit_pos() / 8;
111    let body_end = if let Some(&toc0) = fh.toc_lengths.first() {
112        byte_offset.checked_add(toc0).ok_or(JxlError::Overflow)?
113    } else {
114        cs.len()
115    };
116    if body_end > cs.len() {
117        return Err(JxlError::CorruptStream("JXL TOC section exceeds codestream size"));
118    }
119    let mut section_br = JxlBitReader::new(&cs[byte_offset..body_end]);
120    let (planes, is_mod) = match fh.encoding {
121        JxlEncoding::Modular => (decode_modular_frame_planes(&mut section_br, &hdr, limits)?, true),
122        JxlEncoding::VarDct => (decode_vardct_frame_planes(&mut section_br, &hdr, &fh, limits)?, false),
123    };
124
125    let mut staged = vec![0u8; need];
126    pack_jxl_planes_into_output(&hdr, &planes, is_mod, expected_nc, expected_ba, expected_bs, &mut staged)?;
127    output[..need].copy_from_slice(&staged);
128    Ok(JxlDecodedCodestream { encoding: fh.encoding, has_jbrd_box: unwrapped.has_jbrd_box })
129}
130
131/// Decode encapsulated DICOM Part-10 JPEG-XL Transfer Syntaxes (`.110`, `.111`, `.112`).
132pub fn decode_jxl_part10_into<'a>(
133    part10_bytes: &'a [u8],
134    output: &mut [u8],
135    limits: JxlLimits,
136) -> Result<JxlFrameInfo<'a>, JxlError> {
137    let encap = parse_encapsulated_part10(
138        part10_bytes,
139        &[TS_JXL_LOSSLESS, TS_JXL_JPEG_RECOMPRESSION, TS_JXL],
140        EncapLimits {
141            max_part10_bytes: limits.max_part10_bytes,
142            max_decoded_bytes: limits.max_decoded_bytes,
143            max_compressed_bytes: limits.max_compressed_bytes,
144            max_frames: limits.max_frames,
145            max_fragments: limits.max_fragments,
146            max_width: limits.max_width,
147            max_height: limits.max_height,
148            max_elements: 8192,
149        },
150    )?;
151    if !matches!(encap.samples_per_pixel, 1 | 3 | 4) {
152        return Err(JxlError::Unsupported("JPEG-XL DICOM supports 1, 3, or 4 samples per pixel"));
153    }
154    if encap.samples_per_pixel == 1 {
155        if !matches!(encap.photometric, "MONOCHROME1" | "MONOCHROME2") {
156            return Err(JxlError::Unsupported("monochrome JPEG-XL requires MONOCHROME1/2"));
157        }
158    } else if !matches!(encap.photometric, "RGB" | "RGBA") || encap.planar_configuration.is_some_and(|p| p != 0) {
159        return Err(JxlError::Unsupported("color JPEG-XL requires RGB/RGBA PlanarConfiguration 0"));
160    }
161    if !matches!(encap.bits_allocated, 8 | 16) || encap.bits_stored == 0 || encap.bits_stored > encap.bits_allocated {
162        return Err(JxlError::BitPrecisionMismatch);
163    }
164    let bps = if encap.bits_allocated <= 8 { 1usize } else { 2usize };
165    let frame_bytes = (encap.rows as usize)
166        .checked_mul(encap.columns as usize)
167        .and_then(|v| v.checked_mul(encap.samples_per_pixel as usize))
168        .and_then(|v| v.checked_mul(bps))
169        .ok_or(JxlError::Overflow)?;
170    let total_bytes = frame_bytes.checked_mul(encap.frames as usize).ok_or(JxlError::Overflow)?;
171    if total_bytes > limits.max_decoded_bytes {
172        return Err(JxlError::ByteLimit);
173    }
174    if output.len() < total_bytes {
175        return Err(JxlError::OutputTooSmall);
176    }
177
178    let lossless_only = encap.transfer_syntax_uid == TS_JXL_LOSSLESS;
179    let mut staged = vec![0u8; total_bytes];
180    let mut enc_out = JxlEncoding::Modular;
181    let mut has_jbrd = false;
182
183    for f in 0..encap.frames as usize {
184        let fb = encap.frame_bytes(f, limits.max_compressed_bytes)?;
185        let res = decode_jxl_codestream_into(
186            fb.as_ref(),
187            encap.columns,
188            encap.rows,
189            encap.samples_per_pixel,
190            encap.bits_allocated,
191            encap.bits_stored,
192            lossless_only,
193            limits,
194            &mut staged[f * frame_bytes..(f + 1) * frame_bytes],
195        )?;
196        enc_out = res.encoding;
197        has_jbrd |= res.has_jbrd_box;
198    }
199
200    output[..total_bytes].copy_from_slice(&staged);
201    Ok(JxlFrameInfo {
202        source_blake3: encap.source_blake3,
203        transfer_syntax_uid: encap.transfer_syntax_uid,
204        rows: encap.rows,
205        columns: encap.columns,
206        frames: encap.frames,
207        samples_per_pixel: encap.samples_per_pixel,
208        bits_allocated: encap.bits_allocated,
209        bits_stored: encap.bits_stored,
210        signed: encap.pixel_representation == 1,
211        source_photometric: encap.photometric,
212        encoding: enc_out,
213        has_jbrd_box: has_jbrd,
214        bytes: total_bytes,
215    })
216}