dicom-encoding 0.10.0

DICOM encoding and decoding primitives
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
//! Core module for building pixel data adapters.
//!
//! This module contains the core types and traits
//! for consumers and implementers of
//! transfer syntaxes with encapsulated pixel data.
//!
//! Complete DICOM object types
//! (such as `FileDicomObject<InMemDicomObject>`)
//! implement the [`PixelDataObject`] trait.
//! Transfer syntaxes which define an encapsulated pixel data encoding
//! need to provide suitable implementations of
//! [`PixelDataReader`] and [`PixelDataWriter`]
//! to be able to decode and encode imaging data, respectively.

use dicom_core::{ops::AttributeOp, value::C};
use snafu::Snafu;
use std::borrow::Cow;

/// The possible error conditions when decoding (reading) pixel data.
///
/// Users of this type are free to handle errors based on their variant,
/// but should not make decisions based on the display message,
/// since that is not considered part of the API
/// and may change on any new release.
///
/// Implementers of transfer syntaxes
/// are recommended to choose the most fitting error variant
/// for the tested condition.
/// When no suitable variant is available,
/// the [`Custom`](DecodeError::Custom) variant may be used.
/// See also [`snafu`] for guidance on using context selectors.
#[derive(Debug, Snafu)]
#[non_exhaustive]
#[snafu(visibility(pub), module)]
pub enum DecodeError {
    /// A custom error occurred when decoding,
    /// reported as a dynamic error value with a message.
    ///
    /// The [`whatever!`](snafu::whatever) macro can be used
    /// to easily create an error of this kind.
    #[snafu(whatever, display("{}", message))]
    Custom {
        /// The error message.
        message: String,
        /// The underlying error cause, if any.
        #[snafu(source(from(Box<dyn std::error::Error + Send + Sync + 'static>, Some)))]
        source: Option<Box<dyn std::error::Error + Send + Sync + 'static>>,
    },

    /// The input pixel data is not encapsulated.
    ///
    /// Either the image needs no decoding
    /// or the compressed imaging data was in a flat pixel data element by mistake.
    #[snafu(display("Pixel Data is not encapsulated"))]
    NotEncapsulated,

    /// Pixel Data is missing
    /// or the requested frame range is outside the object's frame range.
    #[snafu(display("Frame of pixel data is missing or out of bounds"))]
    FrameRangeOutOfBounds,

    /// A required attribute is missing
    /// from the DICOM object representing the image.
    #[snafu(display("Missing required attribute `{}`", name))]
    MissingAttribute { name: &'static str },
}

/// The possible error conditions when encoding (writing) pixel data.
///
/// Users of this type are free to handle errors based on their variant,
/// but should not make decisions based on the display message,
/// since that is not considered part of the API
/// and may change on any new release.
///
/// Implementers of transfer syntaxes
/// are recommended to choose the most fitting error variant
/// for the tested condition.
/// When no suitable variant is available,
/// the [`Custom`](EncodeError::Custom) variant may be used.
/// See also [`snafu`] for guidance on using context selectors.
#[derive(Debug, Snafu)]
#[non_exhaustive]
#[snafu(visibility(pub), module)]
pub enum EncodeError {
    /// A custom error when encoding fails.
    /// Read the `message` and the underlying `source`
    /// for more details.
    #[snafu(whatever, display("{}", message))]
    Custom {
        /// The error message.
        message: String,
        /// The underlying error cause, if any.
        #[snafu(source(from(Box<dyn std::error::Error + Send + Sync + 'static>, Some)))]
        source: Option<Box<dyn std::error::Error + Send + Sync + 'static>>,
    },

    /// Input pixel data is not native, should be decoded first.
    #[snafu(display("Pixel Data is not native"))]
    NotNative,

    /// Pixel Data is missing
    /// or the requested frame range is outside the object's frame range.
    #[snafu(display("Frame of pixel data is missing or out of bounds"))]
    FrameRangeOutOfBounds,

    /// A required attribute is missing
    /// from the DICOM object representing the image.
    #[snafu(display("Missing required attribute `{}`", name))]
    MissingAttribute { name: &'static str },
}

/// The result of decoding (reading) pixel data
pub type DecodeResult<T, E = DecodeError> = Result<T, E>;

/// The result of encoding (writing) pixel data
pub type EncodeResult<T, E = EncodeError> = Result<T, E>;

#[derive(Debug)]
pub struct RawPixelData {
    /// Either a byte slice/vector if native pixel data
    /// or byte fragments if encapsulated
    pub fragments: C<Vec<u8>>,

