dcmnorm_encoding/adapters.rs
1//! Core module for building pixel data adapters.
2//!
3//! This module contains the core types and traits
4//! for consumers and implementers of
5//! transfer syntaxes with encapsulated pixel data.
6//!
7//! Complete DICOM object types
8//! (such as `FileDicomObject<InMemDicomObject>`)
9//! implement the [`PixelDataObject`] trait.
10//! Transfer syntaxes which define an encapsulated pixel data encoding
11//! need to provide suitable implementations of
12//! [`PixelDataReader`] and [`PixelDataWriter`]
13//! to be able to decode and encode imaging data, respectively.
14
15use dcmnorm_core::{ops::AttributeOp, value::C};
16use snafu::Snafu;
17use std::borrow::Cow;
18
19/// The possible error conditions when decoding (reading) pixel data.
20///
21/// Users of this type are free to handle errors based on their variant,
22/// but should not make decisions based on the display message,
23/// since that is not considered part of the API
24/// and may change on any new release.
25///
26/// Implementers of transfer syntaxes
27/// are recommended to choose the most fitting error variant
28/// for the tested condition.
29/// When no suitable variant is available,
30/// the [`Custom`](DecodeError::Custom) variant may be used.
31/// See also [`snafu`] for guidance on using context selectors.
32#[derive(Debug, Snafu)]
33#[non_exhaustive]
34#[snafu(visibility(pub), module)]
35pub enum DecodeError {
36 /// A custom error occurred when decoding,
37 /// reported as a dynamic error value with a message.
38 ///
39 /// The [`whatever!`](snafu::whatever) macro can be used
40 /// to easily create an error of this kind.
41 #[snafu(whatever, display("{}", message))]
42 Custom {
43 /// The error message.
44 message: String,
45 /// The underlying error cause, if any.
46 #[snafu(source(from(Box<dyn std::error::Error + Send + Sync + 'static>, Some)))]
47 source: Option<Box<dyn std::error::Error + Send + Sync + 'static>>,
48 },
49
50 /// The input pixel data is not encapsulated.
51 ///
52 /// Either the image needs no decoding
53 /// or the compressed imaging data was in a flat pixel data element by mistake.
54 NotEncapsulated,
55
56 /// The requested frame range is outside the given object's frame range.
57 FrameRangeOutOfBounds,
58
59 /// A required attribute is missing
60 /// from the DICOM object representing the image.
61 #[snafu(display("Missing required attribute `{}`", name))]
62 MissingAttribute { name: &'static str },
63}
64
65/// The possible error conditions when encoding (writing) pixel data.
66///
67/// Users of this type are free to handle errors based on their variant,
68/// but should not make decisions based on the display message,
69/// since that is not considered part of the API
70/// and may change on any new release.
71///
72/// Implementers of transfer syntaxes
73/// are recommended to choose the most fitting error variant
74/// for the tested condition.
75/// When no suitable variant is available,
76/// the [`Custom`](EncodeError::Custom) variant may be used.
77/// See also [`snafu`] for guidance on using context selectors.
78#[derive(Debug, Snafu)]
79#[non_exhaustive]
80#[snafu(visibility(pub), module)]
81pub enum EncodeError {
82 /// A custom error when encoding fails.
83 /// Read the `message` and the underlying `source`
84 /// for more details.
85 #[snafu(whatever, display("{}", message))]
86 Custom {
87 /// The error message.
88 message: String,
89 /// The underlying error cause, if any.
90 #[snafu(source(from(Box<dyn std::error::Error + Send + Sync + 'static>, Some)))]
91 source: Option<Box<dyn std::error::Error + Send + Sync + 'static>>,
92 },
93
94 /// Input pixel data is not native, should be decoded first.
95 NotNative,
96
97 /// The requested frame range is outside the given object's frame range.
98 FrameRangeOutOfBounds,
99
100 /// A required attribute is missing
101 /// from the DICOM object representing the image.
102 #[snafu(display("Missing required attribute `{}`", name))]
103 MissingAttribute { name: &'static str },
104}
105
106/// The result of decoding (reading) pixel data
107pub type DecodeResult<T, E = DecodeError> = Result<T, E>;
108
109/// The result of encoding (writing) pixel data
110pub type EncodeResult<T, E = EncodeError> = Result<T, E>;
111
112#[derive(Debug)]
113pub struct RawPixelData {
114 /// Either a byte slice/vector if native pixel data
115 /// or byte fragments if encapsulated
116 pub fragments: C<Vec<u8>>,
117
118 /// The offset table for the fragments,
119 /// or empty if there is none
120 pub offset_table: C<u32>,
121}
122
123/// A DICOM object trait to be interpreted as pixel data.
124///
125/// This trait extends the concept of DICOM object
126/// as defined in [`dicom_object`],
127/// in order to retrieve important pieces of the object
128/// for pixel data decoding into images or multi-dimensional arrays.
129///
130/// It is defined in this crate so that
131/// transfer syntax implementers only have to depend on `dcmnorm_encoding`.
132///
133/// [`dicom_object`]: https://docs.rs/dicom_object
134pub trait PixelDataObject {
135 /// Return the object's transfer syntax UID.
136 fn transfer_syntax_uid(&self) -> &str;
137
138 /// Return the _Rows_, or `None` if it is not found
139 fn rows(&self) -> Option<u16>;
140
141 /// Return the _Columns_, or `None` if it is not found
142 fn cols(&self) -> Option<u16>;
143
144 /// Return the _Samples Per Pixel_, or `None` if it is not found
145 fn samples_per_pixel(&self) -> Option<u16>;
146
147 /// Return the _Bits Allocated_, or `None` if it is not defined
148 fn bits_allocated(&self) -> Option<u16>;
149
150 /// Return the _Bits Stored_, or `None` if it is not defined
151 fn bits_stored(&self) -> Option<u16>;
152
153 /// Return the _Photometric Interpretation_,
154 /// with trailing whitespace removed,
155 /// or `None` if it is not defined
156 fn photometric_interpretation(&self) -> Option<&str>;
157
158 /// Return the _Number Of Frames_, or `None` if it is not defined
159 fn number_of_frames(&self) -> Option<u32>;
160
161 /// Returns the _Number of Fragments_, or `None` for native pixel data
162 fn number_of_fragments(&self) -> Option<u32>;
163
164 /// Return a specific encoded pixel fragment by index
165 /// (where 0 is the first fragment after the basic offset table)
166 /// as a [`Cow<[u8]>`][1],
167 /// or `None` if no such fragment is available.
168 ///
169 /// In the case of native (non-encapsulated) pixel data,
170 /// the whole data may be obtained
171 /// by requesting fragment number 0.
172 ///
173 /// [1]: std::borrow::Cow
174 fn fragment(&self, fragment: usize) -> Option<Cow<'_, [u8]>>;
175
176 /// Return the object's offset table,
177 /// or `None` if no offset table is available.
178 fn offset_table(&self) -> Option<Cow<'_, [u32]>>;
179
180 /// Should return either a byte slice/vector if the pixel data is native
181 /// or the list of byte fragments and offset table if encapsulated.
182 ///
183 /// Returns `None` if no pixel data is found.
184 fn raw_pixel_data(&self) -> Option<RawPixelData>;
185}
186
187/// Custom options when encoding pixel data into an encapsulated form.
188#[derive(Debug, Default, Clone)]
189#[non_exhaustive]
190pub struct EncodeOptions {
191 /// The quality of the output image as a number between 0 and 100,
192 /// where 100 is the best quality that the encapsulated form can achieve
193 /// and smaller values represent smaller data size
194 /// with an increasingly higher error.
195 /// It is ignored if the transfer syntax only supports lossless compression.
196 /// If it does support lossless compression,
197 /// it is expected that a quality of 100 results in
198 /// a mathematically lossless encoding.
199 ///
200 /// If this option is not specified,
201 /// the output quality is decided automatically by the underlying adapter.
202 pub quality: Option<u8>,
203
204 /// The amount of effort that the encoder may take to encode the pixel data,
205 /// as a number between 0 and 100.
206 /// If supported, higher values result in better compression,
207 /// at the expense of more processing time.
208 /// Encoders are not required to support this option.
209 /// If this option is not specified,
210 /// the actual effort is decided by the underlying adapter.
211 pub effort: Option<u8>,
212}
213
214impl EncodeOptions {
215 pub fn new() -> Self {
216 Self::default()
217 }
218}
219
220/// Trait object responsible for decoding
221/// pixel data based on the transfer syntax.
222///
223/// A transfer syntax with support for decoding encapsulated pixel data
224/// would implement these methods.
225pub trait PixelDataReader {
226 /// Decode the given DICOM object
227 /// containing encapsulated pixel data
228 /// into native pixel data as a byte stream in little endian,
229 /// appending these bytes to the given vector `dst`.
230 ///
231 /// It is a necessary precondition that the object's pixel data
232 /// is encoded in accordance to the transfer syntax(es)
233 /// supported by this adapter.
234 /// A `NotEncapsulated` error is returned otherwise.
235 ///
236 /// The output is a sequence of native pixel values
237 /// which follow the image properties of the given object
238 /// _save for the photometric interpretation and planar configuration_.
239 /// If the image has 3 samples per pixel,
240 /// the output must be in RGB with each pixel contiguous in memory
241 /// (planar configuration of 0).
242 /// However, if the image is monochrome,
243 /// the output should retain the photometric interpretation of the source object
244 /// (so that images in _MONOCHROME1_ continue to be in _MONOCHROME1_
245 /// and images in _MONOCHROME2_ continue to be in _MONOCHROME2_).
246 fn decode(&self, src: &dyn PixelDataObject, dst: &mut Vec<u8>) -> DecodeResult<()> {
247 let frames = src.number_of_frames().unwrap_or(1);
248 for frame in 0..frames {
249 self.decode_frame(src, frame, dst)?;
250 }
251 Ok(())
252 }
253
254 /// Decode the given DICOM object
255 /// containing encapsulated pixel data
256 /// into native pixel data of a single frame
257 /// as a byte stream in little endian,
258 /// appending these bytes to the given vector `dst`.
259 ///
260 /// The frame index is 0-based.
261 ///
262 /// It is a necessary precondition that the object's pixel data
263 /// is encoded in accordance to the transfer syntax(es)
264 /// supported by this adapter.
265 /// A `NotEncapsulated` error is returned otherwise.
266 ///
267 /// The output is a sequence of native pixel values of a frame
268 /// which follow the image properties of the given object
269 /// _save for the photometric interpretation and planar configuration_.
270 /// If the image has 3 samples per pixel,
271 /// the output must be in RGB with each pixel contiguous in memory
272 /// (planar configuration of 0).
273 /// For pixel data with a single sample per pixel,
274 /// the output shall retain the photometric interpretation
275 /// declared in the original object
276 /// if it is one of _MONOCHROME1_, _MONOCHROME2_, or _PALETTE COLOR_.
277 /// For any other photometric interpretation,
278 /// the output shall be assumed to be in _MONOCHROME2_.
279 fn decode_frame(
280 &self,
281 src: &dyn PixelDataObject,
282 frame: u32,
283 dst: &mut Vec<u8>,
284 ) -> DecodeResult<()>;
285}
286
287/// Trait object responsible for encoding
288/// pixel data based on a certain transfer syntax.
289///
290/// A transfer syntax with support for creating compressed pixel data
291/// would implement these methods.
292pub trait PixelDataWriter {
293 /// Encode a DICOM object's image into the format supported by this adapter,
294 /// writing a byte stream of pixel data fragment values
295 /// to the given vector `dst`
296 /// and the offsets to each decoded frame into `offset_table`.
297 ///
298 /// New data is appended to `dst` and `offset_table`,
299 /// which are not cleared before writing.
300 ///
301 /// All implementations are required to support
302 /// writing the object's pixel data when it is in a _native encoding_.
303 /// If the given pixel data object is not in a native encoding,
304 /// and this writer does not support transcoding
305 /// from that encoding to the target transfer syntax,
306 /// a `NotNative` error is returned instead.
307 ///
308 /// When the operation is successful,
309 /// a listing of attribute changes is returned,
310 /// comprising the sequence of operations that the DICOM object
311 /// should consider upon assuming the new encoding.
312 fn encode(
313 &self,
314 src: &dyn PixelDataObject,
315 options: EncodeOptions,
316 dst: &mut Vec<Vec<u8>>,
317 offset_table: &mut Vec<u32>,
318 ) -> EncodeResult<Vec<AttributeOp>> {
319 let frames = src.number_of_frames().unwrap_or(1);
320 let mut out = Vec::new();
321 let mut frame_offset = 0;
322 let mut basic_offset = true;
323 let prev_offset_table_len = offset_table.len();
324 for frame in 0..frames {
325 let mut frame_data = Vec::new();
326 out = self.encode_frame(src, frame, options.clone(), &mut frame_data)?;
327 if basic_offset {
328 // push frame offset to basic offset table
329 offset_table.push(frame_offset);
330
331 if frame < frames - 1 {
332 // and calculate the next one (ensuring that offset fits in a u32).
333 // Each offset is measured from the first byte of the first fragment's item
334 // header, so it advances by the fragment's item header (8 bytes) plus its
335 // value length *as written*: an odd-length fragment is padded to even length
336 // when serialized (PS3.5 ยง7.1), so count that padding byte too.
337 let written_len = frame_data.len() + (frame_data.len() & 1);
338 let new_frame_offset =
339 <u32 as std::convert::TryFrom<usize>>::try_from(written_len)
340 .ok()
341 .and_then(|delta| delta.checked_add(8))
342 .and_then(|delta| frame_offset.checked_add(delta));
343 if let Some(v) = new_frame_offset {
344 // update the offset for the next frame and continue normally
345 frame_offset = v;
346 } else {
347 // cannot build a basic offset table,
348 // clear everything done so far and leave it empty
349 offset_table.truncate(prev_offset_table_len);
350 basic_offset = false;
351 }
352 }
353 }
354 dst.push(frame_data);
355 }
356 Ok(out)
357 }
358
359 /// Encode a single frame of a DICOM object's image
360 /// into the format supported by this adapter,
361 /// by writing a byte stream of pixel data values
362 /// into the given destination.
363 /// The bytes written comprise a single pixel data fragment
364 /// in its entirety.
365 ///
366 /// New data is appended to `dst`,
367 /// keeping all bytes previously present before writing.
368 ///
369 /// All implementations are required to support
370 /// writing the object's pixel data when it is in a _native encoding_.
371 /// If the given pixel data object is not in a native encoding,
372 /// and this writer does not support transcoding
373 /// from that encoding to the target transfer syntax,
374 /// a `NotNative` error is returned instead.
375 ///
376 /// When the operation is successful,
377 /// a listing of attribute changes is returned,
378 /// comprising the sequence of operations that the DICOM object
379 /// should consider upon assuming the new encoding.
380 fn encode_frame(
381 &self,
382 src: &dyn PixelDataObject,
383 frame: u32,
384 options: EncodeOptions,
385 dst: &mut Vec<u8>,
386 ) -> EncodeResult<Vec<AttributeOp>>;
387}
388
389/// Alias type for a dynamically dispatched pixel data reader.
390pub type DynPixelDataReader = Box<dyn PixelDataReader + Send + Sync + 'static>;
391
392/// Alias type for a dynamically dispatched pixel data writer.
393pub type DynPixelDataWriter = Box<dyn PixelDataWriter + Send + Sync + 'static>;
394
395/// An immaterial type representing an adapter which is never provided.
396///
397/// This type may be used as the type parameters `R` and `W`
398/// of [`TransferSyntax`](crate::transfer_syntax::TransferSyntax)
399/// when representing a transfer syntax which
400/// either does not support reading and writing imaging data,
401/// or when such support is not needed in the first place.
402#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
403pub enum NeverPixelAdapter {}
404
405impl PixelDataReader for NeverPixelAdapter {
406 fn decode(&self, _src: &dyn PixelDataObject, _dst: &mut Vec<u8>) -> DecodeResult<()> {
407 unreachable!()
408 }
409
410 fn decode_frame(
411 &self,
412 _src: &dyn PixelDataObject,
413 _frame: u32,
414 _dst: &mut Vec<u8>,
415 ) -> DecodeResult<()> {
416 unreachable!()
417 }
418}
419
420impl PixelDataWriter for NeverPixelAdapter {
421 fn encode(
422 &self,
423 _src: &dyn PixelDataObject,
424 _options: EncodeOptions,
425 _dst: &mut Vec<Vec<u8>>,
426 _offset_table: &mut Vec<u32>,
427 ) -> EncodeResult<Vec<AttributeOp>> {
428 unreachable!()
429 }
430
431 fn encode_frame(
432 &self,
433 _src: &dyn PixelDataObject,
434 _frame: u32,
435 _options: EncodeOptions,
436 _dst: &mut Vec<u8>,
437 ) -> EncodeResult<Vec<AttributeOp>> {
438 unreachable!()
439 }
440}
441
442impl PixelDataReader for crate::transfer_syntax::NeverAdapter {
443 fn decode(&self, _src: &dyn PixelDataObject, _dst: &mut Vec<u8>) -> DecodeResult<()> {
444 unreachable!()
445 }
446
447 fn decode_frame(
448 &self,
449 _src: &dyn PixelDataObject,
450 _frame: u32,
451 _dst: &mut Vec<u8>,
452 ) -> DecodeResult<()> {
453 unreachable!()
454 }
455}
456
457impl PixelDataWriter for crate::transfer_syntax::NeverAdapter {
458 fn encode(
459 &self,
460 _src: &dyn PixelDataObject,
461 _options: EncodeOptions,
462 _dst: &mut Vec<Vec<u8>>,
463 _offset_table: &mut Vec<u32>,
464 ) -> EncodeResult<Vec<AttributeOp>> {
465 unreachable!()
466 }
467
468 fn encode_frame(
469 &self,
470 _src: &dyn PixelDataObject,
471 _frame: u32,
472 _options: EncodeOptions,
473 _dst: &mut Vec<u8>,
474 ) -> EncodeResult<Vec<AttributeOp>> {
475 unreachable!()
476 }
477}
478
479#[cfg(test)]
480mod tests {
481 use super::{EncodeOptions, EncodeResult, PixelDataObject, PixelDataWriter, RawPixelData};
482 use dcmnorm_core::ops::AttributeOp;
483 use std::borrow::Cow;
484
485 /// Only `number_of_frames` matters to the default `PixelDataWriter::encode` implementation.
486 struct Frames(u32);
487
488 impl PixelDataObject for Frames {
489 fn transfer_syntax_uid(&self) -> &str {
490 "1.2.840.10008.1.2.1"
491 }
492 fn rows(&self) -> Option<u16> {
493 Some(1)
494 }
495 fn cols(&self) -> Option<u16> {
496 Some(1)
497 }
498 fn samples_per_pixel(&self) -> Option<u16> {
499 Some(1)
500 }
501 fn bits_allocated(&self) -> Option<u16> {
502 Some(8)
503 }
504 fn bits_stored(&self) -> Option<u16> {
505 Some(8)
506 }
507 fn photometric_interpretation(&self) -> Option<&str> {
508 Some("MONOCHROME2")
509 }
510 fn number_of_frames(&self) -> Option<u32> {
511 Some(self.0)
512 }
513 fn number_of_fragments(&self) -> Option<u32> {
514 Some(1)
515 }
516 fn fragment(&self, _fragment: usize) -> Option<Cow<'_, [u8]>> {
517 None
518 }
519 fn offset_table(&self) -> Option<Cow<'_, [u32]>> {
520 None
521 }
522 fn raw_pixel_data(&self) -> Option<RawPixelData> {
523 None
524 }
525 }
526
527 /// Writes frame `i` as a fragment of `lengths[i]` bytes.
528 struct FixedLengths(Vec<usize>);
529
530 impl PixelDataWriter for FixedLengths {
531 fn encode_frame(
532 &self,
533 _src: &dyn PixelDataObject,
534 frame: u32,
535 _options: EncodeOptions,
536 dst: &mut Vec<u8>,
537 ) -> EncodeResult<Vec<AttributeOp>> {
538 dst.resize(dst.len() + self.0[frame as usize], 0xAB);
539 Ok(Vec::new())
540 }
541 }
542
543 /// Regression test for upstream dicom-rs 59ab4edb, plus odd-length padding: the basic offset
544 /// table holds, for each frame, the byte offset of its fragment's item header relative to the
545 /// first fragment's. Before the fix every entry was `len(frame) + 8 * (frame + 1)` (not even
546 /// starting at 0), so readers that seek through the table landed in the wrong place. Offsets
547 /// must also count the padding byte an odd-length fragment gets when written.
548 #[test]
549 fn default_encode_builds_cumulative_basic_offset_table() {
550 let writer = FixedLengths(vec![6865, 314, 1000, 7]);
551 let mut fragments = Vec::new();
552 let mut offset_table = Vec::new();
553 writer
554 .encode(
555 &Frames(4),
556 EncodeOptions::default(),
557 &mut fragments,
558 &mut offset_table,
559 )
560 .unwrap();
561
562 assert_eq!(
563 fragments.iter().map(Vec::len).collect::<Vec<_>>(),
564 vec![6865, 314, 1000, 7]
565 );
566 assert_eq!(
567 offset_table,
568 vec![
569 0,
570 6866 + 8, // 6865 padded to 6866
571 6866 + 8 + 314 + 8,
572 6866 + 8 + 314 + 8 + 1000 + 8, // the last fragment's own length is never needed
573 ]
574 );
575 }
576
577 #[test]
578 fn default_encode_of_a_single_frame_has_a_single_zero_offset() {
579 let mut fragments = Vec::new();
580 let mut offset_table = Vec::new();
581 FixedLengths(vec![101])
582 .encode(
583 &Frames(1),
584 EncodeOptions::default(),
585 &mut fragments,
586 &mut offset_table,
587 )
588 .unwrap();
589 assert_eq!(offset_table, vec![0]);
590 assert_eq!(fragments.len(), 1);
591 }
592}