dcmnorm 0.22.4

Fast DICOM toolkit: parse, render, transcode, reformat, de-identify and network (DIMSE) DICOM medical images.
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
#[cfg(feature = "jpeg-ls-codec")]
pub mod jpeg_ls_impl {
    use std::borrow::Cow;
    use std::ops::Range;

    use crate::dicom_io::io::encapsulated_frame_fragment_range;
    use dcmnorm_dictionary::tags;
    use dcmnorm_object::DefaultDicomObject;

    /// Near-lossless quantization step used for `.81` (JPEG-LS Lossy) encoding. `near=0` would be
    /// lossless (that's what `.80` uses instead); a small value keeps visible error bounded to a
    /// couple of stored-value counts per sample, matching the modest quality loss real-world
    /// JPEG-LS Lossy presets (e.g. DCMTK's `+E1`/`+ee`) typically target rather than picking an
    /// arbitrary large value that would look closer to a completely different, more lossy codec.
    pub(crate) const NEAR_LOSSLESS_STEP: i32 = 3;

    /// Decode JPEG-LS encoded pixel data - every frame's worth, concatenated into one flat
    /// native-byte-order buffer matching what `replace_with_native_pixel_data` expects.
    ///
    /// One fragment per frame (not the more flexible offset-table-based fragmentation JPEG2000
    /// allows) is the standard DICOM encapsulation convention for JPEG-LS (PS3.5 A.4), so each
    /// fragment is decoded independently - concatenating the still-*encoded* fragments before a
    /// single decode call would feed multiple independent codestreams into one decode as if they
    /// were one, silently corrupting every frame after the first on real multi-frame files. A
    /// frame split over several fragments is reassembled through the offset tables when they
    /// map every frame (`encapsulated_frame_fragment_range`), the same mapping
    /// `decode_jpeg_ls_frame` uses for a single frame.
    pub fn decode_jpeg_ls_pixel_data(object: &DefaultDicomObject) -> Result<Vec<u8>, String> {
        let fragments = encapsulated_fragments(object)?;
        let (rows, cols) = dimensions(object)?;

        // A single frame keeps the historical fragment-by-fragment decode (no reassembly),
        // whatever its fragment count.
        let number_of_frames = number_of_frames(object);
        if number_of_frames > 1 && fragments.len() != number_of_frames {
            let ranges: Option<Vec<_>> = (0..number_of_frames)
                .map(|frame_index| encapsulated_frame_fragment_range(object, frame_index))
                .collect();
            if let Some(ranges) = ranges {
                let total = ranges.len();
                let mut decoded = Vec::new();
                for (index, range) in ranges.into_iter().enumerate() {
                    let frame = decode_codestream(&frame_codestream(fragments, range), rows, cols)?;
                    if index == 0 && total > 1 {
                        let _ = decoded.try_reserve(frame.len().saturating_mul(total));
                    }
                    decoded.extend_from_slice(&frame);
                }
                return Ok(decoded);
            }
        }

        // One fragment per frame. `dcmnorm_jpegls` decodes samples into little-endian byte
        // order, matching what every other codec here hands to `replace_with_native_pixel_data`.
        let total = fragments.len();
        let mut decoded = Vec::new();
        for (index, fragment) in fragments.iter().enumerate() {
            let frame = decode_codestream(fragment, rows, cols)?;
            if index == 0 && total > 1 {
                let _ = decoded.try_reserve(frame.len().saturating_mul(total));
            }
            decoded.extend_from_slice(&frame);
        }

        Ok(decoded)
    }

    /// Decode only frame `frame_index` of multi-frame JPEG-LS pixel data: exactly the bytes
    /// `decode_jpeg_ls_pixel_data` produces for that frame, without decoding any other frame.
    ///
    /// `Ok(None)` when the frame can't be located among the fragments (see
    /// `encapsulated_frame_fragment_range`): the caller then falls back to the full decode,
    /// which reports the error for a malformed file.
    pub fn decode_jpeg_ls_frame(
        object: &DefaultDicomObject,
        frame_index: usize,
    ) -> Result<Option<Vec<u8>>, String> {
        let Some(range) = encapsulated_frame_fragment_range(object, frame_index) else {
            return Ok(None);
        };
        if number_of_frames(object) == 1 && range.len() > 1 {
            // `decode_jpeg_ls_pixel_data` decodes these fragment by fragment; leave it to that.
            return Ok(None);
        }
        let fragments = encapsulated_fragments(object)?;
        let (rows, cols) = dimensions(object)?;
        decode_codestream(&frame_codestream(fragments, range), rows, cols).map(Some)
    }