    /// The offset table for the fragments,
    /// or empty if there is none
    pub offset_table: C<u32>,
}

/// A DICOM object trait to be interpreted as pixel data.
///
/// This trait extends the concept of DICOM object
/// as defined in [`dicom_object`],
/// in order to retrieve important pieces of the object
/// for pixel data decoding into images or multi-dimensional arrays.
///
/// It is defined in this crate so that
/// transfer syntax implementers only have to depend on `dicom_encoding`.
///
/// [`dicom_object`]: https://docs.rs/dicom_object
pub trait PixelDataObject {
    /// Return the object's transfer syntax UID.
    fn transfer_syntax_uid(&self) -> &str;

    /// Return the _Rows_, or `None` if it is not found
    fn rows(&self) -> Option<u16>;

    /// Return the _Columns_, or `None` if it is not found
    fn cols(&self) -> Option<u16>;

    /// Return the _Samples Per Pixel_, or `None` if it is not found
    fn samples_per_pixel(&self) -> Option<u16>;

    /// Return the _Bits Allocated_, or `None` if it is not defined
    fn bits_allocated(&self) -> Option<u16>;

    /// Return the _Bits Stored_, or `None` if it is not defined
    fn bits_stored(&self) -> Option<u16>;

    /// Return the _Photometric Interpretation_,
    /// with trailing whitespace removed,
    /// or `None` if it is not defined
    fn photometric_interpretation(&self) -> Option<&str>;

    /// Return the _Number Of Frames_,
    /// or `None` if it is not defined by this object.
    fn number_of_frames(&self) -> Option<u32>;

    /// Returns the _number of pixel data fragments_,
    /// excluding the basic offset table,
    /// or `None` for native pixel data.
    fn number_of_fragments(&self) -> Option<u32>;

    /// Return a specific encoded pixel fragment by index
    /// (where 0 is the first fragment after the basic offset table)
    /// as a [`Cow<[u8]>`][1],
    /// or `None` if no such fragment is available.
    ///
    /// In the case of native (non-encapsulated) pixel data,
    /// the whole data may be obtained
    /// by requesting fragment number 0.
    ///
    /// [1]: std::borrow::Cow
    fn fragment(&self, fragment: usize) -> Option<Cow<'_, [u8]>>;

    /// Return the object's offset table,
    /// or `None` if no offset table is available.
    fn offset_table(&self) -> Option<Cow<'_, [u32]>>;

    /// Should return either a byte slice/vector if the pixel data is native
    /// or the list of byte fragments and offset table if encapsulated.
    ///
    /// Returns `None` if no pixel data is found.
    fn raw_pixel_data(&self) -> Option<RawPixelData>;

