Skip to main content

qualia_core_db/medical/dicom_codecs/rle/
mod.rs

1//! DICOM RLE Lossless, selected MONOCHROME1/2 integer8/16 profile.
2//! Caller owns decoded output and one byte-plane scratch; no allocation occurs.
3mod frame;
4mod packbits;
5use super::{metadata::IntegerImageInfo, NativePixelView, PixelError};
6use crate::medical::dicom_dataset::{DatasetError, ElementKind, Part10Dataset, WorkBudget};
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum RleError {
9    Dataset(DatasetError),
10    Pixel(PixelError),
11    Unsupported(&'static str),
12    OutputTooSmall,
13    ScratchTooSmall,
14    ByteLimit,
15    FrameLimit,
16    WorkLimit,
17    Overflow,
18    FragmentCount,
19    BasicOffsetTable,
20    SegmentHeader,
21    SegmentOffsets,
22    TruncatedRun,
23    RunCrossesRow,
24    TrailingSegmentData,
25}
26impl From<DatasetError> for RleError {
27    fn from(e: DatasetError) -> Self {
28        Self::Dataset(e)
29    }
30}
31impl From<PixelError> for RleError {
32    fn from(e: PixelError) -> Self {
33        Self::Pixel(e)
34    }
35}
36impl std::fmt::Display for RleError {
37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        write!(f, "DICOM RLE: {self:?}")
39    }
40}
41impl std::error::Error for RleError {}
42#[derive(Clone, Copy, Debug)]
43pub struct RleLimits {
44    pub max_decoded_bytes: usize,
45    pub max_scratch_bytes: usize,
46    pub max_compressed_bytes: usize,
47    pub max_frames: u32,
48    pub max_work: usize,
49}
50impl Default for RleLimits {
51    fn default() -> Self {
52        Self {
53            max_decoded_bytes: 256 * 1024 * 1024,
54            max_scratch_bytes: 16 * 1024 * 1024,
55            max_compressed_bytes: 32 * 1024 * 1024,
56            max_frames: 4096,
57            max_work: 2 * 1024 * 1024 * 1024,
58        }
59    }
60}
61fn bot_entry(bot: &[u8], index: usize) -> Result<u32, RleError> {
62    let start = index.checked_mul(4).ok_or(RleError::Overflow)?;
63    let b = bot
64        .get(start..start.checked_add(4).ok_or(RleError::Overflow)?)
65        .ok_or(RleError::BasicOffsetTable)?;
66    Ok(u32::from_le_bytes(
67        b.try_into().map_err(|_| RleError::BasicOffsetTable)?,
68    ))
69}
70/// Validate all metadata/fragments/segments/runs and admit complete resource/work
71/// bounds before writing output or scratch. Success returns a native-layout view
72/// bound to the ORIGINAL compressed source digest; no source/metadata is changed.
73/// Extra caller buffer tails remain untouched. Every RLE frame must occupy exactly
74/// one fragment. Empty BOT is supported; nonempty BOT is verified, not trusted.
75pub fn decode_rle_lossless_into<'source: 'out, 'out>(
76    ds: &Part10Dataset<'source>,
77    output: &'out mut [u8],
78    scratch: &mut [u8],
79    limits: RleLimits,
80    w: &mut WorkBudget,
81) -> Result<NativePixelView<'out>, RleError> {
82    if ds.transfer_syntax_uid() != "1.2.840.10008.1.2.5" {
83        return Err(RleError::Unsupported(
84            "requires RLE Lossless transfer syntax",
85        ));
86    }
87    let info = IntegerImageInfo::from_dataset(ds, limits.max_decoded_bytes, w)?;
88    if !matches!(info.bits_allocated, 8 | 16) {
89        return Err(RleError::Unsupported(
90            "selected RLE monochrome profile requires BitsAllocated8/16",
91        ));
92    }
93    if ds.find(None, 0x00280006, w)?.is_some() {
94        return Err(RleError::Unsupported(
95            "monochrome RLE requires absent PlanarConfiguration",
96        ));
97    }
98    if ds.find(None, 0x7fe00001, w)?.is_some() || ds.find(None, 0x7fe00002, w)?.is_some() {
99        return Err(RleError::Unsupported(
100            "Extended Offset Table profile not selected",
101        ));
102    }
103    if info.frames > limits.max_frames {
104        return Err(RleError::FrameLimit);
105    }
106    if output.len() < info.bytes {
107        return Err(RleError::OutputTooSmall);
108    }
109    if info.samples_per_frame > limits.max_scratch_bytes {
110        return Err(RleError::ByteLimit);
111    }
112    if scratch.len() < info.samples_per_frame {
113        return Err(RleError::ScratchTooSmall);
114    }
115    let id = ds
116        .find(None, 0x7fe00010, w)?
117        .ok_or(PixelError::Missing(0x7fe00010))?;
118    let element = ds.element(id)?;
119    if element.kind != ElementKind::EncapsulatedPixels || element.vr != Some(*b"OB") {
120        return Err(PixelError::Invalid(0x7fe00010).into());
121    }
122    let planes = info.bits_allocated as usize / 8;
123    let frame_bytes = info
124        .samples_per_frame
125        .checked_mul(planes)
126        .ok_or(RleError::Overflow)?;
127    let mut items = ds.sequence_items(id, w)?;
128    let table = items.next().ok_or(RleError::FragmentCount)?;
129    let bot = ds.item_bytes(table)?;
130    let bot_bytes = (info.frames as usize)
131        .checked_mul(4)
132        .ok_or(RleError::Overflow)?;
133    if !bot.is_empty() && (bot.len() != bot_bytes || bot_entry(bot, 0)? != 0) {
134        return Err(RleError::BasicOffsetTable);
135    }
136    let mut count = 0usize;
137    let mut offset = 0usize;
138    let mut compressed = 0usize;
139    let mut work = 0usize;
140    // First pass admits bytes/work and validates one-fragment-per-frame/BOT.
141    for item in items {
142        if count >= info.frames as usize {
143            return Err(RleError::FragmentCount);
144        }
145        let bytes = ds.item_bytes(item)?;
146        if !bot.is_empty() && bot_entry(bot, count)? as usize != offset {
147            return Err(RleError::BasicOffsetTable);
148        }
149        compressed = compressed
150            .checked_add(bytes.len())
151            .ok_or(RleError::Overflow)?;
152        if compressed > limits.max_compressed_bytes {
153            return Err(RleError::ByteLimit);
154        }
155        let cost = bytes
156            .len()
157            .checked_mul(2)
158            .and_then(|n| frame_bytes.checked_mul(3).and_then(|m| n.checked_add(m)))
159            .and_then(|n| n.checked_add(64))
160            .ok_or(RleError::Overflow)?;
161        work = work.checked_add(cost).ok_or(RleError::Overflow)?;
162        if work > limits.max_work {
163            return Err(RleError::WorkLimit);
164        }
165        offset = offset
166            .checked_add(8)
167            .and_then(|n| n.checked_add(bytes.len()))
168            .ok_or(RleError::Overflow)?;
169        count += 1;
170    }
171    if count != info.frames as usize {
172        return Err(RleError::FragmentCount);
173    }
174    let mut validate = ds.sequence_items(id, w)?;
175    validate.next().ok_or(RleError::FragmentCount)?;
176    for item in validate {
177        frame::validate(
178            ds.item_bytes(item)?,
179            info.rows as usize,
180            info.columns as usize,
181            planes,
182        )?;
183    }
184    // Acquire the final charged iterator before the first output write. The same
185    // immutable source was fully validated, so deterministic decode cannot add a
186    // new data/work validation failure after publication into caller buffers.
187    let mut decode = ds.sequence_items(id, w)?;
188    decode.next().ok_or(RleError::FragmentCount)?;
189    for (index, item) in decode.enumerate() {
190        let start = index.checked_mul(frame_bytes).ok_or(RleError::Overflow)?;
191        let end = start.checked_add(frame_bytes).ok_or(RleError::Overflow)?;
192        frame::decode(
193            ds.item_bytes(item)?,
194            info.rows as usize,
195            info.columns as usize,
196            planes,
197            output.get_mut(start..end).ok_or(RleError::OutputTooSmall)?,
198            scratch,
199        )?;
200    }
201    let needed = info.bytes;
202    NativePixelView::from_admitted_layout(info, &output[..needed]).map_err(RleError::from)
203}
204#[cfg(test)]
205mod tests;