dcmnorm-transcode 0.20.1

DICOM transfer-syntax registry and pixel codecs for dcmnorm, forked from dicom-transfer-syntax-registry 0.9.1. See README.md.
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
//! Support for JPG image decoding.

use dcmnorm_core::ops::{AttributeAction, AttributeOp};
use dcmnorm_core::{PrimitiveValue, Tag};
use dcmnorm_encoding::adapters::{
    decode_error, encode_error, DecodeResult, EncodeOptions, EncodeResult, PixelDataObject,
    PixelDataReader, PixelDataWriter,
};
use dcmnorm_encoding::snafu::prelude::*;
use dcmnorm_jpeg::{ColorTransform, Decoder};
use jpeg_encoder::ColorType;
use std::borrow::Cow;
use std::io::Cursor;

/// Pixel data adapter for JPEG-based transfer syntaxes.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct JpegAdapter;

impl PixelDataReader for JpegAdapter {
    /// Decode DICOM image data with jpeg encoding.
    fn decode(&self, src: &dyn PixelDataObject, dst: &mut Vec<u8>) -> DecodeResult<()> {
        let cols = src
            .cols()
            .context(decode_error::MissingAttributeSnafu { name: "Columns" })?;
        let rows = src
            .rows()
            .context(decode_error::MissingAttributeSnafu { name: "Rows" })?;
        let samples_per_pixel =
            src.samples_per_pixel()
                .context(decode_error::MissingAttributeSnafu {
                    name: "SamplesPerPixel",
                })?;
        let bits_allocated = src
            .bits_allocated()
            .context(decode_error::MissingAttributeSnafu {
                name: "BitsAllocated",
            })?;

        if bits_allocated != 8 && bits_allocated != 16 {
            whatever!("BitsAllocated other than 8 or 16 is not supported");
        }

        let nr_frames = src.number_of_frames().unwrap_or(1) as usize;
        let bytes_per_sample = bits_allocated / 8;

        // `stride` it the total number of bytes for each sample plane
        let stride: usize = bytes_per_sample as usize * cols as usize * rows as usize;
        let base_offset = dst.len();
        dst.resize(
            base_offset + (samples_per_pixel as usize * stride) * nr_frames,
            0,
        );

        let raw = src
            .raw_pixel_data()
            .whatever_context("Expected to have raw pixel data available")?;

        // Some embedded JPEGs might span multiple fragments.
        // Hence we collect all fragments into single vector
        // and then iterate a cursor for each frame
        // Note: not the most efficient way to do this,
        // consider optimizing later with bytes data structures
        let fragments: Vec<u8> = raw.fragments.into_iter().flatten().collect();

        let fragments_len = fragments.len() as u64;
        let mut cursor = Cursor::new(fragments);
        let mut dst_offset = base_offset;

        'frame_loop: for i in 0..nr_frames {
            let mut decoder = Decoder::new(&mut cursor);
            set_default_color_transform(&mut decoder, src);
            let decoded = decoder
                .decode()
                .map_err(|e| Box::new(e) as Box<_>)
                .with_whatever_context(|_| format!("JPEG decoding failure on frame {i}"))?;

            let decoded_len = decoded.len();
            dst[dst_offset..(dst_offset + decoded_len)].copy_from_slice(&decoded);
            dst_offset += decoded_len;

            if next_even(cursor.position()) >= next_even(fragments_len) {
                break;
            }

            // stop if there aren't enough bytes to continue
            if cursor.position() + 2 >= fragments_len {
                break;
            }

            // DICOM fragments should always have an even length,
            // filling this spacing with padding if it is odd.
            // Some implementations might add some padding,
            // whereas other might not.
            // So we check the next 2 bytes
            // until we find the SOI marker
            loop {
                let Some(next_byte_1) = cursor.get_ref().get(cursor.position() as usize).copied()
                else {
                    // no more frames to read
                    break 'frame_loop;
                };

                if next_byte_1 != 0xFF {
                    cursor.set_position(cursor.position() + 1);
                    continue;
                }

                let Some(next_byte_2) = cursor
                    .get_ref()
                    .get(cursor.position() as usize + 1)
                    .copied()
                else {
                    // no more frames to read
                    break 'frame_loop;
                };

                if next_byte_2 == 0xD8 {
                    // next frame found
                    break;
                }
                cursor.set_position(cursor.position() + 1);
            }
        }