    /// Return the pixel data of a specific frame as a byte slice/vector,
    /// in its encoded form.
    ///
    /// Returns `None` if there is no such frame or there is no pixel data at all.
    ///
    /// _Note:_ If pixel data is uncompressed and Bits Allocated is 1,
    /// the slice may include leading or trailing bits
    /// belonging to other frames,
    /// depending on the size of each frame.
    fn frame_pixel_data(&self, frame: u32) -> Option<Cow<'_, [u8]>> {
        match self.number_of_fragments() {
            // Handle cases of single frame object
            // and multi-frame with 1:1 fragment to frame.
            // This is important not just for the shortcut,
            // but because the basic offset table may be missing.
            Some(number_of_fragments)
                if number_of_fragments == self.number_of_frames().unwrap_or(1) =>
            {
                self.fragment(frame as usize)
            }
            // Other cases of multi-frame objects
            Some(number_of_fragments) => {
                // In this case we look up the basic offset table
                // and gather all of the frame's fragments in a single vector.
                // Note: not the most efficient way to do this,
                // consider optimizing later with byte chunk readers
                let offset_table = self.offset_table()?;
                let base_offset = offset_table.get(frame as usize).copied();
                let base_offset = if frame == 0 {
                    base_offset.unwrap_or(0) as usize
                } else {
                    base_offset? as usize
                };
                let next_offset = offset_table.get(frame as usize + 1);

                let mut offset = 0;
                let mut frame_data = Vec::new();
                for idx in 0..number_of_fragments as usize {
                    let fragment = self.fragment(idx)?;
                    // include it
                    if offset >= base_offset {
                        frame_data.extend_from_slice(&fragment);
                    }
                    offset += fragment.len() + 8;
                    if let Some(&next_offset) = next_offset {
                        if offset >= next_offset as usize {
                            // next fragment is for the next frame
                            break;
                        }
                    }
                }

                Some(Cow::Owned(frame_data))
            }
            // In the case of native pixel data, the whole data is considered as a single fragment.
            None => {
                let bits_allocated = self.bits_allocated()?;
                let rows = self.rows()?;
                let columns = self.cols()?;
                let frame_size = determine_bytes_per_native_frame(
                    rows,
                    columns,
                    self.samples_per_pixel()?,
                    bits_allocated,
                    self.photometric_interpretation()?,
                );
                let pixel_data = self.fragment(0)?;

                // special case of 1 bit per sample:
                // include starting byte even it leading bits are outside the frame
                // and include next byte if it ends outside frame boundary
                let (start, end) = if bits_allocated == 1 {
                    let samples_per_frame = rows as usize * columns as usize;
                    let start = frame as usize * samples_per_frame / 8;
                    let end = ((frame as usize + 1) * samples_per_frame).div_ceil(8);
                    (start, end)
                } else {
                    let start = frame as usize * frame_size;
                    let end = start + frame_size;
                    (start, end)
                };
                if end <= pixel_data.len() {
                    match pixel_data {
                        Cow::Borrowed(slice) => slice.get(start..end).map(Cow::Borrowed),
                        Cow::Owned(vec) => vec.get(start..end).map(|s| Cow::Owned(s.to_vec())),
                    }
                } else {
                    None
                }
            }
        }
    }
}

/// Custom options when encoding pixel data into an encapsulated form.
#[derive(Debug, Default, Clone)]
#[non_exhaustive]
pub struct EncodeOptions {
    /// The quality of the output image as a number between 0 and 100,
    /// where 100 is the best quality that the encapsulated form can achieve
    /// and smaller values represent smaller data size
    /// with an increasingly higher error.
    /// It is ignored if the transfer syntax only supports lossless compression.
    /// If it does support lossless compression,
    /// it is expected that a quality of 100 results in
    /// a mathematically lossless encoding.
    ///
    /// If this option is not specified,
    /// the output quality is decided automatically by the underlying adapter.
    pub quality: Option<u8>,

    /// The amount of effort that the encoder may take to encode the pixel data,
    /// as a number between 0 and 100.
    /// If supported, higher values result in better compression,
    /// at the expense of more processing time.
    /// Encoders are not required to support this option.
    /// If this option is not specified,
    /// the actual effort is decided by the underlying adapter.
    pub effort: Option<u8>,
}

impl EncodeOptions {
    pub fn new() -> Self {
        Self::default()
    }
}

/// Trait object responsible for decoding
/// pixel data based on the transfer syntax.
///
/// A transfer syntax with support for decoding encapsulated pixel data
/// would implement these methods.
pub trait PixelDataReader {
    /// Decode the given DICOM object
    /// containing encapsulated pixel data
    /// into native pixel data as a byte stream in little endian,
    /// appending these bytes to the given vector `dst`.
    ///
    /// It is a necessary precondition that the object's pixel data
    /// is encoded in accordance to the transfer syntax(es)
    /// supported by this adapter.
    /// A `NotEncapsulated` error is returned otherwise.
    ///
    /// The output is a sequence of native pixel values
    /// which follow the image properties of the given object
    /// _save for the photometric interpretation and planar configuration_.
    /// If the image has 3 samples per pixel,
    /// the output must be in RGB with each pixel contiguous in memory
    /// (planar configuration of 0).
    /// However, if the image is monochrome,
    /// the output should retain the photometric interpretation of the source object
    /// (so that images in _MONOCHROME1_ continue to be in _MONOCHROME1_
    /// and images in _MONOCHROME2_ continue to be in _MONOCHROME2_).
    fn decode(&self, src: &dyn PixelDataObject, dst: &mut Vec<u8>) -> DecodeResult<()> {
        let frames = src.number_of_frames().unwrap_or(1);
        for frame in 0..frames {
            self.decode_frame(src, frame, dst)?;
        }
        Ok(())
    }

