Skip to main content

qualia_core_db/medical/dicom_codecs/j2k/
mod.rs

1//! ISO/IEC 15444-1 JPEG 2000 (.90/.91) & ISO/IEC 15444-15 HTJ2K (.201-.203) decoder.
2mod color;
3mod dwt;
4mod ht_block;
5pub mod ht_tables;
6mod markers;
7mod mq_coder;
8mod mq_ebcot;
9mod tier2;
10mod types;
11#[cfg(test)]
12mod tests;
13
14pub use ht_block::{HtVlcEntry, HtVlcTables};
15pub use ht_tables::{
16    annex_c_ht_vlc_tables, decode_ht_cblk_annex_c, encode_ht_cleanup_segment, lookup_vlc_codeword,
17    ANNEX_C_HT_VLC_TABLES, ANNEX_C_TBL0, ANNEX_C_TBL1,
18};
19pub use markers::{
20    J2kError, J2kLimits, ProgressionOrder, WaveletTransform, TS_HTJ2K, TS_HTJ2K_LOSSLESS,
21    TS_HTJ2K_RPCL, TS_J2K, TS_J2K_LOSSLESS,
22};
23pub use tier2::{TagTree, TagTreeLevel};
24pub use types::CodingStyle;
25
26use super::encapsulated::{collect_part10_dataset_frames, concat_fragments, parse_encapsulated_part10, EncapLimits};
27use crate::medical::dicom_dataset::{Part10Dataset, WorkBudget};
28use color::{apply_mct_and_level_shift, pack_tile_into_output};
29use dwt::{subband_total_bitplanes, synthesize_level_53, synthesize_level_97};
30use ht_block::decode_ht_cblk_with_tables;
31use markers::{parse_j2k_codestream, ParsedCodestream};
32use mq_ebcot::decode_ebcot_cblk;
33use tier2::{build_subband_grid, decode_packet, packet_iteration_order, PacketBitReader, SubbandGrid};
34
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub struct J2kFrameInfo<'a> {
37    pub source_blake3: [u8; 32],
38    pub transfer_syntax_uid: &'a str,
39    pub rows: u16,
40    pub columns: u16,
41    pub frames: u32,
42    pub samples_per_pixel: u16,
43    pub bits_allocated: u16,
44    pub bits_stored: u16,
45    pub signed: bool,
46    pub source_photometric: &'a str,
47    pub transform: WaveletTransform,
48    pub is_htj2k: bool,
49    pub bytes: usize,
50}
51
52fn decode_frame_with_tables(
53    codestream: &[u8],
54    expected_w: u16,
55    expected_h: u16,
56    expected_nc: u16,
57    expected_ba: u16,
58    expected_bs: u16,
59    lossless_only: bool,
60    limits: J2kLimits,
61    ht_tables: Option<&HtVlcTables<'_>>,
62    out: &mut [u8],
63) -> Result<(WaveletTransform, bool), J2kError> {
64    let cs = parse_j2k_codestream(codestream, limits)?;
65    if cs.siz.width() != expected_w as u32 || cs.siz.height() != expected_h as u32 {
66        return Err(J2kError::DimensionMismatch);
67    }
68    if cs.siz.components.len() != expected_nc as usize {
69        return Err(J2kError::CorruptStream("J2K component count mismatch"));
70    }
71    for comp in &cs.siz.components {
72        if comp.precision as u16 != expected_bs {
73            return Err(J2kError::BitPrecisionMismatch);
74        }
75        if comp.xrsiz != 1 || comp.yrsiz != 1 {
76            return Err(J2kError::Unsupported("subsampled J2K components unsupported"));
77        }
78    }
79    let bps = if expected_ba <= 8 { 1usize } else { 2usize };
80    let need = (expected_w as usize)
81        .checked_mul(expected_h as usize)
82        .and_then(|v| v.checked_mul(expected_nc as usize))
83        .and_then(|v| v.checked_mul(bps))
84        .ok_or(J2kError::Overflow)?;
85    if out.len() < need {
86        return Err(J2kError::OutputTooSmall);
87    }
88    let is_htj2k = cs.cap.ccap_htj2k.is_some() || cs.cod.uses_htj2k_only();
89    if lossless_only && cs.cod.transform != WaveletTransform::Reversible53 {
90        return Err(J2kError::LosslessModeViolation);
91    }
92
93    let mut staged = vec![0u8; need];
94    decode_all_tiles(&cs, bps, limits.max_compressed_bytes, ht_tables, &mut staged)?;
95    out[..need].copy_from_slice(&staged);
96    Ok((cs.cod.transform, is_htj2k))
97}
98
99fn decode_all_tiles(
100    cs: &ParsedCodestream<'_>,
101    bps: usize,
102    max_compressed_bytes: usize,
103    ht_tables: Option<&HtVlcTables<'_>>,
104    staged: &mut [u8],
105) -> Result<(), J2kError> {
106    let nx = cs.siz.num_tiles_x() as usize;
107    let ny = cs.siz.num_tiles_y() as usize;
108    let nc = cs.siz.components.len();
109    let img_w = cs.siz.width() as usize;
110
111    for ty in 0..ny {
112        for tx in 0..nx {
113            let t_idx = (ty * nx + tx) as u16;
114            let tx0 = (cs.siz.xtosiz + tx as u32 * cs.siz.xtsiz).max(cs.siz.xosiz);
115            let ty0 = (cs.siz.ytosiz + ty as u32 * cs.siz.ytsiz).max(cs.siz.yosiz);
116            let tx1 = (cs.siz.xtosiz + (tx as u32 + 1) * cs.siz.xtsiz).min(cs.siz.xsiz);
117            let ty1 = (cs.siz.ytosiz + (ty as u32 + 1) * cs.siz.ytsiz).min(cs.siz.ysiz);
118
119            let mut tile_cod = cs.cod.clone();
120            let mut tile_qcd = cs.qcd.clone();
121            let mut parts: Vec<&[u8]> = Vec::new();
122            for tp in &cs.tile_parts {
123                if tp.tile_idx == t_idx {
124                    if let Some(ref c) = tp.cod { tile_cod = c.clone(); }
125                    if let Some(ref q) = tp.qcd { tile_qcd = q.clone(); }
126                    parts.push(tp.bitstream);
127                }
128            }
129            if parts.is_empty() {
130                return Err(J2kError::CorruptStream("missing J2K tile-part"));
131            }
132            let comp_cod = |c: usize| -> &super::j2k::markers::CodingStyle {
133                cs.coc.iter().find(|&&(ci, _)| ci as usize == c).map(|(_, v)| v).unwrap_or(&tile_cod)
134            };
135            let comp_qcd = |c: usize| -> &super::j2k::markers::QuantizationParams {
136                cs.qcc.iter().find(|&&(ci, _)| ci as usize == c).map(|(_, v)| v).unwrap_or(&tile_qcd)
137            };
138
139            let mut comp_grids: Vec<Vec<Vec<SubbandGrid>>> = Vec::with_capacity(nc);
140            for c in 0..nc {
141                let ccod = comp_cod(c);
142                let mut res_vec = Vec::with_capacity(ccod.decomp_levels as usize + 1);
143                for r in 0..=ccod.decomp_levels {
144                    let sbs = if r == 0 {
145                        vec![build_subband_grid(tx0, ty0, tx1, ty1, r, ccod.decomp_levels, 0, ccod.cblk_w_shift, ccod.cblk_h_shift)]
146                    } else {
147                        vec![
148                            build_subband_grid(tx0, ty0, tx1, ty1, r, ccod.decomp_levels, 1, ccod.cblk_w_shift, ccod.cblk_h_shift),
149                            build_subband_grid(tx0, ty0, tx1, ty1, r, ccod.decomp_levels, 2, ccod.cblk_w_shift, ccod.cblk_h_shift),
150                            build_subband_grid(tx0, ty0, tx1, ty1, r, ccod.decomp_levels, 3, ccod.cblk_w_shift, ccod.cblk_h_shift),
151                        ]
152                    };
153                    res_vec.push(sbs);
154                }
155                comp_grids.push(res_vec);
156            }
157
158            let joined = concat_fragments(&parts, max_compressed_bytes)?;
159            let mut pkt_reader = PacketBitReader::new(joined.as_ref());
160            let max_res = (0..nc).map(|c| comp_cod(c).decomp_levels).max().unwrap_or(0);
161            for (_layer, res, comp) in packet_iteration_order(tile_cod.progression, tile_cod.layers, max_res, nc) {
162                let ccod = comp_cod(comp);
163                if res > ccod.decomp_levels {
164                    continue;
165                }
166                let mut refs: Vec<&mut SubbandGrid> = comp_grids[comp][res as usize].iter_mut().collect();
167                decode_packet(&mut pkt_reader, ccod, _layer, &mut refs)?;
168            }
169
170            let mut planes_f64: Vec<Vec<f64>> = Vec::with_capacity(nc);
171            for c in 0..nc {
172                let ccod = comp_cod(c);
173                let cqcd = comp_qcd(c);
174                let nom_bpp = cs.siz.components[c].precision;
175                let mut sb_seq = 0usize;
176                let mut ll_i32 = Vec::new();
177                let mut ll_f64 = Vec::new();
178                let (mut ll_w, mut ll_h) = (0usize, 0usize);
179
180                for r in 0..=ccod.decomp_levels {
181                    let sbs = &comp_grids[c][r as usize];
182                    if r == 0 {
183                        let sb = &sbs[0];
184                        ll_w = (sb.x1 - sb.x0) as usize;
185                        ll_h = (sb.y1 - sb.y0) as usize;
186                        let (mb, delta) = subband_total_bitplanes(cqcd, sb_seq, ccod.decomp_levels, nom_bpp);
187                        sb_seq += 1;
188                        let raw = assemble_subband(sb, 0, mb, ccod, ht_tables)?;
189                        if ccod.transform == WaveletTransform::Reversible53 {
190                            ll_i32 = raw;
191                        } else {
192                            ll_f64 = raw.into_iter().map(|v| v as f64 * delta).collect();
193                        }
194                    } else {
195                        let mut hl_i32 = Vec::new();
196                        let mut lh_i32 = Vec::new();
197                        let mut hh_i32 = Vec::new();
198                        let mut hl_f64 = Vec::new();
199                        let mut lh_f64 = Vec::new();
200                        let mut hh_f64 = Vec::new();
201                        let w_hl = (sbs[0].x1 - sbs[0].x0) as usize;
202                        let h_lh = (sbs[1].y1 - sbs[1].y0) as usize;
203                        for (idx, sb) in sbs.iter().enumerate() {
204                            let (mb, delta) = subband_total_bitplanes(cqcd, sb_seq, ccod.decomp_levels, nom_bpp);
205                            sb_seq += 1;
206                            let raw = assemble_subband(sb, sb.subband_id, mb, ccod, ht_tables)?;
207                            if ccod.transform == WaveletTransform::Reversible53 {
208                                match idx { 0 => hl_i32 = raw, 1 => lh_i32 = raw, _ => hh_i32 = raw }
209                            } else {
210                                let scaled: Vec<f64> = raw.into_iter().map(|v| v as f64 * delta).collect();
211                                match idx { 0 => hl_f64 = scaled, 1 => lh_f64 = scaled, _ => hh_f64 = scaled }
212                            }
213                        }
214                        let shift = ccod.decomp_levels - r;
215                        let rx0 = tx0.div_ceil(1u32 << shift);
216                        let ry0 = ty0.div_ceil(1u32 << shift);
217                        if ccod.transform == WaveletTransform::Reversible53 {
218                            ll_i32 = synthesize_level_53(&ll_i32, &hl_i32, &lh_i32, &hh_i32, ll_w, ll_h, w_hl, h_lh, rx0, ry0);
219                        } else {
220                            ll_f64 = synthesize_level_97(&ll_f64, &hl_f64, &lh_f64, &hh_f64, ll_w, ll_h, w_hl, h_lh, rx0, ry0);
221                        }
222                        ll_w += w_hl;
223                        ll_h += h_lh;
224                    }
225                }
226                if ccod.transform == WaveletTransform::Reversible53 {
227                    planes_f64.push(ll_i32.into_iter().map(|v| v as f64).collect());
228                } else {
229                    planes_f64.push(ll_f64);
230                }
231            }
232            apply_mct_and_level_shift(&mut planes_f64, tile_cod.mct, tile_cod.transform, &cs.siz.components);
233            let tw = (tx1 - tx0) as usize;
234            let th = (ty1 - ty0) as usize;
235            pack_tile_into_output(&planes_f64, (tx0 - cs.siz.xosiz) as usize, (ty0 - cs.siz.yosiz) as usize, tw, th, img_w, &cs.siz.components, bps, staged);
236        }
237    }
238    Ok(())
239}
240
241fn assemble_subband(
242    sb: &SubbandGrid,
243    sb_id: usize,
244    total_bps: u8,
245    cod: &super::j2k::markers::CodingStyle,
246    ht_tables: Option<&HtVlcTables<'_>>,
247) -> Result<Vec<i32>, J2kError> {
248    let w = (sb.x1 - sb.x0) as usize;
249    let h = (sb.y1 - sb.y0) as usize;
250    let mut out = vec![0i32; w * h];
251    let use_ht = cod.uses_htj2k_only();
252    for cb in &sb.cblks {
253        let cb_vals = if use_ht {
254            decode_ht_cblk_with_tables(cb, total_bps, ht_tables)?
255        } else {
256            decode_ebcot_cblk(cb, sb_id, total_bps, cod.cblk_style)?
257        };
258        let cw = (cb.x1 - cb.x0) as usize;
259        let ch = (cb.y1 - cb.y0) as usize;
260        let ox = (cb.x0 - sb.x0) as usize;
261        let oy = (cb.y0 - sb.y0) as usize;
262        for y in 0..ch {
263            out[(oy + y) * w + ox..(oy + y) * w + ox + cw].copy_from_slice(&cb_vals[y * cw..(y + 1) * cw]);
264        }
265    }
266    Ok(out)
267}
268
269pub fn decode_j2k_codestream_into(
270    codestream: &[u8],
271    expected_width: u16,
272    expected_height: u16,
273    expected_components: u16,
274    expected_bits_allocated: u16,
275    expected_bits_stored: u16,
276    lossless_only: bool,
277    output: &mut [u8],
278) -> Result<WaveletTransform, J2kError> {
279    let (tf, _) = decode_frame_with_tables(
280        codestream,
281        expected_width,
282        expected_height,
283        expected_components,
284        expected_bits_allocated,
285        expected_bits_stored,
286        lossless_only,
287        J2kLimits::default(),
288        Some(annex_c_ht_vlc_tables()),
289        output,
290    )?;
291    Ok(tf)
292}
293
294pub fn decode_j2k_part10_dataset_into<'a>(
295    ds: &Part10Dataset<'a>,
296    output: &mut [u8],
297    limits: J2kLimits,
298    w: &mut WorkBudget,
299) -> Result<J2kFrameInfo<'a>, J2kError> {
300    let ts_uid = ds.transfer_syntax_uid();
301    if !matches!(ts_uid, TS_J2K_LOSSLESS | TS_J2K | TS_HTJ2K_LOSSLESS | TS_HTJ2K_RPCL | TS_HTJ2K) {
302        return Err(J2kError::Unsupported("Part10Dataset path supports .90, .91, and .201-.203"));
303    }
304    for tag in [0x7fe00008, 0x7fe00009, 0x7fe00001, 0x7fe00002] {
305        if ds.find(None, tag, w).map_err(super::encapsulated::EncapError::from)?.is_some() {
306            return Err(J2kError::Unsupported("float PixelData or Extended Offset Table unsupported"));
307        }
308    }
309    let req = |tag, w: &mut WorkBudget| -> Result<u16, J2kError> {
310        ds.unsigned_short(tag, w).map_err(super::encapsulated::EncapError::from)?.ok_or(J2kError::Encap(super::encapsulated::EncapError::Missing(tag)))
311    };
312    let (rows, cols, spp, ba, bs, hb, rep) = (
313        req(0x00280010, w)?, req(0x00280011, w)?, req(0x00280002, w)?,
314        req(0x00280100, w)?, req(0x00280101, w)?, req(0x00280102, w)?, req(0x00280103, w)?,
315    );
316    if !matches!(ba, 8 | 16) || bs == 0 || bs > ba || hb != bs - 1 || rep > 1 {
317        return Err(J2kError::BitPrecisionMismatch);
318    }
319    let photo = ds.text(None, 0x00280004, *b"CS", w).map_err(super::encapsulated::EncapError::from)?.ok_or(J2kError::Encap(super::encapsulated::EncapError::Missing(0x00280004)))?;
320    let frames = ds.frame_count(w).map_err(super::encapsulated::EncapError::from)?;
321    let (frags, ranges) = collect_part10_dataset_frames(ds, frames, limits.max_fragments, limits.max_compressed_bytes, w)?;
322    let bps = if ba <= 8 { 1usize } else { 2usize };
323    let frame_bytes = (rows as usize) * (cols as usize) * (spp as usize) * bps;
324    let total_bytes = frame_bytes.checked_mul(frames as usize).ok_or(J2kError::Overflow)?;
325    if total_bytes > limits.max_decoded_bytes { return Err(J2kError::ByteLimit); }
326    if output.len() < total_bytes { return Err(J2kError::OutputTooSmall); }
327
328    let lossless_only = matches!(ts_uid, TS_J2K_LOSSLESS | TS_HTJ2K_LOSSLESS);
329    let mut staged = vec![0u8; total_bytes];
330    let mut tf_out = WaveletTransform::Reversible53;
331    let mut is_ht = false;
332    for (f, &(s, e)) in ranges.iter().enumerate() {
333        let joined = concat_fragments(&frags[s..e], limits.max_compressed_bytes)?;
334        let (tf, ht) = decode_frame_with_tables(joined.as_ref(), cols, rows, spp, ba, bs, lossless_only, limits, Some(annex_c_ht_vlc_tables()), &mut staged[f * frame_bytes..(f + 1) * frame_bytes])?;
335        tf_out = tf;
336        is_ht |= ht;
337    }
338    output[..total_bytes].copy_from_slice(&staged);
339    Ok(J2kFrameInfo {
340        source_blake3: ds.source_blake3(), transfer_syntax_uid: ts_uid, rows, columns: cols, frames,
341        samples_per_pixel: spp, bits_allocated: ba, bits_stored: bs, signed: rep == 1,
342        source_photometric: photo, transform: tf_out, is_htj2k: is_ht, bytes: total_bytes,
343    })
344}
345
346/// Decode encapsulated DICOM Part-10 J2K (`.90`/`.91`) and HTJ2K (`.201`-`.203`) using the
347/// normative ITU-T T.814 / ISO 15444-15 Annex C `CxtVLC` tables.
348pub fn decode_j2k_part10_with_annex_c_into<'a>(
349    part10_bytes: &'a [u8],
350    output: &mut [u8],
351    limits: J2kLimits,
352) -> Result<J2kFrameInfo<'a>, J2kError> {
353    decode_j2k_part10_into(part10_bytes, output, limits, Some(annex_c_ht_vlc_tables()))
354}
355
356pub fn decode_j2k_part10_into<'a>(
357    part10_bytes: &'a [u8],
358    output: &mut [u8],
359    limits: J2kLimits,
360    ht_tables: Option<&HtVlcTables<'_>>,
361) -> Result<J2kFrameInfo<'a>, J2kError> {
362    let encap = parse_encapsulated_part10(
363        part10_bytes,
364        &[TS_J2K_LOSSLESS, TS_J2K, TS_HTJ2K_LOSSLESS, TS_HTJ2K_RPCL, TS_HTJ2K],
365        EncapLimits {
366            max_part10_bytes: limits.max_part10_bytes, max_decoded_bytes: limits.max_decoded_bytes,
367            max_compressed_bytes: limits.max_compressed_bytes, max_frames: limits.max_frames,
368            max_fragments: limits.max_fragments, max_width: limits.max_width, max_height: limits.max_height, max_elements: 8192,
369        },
370    )?;
371    let bps = if encap.bits_allocated <= 8 { 1usize } else { 2usize };
372    let frame_bytes = (encap.rows as usize) * (encap.columns as usize) * (encap.samples_per_pixel as usize) * bps;
373    let total_bytes = frame_bytes.checked_mul(encap.frames as usize).ok_or(J2kError::Overflow)?;
374    if total_bytes > limits.max_decoded_bytes { return Err(J2kError::ByteLimit); }
375    if output.len() < total_bytes { return Err(J2kError::OutputTooSmall); }
376    let lossless_only = matches!(encap.transfer_syntax_uid, TS_J2K_LOSSLESS | TS_HTJ2K_LOSSLESS);
377    let mut staged = vec![0u8; total_bytes];
378    let mut tf_out = WaveletTransform::Reversible53;
379    let mut is_ht = false;
380    for f in 0..encap.frames as usize {
381        let fb = encap.frame_bytes(f, limits.max_compressed_bytes)?;
382        let (tf, ht) = decode_frame_with_tables(fb.as_ref(), encap.columns, encap.rows, encap.samples_per_pixel, encap.bits_allocated, encap.bits_stored, lossless_only, limits, ht_tables, &mut staged[f * frame_bytes..(f + 1) * frame_bytes])?;
383        tf_out = tf;
384        is_ht |= ht;
385    }
386    output[..total_bytes].copy_from_slice(&staged);
387    Ok(J2kFrameInfo {
388        source_blake3: encap.source_blake3, transfer_syntax_uid: encap.transfer_syntax_uid, rows: encap.rows,
389        columns: encap.columns, frames: encap.frames, samples_per_pixel: encap.samples_per_pixel,
390        bits_allocated: encap.bits_allocated, bits_stored: encap.bits_stored, signed: encap.pixel_representation == 1,
391        source_photometric: encap.photometric, transform: tf_out, is_htj2k: is_ht, bytes: total_bytes,
392    })
393}