    fn number_of_frames(object: &DefaultDicomObject) -> usize {
        object
            .get(tags::NUMBER_OF_FRAMES)
            .and_then(|e| e.to_str().ok())
            .and_then(|s| s.trim().parse::<usize>().ok())
            .unwrap_or(1)
            .max(1)
    }

    fn encapsulated_fragments(object: &DefaultDicomObject) -> Result<&[Vec<u8>], String> {
        let fragments = object
            .element(tags::PIXEL_DATA)
            .map_err(|e| format!("missing PixelData: {e}"))?
            .fragments()
            .ok_or_else(|| "expected encapsulated JPEG-LS pixel data".to_owned())?;
        if fragments.is_empty() {
            return Err("no JPEG-LS data to decode".to_owned());
        }
        Ok(fragments)
    }

    fn dimensions(object: &DefaultDicomObject) -> Result<(u32, u32), String> {
        let rows = object
            .get(tags::ROWS)
            .and_then(|e| e.uint16().ok())
            .ok_or_else(|| "missing Rows attribute".to_owned())? as u32;
        let cols = object
            .get(tags::COLUMNS)
            .and_then(|e| e.uint16().ok())
            .ok_or_else(|| "missing Columns attribute".to_owned())? as u32;
        Ok((rows, cols))
    }