    /// Decode the given DICOM object
    /// containing encapsulated pixel data
    /// into native pixel data of a single frame
    /// as a byte stream in little endian,
    /// appending these bytes to the given vector `dst`.
    ///
    /// The frame index is 0-based.
    ///
    /// It is a necessary precondition that the object's pixel data
    /// is encoded in accordance to the transfer syntax(es)
    /// supported by this adapter.
    /// A `NotEncapsulated` error is returned otherwise.
    ///
    /// The output is a sequence of native pixel values of a frame
    /// which follow the image properties of the given object
    /// _save for the photometric interpretation and planar configuration_.
    /// If the image has 3 samples per pixel,
    /// the output must be in RGB with each pixel contiguous in memory
    /// (planar configuration of 0).
    /// For pixel data with a single sample per pixel,
    /// the output shall retain the photometric interpretation
    /// declared in the original object
    /// if it is one of _MONOCHROME1_, _MONOCHROME2_, or _PALETTE COLOR_.
    /// For any other photometric interpretation,
    /// the output shall be assumed to be in _MONOCHROME2_.
    fn decode_frame(
        &self,
        src: &dyn PixelDataObject,
        frame: u32,
        dst: &mut Vec<u8>,
    ) -> DecodeResult<()>;
}

/// Trait object responsible for encoding
/// pixel data based on a certain transfer syntax.
///
/// A transfer syntax with support for creating compressed pixel data
/// would implement these methods.
pub trait PixelDataWriter {
    /// Encode a DICOM object's image into the format supported by this adapter,
    /// writing a byte stream of pixel data fragment values
    /// to the given vector `dst`
    /// and the offsets to each decoded frame into `offset_table`.
    ///
    /// New data is appended to `dst` and `offset_table`,
    /// which are not cleared before writing.
    ///
    /// All implementations are required to support
    /// writing the object's pixel data when it is in a _native encoding_.
    /// If the given pixel data object is not in a native encoding,
    /// and this writer does not support transcoding
    /// from that encoding to the target transfer syntax,
    /// a `NotNative` error is returned instead.
    ///
    /// When the operation is successful,
    /// a listing of attribute changes is returned,
    /// comprising the sequence of operations that the DICOM object
    /// should consider upon assuming the new encoding.
    fn encode(
        &self,
        src: &dyn PixelDataObject,
        options: EncodeOptions,
        dst: &mut Vec<Vec<u8>>,
        offset_table: &mut Vec<u32>,
    ) -> EncodeResult<Vec<AttributeOp>> {
        let frames = src.number_of_frames().unwrap_or(1);
        let mut out = Vec::new();
        for frame in 0..frames {
            let mut frame_data = Vec::new();
            out = self.encode_frame(src, frame, options.clone(), &mut frame_data)?;
            offset_table.push(frame_data.len() as u32 + 8 * (frame + 1));
            dst.push(frame_data);
        }
        Ok(out)
    }

    /// Encode a single frame of a DICOM object's image
    /// into the format supported by this adapter,
    /// by writing a byte stream of pixel data values
    /// into the given destination.
    /// The bytes written comprise a single pixel data fragment
    /// in its entirety.
    ///
    /// New data is appended to `dst`,
    /// keeping all bytes previously present before writing.
    ///
    /// All implementations are required to support
    /// writing the object's pixel data when it is in a _native encoding_.
    /// If the given pixel data object is not in a native encoding,
    /// and this writer does not support transcoding
    /// from that encoding to the target transfer syntax,
    /// a `NotNative` error is returned instead.
    ///
    /// When the operation is successful,
    /// a listing of attribute changes is returned,
    /// comprising the sequence of operations that the DICOM object
    /// should consider upon assuming the new encoding.
    fn encode_frame(
        &self,
        src: &dyn PixelDataObject,
        frame: u32,
        options: EncodeOptions,
        dst: &mut Vec<u8>,
    ) -> EncodeResult<Vec<AttributeOp>>;
}

/// Alias type for a dynamically dispatched pixel data reader.
pub type DynPixelDataReader = Box<dyn PixelDataReader + Send + Sync + 'static>;

/// Alias type for a dynamically dispatched pixel data writer.
pub type DynPixelDataWriter = Box<dyn PixelDataWriter + Send + Sync + 'static>;

/// An immaterial type representing an adapter which is never provided.
///
/// This type may be used as the type parameters `R` and `W`
/// of [`TransferSyntax`](crate::transfer_syntax::TransferSyntax)
/// when representing a transfer syntax which
/// either does not support reading and writing imaging data,
/// or when such support is not needed in the first place.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum NeverPixelAdapter {}

impl PixelDataReader for NeverPixelAdapter {
    fn decode(&self, _src: &dyn PixelDataObject, _dst: &mut Vec<u8>) -> DecodeResult<()> {
        unreachable!()
    }