        Ok(())
    }

    /// Decode DICOM image data with jpeg encoding.
    fn decode_frame(
        &self,
        src: &dyn PixelDataObject,
        frame: u32,
        dst: &mut Vec<u8>,
    ) -> DecodeResult<()> {
        let cols = src
            .cols()
            .context(decode_error::MissingAttributeSnafu { name: "Columns" })?;
        let rows = src
            .rows()
            .context(decode_error::MissingAttributeSnafu { name: "Rows" })?;
        let samples_per_pixel =
            src.samples_per_pixel()
                .context(decode_error::MissingAttributeSnafu {
                    name: "SamplesPerPixel",
                })?;
        let bits_allocated = src
            .bits_allocated()
            .context(decode_error::MissingAttributeSnafu {
                name: "BitsAllocated",
            })?;

        ensure_whatever!(
            bits_allocated == 8 || bits_allocated == 16,
            "BitsAllocated other than 8 or 16 is not supported"
        );

        let nr_frames = src.number_of_frames().unwrap_or(1) as usize;

        ensure!(
            nr_frames > frame as usize,
            decode_error::FrameRangeOutOfBoundsSnafu
        );

        let bytes_per_sample = bits_allocated / 8;

        // `stride` is the total number of bytes for each sample plane
        let stride: usize = bytes_per_sample as usize * cols as usize * rows as usize;
        let expected_len = samples_per_pixel as usize * stride;
        let base_offset = dst.len();

        // Common case first, checked without ever fetching the full `raw_pixel_data()` (which
        // clones every fragment): a 1:1 frame-to-fragment mapping only needs the one fragment
        // this call is actually about, available zero-copy via `fragment()`. This matters
        // because `decode_frame` is called once per frame for a multi-frame series (see
        // `decode_pixel_data_parallel_frames` in dcmnorm's own `io.rs`) - going through
        // `raw_pixel_data()` on every call would clone the *entire* pixel buffer each time,
        // O(frames^2) total bytes copied for an N-frame series where O(N) would do.
        let number_of_fragments = src.number_of_fragments().unwrap_or(0) as usize;
        let frame_data = if number_of_fragments == 1 || number_of_fragments == nr_frames {
            // assuming 1:1 frame-to-fragment mapping
            src.fragment(frame as usize).with_whatever_context(|| {
                format!("Missing fragment #{frame} for the frame requested")
            })?
        } else {
            // Some embedded JPEGs might span multiple fragments. This is the rare path (most
            // real encoders keep a 1:1 mapping), so the extra clone cost of `raw_pixel_data()`
            // here is acceptable - it's genuinely needed to 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 raw = src
                .raw_pixel_data()
                .whatever_context("Expected to have raw pixel data available")?;

            let base_offset = raw.offset_table.get(frame as usize).copied();
            let base_offset = if frame == 0 {
                base_offset.unwrap_or(0) as usize
            } else {
                base_offset
                    .with_whatever_context(|| format!("Missing offset for frame #{frame}"))?
                    as usize
            };
            let next_offset = raw.offset_table.get(frame as usize + 1);

            let mut offset = 0;
            let mut fragments = Vec::new();
            for fragment in &raw.fragments {
                // include it
                if offset >= base_offset {
                    fragments.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;
                    }
                }
            }

            Cow::Owned(fragments)
        };

        let mut cursor = Cursor::new(&*frame_data);

        let mut decoder = Decoder::new(&mut cursor);
        set_default_color_transform(&mut decoder, src);
        let decoded = decoder
            .decode()
            .map_err(|e| Box::new(e) as Box<_>)
            .whatever_context("JPEG decoder failure")?;

        if decoded.len() != expected_len {
            whatever!(
                "JPEG decoded length mismatch: expected {expected_len} bytes, got {}",
                decoded.len()
            );
        }

        if base_offset == 0 {
            *dst = decoded;
        } else {
            dst.resize(base_offset + expected_len, 0);
            dst[base_offset..(base_offset + expected_len)].copy_from_slice(&decoded);
        }

        Ok(())
    }
}