    /// The frame's codestream: its one fragment borrowed, or its fragments joined.
    fn frame_codestream(fragments: &[Vec<u8>], range: Range<usize>) -> Cow<'_, [u8]> {
        if range.len() == 1 {
            Cow::Borrowed(fragments[range.start].as_slice())
        } else {
            Cow::Owned(fragments[range].concat())
        }
    }

    /// Decode one JPEG-LS codestream (one frame), checking its header against Rows/Columns
    /// first - a mismatch here means either a corrupt fragment or the wrong PixelData
    /// attributes, and either way is worth a clear error instead of the confusing shape
    /// mismatch that would otherwise surface downstream. `dcmnorm-jpegls` decodes samples into
    /// native (little-endian) byte order.
    pub fn decode_codestream(codestream: &[u8], rows: u32, cols: u32) -> Result<Vec<u8>, String> {
        if codestream.is_empty() {
            return Err("empty JPEG-LS fragment".to_owned());
        }

        let frame_info = dcmnorm_jpegls::read_frame_info(codestream)
            .map_err(|e| format!("failed to read JPEG-LS header: {e}"))?;
        if frame_info.width != cols || frame_info.height != rows {
            return Err(format!(
                "JPEG-LS codestream dimensions ({}x{}) do not match DICOM Rows/Columns ({rows}x{cols})",
                frame_info.width, frame_info.height
            ));
        }

        // Size budget for the decoded byte buffer; dimensions already matched DICOM Rows/Columns.
        let bps = if frame_info.bits_per_sample <= 8 {
            1
        } else {
            2
        };
        let required_bytes = (rows as usize)
            .saturating_mul(cols as usize)
            .saturating_mul(usize::from(frame_info.components))
            .saturating_mul(bps);
        let opts = dcmnorm_jpegls::DecodeImageOptions {
            max_decoded_bytes: required_bytes.max(64 * 1024 * 1024),
        };
        // Decode directly into a single sample-interleaved byte buffer (PlanarConfiguration=0),
        // including 3-component ILV=0 planar streams, without allocating a second full-frame buffer.
        dcmnorm_jpegls::decode_to_interleaved_bytes_with_options(codestream, &opts)
            .map(|(bytes, _)| bytes)
            .map_err(|e| format!("JPEG-LS decode failed: {e}"))
    }

    pub fn encode_jpeg_ls_frame(
        frame_bytes: &[u8],
        rows: u16,
        cols: u16,
        samples_per_pixel: u16,
        bits_stored: u16,
        planar_configuration: u16,
        lossless: bool,
    ) -> Result<Vec<u8>, String> {
        let near = if lossless {
            0
        } else {
            NEAR_LOSSLESS_STEP as u8
        };
        let interleave_mode = if samples_per_pixel > 1 && planar_configuration == 0 {
            2
        } else {
            0
        };
        let components = u8::try_from(samples_per_pixel)
            .map_err(|_| format!("unsupported SamplesPerPixel {samples_per_pixel}"))?;
        let bits = u8::try_from(bits_stored)
            .map_err(|_| format!("unsupported BitsStored {bits_stored}"))?;

        // DICOM allows unused high bits in 8-bit and 16-bit containers (e.g. sign-extended
        // negative 12-bit CT values like 0xFFFF, or 7-bit-in-8-bit with bit 7 set). Mask
        // them to `bits_stored` bits before handing to JPEG-LS, matching CharLS's input
        // masking without copying when all samples are already in range.
        let masked_buf: Vec<u8>;
        let encode_input: &[u8] = if (2..8).contains(&bits) {
            let mask = (1u8 << bits) - 1;
            if frame_bytes.iter().any(|&b| b > mask) {
                masked_buf = frame_bytes.iter().map(|&b| b & mask).collect();
                &masked_buf
            } else {
                frame_bytes
            }
        } else if (9..16).contains(&bits) {
            let mask = (1u16 << bits) - 1;
            let needs_mask = frame_bytes
                .as_chunks::<2>()
                .0
                .iter()
                .any(|&c| u16::from_le_bytes(c) > mask);
            if needs_mask {
                let mut buf = Vec::with_capacity(frame_bytes.len());
                for &c in frame_bytes.as_chunks::<2>().0 {
                    buf.extend_from_slice(&(u16::from_le_bytes(c) & mask).to_le_bytes());
                }
                masked_buf = buf;
                &masked_buf
            } else {
                frame_bytes
            }
        } else {
            frame_bytes
        };

        dcmnorm_jpegls::encode_bytes(
            encode_input,
            u32::from(cols),
            u32::from(rows),
            components,
            bits,
            near,
            interleave_mode,
        )
        .map_err(|e| format!("{e}"))
    }

    /// Encode raw native pixel data to JPEG-LS, one fragment per frame - the mirror image of
    /// `decode_jpeg_ls_pixel_data` above, and matching the "one fragment per frame" convention
    /// its own doc comment explains.
    pub fn encode_jpeg_ls_pixel_data(
        object: &DefaultDicomObject,
        lossless: bool,
    ) -> Result<Vec<Vec<u8>>, String> {
        let pixel_data = object
            .element(tags::PIXEL_DATA)
            .map_err(|e| format!("missing PixelData: {e}"))?
            .to_bytes()
            .map_err(|e| format!("failed to access pixel data: {e}"))?;

        let rows = object
            .get(tags::ROWS)
            .and_then(|e| e.uint16().ok())
            .ok_or_else(|| "missing Rows attribute".to_owned())?;
        let cols = object
            .get(tags::COLUMNS)
            .and_then(|e| e.uint16().ok())
            .ok_or_else(|| "missing Columns attribute".to_owned())?;
        let samples_per_pixel = object
            .get(tags::SAMPLES_PER_PIXEL)
            .and_then(|e| e.uint16().ok())
            .unwrap_or(1);
        let bits_allocated = object
            .get(tags::BITS_ALLOCATED)
            .and_then(|e| e.uint16().ok())
            .ok_or_else(|| "missing BitsAllocated attribute".to_owned())?;
        // JPEG-LS's own sample precision, not the (possibly wider) storage container - e.g.
        // 12-bit CT data allocated in 16-bit words encodes with bits_per_sample: 12. Lossless
        // round-tripping only needs this to exactly match what the encoder used, not to reflect
        // anything about signedness: JPEG-LS's predictive coding operates on the raw sample
        // bit pattern either way, and reproduces those exact bits back out on decode.
        let bits_stored = object
            .get(tags::BITS_STORED)
            .and_then(|e| e.uint16().ok())
            .unwrap_or(bits_allocated);
        let number_of_frames = object
            .get(tags::NUMBER_OF_FRAMES)
            .and_then(|e| e.to_str().ok())
            .and_then(|s| s.trim().parse::<usize>().ok())
            .unwrap_or(1)
            .max(1);
        let planar_configuration = object
            .get(tags::PLANAR_CONFIGURATION)
            .and_then(|e| e.uint16().ok())
            .unwrap_or(0);

        if bits_allocated == 0 || bits_allocated > 16 {
            return Err(format!(
                "unsupported BitsAllocated for JPEG-LS encoding: {bits_allocated}"
            ));
        }
        if bits_allocated == 16 && bits_stored <= 8 {
            return Err(format!(
                "unsupported BitsAllocated={bits_allocated} with BitsStored={bits_stored} for JPEG-LS encoding"
            ));
        }
        let bytes_per_sample = if bits_allocated <= 8 { 1usize } else { 2usize };
        let frame_len = usize::from(rows)
            * usize::from(cols)
            * usize::from(samples_per_pixel)
            * bytes_per_sample;
        let expected_len = frame_len * number_of_frames;
        if pixel_data.len() < expected_len {
            return Err(format!(
                "PixelData too short for {number_of_frames} frame(s) of {rows}x{cols}x{samples_per_pixel} \
                 at {bits_allocated} bits allocated: expected at least {expected_len} bytes, got {}",
                pixel_data.len()
            ));
        }

        let mut fragments = Vec::with_capacity(number_of_frames);
        for frame_index in 0..number_of_frames {
            let start = frame_index * frame_len;
            let frame_bytes = &pixel_data[start..start + frame_len];
            let encoded = encode_jpeg_ls_frame(
                frame_bytes,
                rows,
                cols,
                samples_per_pixel,
                bits_stored,
                planar_configuration,
                lossless,
            )
            .map_err(|e| format!("JPEG-LS encode failed for frame {frame_index}: {e}"))?;
            fragments.push(encoded);
        }

        Ok(fragments)
    }
}