    fn decode_frame(
        &self,
        _src: &dyn PixelDataObject,
        _frame: u32,
        _dst: &mut Vec<u8>,
    ) -> DecodeResult<()> {
        unreachable!()
    }
}

impl PixelDataWriter for NeverPixelAdapter {
    fn encode(
        &self,
        _src: &dyn PixelDataObject,
        _options: EncodeOptions,
        _dst: &mut Vec<Vec<u8>>,
        _offset_table: &mut Vec<u32>,
    ) -> EncodeResult<Vec<AttributeOp>> {
        unreachable!()
    }

    fn encode_frame(
        &self,
        _src: &dyn PixelDataObject,
        _frame: u32,
        _options: EncodeOptions,
        _dst: &mut Vec<u8>,
    ) -> EncodeResult<Vec<AttributeOp>> {
        unreachable!()
    }
}

impl PixelDataReader for crate::transfer_syntax::NeverAdapter {
    fn decode(&self, _src: &dyn PixelDataObject, _dst: &mut Vec<u8>) -> DecodeResult<()> {
        unreachable!()
    }

    fn decode_frame(
        &self,
        _src: &dyn PixelDataObject,
        _frame: u32,
        _dst: &mut Vec<u8>,
    ) -> DecodeResult<()> {
        unreachable!()
    }
}

impl PixelDataWriter for crate::transfer_syntax::NeverAdapter {
    fn encode(
        &self,
        _src: &dyn PixelDataObject,
        _options: EncodeOptions,
        _dst: &mut Vec<Vec<u8>>,
        _offset_table: &mut Vec<u32>,
    ) -> EncodeResult<Vec<AttributeOp>> {
        unreachable!()
    }

    fn encode_frame(
        &self,
        _src: &dyn PixelDataObject,
        _frame: u32,
        _options: EncodeOptions,
        _dst: &mut Vec<u8>,
    ) -> EncodeResult<Vec<AttributeOp>> {
        unreachable!()
    }
}

/// Use the information in a pixel data object
/// to determine the number of bytes needed to encode one frame.
///
/// Only makes sense if the object contains native pixel data.
#[inline]
fn determine_bytes_per_native_frame(
    rows: u16,
    columns: u16,
    samples_per_pixel: u16,
    bits_allocated: u16,
    photometric_interpretation: &str,
) -> usize {
    // handle special case of 1 bit per sample
    if bits_allocated == 1 {
        return (rows as usize * columns as usize).div_ceil(8);
    }

    let real_samples_per_pixel =
        if samples_per_pixel == 3 && photometric_interpretation == "YBR_FULL_422" {
            2
        } else {
            samples_per_pixel
        };
    rows as usize
        * columns as usize
        * real_samples_per_pixel as usize
        * (bits_allocated as usize).div_ceil(8)
}

#[cfg(test)]
mod tests {
    use std::borrow::Cow;

    use dicom_core::value::{InMemFragment, PixelFragmentSequence};

    use crate::adapters::RawPixelData;

    use super::PixelDataObject;

    /// Generates frames with solid pixel data values 0, 1, and so on.
    fn generated_rgb_frames(columns: u16, rows: u16) -> impl Iterator<Item = Vec<u8>> {
        (0..=255_u8).map(move |n| vec![n; columns as usize * rows as usize * 3])
    }

    pub(crate) struct TestDataObject {
        pub ts_uid: &'static str,
        pub rows: u16,
        pub columns: u16,
        pub bits_allocated: u16,
        pub bits_stored: u16,
        pub samples_per_pixel: u16,
        pub photometric_interpretation: &'static str,
        pub number_of_frames: u32,
        pub flat_pixel_data: Option<Vec<u8>>,
        pub pixel_data_sequence: Option<PixelFragmentSequence<InMemFragment>>,
    }

    impl PixelDataObject for TestDataObject {
        fn transfer_syntax_uid(&self) -> &str {
            &self.ts_uid
        }

        fn rows(&self) -> Option<u16> {
            Some(self.rows)
        }

        fn cols(&self) -> Option<u16> {
            Some(self.columns)
        }

        fn samples_per_pixel(&self) -> Option<u16> {
            Some(self.samples_per_pixel)
        }

        fn bits_allocated(&self) -> Option<u16> {
            Some(self.bits_allocated)
        }

        fn bits_stored(&self) -> Option<u16> {
            Some(self.bits_stored)
        }

        fn photometric_interpretation(&self) -> Option<&str> {
            Some(self.photometric_interpretation)
        }

