Skip to main content

qualia_core_db/medical/dicom_codecs/jxl/
container.rs

1//! ISO/IEC 18181-1 & 18181-2 JPEG-XL container (`JXL ` ISOBMFF + `jxlc`/`jxlp`/`jbrd`),
2//! bare codestream (`FF 0A`) signature unwrapper, types, and limits.
3use crate::medical::dicom_codecs::encapsulated::EncapError;
4use std::borrow::Cow;
5
6pub const TS_JXL_LOSSLESS: &str = "1.2.840.10008.1.2.4.110";
7pub const TS_JXL_JPEG_RECOMPRESSION: &str = "1.2.840.10008.1.2.4.111";
8pub const TS_JXL: &str = "1.2.840.10008.1.2.4.112";
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum JxlError {
12    Encap(EncapError),
13    Unsupported(&'static str),
14    OutputTooSmall,
15    ByteLimit,
16    FrameLimit,
17    DimensionLimit,
18    Overflow,
19    CorruptStream(&'static str),
20    DimensionMismatch,
21    BitPrecisionMismatch,
22    LosslessModeViolation,
23}
24
25impl From<EncapError> for JxlError {
26    fn from(e: EncapError) -> Self {
27        Self::Encap(e)
28    }
29}
30impl std::fmt::Display for JxlError {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        write!(f, "DICOM JPEG-XL: {self:?}")
33    }
34}
35impl std::error::Error for JxlError {}
36
37#[derive(Clone, Copy, Debug)]
38pub struct JxlLimits {
39    pub max_part10_bytes: usize,
40    pub max_decoded_bytes: usize,
41    pub max_compressed_bytes: usize,
42    pub max_frames: u32,
43    pub max_fragments: usize,
44    pub max_width: u16,
45    pub max_height: u16,
46    pub max_extra_channels: usize,
47    pub max_tree_nodes: usize,
48}
49
50impl Default for JxlLimits {
51    fn default() -> Self {
52        Self {
53            max_part10_bytes: 128 * 1024 * 1024,
54            max_decoded_bytes: 256 * 1024 * 1024,
55            max_compressed_bytes: 64 * 1024 * 1024,
56            max_frames: 4096,
57            max_fragments: 65536,
58            max_width: 16384,
59            max_height: 16384,
60            max_extra_channels: 8,
61            max_tree_nodes: 16384,
62        }
63    }
64}
65
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
67pub enum JxlEncoding {
68    VarDct,
69    Modular,
70}
71
72#[derive(Clone, Copy, Debug, PartialEq, Eq)]
73pub enum JxlFrameType {
74    Regular,
75    LfFrame,
76    ReferenceOnly,
77    SkipProgressive,
78}
79
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81pub enum JxlTransferFunction {
82    Srgb,
83    Linear,
84    Pq,
85    Hlg,
86    Gamma(u32),
87}
88
89#[derive(Clone, Debug)]
90#[allow(dead_code)]
91pub struct JxlBoxResult<'a> {
92    pub codestream: Cow<'a, [u8]>,
93    pub has_jbrd_box: bool,
94    pub jbrd: Option<&'a [u8]>,
95    pub is_container: bool,
96}
97
98#[derive(Clone, Debug)]
99pub struct JxlImageHeader {
100    pub width: u32,
101    pub height: u32,
102    pub bits_per_sample: u8,
103    pub floating_point: bool,
104    pub xyb_encoded: bool,
105    pub is_gray: bool,
106    pub num_extra_channels: u16,
107    pub has_alpha: bool,
108    pub transfer: JxlTransferFunction,
109    pub opsin_inverse_matrix: [[f64; 3]; 3],
110    pub opsin_bias: [f64; 3],
111    pub cfl_default_factors: bool,
112}
113
114#[derive(Clone, Debug)]
115#[allow(dead_code)]
116pub struct JxlFrameHeader {
117    pub frame_type: JxlFrameType,
118    pub encoding: JxlEncoding,
119    pub flags: u64,
120    pub do_ycbcr: bool,
121    pub group_size_shift: u8,
122    pub num_passes: u32,
123    pub is_last: bool,
124    pub gab: bool,
125    pub epf_iters: u8,
126    pub toc_lengths: Vec<usize>,
127    pub x_qm_scale: u8,
128    pub b_qm_scale: u8,
129}
130
131pub const JXL_CONTAINER_SIG: [u8; 12] = [
132    0x00, 0x00, 0x00, 0x0C, b'J', b'X', b'L', b' ', 0x0D, 0x0A, 0x87, 0x0A,
133];
134
135/// Default ISO/IEC 18181-1 opsin forward matrix (`M_1`) inverted analytically at runtime.
136pub fn default_opsin_inverse_matrix() -> [[f64; 3]; 3] {
137    let m = [
138        [0.300, 0.622, 0.078],
139        [0.230, 0.692, 0.078],
140        [0.243_422_689_245_478, 0.204_767_444_244_968, 0.551_809_866_509_554],
141    ];
142    invert_3x3(m).unwrap_or([[11.031567, -9.866944, -0.164623], [-3.254147, 4.418770, -0.164623], [-3.658851, 2.712923, 1.945928]])
143}
144
145pub fn invert_3x3(m: [[f64; 3]; 3]) -> Option<[[f64; 3]; 3]> {
146    let c00 = m[1][1] * m[2][2] - m[1][2] * m[2][1];
147    let c01 = -(m[1][0] * m[2][2] - m[1][2] * m[2][0]);
148    let c02 = m[1][0] * m[2][1] - m[1][1] * m[2][0];
149    let det = m[0][0] * c00 + m[0][1] * c01 + m[0][2] * c02;
150    if det.abs() < 1e-15 || !det.is_finite() {
151        return None;
152    }
153    let inv = 1.0 / det;
154    let c10 = -(m[0][1] * m[2][2] - m[0][2] * m[2][1]);
155    let c11 = m[0][0] * m[2][2] - m[0][2] * m[2][0];
156    let c12 = -(m[0][0] * m[2][1] - m[0][1] * m[2][0]);
157    let c20 = m[0][1] * m[1][2] - m[0][2] * m[1][1];
158    let c21 = -(m[0][0] * m[1][2] - m[0][2] * m[1][0]);
159    let c22 = m[0][0] * m[1][1] - m[0][1] * m[1][0];
160    Some([
161        [c00 * inv, c10 * inv, c20 * inv],
162        [c01 * inv, c11 * inv, c21 * inv],
163        [c02 * inv, c12 * inv, c22 * inv],
164    ])
165}
166
167/// Unwrap ISOBMFF `JXL ` container boxes (`jxlc`, sequenced `jxlp`, and `jbrd` detection)
168/// or accept a bare `FF 0A` codestream directly, subject to `max_compressed_bytes`.
169pub fn unwrap_jxl_container<'a>(bytes: &'a [u8], max_compressed_bytes: usize) -> Result<JxlBoxResult<'a>, JxlError> {
170    if bytes.len() > max_compressed_bytes {
171        return Err(JxlError::ByteLimit);
172    }
173    if bytes.starts_with(&[0xFF, 0x0A]) {
174        return Ok(JxlBoxResult {
175            codestream: Cow::Borrowed(bytes),
176            has_jbrd_box: false,
177            jbrd: None,
178            is_container: false,
179        });
180    }
181    if !bytes.starts_with(&JXL_CONTAINER_SIG) {
182        return Err(JxlError::CorruptStream("missing JPEG-XL FF0A or ISOBMFF JXL signature"));
183    }
184    let mut pos = JXL_CONTAINER_SIG.len();
185    let mut jxlc: Option<&'a [u8]> = None;
186    let mut jxlp_parts: Vec<(u32, &'a [u8])> = Vec::new();
187    let mut jbrd: Option<&'a [u8]> = None;
188    let mut saw_last_jxlp = false;
189
190    while pos < bytes.len() {
191        if pos + 1 == bytes.len() && bytes[pos] == 0 && (jxlc.is_some() || saw_last_jxlp) {
192            break;
193        }
194        if pos + 8 > bytes.len() {
195            return Err(JxlError::CorruptStream("truncated ISOBMFF box header"));
196        }
197        let size32 = u32::from_be_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]]) as usize;
198        let box_type = &bytes[pos + 4..pos + 8];
199        let (hdr_len, box_end) = if size32 == 1 {
200            if pos + 16 > bytes.len() {
201                return Err(JxlError::CorruptStream("truncated ISOBMFF 64-bit box header"));
202            }
203            let s64 = u64::from_be_bytes(bytes[pos + 8..pos + 16].try_into().map_err(|_| JxlError::CorruptStream("box size"))?);
204            let s = usize::try_from(s64).map_err(|_| JxlError::Overflow)?;
205            if s < 16 {
206                return Err(JxlError::CorruptStream("invalid 64-bit box length"));
207            }
208            (16usize, pos.checked_add(s).ok_or(JxlError::Overflow)?)
209        } else if size32 == 0 {
210            (8usize, bytes.len())
211        } else if size32 < 8 {
212            return Err(JxlError::CorruptStream("invalid ISOBMFF box size < 8"));
213        } else {
214            (8usize, pos.checked_add(size32).ok_or(JxlError::Overflow)?)
215        };
216        if box_end > bytes.len() {
217            return Err(JxlError::CorruptStream("ISOBMFF box extends past stream end"));
218        }
219        let payload = &bytes[pos + hdr_len..box_end];
220        match box_type {
221            b"jxlc" => {
222                if jxlc.is_some() || !jxlp_parts.is_empty() {
223                    return Err(JxlError::CorruptStream("duplicate jxlc codestream box"));
224                }
225                jxlc = Some(payload);
226            }
227            b"jxlp" => {
228                if jxlc.is_some() || payload.len() < 4 {
229                    return Err(JxlError::CorruptStream("invalid jxlp partial codestream box"));
230                }
231                let idx_raw = u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]);
232                if (idx_raw & 0x8000_0000) != 0 {
233                    saw_last_jxlp = true;
234                }
235                jxlp_parts.push((idx_raw & 0x7FFF_FFFF, &payload[4..]));
236            }
237            b"jbrd" => {
238                if jbrd.is_some() {
239                    return Err(JxlError::CorruptStream("duplicate jbrd reconstruction box"));
240                }
241                if payload.is_empty() {
242                    return Err(JxlError::CorruptStream("empty jbrd reconstruction box"));
243                }
244                jbrd = Some(payload);
245            }
246            _ => {}
247        }
248        pos = box_end;
249    }
250
251    if let Some(cs) = jxlc {
252        if !cs.starts_with(&[0xFF, 0x0A]) {
253            return Err(JxlError::CorruptStream("jxlc payload missing FF0A signature"));
254        }
255        return Ok(JxlBoxResult {
256            codestream: Cow::Borrowed(cs),
257            has_jbrd_box: jbrd.is_some(),
258            jbrd,
259            is_container: true,
260        });
261    }
262    if jxlp_parts.is_empty() || !saw_last_jxlp {
263        return Err(JxlError::CorruptStream("JXL container missing jxlc/jxlp codestream"));
264    }
265    jxlp_parts.sort_by_key(|p| p.0);
266    for (expected, (idx, _)) in jxlp_parts.iter().enumerate() {
267        if *idx as usize != expected {
268            return Err(JxlError::CorruptStream("non-contiguous jxlp sequence indices"));
269        }
270    }
271    let total: usize = jxlp_parts.iter().map(|p| p.1.len()).sum();
272    if total > max_compressed_bytes {
273        return Err(JxlError::ByteLimit);
274    }
275    let mut joined = Vec::new();
276    joined.try_reserve_exact(total).map_err(|_| JxlError::ByteLimit)?;
277    for (_, part) in jxlp_parts {
278        joined.extend_from_slice(part);
279    }
280    if !joined.starts_with(&[0xFF, 0x0A]) {
281        return Err(JxlError::CorruptStream("reassembled jxlp missing FF0A signature"));
282    }
283    Ok(JxlBoxResult {
284        codestream: Cow::Owned(joined),
285        has_jbrd_box: jbrd.is_some(),
286        jbrd,
287        is_container: true,
288    })
289}
290
291/// Validate ISOBMFF JXL container framing and extract the `jbrd` JPEG reconstruction box
292/// payload (`.111`), failing closed if missing, empty, duplicated, or truncated.
293pub fn extract_jbrd_payload<'a>(bytes: &'a [u8], limits: JxlLimits) -> Result<&'a [u8], JxlError> {
294    let unwrapped = unwrap_jxl_container(bytes, limits.max_compressed_bytes)?;
295    unwrapped.jbrd.ok_or(JxlError::CorruptStream("missing jbrd box for JPEG reconstruction"))
296}