#[cfg(not(feature = "jpeg-ls-codec"))]
pub mod jpeg_ls_impl {
    use dcmnorm_object::DefaultDicomObject;

    pub fn decode_jpeg_ls_pixel_data(_object: &DefaultDicomObject) -> Result<Vec<u8>, String> {
        Err("JPEG-LS codec support requires 'jpeg-ls-codec' feature to be enabled".to_owned())
    }

    pub fn decode_jpeg_ls_frame(
        _object: &DefaultDicomObject,
        _frame_index: usize,
    ) -> Result<Option<Vec<u8>>, String> {
        Err("JPEG-LS codec support requires 'jpeg-ls-codec' feature to be enabled".to_owned())
    }

    pub fn decode_codestream(
        _codestream: &[u8],
        _rows: u32,
        _cols: u32,
    ) -> Result<Vec<u8>, String> {
        Err("JPEG-LS codec support requires 'jpeg-ls-codec' feature to be enabled".to_owned())
    }

    #[allow(clippy::too_many_arguments)]
    pub fn encode_jpeg_ls_frame(
        _frame_bytes: &[u8],
        _rows: u16,
        _cols: u16,
        _samples_per_pixel: u16,
        _bits_stored: u16,
        _planar_configuration: u16,
        _lossless: bool,
    ) -> Result<Vec<u8>, String> {
        Err("JPEG-LS codec support requires 'jpeg-ls-codec' feature to be enabled".to_owned())
    }

    pub fn encode_jpeg_ls_pixel_data(
        _object: &DefaultDicomObject,
        _lossless: bool,
    ) -> Result<Vec<Vec<u8>>, String> {
        Err("JPEG-LS codec support requires 'jpeg-ls-codec' feature to be enabled".to_owned())
    }
}

pub use jpeg_ls_impl::{
    decode_codestream as decode_jpeg_ls_codestream, decode_jpeg_ls_frame,
    decode_jpeg_ls_pixel_data, encode_jpeg_ls_frame, encode_jpeg_ls_pixel_data,
};

#[cfg(test)]
mod tests {
    use super::{decode_jpeg_ls_pixel_data, encode_jpeg_ls_pixel_data};
    use crate::dicom_io::read_dicom_file;
    use dcmnorm_object::DefaultDicomObject;
    use std::path::PathBuf;

    fn fixture(name: &str) -> DefaultDicomObject {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("test")
            .join("files")
            .join(name);
        read_dicom_file(path).expect("fixture should be readable")
    }