        fn number_of_frames(&self) -> Option<u32> {
            Some(self.number_of_frames)
        }

        fn number_of_fragments(&self) -> Option<u32> {
            self.pixel_data_sequence
                .as_ref()
                .map(|v| v.fragments().len() as u32)
        }

        fn fragment(&self, fragment: usize) -> Option<Cow<'_, [u8]>> {
            match (&self.flat_pixel_data, &self.pixel_data_sequence) {
                (Some(_), Some(_)) => {
                    panic!("Invalid pixel data object (both flat and fragment sequence)")
                }
                (_, Some(v)) => v
                    .fragments()
                    .get(fragment)
                    .map(|f| Cow::Borrowed(f.as_slice())),
                (Some(v), _) => {
                    if fragment == 0 {
                        Some(Cow::Borrowed(v))
                    } else {
                        None
                    }
                }
                (None, None) => None,
            }
        }

        fn offset_table(&self) -> Option<Cow<'_, [u32]>> {
            match &self.pixel_data_sequence {
                Some(v) => Some(Cow::Borrowed(v.offset_table())),
                _ => None,
            }
        }

        fn raw_pixel_data(&self) -> Option<RawPixelData> {
            match (&self.flat_pixel_data, &self.pixel_data_sequence) {
                (Some(_), Some(_)) => {
                    panic!("Invalid pixel data object (both flat and fragment sequence)")
                }
                (Some(v), _) => Some(RawPixelData {
                    fragments: vec![v.clone()].into(),
                    offset_table: Default::default(),
                }),
                (_, Some(v)) => Some(RawPixelData {
                    fragments: v.fragments().into(),
                    offset_table: v.offset_table().into(),
                }),
                _ => None,
            }
        }
    }

    /// Frame pixel data can be retrieved from an object
    /// with native pixel data.
    #[test]
    fn frame_pixel_data_in_object_flat() {
        let rows = 10;
        let columns = 10;
        let number_of_frames = 4;

        let obj = TestDataObject {
            ts_uid: "1.2.840.10008.1.2.1",
            rows,
            columns,
            bits_allocated: 8,
            bits_stored: 8,
            samples_per_pixel: 3,
            photometric_interpretation: "RGB",
            number_of_frames,
            flat_pixel_data: Some(
                generated_rgb_frames(columns, rows)
                    .take(number_of_frames as usize)
                    .flatten()
                    .collect(),
            ),
            pixel_data_sequence: None,
        };

        assert_eq!(obj.frame_pixel_data(0), Some(vec![0; 10 * 10 * 3].into()));
        assert_eq!(obj.frame_pixel_data(1), Some(vec![1; 10 * 10 * 3].into()));
        assert_eq!(obj.frame_pixel_data(2), Some(vec![2; 10 * 10 * 3].into()));
        assert_eq!(obj.frame_pixel_data(3), Some(vec![3; 10 * 10 * 3].into()));
        assert_eq!(obj.frame_pixel_data(4), None);
    }

    /// Frame pixel data can be retrieved from an object
    /// with encapsulated pixel data.
    #[test]
    fn frame_pixel_data_in_object_encapsulated() {
        let obj = TestDataObject {
            ts_uid: "9.9.999.9999.9.9.99",
            rows: 512,
            columns: 512,
            bits_allocated: 16,
            bits_stored: 12,
            samples_per_pixel: 1,
            photometric_interpretation: "MONOCHROME2",
            number_of_frames: 3,
            flat_pixel_data: None,
            pixel_data_sequence: Some(PixelFragmentSequence::new(
                // offset table: 1 frame with 2 fragments + 2 frames with 1 fragment
                vec![0, 16 + 20, 16 + 20 + 24],
                vec![
                    // fragment 0 (frame 0)
                    vec![0x33; 16],
                    // fragment 1 (frame 0)
                    vec![0x55; 20],
                    // fragment 2 (frame 1)
                    vec![0x77; 24],
                    // fragment 3 (frame 2)
                    vec![0x99; 36],
                ],
            )),
        };

        // the first two fragments will be combined
        let frame_1: Vec<u8> = IntoIterator::into_iter([0x33; 16])
            .chain(IntoIterator::into_iter([0x55; 20]))
            .collect();
        assert_eq!(obj.frame_pixel_data(0), Some(frame_1.into()));

        assert_eq!(obj.frame_pixel_data(1), Some(vec![0x77; 24].into()));
        assert_eq!(obj.frame_pixel_data(2), Some(vec![0x99; 36].into()));
    }
}