/// The colour space of a stream that declares none comes from Photometric Interpretation
/// (pohcee/dcmnorm#32): RGB with component identifiers 0,1,2 and no JFIF/Adobe marker is RGB,
/// not the YCbCr a standalone JPEG would default to.
fn set_default_color_transform<R: std::io::Read>(
    decoder: &mut Decoder<R>,
    src: &dyn PixelDataObject,
) {
    if src.photometric_interpretation().map(str::trim) == Some("RGB") {
        decoder.set_default_color_transform(ColorTransform::RGB);
    }
}

impl PixelDataWriter for JpegAdapter {
    fn encode_frame(
        &self,
        src: &dyn PixelDataObject,
        frame: u32,
        options: EncodeOptions,
        dst: &mut Vec<u8>,
    ) -> EncodeResult<Vec<AttributeOp>> {
        let cols = src
            .cols()
            .context(encode_error::MissingAttributeSnafu { name: "Columns" })?;
        let rows = src
            .rows()
            .context(encode_error::MissingAttributeSnafu { name: "Rows" })?;
        let samples_per_pixel =
            src.samples_per_pixel()
                .context(encode_error::MissingAttributeSnafu {
                    name: "SamplesPerPixel",
                })?;
        let bits_allocated = src
            .bits_allocated()
            .context(encode_error::MissingAttributeSnafu {
                name: "BitsAllocated",
            })?;
        let bits_stored = src
            .bits_stored()
            .context(encode_error::MissingAttributeSnafu { name: "BitsStored" })?;

        ensure_whatever!(
            bits_allocated == 8 || bits_allocated == 16,
            "BitsAllocated other than 8 or 16 is not supported"
        );

        let quality = options.quality.unwrap_or(85);

        let bytes_per_sample = (bits_allocated / 8) as usize;
        let frame_size =
            cols as usize * rows as usize * samples_per_pixel as usize * bytes_per_sample;

        let color_type = match samples_per_pixel {
            1 => ColorType::Luma,
            3 => ColorType::Rgb,
            _ => {
                whatever!("Unsupported samples per pixel: {}", samples_per_pixel)
            }
        };

        // record dst length before encoding to know full jpeg size
        let len_before = dst.len();

        // identify frame data using the frame index. The source pixel data being encoded here
        // is always uncompressed native format (one fragment holding all frames back-to-back),
        // so `fragment(0)` (zero-copy) is exactly the same data `raw_pixel_data().fragments[0]`
        // would give, without cloning it first - see decode_frame's doc comment for why that
        // matters when this runs once per frame.
        let pixeldata_uncompressed = src
            .fragment(0)
            .context(encode_error::MissingAttributeSnafu { name: "Pixel Data" })?;

        let frame_data = pixeldata_uncompressed
            .get(frame_size * frame as usize..frame_size * (frame as usize + 1))
            .whatever_context("Frame index out of bounds")?;

        let frame_data = narrow_8bit(frame_data, bits_stored)?;

        // Encode the data
        let mut encoder = jpeg_encoder::Encoder::new(&mut *dst, quality);
        encoder.set_progressive(false);
        // `jpeg-encoder` subsamples chroma (4:2:0) below quality 90, and not at all above
        let chroma_subsampled = encoder.sampling_factor() != jpeg_encoder::SamplingFactor::F_1_1;
        encoder
            .encode(&frame_data, cols, rows, color_type)
            .whatever_context("JPEG encoding failed")?;

        let compressed_frame_size = dst.len() - len_before;

        let compression_ratio = frame_size as f64 / compressed_frame_size as f64;
        let compression_ratio = format!("{compression_ratio:.6}");

        // provide attribute changes
        let mut changes = vec![
            // bits allocated
            AttributeOp::new(
                Tag(0x0028, 0x0100),
                AttributeAction::Set(PrimitiveValue::from(8_u16)),
            ),
            // bits stored
            AttributeOp::new(
                Tag(0x0028, 0x0101),
                AttributeAction::Set(PrimitiveValue::from(8_u16)),
            ),
            // high bit
            AttributeOp::new(
                Tag(0x0028, 0x0102),
                AttributeAction::Set(PrimitiveValue::from(7_u16)),
            ),
            // lossy image compression
            AttributeOp::new(Tag(0x0028, 0x2110), AttributeAction::SetStr("01".into())),
            // lossy image compression ratio
            AttributeOp::new(
                Tag(0x0028, 0x2112),
                AttributeAction::PushStr(compression_ratio.into()),
            ),
        ];

        let pmi = src.photometric_interpretation();

        if samples_per_pixel == 1 {
            // set Photometric Interpretation to Monochrome2
            // if it was neither of the expected monochromes
            if pmi != Some("MONOCHROME1") && pmi != Some("MONOCHROME2") {
                changes.push(AttributeOp::new(
                    Tag(0x0028, 0x0004),
                    AttributeAction::SetStr("MONOCHROME2".into()),
                ));
            }
        } else if samples_per_pixel == 3 {
            // set Photometric Interpretation to describe the compressed stream (PS3.5 Section
            // 8.2.1): `jpeg-encoder` converts the RGB samples to YCbCr, so YBR_FULL_422 when
            // chroma is subsampled (as upstream dicom-rs does), or YBR_FULL when it is not
            let ybr = if chroma_subsampled {
                "YBR_FULL_422"
            } else {
                "YBR_FULL"
            };
            if pmi != Some(ybr) {
                changes.push(AttributeOp::new(
                    Tag(0x0028, 0x0004),
                    AttributeAction::SetStr(ybr.into()),
                ));
            }
        }

        Ok(changes)
    }
}