    /// Encodes `mr_small.dcm`'s own native (uncompressed) pixel data to JPEG-LS Lossless and
    /// decodes it straight back, entirely in memory (no transcode/file round trip) - the
    /// tightest possible test of `encode_jpeg_ls_pixel_data`/`decode_jpeg_ls_pixel_data`
    /// agreeing with each other, independent of `mr_jpegls_lossless.dcm`'s own third-party
    /// encoder.
    #[test]
    fn lossless_encode_then_decode_round_trips_exactly() {
        let object = fixture("mr_small.dcm");
        let original_bytes = object
            .element(dcmnorm_dictionary::tags::PIXEL_DATA)
            .unwrap()
            .to_bytes()
            .unwrap()
            .to_vec();

        let fragments =
            encode_jpeg_ls_pixel_data(&object, true).expect("lossless encode should succeed");
        assert_eq!(
            fragments.len(),
            1,
            "single-frame source should produce exactly one fragment"
        );

        // Rebuild an object carrying the encoded fragment as encapsulated PixelData, the same
        // shape decode_jpeg_ls_pixel_data expects from a real file.
        let mut encoded_object = object.clone();
        encoded_object.put(dcmnorm_core::DataElement::new(
            dcmnorm_dictionary::tags::PIXEL_DATA,
            dcmnorm_core::VR::OB,
            dcmnorm_core::value::PixelFragmentSequence::new(vec![0], fragments),
        ));

        let decoded = decode_jpeg_ls_pixel_data(&encoded_object).expect("decode should succeed");
        assert_eq!(decoded, original_bytes);
    }

    /// Near-lossless (.81) must bound every sample's error to at most `NEAR_LOSSLESS_STEP` -
    /// that per-sample error bound is JPEG-LS's whole point (as opposed to a general-purpose
    /// lossy codec with no per-sample guarantee), so this is checking the actual codec contract,
    /// not just "produces plausible-looking output".
    #[test]
    fn near_lossless_encode_bounds_error_to_the_configured_step() {
        let object = fixture("mr_small.dcm");
        let original_bytes = object
            .element(dcmnorm_dictionary::tags::PIXEL_DATA)
            .unwrap()
            .to_bytes()
            .unwrap()
            .to_vec();

        let fragments =
            encode_jpeg_ls_pixel_data(&object, false).expect("near-lossless encode should succeed");
        let mut encoded_object = object.clone();
        encoded_object.put(dcmnorm_core::DataElement::new(
            dcmnorm_dictionary::tags::PIXEL_DATA,
            dcmnorm_core::VR::OB,
            dcmnorm_core::value::PixelFragmentSequence::new(vec![0], fragments),
        ));
        let decoded = decode_jpeg_ls_pixel_data(&encoded_object).expect("decode should succeed");

        assert_eq!(decoded.len(), original_bytes.len());
        assert_ne!(
            decoded, original_bytes,
            "near-lossless should not be byte-identical to lossless"
        );
        for (original, roundtripped) in original_bytes.chunks_exact(2).zip(decoded.chunks_exact(2))
        {
            let a = u16::from_le_bytes([original[0], original[1]]);
            let b = u16::from_le_bytes([roundtripped[0], roundtripped[1]]);
            assert!(
                a.abs_diff(b) <= super::jpeg_ls_impl::NEAR_LOSSLESS_STEP as u16,
                "sample error {} exceeds the configured near-lossless step",
                a.abs_diff(b)
            );
        }
    }

    /// Round-trips a real *third-party* JPEG-LS Lossless file (not one this codebase encoded
    /// itself) through re-encode: decode it, re-encode the result, decode again, and confirm the
    /// second decode matches the first exactly - proof the encoder and decoder agree on a file
    /// this codebase didn't produce, not just on each other's own conventions.
    #[test]
    fn reencoding_a_real_third_party_jpeg_ls_file_round_trips_exactly() {
        let source = fixture("mr_jpegls_lossless.dcm");
        let first_decode =
            decode_jpeg_ls_pixel_data(&source).expect("initial decode should succeed");

        let mut native_object = source.clone();
        native_object.put(dcmnorm_core::DataElement::new(
            dcmnorm_dictionary::tags::PIXEL_DATA,
            dcmnorm_core::VR::OW,
            dcmnorm_core::PrimitiveValue::U16(
                first_decode
                    .chunks_exact(2)
                    .map(|c| u16::from_le_bytes([c[0], c[1]]))
                    .collect(),
            ),
        ));

        let fragments =
            encode_jpeg_ls_pixel_data(&native_object, true).expect("re-encode should succeed");
        let mut reencoded_object = native_object.clone();
        reencoded_object.put(dcmnorm_core::DataElement::new(
            dcmnorm_dictionary::tags::PIXEL_DATA,
            dcmnorm_core::VR::OB,
            dcmnorm_core::value::PixelFragmentSequence::new(vec![0], fragments),
        ));

        let second_decode =
            decode_jpeg_ls_pixel_data(&reencoded_object).expect("re-decode should succeed");
        assert_eq!(first_decode, second_decode);
    }

