Skip to main content

dcmnorm_transcode/
lib.rs

1#![deny(trivial_numeric_casts, unsafe_code, unstable_features)]
2#![warn(
3    missing_debug_implementations,
4    missing_docs,
5    unused_qualifications,
6    unused_import_braces
7)]
8//! This crate contains the DICOM transfer syntax registry.
9//!
10//! The transfer syntax registry maps a DICOM UID of a transfer syntax (TS)
11//! into the respective transfer syntax specifier.
12//! This specifier defines:
13//!
14//! 1. how to read and write DICOM data sets;
15//! 2. how to decode and encode pixel data.
16//!
17//! Support may be partial, in which case the data set can be retrieved
18//! but the pixel data may not be decoded through this crate. To include
19//! support for some transfer syntaxes with encapsulated pixel data,
20//! add the **`native`** Cargo feature
21//! or one of the other image encoding features available.
22//!
23//! All registered TSes are readily available
24//! through the [`TransferSyntaxRegistry`] type.
25//!
26//! This registry is intended to be used in the development of higher level APIs,
27//! which should learn to negotiate and resolve the expected
28//! transfer syntax automatically.
29//!
30//! ## Transfer Syntaxes
31//!
32//! This crate encompasses basic DICOM level of conformance,
33//! plus support for some transfer syntaxes with compressed pixel data.
34//! _Implicit VR Little Endian_,
35//! _Explicit VR Little Endian_,
36//! and _Explicit VR Big Endian_
37//! are fully supported.
38//! Support may vary for transfer syntaxes which rely on encapsulated pixel data.
39//!
40//! | transfer syntax               | decoding support     | encoding support |
41//! |-------------------------------|----------------------|------------------|
42//! | Deflated Explicit VR Little Endian | Cargo feature `deflate` | ✓ |
43//! | JPEG Baseline (Process 1)     | Cargo feature `jpeg` | ✓ |
44//! | JPEG Extended (Process 2 & 4) | Cargo feature `jpeg` | x |
45//! | JPEG Lossless, Non-Hierarchical (Process 14) | Cargo feature `jpeg` | x |
46//! | JPEG Lossless, Non-Hierarchical, First-Order Prediction (Process 14 [Selection Value 1]) | Cargo feature `jpeg` | x |
47//! | JPEG-LS Lossless              | not supported here; see `src/dicom_io/jpeg_ls.rs` | - |
48//! | JPEG-LS Lossy (Near-Lossless) | not supported here; see `src/dicom_io/jpeg_ls.rs` | - |
49//! | JPEG 2000 (Lossless Only)     | Cargo feature `jpeg2000` (OpenJPEG) | x |
50//! | JPEG 2000                     | Cargo feature `jpeg2000` (OpenJPEG) | x |
51//! | JPEG 2000 Part 2 Multi-component Image Compression (Lossless Only) | Cargo feature `jpeg2000` (OpenJPEG) | x |
52//! | JPEG 2000 Part 2 Multi-component Image Compression | Cargo feature `jpeg2000` (OpenJPEG) | x |
53//! | JPIP Referenced Deflate       | Cargo feature `deflate` | ✓ |
54//! | High-Throughput JPEG 2000 (Lossless Only) | Cargo feature `jpeg2000` (OpenHTJ2K) | x (dcmnorm encodes it directly) |
55//! | High-Throughput JPEG 2000 with RPCL Options (Lossless Only) | Cargo feature `jpeg2000` (OpenHTJ2K) | x |
56//! | High-Throughput JPEG 2000     | Cargo feature `jpeg2000` (OpenHTJ2K) | x (dcmnorm encodes it directly) |
57//! | JPIP HTJ2K Referenced Deflate | Cargo feature `deflate` | ✓ |
58//! | JPEG XL (Lossless/Recompression/general) | Cargo feature `jpeg-xl-codec` on the top-level `dcmnorm` crate; see `src/dicom_io/jpeg_xl.rs` | x |
59//! | RLE Lossless                  | Cargo feature `rle` | x |
60//! | Deflated Image Frame          | Cargo feature `deflate` | ✓ |
61//!
62//! Cargo features behind `native` (`jpeg`, `rle`, `deflate`)
63//! provide implementations that are written in pure Rust (JPEG decoding via
64//! the in-house `dcmnorm-jpeg`, encoding via `jpeg-encoder`) and are likely
65//! available on all supported platforms without issues.
66//! Additional codecs are opt-in by enabling Cargo features,
67//! for scenarios where a native implementation is not available,
68//! or alternative implementations are available.
69//!
70//! - `jpeg2000` provides JPEG 2000 decoding through the `dcmnorm-jpeg2000` crate: OpenJPEG (C,
71//!   statically linked) for classic JPEG 2000 and the vendored OpenHTJ2K (C++) for
72//!   High-Throughput JPEG 2000. Neither can be used in WebAssembly.
73//!
74//! JPEG-LS and JPEG XL are not supported via this registry - see `entries.rs`
75//! for the reasoning. Transfer syntaxes which are not supported,
76//! either due to being unable to read the data set
77//! or decode encapsulated pixel data,
78//! are listed as _stubs_ for partial support.
79//! The full list is available in the [`entries`] module.
80
81use dcmnorm_encoding::transfer_syntax::{AdapterFreeTransferSyntax as Ts, Codec};
82use lazy_static::lazy_static;
83use std::collections::hash_map::Entry;
84use std::collections::HashMap;
85use std::fmt;
86
87pub use dcmnorm_encoding::{TransferSyntax, TransferSyntaxIndex};
88pub mod entries;
89
90pub(crate) mod alloc;
91
92mod adapters;
93#[cfg(feature = "deflate")]
94mod deflate;
95
96/// Main implementation of a registry of DICOM transfer syntaxes.
97///
98/// Consumers would generally use [`TransferSyntaxRegistry`] instead.
99pub struct TransferSyntaxRegistryImpl {
100    m: HashMap<&'static str, TransferSyntax>,
101}
102
103impl fmt::Debug for TransferSyntaxRegistryImpl {
104    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
105        let entries: HashMap<&str, &str> =
106            self.m.iter().map(|(uid, ts)| (*uid, ts.name())).collect();
107        f.debug_struct("TransferSyntaxRegistryImpl")
108            .field("m", &entries)
109            .finish()
110    }
111}
112
113impl TransferSyntaxRegistryImpl {
114    /// Obtain an iterator of all registered transfer syntaxes.
115    pub fn iter(&self) -> impl Iterator<Item = &TransferSyntax> {
116        self.m.values()
117    }
118
119    /// Obtain a DICOM codec by transfer syntax UID.
120    fn get<U: AsRef<str>>(&self, uid: U) -> Option<&TransferSyntax> {
121        let ts_uid = uid
122            .as_ref()
123            .trim_end_matches(|c: char| c.is_whitespace() || c == '\0');
124        self.m.get(ts_uid)
125    }
126
127    /// Register the given transfer syntax (TS) to the system. It can override
128    /// another TS with the same UID, in the only case that the TS requires
129    /// certain codecs which are not supported by the previously registered
130    /// TS. If no such requirements are imposed, this function returns `false`
131    /// and no changes are made.
132    fn register(&mut self, ts: TransferSyntax) -> bool {
133        match self.m.entry(ts.uid()) {
134            Entry::Occupied(mut e) => {
135                let replace = match (&e.get().codec(), ts.codec()) {
136                    (Codec::Dataset(None), Codec::Dataset(Some(_)))
137                    | (
138                        Codec::EncapsulatedPixelData(None, None),
139                        Codec::EncapsulatedPixelData(..),
140                    )
141                    | (
142                        Codec::EncapsulatedPixelData(Some(_), None),
143                        Codec::EncapsulatedPixelData(Some(_), Some(_)),
144                    )
145                    | (
146                        Codec::EncapsulatedPixelData(None, Some(_)),
147                        Codec::EncapsulatedPixelData(Some(_), Some(_)),
148                    ) => true,
149                    // weird one ahead: the two specifiers do not agree on
150                    // requirements, better keep it as a separate match arm for
151                    // debugging purposes
152                    (Codec::Dataset(None), Codec::EncapsulatedPixelData(_, _)) => {
153                        tracing::warn!("Inconsistent requirements for transfer syntax {}: `Dataset` cannot be replaced by `EncapsulatedPixelData`", ts.uid());
154                        false
155                    }
156                    // another weird one:
157                    // the two codecs do not agree on requirements
158                    (Codec::EncapsulatedPixelData(_, _), Codec::Dataset(None)) => {
159                        tracing::warn!("Inconsistent requirements for transfer syntax {}: `EncapsulatedPixelData` cannot be replaced by `Dataset`", ts.uid());
160                        false
161                    }
162                    // ignoring TS with less or equal implementation
163                    _ => false,
164                };
165
166                if replace {
167                    e.insert(ts);
168                    true
169                } else {
170                    false
171                }
172            }
173            Entry::Vacant(e) => {
174                e.insert(ts);
175                true
176            }
177        }
178    }
179}
180
181impl TransferSyntaxIndex for TransferSyntaxRegistryImpl {
182    #[inline]
183    fn get(&self, uid: &str) -> Option<&TransferSyntax> {
184        Self::get(self, uid)
185    }
186}
187
188impl TransferSyntaxRegistry {
189    /// Obtain an iterator of all registered transfer syntaxes.
190    #[inline]
191    pub fn iter(&self) -> impl Iterator<Item = &TransferSyntax> {
192        get_registry().iter()
193    }
194}
195
196/// Zero-sized representative of the main transfer syntax registry.
197#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash)]
198pub struct TransferSyntaxRegistry;
199
200impl TransferSyntaxIndex for TransferSyntaxRegistry {
201    #[inline]
202    fn get(&self, uid: &str) -> Option<&TransferSyntax> {
203        get_registry().get(uid)
204    }
205}
206
207lazy_static! {
208
209    static ref REGISTRY: TransferSyntaxRegistryImpl = {
210        let mut registry = TransferSyntaxRegistryImpl {
211            m: HashMap::with_capacity(64),
212        };
213
214        use self::entries::*;
215        let built_in_ts: [TransferSyntax; 46] = [
216            IMPLICIT_VR_LITTLE_ENDIAN.erased(),
217            EXPLICIT_VR_LITTLE_ENDIAN.erased(),
218            EXPLICIT_VR_BIG_ENDIAN.erased(),
219
220            ENCAPSULATED_UNCOMPRESSED_EXPLICIT_VR_LITTLE_ENDIAN.erased(),
221
222            DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN.erased(),
223            JPIP_REFERENCED_DEFLATE.erased(),
224            JPIP_HTJ2K_REFERENCED_DEFLATE.erased(),
225
226            JPEG_BASELINE.erased(),
227            JPEG_EXTENDED.erased(),
228            JPEG_LOSSLESS_NON_HIERARCHICAL.erased(),
229            JPEG_LOSSLESS_NON_HIERARCHICAL_FIRST_ORDER_PREDICTION.erased(),
230            JPEG_LS_LOSSLESS_IMAGE_COMPRESSION.erased(),
231            JPEG_LS_LOSSY_IMAGE_COMPRESSION.erased(),
232            JPEG_2000_IMAGE_COMPRESSION_LOSSLESS_ONLY.erased(),
233            JPEG_2000_IMAGE_COMPRESSION.erased(),
234            JPEG_2000_PART2_MULTI_COMPONENT_IMAGE_COMPRESSION_LOSSLESS_ONLY.erased(),
235            JPEG_2000_PART2_MULTI_COMPONENT_IMAGE_COMPRESSION.erased(),
236            HIGH_THROUGHPUT_JPEG_2000_IMAGE_COMPRESSION_LOSSLESS_ONLY.erased(),
237            HIGH_THROUGHPUT_JPEG_2000_WITH_RPCL_OPTIONS_IMAGE_COMPRESSION_LOSSLESS_ONLY.erased(),
238            HIGH_THROUGHPUT_JPEG_2000_IMAGE_COMPRESSION.erased(),
239            JPEG_XL_LOSSLESS.erased(),
240            JPEG_XL_RECOMPRESSION.erased(),
241            JPEG_XL.erased(),
242            JPIP_REFERENCED.erased(),
243            JPIP_HTJ2K_REFERENCED.erased(),
244            MPEG2_MAIN_PROFILE_MAIN_LEVEL.erased(),
245            FRAGMENTABLE_MPEG2_MAIN_PROFILE_MAIN_LEVEL.erased(),
246            MPEG2_MAIN_PROFILE_HIGH_LEVEL.erased(),
247            FRAGMENTABLE_MPEG2_MAIN_PROFILE_HIGH_LEVEL.erased(),
248            MPEG4_AVC_H264_HIGH_PROFILE.erased(),
249            FRAGMENTABLE_MPEG4_AVC_H264_HIGH_PROFILE.erased(),
250            MPEG4_AVC_H264_BD_COMPATIBLE_HIGH_PROFILE.erased(),
251            FRAGMENTABLE_MPEG4_AVC_H264_BD_COMPATIBLE_HIGH_PROFILE.erased(),
252            MPEG4_AVC_H264_HIGH_PROFILE_FOR_2D_VIDEO.erased(),
253            FRAGMENTABLE_MPEG4_AVC_H264_HIGH_PROFILE_FOR_2D_VIDEO.erased(),
254            MPEG4_AVC_H264_HIGH_PROFILE_FOR_3D_VIDEO.erased(),
255            FRAGMENTABLE_MPEG4_AVC_H264_HIGH_PROFILE_FOR_3D_VIDEO.erased(),
256            MPEG4_AVC_H264_STEREO_HIGH_PROFILE.erased(),
257            FRAGMENTABLE_MPEG4_AVC_H264_STEREO_HIGH_PROFILE.erased(),
258            HEVC_H265_MAIN_PROFILE.erased(),
259            HEVC_H265_MAIN_10_PROFILE.erased(),
260            RLE_LOSSLESS.erased(),
261            DEFLATED_IMAGE_FRAME_COMPRESSION.erased(),
262            SMPTE_ST_2110_20_UNCOMPRESSED_PROGRESSIVE.erased(),
263            SMPTE_ST_2110_20_UNCOMPRESSED_INTERLACED.erased(),
264            SMPTE_ST_2110_30_PCM.erased(),
265        ];
266
267        // add built-in TSes manually
268        for ts in built_in_ts {
269            registry.register(ts);
270        }
271
272        registry
273    };
274}
275
276/// Retrieve a reference to the global codec registry.
277#[inline]
278pub(crate) fn get_registry() -> &'static TransferSyntaxRegistryImpl {
279    &REGISTRY
280}
281
282/// create a TS with an unsupported pixel encapsulation
283pub(crate) const fn create_ts_stub(uid: &'static str, name: &'static str) -> Ts {
284    TransferSyntax::new_ele(uid, name, Codec::EncapsulatedPixelData(None, None))
285}
286
287/// Retrieve the default transfer syntax.
288pub fn default() -> Ts {
289    entries::IMPLICIT_VR_LITTLE_ENDIAN
290}
291
292#[cfg(test)]
293mod tests {
294    use dcmnorm_encoding::TransferSyntaxIndex;
295
296    use crate::TransferSyntaxRegistry;
297
298    #[test]
299    fn has_mandatory_tss() {
300        let implicit_vr_le = TransferSyntaxRegistry
301            .get("1.2.840.10008.1.2")
302            .expect("transfer syntax registry should provide Implicit VR Little Endian");
303        assert_eq!(implicit_vr_le.uid(), "1.2.840.10008.1.2");
304        assert!(implicit_vr_le.is_fully_supported());
305
306        // should also work with trailing null character
307        let implicit_vr_le_2 = TransferSyntaxRegistry.get("1.2.840.10008.1.2\0").expect(
308            "transfer syntax registry should provide Implicit VR Little Endian with padded TS UID",
309        );
310
311        assert_eq!(implicit_vr_le_2.uid(), implicit_vr_le.uid());
312
313        let explicit_vr_le = TransferSyntaxRegistry
314            .get("1.2.840.10008.1.2.1")
315            .expect("transfer syntax registry should provide Explicit VR Little Endian");
316        assert_eq!(explicit_vr_le.uid(), "1.2.840.10008.1.2.1");
317        assert!(explicit_vr_le.is_fully_supported());
318
319        // should also work with trailing null character
320        let explicit_vr_le_2 = TransferSyntaxRegistry.get("1.2.840.10008.1.2.1\0").expect(
321            "transfer syntax registry should provide Explicit VR Little Endian with padded TS UID",
322        );
323
324        assert_eq!(explicit_vr_le_2.uid(), explicit_vr_le.uid());
325    }
326
327    #[test]
328    fn provides_iter() {
329        let all_tss: Vec<_> = TransferSyntaxRegistry.iter().collect();
330
331        assert!(all_tss.len() >= 2);
332
333        // contains at least Implicit VR Little Endian and Explicit VR Little Endian
334        assert!(all_tss.iter().any(|ts| ts.uid() == "1.2.840.10008.1.2"));
335        assert!(all_tss.iter().any(|ts| ts.uid() == "1.2.840.10008.1.2.1"));
336    }
337}