Skip to main content

qualia_core_db/medical/dicom_codecs/
native.rs

1use crate::medical::dicom_dataset::{
2    DatasetError, ElementKind, Part10Dataset, TransferSyntax, WorkBudget,
3};
4#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5pub enum PixelError {
6    Dataset(DatasetError),
7    Missing(u32),
8    Unsupported(&'static str),
9    Invalid(u32),
10    Bounds,
11    Overflow,
12    ByteLimit,
13}
14impl From<DatasetError> for PixelError {
15    fn from(e: DatasetError) -> Self {
16        Self::Dataset(e)
17    }
18}
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub enum StoredSample {
21    Unsigned(u32),
22    Signed(i32),
23}
24impl StoredSample {
25    pub fn as_f64(self) -> f64 {
26        match self {
27            Self::Unsigned(n) => n as f64,
28            Self::Signed(n) => n as f64,
29        }
30    }
31}
32/// Borrowed native values with sign extension from BitsStored. Unused bits/source
33/// bytes remain intact. MONOCHROME1 is not inverted; no display LUT is applied.
34pub struct NativePixelView<'a> {
35    data: &'a [u8],
36    source_blake3: [u8; 32],
37    rows: u16,
38    columns: u16,
39    frames: u32,
40    bits_allocated: u16,
41    bits_stored: u16,
42    signed: bool,
43    photometric: &'a str,
44    samples_per_frame: usize,
45    padding_declared: bool,
46}
47impl<'a> NativePixelView<'a> {
48    pub fn from_dataset(
49        ds: &Part10Dataset<'a>,
50        max_pixel_bytes: usize,
51        w: &mut WorkBudget,
52    ) -> Result<Self, PixelError> {
53        if ds.transfer_syntax() == TransferSyntax::EncapsulatedExplicitLittleEndian {
54            return Err(PixelError::Unsupported(
55                "encapsulated bytes require a qualified codec adapter",
56            ));
57        }
58        let info = super::metadata::IntegerImageInfo::from_dataset(ds, max_pixel_bytes, w)?;
59        let need = info.bytes;
60        let id = ds
61            .find(None, 0x7fe00010, w)?
62            .ok_or(PixelError::Missing(0x7fe00010))?;
63        let e = ds.element(id)?;
64        if e.kind != ElementKind::Value || e.vr.is_some_and(|vr| !matches!(&vr, b"OB" | b"OW")) {
65            return Err(PixelError::Invalid(0x7fe00010));
66        }
67        let all = ds.value(id)?;
68        let padded = need.checked_add(need % 2).ok_or(PixelError::Overflow)?;
69        if all.len() != padded
70            || all
71                .get(need..)
72                .is_some_and(|padding| padding.iter().any(|b| *b != 0))
73        {
74            return Err(PixelError::Invalid(0x7fe00010));
75        }
76        Self::from_admitted_layout(info, &all[..need])
77    }
78    pub(super) fn from_admitted_layout(
79        info: super::metadata::IntegerImageInfo<'a>,
80        data: &'a [u8],
81    ) -> Result<Self, PixelError> {
82        if data.len() != info.bytes {
83            return Err(PixelError::Invalid(0x7fe00010));
84        }
85        Ok(Self {
86            data,
87            source_blake3: info.source_blake3,
88            rows: info.rows,
89            columns: info.columns,
90            frames: info.frames,
91            bits_allocated: info.bits_allocated,
92            bits_stored: info.bits_stored,
93            signed: info.signed,
94            photometric: info.photometric,
95            samples_per_frame: info.samples_per_frame,
96            padding_declared: info.padding_declared,
97        })
98    }
99    pub fn source_blake3(&self) -> [u8; 32] {
100        self.source_blake3
101    }
102    pub fn rows(&self) -> u16 {
103        self.rows
104    }
105    pub fn columns(&self) -> u16 {
106        self.columns
107    }
108    pub fn frames(&self) -> u32 {
109        self.frames
110    }
111    pub fn photometric(&self) -> &'a str {
112        self.photometric
113    }
114    /// Raw stored-sample access does not classify these values as measurements.
115    pub fn padding_declared(&self) -> bool {
116        self.padding_declared
117    }
118    /// Stored sample layout: borrowed native bytes or losslessly decoded bytes.
119    /// The encoded original always remains in Part10Dataset::original_bytes.
120    pub fn stored_sample_bytes(&self) -> &'a [u8] {
121        self.data
122    }
123    pub fn sample(
124        &self,
125        frame_index: u32,
126        row: u16,
127        column: u16,
128    ) -> Result<StoredSample, PixelError> {
129        if frame_index >= self.frames || row >= self.rows || column >= self.columns {
130            return Err(PixelError::Bounds);
131        }
132        let row_offset = (row as usize)
133            .checked_mul(self.columns as usize)
134            .ok_or(PixelError::Overflow)?;
135        let index = (frame_index as usize)
136            .checked_mul(self.samples_per_frame)
137            .and_then(|v| v.checked_add(row_offset))
138            .and_then(|v| v.checked_add(column as usize))
139            .ok_or(PixelError::Overflow)?;
140        let width = self.bits_allocated as usize / 8;
141        let start = index.checked_mul(width).ok_or(PixelError::Overflow)?;
142        let b = self
143            .data
144            .get(start..start.checked_add(width).ok_or(PixelError::Overflow)?)
145            .ok_or(PixelError::Bounds)?;
146        let word = match width {
147            1 => b[0] as u32,
148            2 => u16::from_le_bytes([b[0], b[1]]) as u32,
149            4 => u32::from_le_bytes([b[0], b[1], b[2], b[3]]),
150            _ => return Err(PixelError::Invalid(0x00280100)),
151        };
152        let shift = 32 - self.bits_stored;
153        let masked = if self.bits_stored == 32 {
154            word
155        } else {
156            word & ((1u32 << self.bits_stored) - 1)
157        };
158        Ok(if self.signed {
159            StoredSample::Signed(((masked << shift) as i32) >> shift)
160        } else {
161            StoredSample::Unsigned(masked)
162        })
163    }
164}