    #[test]
    fn encode_rejects_pixel_data_too_short_for_the_declared_shape() {
        let mut object = fixture("mr_small.dcm");
        object.put(dcmnorm_core::DataElement::new(
            dcmnorm_dictionary::tags::PIXEL_DATA,
            dcmnorm_core::VR::OW,
            dcmnorm_core::PrimitiveValue::U16(vec![0u16; 4].into()),
        ));
        let result = encode_jpeg_ls_pixel_data(&object, true);
        assert!(result.is_err(), "expected an error, got {result:?}");
    }

    #[test]
    fn decode_codestream_interleaves_planar_ilv0_rgb_to_match_dicom_contract() {
        // 4x3 RGB planar (ILV=0): R plane, G plane, B plane.
        let (rows, cols) = (3u16, 4u16);
        let n = usize::from(rows) * usize::from(cols);
        let mut planar = Vec::with_capacity(n * 3);
        let mut expected_interleaved = Vec::with_capacity(n * 3);
        for i in 0..n {
            planar.push((10 + i) as u8);
        }
        for i in 0..n {
            planar.push((100 + i) as u8);
        }
        for i in 0..n {
            planar.push((200 + i) as u8);
        }
        for i in 0..n {
            expected_interleaved.push((10 + i) as u8);
            expected_interleaved.push((100 + i) as u8);
            expected_interleaved.push((200 + i) as u8);
        }
        let encoded = super::encode_jpeg_ls_frame(&planar, rows, cols, 3, 8, 1, true)
            .expect("planar ILV=0 encode should succeed");
        let decoded = super::decode_jpeg_ls_codestream(&encoded, u32::from(rows), u32::from(cols))
            .expect("planar ILV=0 decode should succeed");
        assert_eq!(decoded, expected_interleaved);
    }

    #[test]
    fn encode_masks_unused_high_bits_in_16bit_containers() {
        // Signed 12-bit-in-16-bit CT pixels with sign-extended high bits (0xFFFF == -1).
        let (rows, cols) = (4u16, 4u16);
        let raw_samples: Vec<u16> = (0..16)
            .map(|i| if i % 2 == 0 { 0xFFFFu16 - i } else { i * 100 })
            .collect();
        let mut raw_bytes = Vec::with_capacity(raw_samples.len() * 2);
        let mut expected_masked = Vec::with_capacity(raw_samples.len() * 2);
        for &s in &raw_samples {
            raw_bytes.extend_from_slice(&s.to_le_bytes());
            expected_masked.extend_from_slice(&(s & 0x0FFF).to_le_bytes());
        }
        let encoded = super::encode_jpeg_ls_frame(&raw_bytes, rows, cols, 1, 12, 0, true)
            .expect("12-bit encode with sign-extended high bits should succeed");
        let decoded = super::decode_jpeg_ls_codestream(&encoded, u32::from(rows), u32::from(cols))
            .expect("decode should succeed");
        assert_eq!(decoded, expected_masked);

        // 7-bit-in-8-bit samples with unused bit 7 set (0x80..=0xFF).
        let raw_8: Vec<u8> = (0..16u8).map(|i| 0x80 | (i * 7)).collect();
        let expected_8: Vec<u8> = raw_8.iter().map(|&b| b & 0x7F).collect();
        let encoded_8 = super::encode_jpeg_ls_frame(&raw_8, rows, cols, 1, 7, 0, true)
            .expect("7-bit-in-8-bit encode with unused high bit should succeed");
        let decoded_8 =
            super::decode_jpeg_ls_codestream(&encoded_8, u32::from(rows), u32::from(cols))
                .expect("7-bit decode should succeed");
        assert_eq!(decoded_8, expected_8);
    }
}