Skip to main content

dcmnorm_encoding/transfer_syntax/
mod.rs

1//! Module containing the DICOM Transfer Syntax data structure and related methods.
2//! Similar to the DcmCodec in DCMTK, the `TransferSyntax` contains all of the necessary
3//! algorithms for decoding and encoding DICOM data in a certain transfer syntax.
4//!
5//! This crate does not host specific transfer syntaxes. Instead, they are created in
6//! other crates and registered in the global transfer syntax registry,
7//! which implements [`TransferSyntaxIndex`].
8//! For more information, please see the [`dicom-transfer-syntax-registry`] crate,
9//! which provides built-in implementations.
10//!
11//! This module allows you to roll your own [transfer syntax index][1] by
12//! implementing [`TransferSyntaxIndex`] directly.
13//!
14//! [1]: TransferSyntaxIndex
15//! [`dicom-transfer-syntax-registry`]: https://docs.rs/dicom-transfer-syntax-registry
16
17use crate::adapters::{
18    DynPixelDataReader, DynPixelDataWriter, NeverPixelAdapter, PixelDataReader, PixelDataWriter,
19};
20use crate::decode::{
21    basic::BasicDecoder, explicit_be::ExplicitVRBigEndianDecoder,
22    explicit_le::ExplicitVRLittleEndianDecoder, implicit_le::ImplicitVRLittleEndianDecoder,
23    DecodeFrom,
24};
25use crate::encode::{
26    explicit_be::ExplicitVRBigEndianEncoder, explicit_le::ExplicitVRLittleEndianEncoder,
27    implicit_le::ImplicitVRLittleEndianEncoder, EncodeTo, EncoderFor,
28};
29use std::io::{Read, Write};
30
31pub use byteordered::Endianness;
32
33/// A decoder with its type erased.
34pub type DynDecoder<S> = Box<dyn DecodeFrom<S>>;
35
36/// An encoder with its type erased.
37pub type DynEncoder<'w, W> = Box<dyn EncodeTo<W> + 'w>;
38
39/// A DICOM transfer syntax specifier.
40///
41/// Custom encoding and decoding capabilities
42/// are defined via the parameter types `D` and `P`,
43/// The type parameter `D` specifies
44/// an adapter for reading and writing data sets,
45/// whereas `P` specifies the encoder and decoder of encapsulated pixel data.
46///
47/// This type is usually consumed in its "type erased" form,
48/// with its default parameter types.
49/// On the other hand, implementers of `TransferSyntax` will typically specify
50/// concrete types for `D` and `P`,
51/// which are type-erased before registration.
52/// If the transfer syntax requires no data set codec,
53/// `D` can be assigned to the utility type [`NeverAdapter`].
54/// If pixel data encoding/decoding is not needed or not supported,
55/// you can assign `P` to [`NeverPixelAdapter`].
56#[derive(Debug)]
57pub struct TransferSyntax<D = DynDataRWAdapter, R = DynPixelDataReader, W = DynPixelDataWriter> {
58    /// The unique identifier of the transfer syntax.
59    uid: &'static str,
60    /// The name of the transfer syntax.
61    name: &'static str,
62    /// The byte order of data.
63    byte_order: Endianness,
64    /// Whether the transfer syntax mandates an explicit value representation,
65    /// or the VR is implicit.
66    explicit_vr: bool,
67    /// The transfer syntax' requirements and implemented capabilities.
68    codec: Codec<D, R, W>,
69}
70
71/// Trait for a container/repository of transfer syntax specifiers.
72///
73/// Types implementing this trait are held responsible for populating
74/// themselves with a set of transfer syntaxes, which can be fully supported,
75/// partially supported, or not supported. Usually, only one implementation
76/// of this trait is used for the entire program,
77/// the most common one being the `TransferSyntaxRegistry` type
78/// from [`transfer-syntax-registry`].
79///
80/// [`transfer-syntax-registry`]: https://docs.rs/dicom-transfer-syntax-registry
81pub trait TransferSyntaxIndex {
82    /// Obtain a DICOM transfer syntax by its respective UID.
83    ///
84    /// Implementations of this method should be robust to the possible
85    /// presence of trailing null characters (`\0`) in `uid`.
86    fn get(&self, uid: &str) -> Option<&TransferSyntax>;
87}
88
89impl<T: ?Sized> TransferSyntaxIndex for &T
90where
91    T: TransferSyntaxIndex,
92{
93    fn get(&self, uid: &str) -> Option<&TransferSyntax> {
94        (**self).get(uid)
95    }
96}
97
98#[macro_export]
99/// Submit a transfer syntax specifier to be supported by the program's
100/// runtime. No-op: dcmnorm registers its transfer syntaxes directly in
101/// `dcmnorm-transcode`'s static built-in table rather than through a
102/// plugin/inventory mechanism (removed - never used by anything in this
103/// workspace). Kept as a no-op for API compatibility with any external code
104/// still calling it.
105macro_rules! submit_transfer_syntax {
106    ($ts: expr) => {
107        // ignore request - see doc comment above
108    };
109}
110
111#[macro_export]
112/// Submit an explicit VR little endian transfer syntax specifier to be
113/// supported by the program's runtime. No-op, for the same reason as
114/// [`submit_transfer_syntax`].
115macro_rules! submit_ele_transfer_syntax {
116    ($uid: literal, $name: literal, $codec: expr) => {
117        // ignore request - see doc comment above
118    };
119}
120
121/// A description and possible implementation regarding
122/// the encoding and decoding requirements of a transfer syntax.
123/// This is also used as a means to describe whether pixel data is encapsulated
124/// and whether this implementation supports decoding and/or encoding it.
125///
126/// ### Type parameters
127///
128/// - `D` should implement [`DataRWAdapter`]
129///   and defines how one should read and write DICOM data sets,
130///   such as in the case for deflated data.
131///   When no special considerations for data set reading and writing
132///   are necessary, this can be set to [`NeverAdapter`].
133/// - `R` should implement [`PixelDataReader`],
134///   and enables programs to convert encapsulated pixel data fragments
135///   into native pixel data.
136/// - `W` should implement [`PixelDataWriter`],
137///   and enables programs to convert native pixel data
138///   into encapsulated pixel data.
139///
140#[derive(Debug, Clone, PartialEq)]
141pub enum Codec<D, R, W> {
142    /// No codec is required for this transfer syntax.
143    ///
144    /// Pixel data, if any, should be in its _native_, unencapsulated format.
145    None,
146    /// Pixel data for this transfer syntax is encapsulated
147    /// and likely subjected to a specific encoding process.
148    /// The first part of the tuple struct contains the pixel data decoder,
149    /// whereas the second item is for the pixel data encoder.
150    ///
151    /// Decoding of the pixel data is not supported
152    /// if the decoder is `None`.
153    /// In this case, the program should still be able to
154    /// parse DICOM data sets
155    /// and fetch the pixel data in its encapsulated form.
156    EncapsulatedPixelData(Option<R>, Option<W>),
157    /// A custom data set codec is required for reading and writing data sets.
158    ///
159    /// If the item in the tuple struct is `None`,
160    /// then no reading and writing whatsoever is supported.
161    /// This could be used by a stub of
162    /// _Deflated Explicit VR Little Endian_, for example.
163    Dataset(Option<D>),
164}
165
166impl Codec<NeverAdapter, NeverPixelAdapter, NeverPixelAdapter> {
167    /// Create a stub codec for encapsulated pixel data
168    pub fn encapsulated_pixel_data_stub() -> Self {
169        Codec::EncapsulatedPixelData(None, None)
170    }
171}
172
173impl<R> Codec<NeverAdapter, R, NeverPixelAdapter> {
174    /// Create a codec for encapsulated pixel data
175    /// with a pixel data decoder but not an encoder
176    pub fn encapsulated_pixel_data_reader(reader: R) -> Self {
177        Codec::EncapsulatedPixelData(Some(reader), None)
178    }
179}
180
181impl<R, W> Codec<NeverAdapter, R, W> {
182    /// Create a codec for encapsulated pixel data
183    /// with a pixel data decoder and encoder
184    pub fn encapsulated_pixel_data(reader: R, writer: W) -> Self {
185        Codec::EncapsulatedPixelData(Some(reader), Some(writer))
186    }
187}
188
189/// An alias for a transfer syntax specifier with no pixel data encapsulation
190/// nor data set deflating.
191pub type AdapterFreeTransferSyntax =
192    TransferSyntax<NeverAdapter, NeverPixelAdapter, NeverPixelAdapter>;
193
194/// A fully dynamic adapter of byte read and write streams.
195pub trait DataRWAdapter {
196    /// Adapt a byte reader.
197    fn adapt_reader<'r>(&self, reader: Box<dyn Read + 'r>) -> Box<dyn Read + 'r>;
198
199    /// Adapt a byte writer.
200    fn adapt_writer<'w>(&self, writer: Box<dyn Write + 'w>) -> Box<dyn Write + 'w>;
201}
202
203/// Alias type for a dynamically dispatched data adapter.
204pub type DynDataRWAdapter = Box<dyn DataRWAdapter + Send + Sync>;
205
206impl<T> DataRWAdapter for &'_ T
207where
208    T: DataRWAdapter,
209{
210    /// Adapt a byte reader.
211    fn adapt_reader<'r>(&self, reader: Box<dyn Read + 'r>) -> Box<dyn Read + 'r> {
212        (**self).adapt_reader(reader)
213    }
214
215    /// Adapt a byte writer.
216    fn adapt_writer<'w>(&self, writer: Box<dyn Write + 'w>) -> Box<dyn Write + 'w> {
217        (**self).adapt_writer(writer)
218    }
219}
220
221/// An immaterial type representing a data set adapter which is never required,
222/// and as such is never instantiated.
223/// Most transfer syntaxes use this,
224/// as they do not have to adapt readers and writers
225/// for encoding and decoding data sets.
226/// The main exception is in the family of
227/// _Deflated Explicit VR Little Endian_ transfer syntaxes.
228#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
229pub enum NeverAdapter {}
230
231impl DataRWAdapter for NeverAdapter {
232    fn adapt_reader<'r>(&self, _reader: Box<dyn Read + 'r>) -> Box<dyn Read + 'r> {
233        unreachable!()
234    }
235
236    fn adapt_writer<'w>(&self, _writer: Box<dyn Write + 'w>) -> Box<dyn Write + 'w> {
237        unreachable!()
238    }
239}
240
241impl<D, R, W> TransferSyntax<D, R, W> {
242    /// Create a new transfer syntax descriptor.
243    ///
244    /// Note that only transfer syntax implementers are expected to
245    /// construct TS descriptors from scratch.
246    /// For a practical usage of transfer syntaxes,
247    /// one should look up an existing transfer syntax registry by UID.
248    ///
249    /// # Example
250    ///
251    /// To register a private transfer syntax in your program,
252    /// use [`submit_transfer_syntax`](crate::submit_transfer_syntax)
253    /// outside of a function body:
254    ///  
255    /// ```no_run
256    /// # use dcmnorm_encoding::{
257    /// #     submit_transfer_syntax, Codec, Endianness,
258    /// #     NeverAdapter, NeverPixelAdapter, TransferSyntax,
259    /// # };
260    /// submit_transfer_syntax! {
261    ///     TransferSyntax::<NeverAdapter, NeverPixelAdapter, NeverPixelAdapter>::new(
262    ///         "1.3.46.670589.33.1.4.1",
263    ///         "CT-Private-ELE",
264    ///         Endianness::Little,
265    ///         true,
266    ///         Codec::EncapsulatedPixelData(None, None),
267    ///     )
268    /// }
269    /// ```
270    pub const fn new(
271        uid: &'static str,
272        name: &'static str,
273        byte_order: Endianness,
274        explicit_vr: bool,
275        codec: Codec<D, R, W>,
276    ) -> Self {
277        TransferSyntax {
278            uid,
279            name,
280            byte_order,
281            explicit_vr,
282            codec,
283        }
284    }
285
286    /// Create a new descriptor
287    /// for a transfer syntax in explicit VR little endian.
288    ///
289    /// Note that only transfer syntax implementers are expected to
290    /// construct TS descriptors from scratch.
291    /// For a practical usage of transfer syntaxes,
292    /// one should look up an existing transfer syntax registry by UID.
293    ///
294    /// # Example
295    ///
296    /// To register a private transfer syntax in your program,
297    /// use [`submit_transfer_syntax`](crate::submit_transfer_syntax)
298    /// outside of a function body:
299    ///  
300    /// ```no_run
301    /// # use dcmnorm_encoding::{
302    /// #     submit_transfer_syntax, Codec,
303    /// #     NeverAdapter, NeverPixelAdapter, TransferSyntax,
304    /// # };
305    /// submit_transfer_syntax! {
306    ///     TransferSyntax::<NeverAdapter, NeverPixelAdapter, NeverPixelAdapter>::new_ele(
307    ///         "1.3.46.670589.33.1.4.1",
308    ///         "CT-Private-ELE",
309    ///         Codec::EncapsulatedPixelData(None, None),
310    ///     )
311    /// }
312    /// ```
313    ///
314    /// See [`submit_ele_transfer_syntax`](crate::submit_ele_transfer_syntax)
315    /// for an alternative.
316    pub const fn new_ele(uid: &'static str, name: &'static str, codec: Codec<D, R, W>) -> Self {
317        TransferSyntax {
318            uid,
319            name,
320            byte_order: Endianness::Little,
321            explicit_vr: true,
322            codec,
323        }
324    }
325
326    /// Obtain this transfer syntax' unique identifier.
327    pub const fn uid(&self) -> &'static str {
328        self.uid
329    }
330
331    /// Obtain the name of this transfer syntax.
332    pub const fn name(&self) -> &'static str {
333        self.name
334    }
335
336    /// Obtain this transfer syntax' expected endianness.
337    pub const fn endianness(&self) -> Endianness {
338        self.byte_order
339    }
340
341    /// Whether data sets in this transfer syntax are encoded with explicit VR.
342    pub const fn explicit_vr(&self) -> bool {
343        self.explicit_vr
344    }
345
346    /// Obtain this transfer syntax' codec specification.
347    pub fn codec(&self) -> &Codec<D, R, W> {
348        &self.codec
349    }
350
351    /// Check whether this transfer syntax specifier provides a complete
352    /// implementation,
353    /// meaning that it can both decode and encode in this transfer syntax.
354    pub fn is_fully_supported(&self) -> bool {
355        matches!(
356            self.codec,
357            Codec::None | Codec::Dataset(Some(_)) | Codec::EncapsulatedPixelData(Some(_), Some(_)),
358        )
359    }
360
361    /// Check whether no codecs are required for this transfer syntax,
362    /// meaning that a complete implementation is available
363    /// and no pixel data conversion is required.
364    pub fn is_codec_free(&self) -> bool {
365        matches!(self.codec, Codec::None)
366    }
367
368    /// Check whether neither reading nor writing of data sets is supported.
369    /// If this is `true`, encoding and decoding will not be available.
370    pub fn is_unsupported(&self) -> bool {
371        matches!(self.codec, Codec::Dataset(None))
372    }
373
374    /// Check whether this transfer syntax expects pixel data to be encapsulated.
375    ///
376    /// This does not imply that the pixel data can be decoded.
377    pub fn is_encapsulated_pixel_data(&self) -> bool {
378        matches!(self.codec, Codec::EncapsulatedPixelData(..))
379    }
380
381    /// Check whether reading and writing the pixel data is unsupported.
382    /// If this is `true`, encoding and decoding of the data set may still
383    /// be possible, but the pixel data will only be available in its
384    /// encapsulated form.
385    pub fn is_unsupported_pixel_encapsulation(&self) -> bool {
386        matches!(
387            self.codec,
388            Codec::Dataset(None) | Codec::EncapsulatedPixelData(None, None)
389        )
390    }
391
392    /// Check whether this codec can fully decode
393    /// both data sets and pixel data.
394    pub fn can_decode_all(&self) -> bool {
395        matches!(
396            self.codec,
397            Codec::None | Codec::Dataset(Some(_)) | Codec::EncapsulatedPixelData(Some(_), _)
398        )
399    }
400
401    /// Check whether this codec can decode the data set.
402    pub fn can_decode_dataset(&self) -> bool {
403        matches!(
404            self.codec,
405            Codec::None | Codec::Dataset(Some(_)) | Codec::EncapsulatedPixelData(..)
406        )
407    }
408
409    /// Retrieve the appropriate data element decoder for this transfer syntax.
410    /// Can yield none if decoding is not supported.
411    ///
412    /// The resulting decoder does not consider pixel data encapsulation or
413    /// data set compression rules. This means that the consumer of this method
414    /// needs to adapt the reader before using the decoder.
415    pub fn decoder<'s>(&self) -> Option<DynDecoder<dyn Read + 's>> {
416        self.decoder_for()
417    }
418
419    /// Retrieve the appropriate data element decoder for this transfer syntax
420    /// and given reader type (this method is not object safe).
421    /// Can yield none if decoding is not supported.
422    ///
423    /// The resulting decoder does not consider pixel data encapsulation or
424    /// data set compression rules. This means that the consumer of this method
425    /// needs to adapt the reader before using the decoder.
426    pub fn decoder_for<S>(&self) -> Option<DynDecoder<S>>
427    where
428        Self: Sized,
429        S: ?Sized + Read,
430    {
431        match (self.byte_order, self.explicit_vr) {
432            (Endianness::Little, false) => Some(Box::<ImplicitVRLittleEndianDecoder<_>>::default()),
433            (Endianness::Little, true) => Some(Box::<ExplicitVRLittleEndianDecoder>::default()),
434            (Endianness::Big, true) => Some(Box::<ExplicitVRBigEndianDecoder>::default()),
435            _ => None,
436        }
437    }
438
439    /// Retrieve the appropriate data element encoder for this transfer syntax.
440    /// Can yield none if encoding is not supported. The resulting encoder does not
441    /// consider pixel data encapsulation or data set compression rules.
442    pub fn encoder<'w>(&self) -> Option<DynEncoder<'w, dyn Write + 'w>> {
443        self.encoder_for()
444    }
445
446    /// Retrieve the appropriate data element encoder for this transfer syntax
447    /// and the given writer type (this method is not object safe).
448    /// Can yield none if encoding is not supported. The resulting encoder does not
449    /// consider pixel data encapsulation or data set compression rules.
450    pub fn encoder_for<'w, T>(&self) -> Option<DynEncoder<'w, T>>
451    where
452        Self: Sized,
453        T: ?Sized + Write + 'w,
454    {
455        match (self.byte_order, self.explicit_vr) {
456            (Endianness::Little, false) => Some(Box::new(EncoderFor::new(
457                ImplicitVRLittleEndianEncoder::default(),
458            ))),
459            (Endianness::Little, true) => Some(Box::new(EncoderFor::new(
460                ExplicitVRLittleEndianEncoder::default(),
461            ))),
462            (Endianness::Big, true) => Some(Box::new(EncoderFor::new(
463                ExplicitVRBigEndianEncoder::default(),
464            ))),
465            _ => None,
466        }
467    }
468
469    /// Obtain a dynamic basic decoder, based on this transfer syntax' expected endianness.
470    pub fn basic_decoder(&self) -> BasicDecoder {
471        BasicDecoder::from(self.endianness())
472    }
473
474    /// Obtain a reference to the underlying pixel data reader.
475    ///
476    /// Returns `None` if pixel data is not encapsulated
477    /// or a pixel data decoder implementation is not available.
478    pub fn pixel_data_reader(&self) -> Option<&R> {
479        match &self.codec {
480            Codec::EncapsulatedPixelData(r, _) => r.as_ref(),
481            _ => None,
482        }
483    }
484
485    /// Obtain a reference to the underlying pixel data writer.
486    ///
487    /// Returns `None` if pixel data is not encapsulated
488    /// or a pixel data encoder implementation is not available.
489    pub fn pixel_data_writer(&self) -> Option<&W> {
490        match &self.codec {
491            Codec::EncapsulatedPixelData(_, w) => w.as_ref(),
492            _ => None,
493        }
494    }
495
496    /// Type-erase the pixel data or data set codec.
497    pub fn erased(self) -> TransferSyntax
498    where
499        D: Send + Sync + 'static,
500        D: DataRWAdapter,
501        R: Send + Sync + 'static,
502        R: PixelDataReader,
503        W: Send + Sync + 'static,
504        W: PixelDataWriter,
505    {
506        let codec = match self.codec {
507            Codec::Dataset(d) => Codec::Dataset(d.map(|d| Box::new(d) as _)),
508            Codec::EncapsulatedPixelData(r, w) => Codec::EncapsulatedPixelData(
509                r.map(|r| Box::new(r) as _),
510                w.map(|w| Box::new(w) as _),
511            ),
512            Codec::None => Codec::None,
513        };
514
515        TransferSyntax {
516            uid: self.uid,
517            name: self.name,
518            byte_order: self.byte_order,
519            explicit_vr: self.explicit_vr,
520            codec,
521        }
522    }
523}