fn next_even(l: u64) -> u64 {
    (l + 1) & !1
}

/// reduce data precision to 8 bits if necessary
/// data loss is possible
fn narrow_8bit(frame_data: &[u8], bits_stored: u16) -> EncodeResult<Cow<'_, [u8]>> {
    debug_assert!(bits_stored >= 8);
    match bits_stored {
        8 => Ok(Cow::Borrowed(frame_data)),
        9..=16 => {
            let mut v = Vec::with_capacity(frame_data.len() / 2);
            for chunk in frame_data.chunks(2) {
                let b = u16::from(chunk[0]) | (u16::from(chunk[1]) << 8);
                v.push((b >> (bits_stored - 8)) as u8);
            }
            Ok(Cow::Owned(v))
        }
        b => {
            whatever!("Unsupported Bits Stored {}", b)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::JpegAdapter;
    use dcmnorm_core::ops::{AttributeAction, AttributeOp};
    use dcmnorm_core::Tag;
    use dcmnorm_encoding::adapters::{
        EncodeOptions, PixelDataObject, PixelDataWriter, RawPixelData,
    };
    use std::borrow::Cow;

    /// A native 8-bit RGB single frame.
    struct NativeRgb {
        size: u16,
        samples: Vec<u8>,
    }

    impl PixelDataObject for NativeRgb {
        fn transfer_syntax_uid(&self) -> &str {
            "1.2.840.10008.1.2.1"
        }
        fn rows(&self) -> Option<u16> {
            Some(self.size)
        }
        fn cols(&self) -> Option<u16> {
            Some(self.size)
        }
        fn samples_per_pixel(&self) -> Option<u16> {
            Some(3)
        }
        fn bits_allocated(&self) -> Option<u16> {
            Some(8)
        }
        fn bits_stored(&self) -> Option<u16> {
            Some(8)
        }
        fn photometric_interpretation(&self) -> Option<&str> {
            Some("RGB")
        }
        fn number_of_frames(&self) -> Option<u32> {
            Some(1)
        }
        fn number_of_fragments(&self) -> Option<u32> {
            Some(1)
        }
        fn fragment(&self, fragment: usize) -> Option<Cow<'_, [u8]>> {
            (fragment == 0).then(|| Cow::Borrowed(&self.samples[..]))
        }
        fn offset_table(&self) -> Option<Cow<'_, [u32]>> {
            None
        }
        fn raw_pixel_data(&self) -> Option<RawPixelData> {
            None
        }
    }

    fn encode_red_square(quality: Option<u8>) -> (Vec<AttributeOp>, Vec<u8>) {
        let size = 16;
        let samples = [255u8, 0, 0]
            .iter()
            .copied()
            .cycle()
            .take(size as usize * size as usize * 3)
            .collect();
        let mut options = EncodeOptions::new();
        options.quality = quality;
        let mut encoded = Vec::new();
        let ops = JpegAdapter
            .encode_frame(&NativeRgb { size, samples }, 0, options, &mut encoded)
            .expect("JPEG frame encoding should succeed");
        (ops, encoded)
    }

    fn photometric_interpretation_set(ops: &[AttributeOp]) -> Option<String> {
        ops.iter()
            .find(|op| op.selector == Tag(0x0028, 0x0004).into())
            .map(|op| match &op.action {
                AttributeAction::SetStr(value) => value.to_string(),
                other => panic!("unexpected Photometric Interpretation action {:?}", other),
            })
    }

    /// Port of upstream dicom-rs's `write_jpeg_baseline_sets_ybr_full_422` (636ae060): the encoder
    /// converts RGB samples to YCbCr, so the object must no longer say RGB. At the default quality
    /// `jpeg-encoder` also subsamples chroma, hence YBR_FULL_422.
    #[test]
    fn encoding_rgb_labels_the_result_ybr_full_422_when_chroma_is_subsampled() {
        let (ops, encoded) = encode_red_square(None);
        assert_eq!(
            photometric_interpretation_set(&ops).as_deref(),
            Some("YBR_FULL_422")
        );

        // and the codestream agrees: `jpeg-encoder` writes a JFIF stream, which is YCbCr,
        // with 2x2 sampling on the luma component of the 3-component SOF0 frame header
        assert_eq!(&encoded[0..2], &[0xFF, 0xD8], "expected SOI marker");
        assert_eq!(&encoded[2..4], &[0xFF, 0xE0], "expected APP0 marker");
        assert_eq!(&encoded[6..11], b"JFIF\0", "expected JFIF identifier");
        assert_eq!(sof0_luma_sampling(&encoded), 0x22);
    }

    /// Without chroma subsampling (quality 90 and above), the stream is plain YCbCr 4:4:4.
    #[test]
    fn encoding_rgb_labels_the_result_ybr_full_without_chroma_subsampling() {
        let (ops, encoded) = encode_red_square(Some(95));
        assert_eq!(
            photometric_interpretation_set(&ops).as_deref(),
            Some("YBR_FULL")
        );
        assert_eq!(sof0_luma_sampling(&encoded), 0x11);
    }

    /// Sampling factors (H << 4 | V) of the first component in the SOF0 segment.
    fn sof0_luma_sampling(jpeg: &[u8]) -> u8 {
        let sof = jpeg
            .windows(2)
            .position(|w| w == [0xFF, 0xC0])
            .expect("baseline SOF0 marker");
        // FFC0, length (2), precision (1), height (2), width (2), components (1), then
        // per component: id (1), sampling (1), quantization table (1)
        assert_eq!(jpeg[sof + 9], 3, "expected a 3-component frame");
        jpeg[sof + 11]
    }
}