1use crate::medical::dicom_dataset::{DatasetError, ElementKind, Part10Dataset, WorkBudget};
5use std::borrow::Cow;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum EncapError {
9 NotPart10,
10 UnsupportedSyntax,
11 Truncated,
12 MalformedHeader,
13 Missing(u32),
14 Invalid(u32),
15 ByteLimit,
16 FrameLimit,
17 FragmentLimit,
18 DimensionLimit,
19 Overflow,
20 FragmentCount,
21 BasicOffsetTable,
22 Unsupported(&'static str),
23}
24impl From<DatasetError> for EncapError {
25 fn from(e: DatasetError) -> Self {
26 match e {
27 DatasetError::NotPart10 => Self::NotPart10,
28 DatasetError::Truncated => Self::Truncated,
29 DatasetError::Overflow => Self::Overflow,
30 DatasetError::ByteLimit | DatasetError::IndexLimit => Self::ByteLimit,
31 DatasetError::Missing(t) => Self::Missing(t),
32 DatasetError::Invalid(t) => Self::Invalid(t),
33 DatasetError::UnsupportedSyntax => Self::UnsupportedSyntax,
34 _ => Self::MalformedHeader,
35 }
36 }
37}
38impl std::fmt::Display for EncapError {
39 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40 write!(f, "DICOM encapsulated framing: {self:?}")
41 }
42}
43impl std::error::Error for EncapError {}
44
45#[derive(Clone, Copy, Debug)]
46pub struct EncapLimits {
47 pub max_part10_bytes: usize,
48 pub max_decoded_bytes: usize,
49 pub max_compressed_bytes: usize,
50 pub max_frames: u32,
51 pub max_fragments: usize,
52 pub max_width: u16,
53 pub max_height: u16,
54 pub max_elements: usize,
55}
56impl Default for EncapLimits {
57 fn default() -> Self {
58 Self {
59 max_part10_bytes: 128 * 1024 * 1024,
60 max_decoded_bytes: 256 * 1024 * 1024,
61 max_compressed_bytes: 64 * 1024 * 1024,
62 max_frames: 4096,
63 max_fragments: 16384,
64 max_width: 16384,
65 max_height: 16384,
66 max_elements: 8192,
67 }
68 }
69}
70
71pub struct EncapsulatedPart10<'a> {
72 pub source_blake3: [u8; 32],
73 pub transfer_syntax_uid: &'a str,
74 pub rows: u16,
75 pub columns: u16,
76 pub frames: u32,
77 pub samples_per_pixel: u16,
78 pub photometric: &'a str,
79 pub planar_configuration: Option<u16>,
80 pub bits_allocated: u16,
81 pub bits_stored: u16,
82 pub high_bit: u16,
83 pub pixel_representation: u16,
84 pub fragments: Vec<&'a [u8]>,
85 pub frame_ranges: Vec<(usize, usize)>,
86}
87
88impl<'a> EncapsulatedPart10<'a> {
89 pub fn frame_bytes(&self, frame_idx: usize, max_bytes: usize) -> Result<Cow<'a, [u8]>, EncapError> {
90 let &(start, end) = self.frame_ranges.get(frame_idx).ok_or(EncapError::FragmentCount)?;
91 concat_fragments(&self.fragments[start..end], max_bytes)
92 }
93}
94
95pub fn concat_fragments<'a>(
96 fragments: &[&'a [u8]],
97 max_bytes: usize,
98) -> Result<Cow<'a, [u8]>, EncapError> {
99 if fragments.is_empty() {
100 return Err(EncapError::FragmentCount);
101 }
102 if fragments.len() == 1 {
103 if fragments[0].len() > max_bytes {
104 return Err(EncapError::ByteLimit);
105 }
106 return Ok(Cow::Borrowed(fragments[0]));
107 }
108 let mut total = 0usize;
109 for frag in fragments {
110 total = total.checked_add(frag.len()).ok_or(EncapError::Overflow)?;
111 if total > max_bytes {
112 return Err(EncapError::ByteLimit);
113 }
114 }
115 let mut buf = Vec::new();
116 buf.try_reserve_exact(total).map_err(|_| EncapError::ByteLimit)?;
117 for frag in fragments {
118 buf.extend_from_slice(frag);
119 }
120 Ok(Cow::Owned(buf))
121}
122
123#[inline]
124fn u16le(b: &[u8], at: usize) -> Result<u16, EncapError> {
125 let s = b.get(at..at.checked_add(2).ok_or(EncapError::Overflow)?).ok_or(EncapError::Truncated)?;
126 Ok(u16::from_le_bytes([s[0], s[1]]))
127}
128#[inline]
129fn u32le(b: &[u8], at: usize) -> Result<u32, EncapError> {
130 let s = b.get(at..at.checked_add(4).ok_or(EncapError::Overflow)?).ok_or(EncapError::Truncated)?;
131 Ok(u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
132}
133fn is_long_vr(vr: &[u8; 2]) -> bool {
134 matches!(vr, b"OB" | b"OD" | b"OF" | b"OL" | b"OV" | b"OW" | b"SQ" | b"SV" | b"UC" | b"UN" | b"UR" | b"UT" | b"UV")
135}
136fn read_explicit_header(b: &[u8], at: usize) -> Result<(u32, [u8; 2], u32, usize), EncapError> {
137 let tag = ((u16le(b, at)? as u32) << 16) | u16le(b, at + 2)? as u32;
138 let vr = [
139 *b.get(at + 4).ok_or(EncapError::Truncated)?,
140 *b.get(at + 5).ok_or(EncapError::Truncated)?,
141 ];
142 if is_long_vr(&vr) {
143 let reserved = u16le(b, at + 6)?;
144 if reserved != 0 {
145 return Err(EncapError::MalformedHeader);
146 }
147 let len = u32le(b, at + 8)?;
148 Ok((tag, vr, len, at + 12))
149 } else {
150 let len = u16le(b, at + 6)? as u32;
151 Ok((tag, vr, len, at + 8))
152 }
153}
154fn skip_undefined_sequence(b: &[u8], mut cur: usize, depth: usize, budget: &mut usize) -> Result<usize, EncapError> {
155 if depth > 16 {
156 return Err(EncapError::MalformedHeader);
157 }
158 while cur < b.len() {
159 *budget = budget.checked_sub(1).ok_or(EncapError::MalformedHeader)?;
160 let tag = ((u16le(b, cur)? as u32) << 16) | u16le(b, cur + 2)? as u32;
161 let len = u32le(b, cur + 4)?;
162 cur += 8;
163 if tag == 0xFFFEE0DD && len == 0 {
164 return Ok(cur);
165 }
166 if tag != 0xFFFEE000 {
167 return Err(EncapError::MalformedHeader);
168 }
169 if len != u32::MAX {
170 cur = cur.checked_add(len as usize).ok_or(EncapError::Overflow)?;
171 if cur > b.len() {
172 return Err(EncapError::Truncated);
173 }
174 } else {
175 while cur < b.len() {
176 *budget = budget.checked_sub(1).ok_or(EncapError::MalformedHeader)?;
177 let itag = ((u16le(b, cur)? as u32) << 16) | u16le(b, cur + 2)? as u32;
178 if itag == 0xFFFEE00D {
179 if u32le(b, cur + 4)? != 0 {
180 return Err(EncapError::MalformedHeader);
181 }
182 cur += 8;
183 break;
184 }
185 let (_, _, elen, val_at) = read_explicit_header(b, cur)?;
186 cur = if elen == u32::MAX {
187 skip_undefined_sequence(b, val_at, depth + 1, budget)?
188 } else {
189 val_at.checked_add(elen as usize).ok_or(EncapError::Overflow)?
190 };
191 if cur > b.len() {
192 return Err(EncapError::Truncated);
193 }
194 }
195 }
196 }
197 Err(EncapError::Truncated)
198}
199fn bot_entry(bot: &[u8], index: usize) -> Result<u32, EncapError> {
200 let start = index.checked_mul(4).ok_or(EncapError::Overflow)?;
201 let end = start.checked_add(4).ok_or(EncapError::Overflow)?;
202 let slice = bot.get(start..end).ok_or(EncapError::BasicOffsetTable)?;
203 Ok(u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]))
204}
205fn parse_ascii_trimmed<'a>(raw: &'a [u8], tag: u32) -> Result<&'a str, EncapError> {
206 let mut end = raw.len();
207 while end > 0 && matches!(raw[end - 1], 0 | b' ') {
208 end -= 1;
209 }
210 let mut start = 0;
211 while start < end && raw[start] == b' ' {
212 start += 1;
213 }
214 std::str::from_utf8(&raw[start..end]).map_err(|_| EncapError::Invalid(tag))
215}
216
217pub fn parse_encapsulated_part10<'a>(
218 bytes: &'a [u8],
219 allowed_uids: &[&str],
220 limits: EncapLimits,
221) -> Result<EncapsulatedPart10<'a>, EncapError> {
222 if bytes.len() > limits.max_part10_bytes {
223 return Err(EncapError::ByteLimit);
224 }
225 if bytes.len() < 132 || &bytes[128..132] != b"DICM" {
226 return Err(EncapError::NotPart10);
227 }
228 let mut cur = 132usize;
229 let mut budget = limits.max_elements;
230 let mut ts_uid: Option<&'a str> = None;
231 let mut last_tag: Option<u32> = None;
232 while cur < bytes.len() && u16le(bytes, cur)? == 2 {
233 budget = budget.checked_sub(1).ok_or(EncapError::MalformedHeader)?;
234 let (tag, _vr, len, val_at) = read_explicit_header(bytes, cur)?;
235 if len == u32::MAX || len % 2 != 0 || last_tag.is_some_and(|t| tag <= t) {
236 return Err(EncapError::MalformedHeader);
237 }
238 last_tag = Some(tag);
239 let end = val_at.checked_add(len as usize).ok_or(EncapError::Overflow)?;
240 let val = bytes.get(val_at..end).ok_or(EncapError::Truncated)?;
241 if tag == 0x00020010 {
242 ts_uid = Some(parse_ascii_trimmed(val, tag)?);
243 }
244 cur = end;
245 }
246 let ts_uid = ts_uid.ok_or(EncapError::Missing(0x00020010))?;
247 if !allowed_uids.contains(&ts_uid) {
248 return Err(EncapError::UnsupportedSyntax);
249 }
250 let (mut rows, mut cols, mut frames, mut spp) = (None, None, 1u32, None);
251 let (mut planar, mut ba, mut bs, mut hb, mut rep) = (None, None, None, None, None);
252 let mut photometric: Option<&'a str> = None;
253 let mut pixel_at: Option<usize> = None;
254 last_tag = None;
255 while cur < bytes.len() {
256 budget = budget.checked_sub(1).ok_or(EncapError::MalformedHeader)?;
257 let (tag, vr, len, val_at) = read_explicit_header(bytes, cur)?;
258 if last_tag.is_some_and(|t| tag <= t) {
259 return Err(EncapError::MalformedHeader);
260 }
261 last_tag = Some(tag);
262 if matches!(tag, 0x7FE00008 | 0x7FE00009 | 0x7FE00001 | 0x7FE00002) {
263 return Err(EncapError::Unsupported("float PixelData or Extended Offset Table unsupported"));
264 }
265 if tag == 0x7FE00010 {
266 if len != u32::MAX || !matches!(&vr, b"OB" | b"OW") {
267 return Err(EncapError::Invalid(0x7FE00010));
268 }
269 pixel_at = Some(val_at);
270 break;
271 }
272 if len == u32::MAX {
273 cur = skip_undefined_sequence(bytes, val_at, 1, &mut budget)?;
274 continue;
275 }
276 if len % 2 != 0 {
277 return Err(EncapError::MalformedHeader);
278 }
279 let end = val_at.checked_add(len as usize).ok_or(EncapError::Overflow)?;
280 let val = bytes.get(val_at..end).ok_or(EncapError::Truncated)?;
281 match tag {
282 0x00280002 => spp = Some(u16le(val, 0)?),
283 0x00280004 => photometric = Some(parse_ascii_trimmed(val, tag)?),
284 0x00280006 => planar = Some(u16le(val, 0)?),
285 0x00280008 => {
286 let s = parse_ascii_trimmed(val, tag)?;
287 frames = s.parse::<u32>().map_err(|_| EncapError::Invalid(tag))?;
288 }
289 0x00280010 => rows = Some(u16le(val, 0)?),
290 0x00280011 => cols = Some(u16le(val, 0)?),
291 0x00280100 => ba = Some(u16le(val, 0)?),
292 0x00280101 => bs = Some(u16le(val, 0)?),
293 0x00280102 => hb = Some(u16le(val, 0)?),
294 0x00280103 => rep = Some(u16le(val, 0)?),
295 _ => {}
296 }
297 cur = end;
298 }
299 let (rows, cols) = (rows.ok_or(EncapError::Missing(0x00280010))?, cols.ok_or(EncapError::Missing(0x00280011))?);
300 if rows == 0 || cols == 0 {
301 return Err(EncapError::Invalid(0x00280010));
302 }
303 if cols > limits.max_width || rows > limits.max_height {
304 return Err(EncapError::DimensionLimit);
305 }
306 if frames == 0 || frames > limits.max_frames {
307 return Err(EncapError::FrameLimit);
308 }
309 let spp = spp.ok_or(EncapError::Missing(0x00280002))?;
310 let photometric = photometric.ok_or(EncapError::Missing(0x00280004))?;
311 let ba = ba.ok_or(EncapError::Missing(0x00280100))?;
312 let bs = bs.ok_or(EncapError::Missing(0x00280101))?;
313 let hb = hb.ok_or(EncapError::Missing(0x00280102))?;
314 let rep = rep.ok_or(EncapError::Missing(0x00280103))?;
315 if bs == 0 || bs > ba || hb != bs - 1 || rep > 1 {
316 return Err(EncapError::Invalid(0x00280101));
317 }
318 let mut pcur = pixel_at.ok_or(EncapError::Missing(0x7FE00010))?;
319 let bot_tag = ((u16le(bytes, pcur)? as u32) << 16) | u16le(bytes, pcur + 2)? as u32;
320 let bot_len = u32le(bytes, pcur + 4)?;
321 if bot_tag != 0xFFFEE000 || bot_len == u32::MAX || bot_len % 4 != 0 {
322 return Err(EncapError::BasicOffsetTable);
323 }
324 let bot_start = pcur + 8;
325 let bot_end = bot_start.checked_add(bot_len as usize).ok_or(EncapError::Overflow)?;
326 let bot = bytes.get(bot_start..bot_end).ok_or(EncapError::Truncated)?;
327 let expected_bot = (frames as usize).checked_mul(4).ok_or(EncapError::Overflow)?;
328 if !bot.is_empty() && (bot.len() != expected_bot || bot_entry(bot, 0)? != 0) {
329 return Err(EncapError::BasicOffsetTable);
330 }
331 pcur = bot_end;
332 let (mut frags, mut starts) = (Vec::new(), Vec::new());
333 let (mut compressed, mut offset, mut next_frame, mut found_eod) = (0usize, 0usize, 0usize, false);
334 while pcur < bytes.len() {
335 let itag = ((u16le(bytes, pcur)? as u32) << 16) | u16le(bytes, pcur + 2)? as u32;
336 let ilen = u32le(bytes, pcur + 4)?;
337 pcur += 8;
338 if itag == 0xFFFEE0DD && ilen == 0 {
339 found_eod = true;
340 break;
341 }
342 if itag != 0xFFFEE000 || ilen == u32::MAX {
343 return Err(EncapError::MalformedHeader);
344 }
345 if frags.len() >= limits.max_fragments {
346 return Err(EncapError::FragmentLimit);
347 }
348 compressed = compressed.checked_add(ilen as usize).ok_or(EncapError::Overflow)?;
349 if compressed > limits.max_compressed_bytes {
350 return Err(EncapError::ByteLimit);
351 }
352 let fend = pcur.checked_add(ilen as usize).ok_or(EncapError::Overflow)?;
353 let frag = bytes.get(pcur..fend).ok_or(EncapError::Truncated)?;
354 if !bot.is_empty() && next_frame < frames as usize {
355 let expected = bot_entry(bot, next_frame)? as usize;
356 if offset == expected {
357 starts.push(frags.len());
358 next_frame += 1;
359 } else if offset > expected {
360 return Err(EncapError::BasicOffsetTable);
361 }
362 }
363 offset = offset.checked_add(8).and_then(|v| v.checked_add(frag.len())).ok_or(EncapError::Overflow)?;
364 frags.push(frag);
365 pcur = fend;
366 }
367 if !found_eod || frags.is_empty() || (!bot.is_empty() && next_frame != frames as usize) {
368 return Err(if frags.is_empty() { EncapError::FragmentCount } else if !found_eod { EncapError::Truncated } else { EncapError::BasicOffsetTable });
369 }
370 if bot.is_empty() && frames > 1 && frags.len() != frames as usize {
371 return Err(EncapError::BasicOffsetTable);
372 }
373 let frame_ranges = build_frame_ranges(frames, &starts, &frags, bot.is_empty())?;
374 Ok(EncapsulatedPart10 {
375 source_blake3: *blake3::hash(bytes).as_bytes(),
376 transfer_syntax_uid: ts_uid,
377 rows,
378 columns: cols,
379 frames,
380 samples_per_pixel: spp,
381 photometric,
382 planar_configuration: planar,
383 bits_allocated: ba,
384 bits_stored: bs,
385 high_bit: hb,
386 pixel_representation: rep,
387 fragments: frags,
388 frame_ranges,
389 })
390}
391
392pub fn collect_part10_dataset_frames<'a>(
393 ds: &Part10Dataset<'a>,
394 frames: u32,
395 max_fragments: usize,
396 max_compressed_bytes: usize,
397 w: &mut WorkBudget,
398) -> Result<(Vec<&'a [u8]>, Vec<(usize, usize)>), EncapError> {
399 let id = ds.find(None, 0x7FE00010, w)?.ok_or(EncapError::Missing(0x7FE00010))?;
400 let elem = ds.element(id)?;
401 if elem.kind != ElementKind::EncapsulatedPixels || elem.vr != Some(*b"OB") {
402 return Err(EncapError::Invalid(0x7FE00010));
403 }
404 let mut items = ds.sequence_items(id, w)?;
405 let bot = ds.item_bytes(items.next().ok_or(EncapError::FragmentCount)?)?;
406 let bot_len = (frames as usize).checked_mul(4).ok_or(EncapError::Overflow)?;
407 if !bot.is_empty() && (bot.len() != bot_len || bot_entry(bot, 0)? != 0) {
408 return Err(EncapError::BasicOffsetTable);
409 }
410 let (mut frags, mut starts) = (Vec::new(), Vec::new());
411 let (mut compressed, mut offset, mut next_frame) = (0usize, 0usize, 0usize);
412 for item in items {
413 if frags.len() >= max_fragments {
414 return Err(EncapError::FragmentLimit);
415 }
416 let frag = ds.item_bytes(item)?;
417 compressed = compressed.checked_add(frag.len()).ok_or(EncapError::Overflow)?;
418 if compressed > max_compressed_bytes {
419 return Err(EncapError::ByteLimit);
420 }
421 if !bot.is_empty() && next_frame < frames as usize {
422 let expected = bot_entry(bot, next_frame)? as usize;
423 if offset == expected {
424 starts.push(frags.len());
425 next_frame += 1;
426 } else if offset > expected {
427 return Err(EncapError::BasicOffsetTable);
428 }
429 }
430 offset = offset.checked_add(8).and_then(|v| v.checked_add(frag.len())).ok_or(EncapError::Overflow)?;
431 frags.push(frag);
432 }
433 if frags.is_empty() || (!bot.is_empty() && next_frame != frames as usize) {
434 return Err(if frags.is_empty() { EncapError::FragmentCount } else { EncapError::BasicOffsetTable });
435 }
436 if bot.is_empty() && frames > 1 && frags.len() != frames as usize {
437 return Err(EncapError::BasicOffsetTable);
438 }
439 let ranges = build_frame_ranges(frames, &starts, &frags, bot.is_empty())?;
440 Ok((frags, ranges))
441}
442
443fn build_frame_ranges(frames: u32, starts: &[usize], frags: &[&[u8]], empty_bot: bool) -> Result<Vec<(usize, usize)>, EncapError> {
444 let mut ranges = Vec::new();
445 ranges.try_reserve_exact(frames as usize).map_err(|_| EncapError::FrameLimit)?;
446 if !empty_bot {
447 for i in 0..frames as usize {
448 let end = if i + 1 < frames as usize { starts[i + 1] } else { frags.len() };
449 if starts[i] >= end {
450 return Err(EncapError::FragmentCount);
451 }
452 ranges.push((starts[i], end));
453 }
454 } else if frames == 1 {
455 ranges.push((0, frags.len()));
456 } else {
457 for i in 0..frames as usize {
458 ranges.push((i, i + 1));
459 }
460 }
461 Ok(ranges)
462}