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
#![deny(trivial_numeric_casts, unsafe_code, unstable_features)]
#![warn(
    missing_debug_implementations,
    missing_docs,
    unused_qualifications,
    unused_import_braces
)]
//! This crate contains the DICOM transfer syntax registry.
//! The transfer syntax registry maps a DICOM UID of a transfer syntax into the
//! respective transfer syntax specifier. In the default implementation, the
//! container of transfer syntaxes is populated before-main through the
//! [inventory] pattern, then making all registerd TSes readily available
//! through the [`TransferSyntaxRegistry`] type.
//!
//! The default Cargo feature `inventory-registry` can be deactivated for
//! environments which do not support `inventory`, with the downside of only
//! providing the built-in transfer syntaxes.
//!
//! This registry should not have to be used directly, except when developing
//! higher level APIs, which should learn to negotiate and resolve the expected
//! transfer syntax automatically.
//!
//! ## Transfer Syntax descriptors
//!
//! This crate encompasses the basic DICOM level of conformance:
//! _Implicit VR Little Endian_,
//! _Explicit VR Little Endian_,
//! and _Explicit VR Big Endian_ are built-in.
//! Transfer syntaxes which are not supported,
//! or which rely on encapsulated pixel data,
//! are only listed as _stubs_ to be replaced by separate libraries.
//! The full list is available in the [`entries`](entries) module.
//!
//! [inventory]: https://docs.rs/inventory/0.1.4/inventory

use byteordered::Endianness;
use dicom_encoding::transfer_syntax::{
    AdapterFreeTransferSyntax as Ts, Codec, TransferSyntaxIndex,
};
use lazy_static::lazy_static;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::fmt;

pub use dicom_encoding::TransferSyntax;
pub mod entries;

/// Data type for a registry of DICOM.
pub struct TransferSyntaxRegistryImpl {
    m: HashMap<&'static str, TransferSyntax>,
}

impl fmt::Debug for TransferSyntaxRegistryImpl {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let entries: HashMap<&str, &str> =
            self.m.iter().map(|(uid, ts)| (*uid, ts.name())).collect();
        f.debug_struct("TransferSyntaxRegistryImpl")
            .field("m", &entries)
            .finish()
    }
}

impl TransferSyntaxRegistryImpl {
    /// Obtain an iterator of all registered transfer syntaxes.
    pub fn iter(&self) -> impl Iterator<Item = &TransferSyntax> {
        self.m.values()
    }

    /// Obtain a DICOM codec by transfer syntax UID.
    fn get<U: AsRef<str>>(&self, uid: U) -> Option<&TransferSyntax> {
        let ts_uid = uid
            .as_ref()
            .trim_end_matches(|c: char| c.is_whitespace() || c == '\0');
        self.m.get(ts_uid)
    }

    /// Register the given transfer syntax (TS) to the system. It can override
    /// another TS with the same UID, in the only case that the TS requires
    /// certain codecs which are not supported by the previously registered
    /// TS. If no such requirements are imposed, this function returns `false`
    /// and no changes are made.
    fn register(&mut self, ts: TransferSyntax) -> bool {
        match self.m.entry(ts.uid()) {
            Entry::Occupied(mut e) => {
                let replace = match (&e.get().codec(), ts.codec()) {
                    (Codec::Unsupported, Codec::Dataset(_))
                    | (Codec::EncapsulatedPixelData, Codec::PixelData(_)) => true,
                    // weird one ahead: the two specifiers do not agree on
                    // requirements, better keep it as a separate match arm for
                    // debugging purposes
                    (Codec::Unsupported, Codec::PixelData(_)) => {
                        tracing::warn!("Inconsistent requirements for transfer syntax {}: `Unsupported` cannot be replaced with `PixelData`", ts.uid());
                        false
                    }
                    // ignoring TS with less or equal implementation
                    _ => false,
                };

                if replace {
                    e.insert(ts);
                    true
                } else {
                    false
                }
            }
            Entry::Vacant(e) => {
                e.insert(ts);
                true
            }
        }
    }
}

impl TransferSyntaxIndex for TransferSyntaxRegistryImpl {
    #[inline]
    fn get(&self, uid: &str) -> Option<&TransferSyntax> {
        Self::get(self, uid)
    }
}

impl TransferSyntaxRegistry {
    /// Obtain an iterator of all registered transfer syntaxes.
    #[inline]
    pub fn iter(&self) -> impl Iterator<Item = &TransferSyntax> {
        get_registry().iter()
    }
}

/// Zero-sized representative of the main transfer syntax registry.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash)]
pub struct TransferSyntaxRegistry;

impl TransferSyntaxIndex for TransferSyntaxRegistry {
    #[inline]
    fn get(&self, uid: &str) -> Option<&TransferSyntax> {
        get_registry().get(uid)
    }
}

lazy_static! {

    static ref REGISTRY: TransferSyntaxRegistryImpl = {
        let mut registry = TransferSyntaxRegistryImpl {
            m: HashMap::with_capacity(32),
        };

        use self::entries::*;
        let built_in_ts: [TransferSyntax; 29] = [
            IMPLICIT_VR_LITTLE_ENDIAN.erased(),
            EXPLICIT_VR_LITTLE_ENDIAN.erased(),
            EXPLICIT_VR_BIG_ENDIAN.erased(),

            DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN.erased(),
            JPIP_REFERENCED_DEFLATE.erased(),
            JPEG_BASELINE.erased(),
            JPEG_EXTENDED.erased(),
            JPEG_LOSSLESS_NON_HIERARCHICAL.erased(),
            JPEG_LOSSLESS_NON_HIERARCHICAL_FIRST_ORDER_PREDICTION.erased(),
            JPEG_LS_LOSSLESS_IMAGE_COMPRESSION.erased(),
            JPEG_LS_LOSSY_IMAGE_COMPRESSION.erased(),
            JPEG_2000_IMAGE_COMPRESSION_LOSSLESS_ONLY.erased(),
            JPEG_2000_IMAGE_COMPRESSION.erased(),
            JPEG_2000_PART2_MULTI_COMPONENT_IMAGE_COMPRESSION_LOSSLESS_ONLY.erased(),
            JPEG_2000_PART2_MULTI_COMPONENT_IMAGE_COMPRESSION.erased(),
            JPIP_REFERENCED.erased(),
            MPEG2_MAIN_PROFILE_MAIN_LEVEL.erased(),
            MPEG2_MAIN_PROFILE_HIGH_LEVEL.erased(),
            MPEG4_AVC_H264_HIGH_PROFILE.erased(),
            MPEG4_AVC_H264_BD_COMPATIBLE_HIGH_PROFILE.erased(),
            MPEG4_AVC_H264_HIGH_PROFILE_FOR_2D_VIDEO.erased(),
            MPEG4_AVC_H264_HIGH_PROFILE_FOR_3D_VIDEO.erased(),
            MPEG4_AVC_H264_STEREO_HIGH_PROFILE.erased(),
            HEVC_H265_MAIN_PROFILE.erased(),
            HEVC_H265_MAIN_10_PROFILE.erased(),
            RLE_LOSSLESS.erased(),
            SMPTE_ST_2110_20_UNCOMPRESSED_PROGRESSIVE.erased(),
            SMPTE_ST_2110_20_UNCOMPRESSED_INTERLACED.erased(),
            SMPTE_ST_2110_30_PCM.erased(),
        ];

        // add built-in TSes manually
        for ts in built_in_ts {
            registry.register(ts);
        }
        // add TSes from inventory, if available
        inventory_populate(&mut registry);

        registry
    };
}

#[cfg(feature = "inventory-registry")]
#[inline]
fn inventory_populate(registry: &mut TransferSyntaxRegistryImpl) {
    use dicom_encoding::transfer_syntax::TransferSyntaxFactory;

    for TransferSyntaxFactory(tsf) in inventory::iter::<TransferSyntaxFactory> {
        let ts = tsf();
        registry.register(ts);
    }
}

#[cfg(not(feature = "inventory-registry"))]
#[inline]
fn inventory_populate(_: &mut TransferSyntaxRegistryImpl) {
    // do nothing
}

/// Retrieve a reference to the global codec registry.
#[inline]
pub(crate) fn get_registry() -> &'static TransferSyntaxRegistryImpl {
    &REGISTRY
}

/// create a TS with an unsupported pixel encapsulation
pub(crate) const fn create_ts_stub(uid: &'static str, name: &'static str) -> Ts {
    TransferSyntax::new(
        uid,
        name,
        Endianness::Little,
        true,
        Codec::EncapsulatedPixelData,
    )
}

/// Retrieve the default transfer syntax.
pub fn default() -> Ts {
    entries::IMPLICIT_VR_LITTLE_ENDIAN
}

#[cfg(test)]
mod tests {
    use dicom_encoding::TransferSyntaxIndex;

    use crate::TransferSyntaxRegistry;

    #[test]
    fn has_mandatory_tss() {
        let implicit_vr_le = TransferSyntaxRegistry
            .get("1.2.840.10008.1.2")
            .expect("transfer syntax registry should provide Implicit VR Little Endian");
        assert_eq!(implicit_vr_le.uid(), "1.2.840.10008.1.2");
        assert!(implicit_vr_le.fully_supported());

        // should also work with trailing null character
        let implicit_vr_le_2 = TransferSyntaxRegistry.get("1.2.840.10008.1.2\0").expect(
            "transfer syntax registry should provide Implicit VR Little Endian with padded TS UID",
        );

        assert_eq!(implicit_vr_le_2.uid(), implicit_vr_le.uid());

        let explicit_vr_le = TransferSyntaxRegistry
            .get("1.2.840.10008.1.2.1")
            .expect("transfer syntax registry should provide Explicit VR Little Endian");
        assert_eq!(explicit_vr_le.uid(), "1.2.840.10008.1.2.1");
        assert!(explicit_vr_le.fully_supported());

        // should also work with trailing null character
        let explicit_vr_le_2 = TransferSyntaxRegistry.get("1.2.840.10008.1.2.1\0").expect(
            "transfer syntax registry should provide Explicit VR Little Endian with padded TS UID",
        );

        assert_eq!(explicit_vr_le_2.uid(), explicit_vr_le.uid());
    }

    #[test]
    fn provides_iter() {
        let all_tss: Vec<_> = TransferSyntaxRegistry.iter().collect();

        assert!(all_tss.len() >= 2);

        // contains at least Implicit VR Little Endian and Explicit VR Little Endian
        assert!(all_tss.iter().any(|ts| ts.uid() == "1.2.840.10008.1.2"));
        assert!(all_tss.iter().any(|ts| ts.uid() == "1.2.840.10008.1.2.1"));
    }
}