dcmnorm 0.23.2

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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
use dcmnorm_dictionary::tags;
use dcmnorm_object::DefaultDicomObject;

pub(crate) fn transfer_syntax_uid(object: &DefaultDicomObject) -> String {
    object
        .meta()
        .transfer_syntax
        .trim_end_matches(['\0', ' '])
        .to_owned()
}

/// Frames per second to encode at: `CineRate` (0018,0040) if present, else derived from
/// `FrameTime` (0018,1063, milliseconds/frame), else a plain default. Real-world cine
/// loops nearly always carry one of these; the default only matters for synthetic inputs.
pub(crate) fn frames_per_second(object: &DefaultDicomObject) -> f64 {
    if let Some(rate) = object
        .get(tags::CINE_RATE)
        .and_then(|e| e.to_str().ok())
        .and_then(|s| s.trim().parse::<f64>().ok())
    {
        if rate > 0.0 {
            return rate;
        }
    }
    if let Some(frame_time_ms) = object
        .get(tags::FRAME_TIME)
        .and_then(|e| e.to_str().ok())
        .and_then(|s| s.trim().parse::<f64>().ok())
    {
        if frame_time_ms > 0.0 {
            return 1000.0 / frame_time_ms;
        }
    }
    30.0
}

#[cfg(feature = "ffmpeg-codec-linked")]
pub mod mpeg_impl {
    use dcmnorm_dictionary::tags;
    use dcmnorm_object::DefaultDicomObject;

    use super::{frames_per_second, transfer_syntax_uid};
    use ffmpeg::codec::{self, packet::Packet};
    use ffmpeg::format::Pixel;
    use ffmpeg::frame;
    use ffmpeg::software::scaling;
    use ffmpeg_next as ffmpeg;

    /// Splits a concatenated elementary stream into individual access-unit-sized packets using
    /// FFmpeg's own bitstream parser (`av_parser_*`, not exposed by `ffmpeg-next`'s safe API, so
    /// called directly via the `ffi` module it re-exports).
    ///
    /// This is not optional: DICOM PS3.5's video transfer syntaxes require the *entire*
    /// multi-frame bitstream in one PixelData fragment, and `avcodec_send_packet` does not
    /// reliably decode more than the first access unit when handed one packet spanning several -
    /// confirmed empirically (a real multi-frame H.264 round trip decoded frame 0 correctly, then
    /// failed with "decode_slice_header error" on every frame after). Splitting into properly
    /// bounded packets first, exactly as a real demuxer would, is what actually works.
    fn split_into_access_units(
        codec_id: codec::Id,
        decoder_context: *mut ffmpeg::ffi::AVCodecContext,
        stream: &[u8],
    ) -> Result<Vec<Vec<u8>>, String> {
        let raw_id: ffmpeg::ffi::AVCodecID = codec_id.into();
        let parser = unsafe { ffmpeg::ffi::av_parser_init(raw_id as i32) };
        if parser.is_null() {
            return Err(format!("no bitstream parser available for {codec_id:?}"));
        }

        struct ParserGuard(*mut ffmpeg::ffi::AVCodecParserContext);
        impl Drop for ParserGuard {
            fn drop(&mut self) {
                unsafe { ffmpeg::ffi::av_parser_close(self.0) };
            }
        }
        let _guard = ParserGuard(parser);

        // One call to av_parser_parse2: `buf`/`buf_size` of (null, 0) signals EOF, which is
        // required at the very end (not just when input runs out) - byte-stream parsers only
        // recognize an access unit's end once they see the *next* one's start code, so the very
        // last access unit sits in the parser's internal buffer until explicitly flushed. Without
        // this, the last frame of every stream would silently go missing.
        let parse_one = |parser: *mut ffmpeg::ffi::AVCodecParserContext,
                         buf: &[u8]|
         -> Result<(i32, Vec<u8>), String> {
            let mut out_ptr: *mut u8 = std::ptr::null_mut();
            let mut out_size: std::os::raw::c_int = 0;
            let consumed = unsafe {
                ffmpeg::ffi::av_parser_parse2(
                    parser,
                    decoder_context,
                    &mut out_ptr,
                    &mut out_size,
                    buf.as_ptr(),
                    buf.len() as std::os::raw::c_int,
                    ffmpeg::ffi::AV_NOPTS_VALUE,
                    ffmpeg::ffi::AV_NOPTS_VALUE,
                    0,
                )
            };
            if consumed < 0 {
                return Err("bitstream parser error while splitting video access units".to_owned());
            }
            let packet = if out_size > 0 && !out_ptr.is_null() {
                unsafe { std::slice::from_raw_parts(out_ptr, out_size as usize) }.to_vec()
            } else {
                Vec::new()
            };
            Ok((consumed, packet))
        };

        let mut packets = Vec::new();
        let mut remaining = stream;
        while !remaining.is_empty() {
            let (consumed, packet) = parse_one(parser, remaining)?;
            if !packet.is_empty() {
                packets.push(packet);
            }
            if consumed == 0 {
                // Parser made no progress - stop rather than loop forever on malformed input.
                break;
            }
            remaining = &remaining[consumed as usize..];
        }
        // Flush the last buffered access unit.
        let (_, packet) = parse_one(parser, &[])?;
        if !packet.is_empty() {
            packets.push(packet);
        }

        Ok(packets)
    }

    /// `ffmpeg::init()` is safe to call more than once, but does real work (registering codecs,
    /// setting up the log callback) each time - do it exactly once per process.
    fn ensure_ffmpeg_init() -> Result<(), String> {
        static INIT: std::sync::Once = std::sync::Once::new();
        static INIT_RESULT: std::sync::OnceLock<Result<(), String>> = std::sync::OnceLock::new();
        INIT.call_once(|| {
            let _ =
                INIT_RESULT.set(ffmpeg::init().map_err(|e| format!("ffmpeg::init failed: {e}")));
        });
        INIT_RESULT.get().cloned().unwrap_or(Ok(()))
    }

    fn codec_id_for_transfer_syntax(uid: &str) -> Option<codec::Id> {
        match uid {
            "1.2.840.10008.1.2.4.100" | "1.2.840.10008.1.2.4.101" => Some(codec::Id::MPEG2VIDEO),
            "1.2.840.10008.1.2.4.102"
            | "1.2.840.10008.1.2.4.103"
            | "1.2.840.10008.1.2.4.104"
            | "1.2.840.10008.1.2.4.105"
            | "1.2.840.10008.1.2.4.106" => Some(codec::Id::H264),
            "1.2.840.10008.1.2.4.107" | "1.2.840.10008.1.2.4.108" => Some(codec::Id::HEVC),
            _ => None,
        }
    }

    /// Whether this FFmpeg build has an encoder for `uid`. The linked FFmpeg is built with only
    /// FFmpeg's own (LGPL) codecs, which include an MPEG-2 encoder but no H.264 or HEVC encoder
    /// (those come from libx264 / libx265), so those transfer syntaxes decode but don't encode.
    pub fn can_encode_video(uid: &str) -> bool {
        ensure_ffmpeg_init().is_ok()
            && codec_id_for_transfer_syntax(uid)
                .and_then(ffmpeg::encoder::find)
                .is_some()
    }

    /// Decode MPEG2/H.264/HEVC-encoded pixel data using FFmpeg's raw codec API (not a
    /// container/demuxer - DICOM stores a bare elementary stream, not an MP4/MPEG-TS wrapper).
    ///
    /// PS3.5's video transfer syntaxes (as opposed to their "Fragmentable" siblings, which this
    /// codebase doesn't register - see entries.rs) require the entire bitstream in a single
    /// PixelData fragment; fragments are still concatenated defensively here in case a peer
    /// split one anyway. The concatenated stream is then split into individual access units via
    /// `split_into_access_units` before being handed to the decoder one packet at a time - see
    /// that function's own doc comment for why a single "whole stream as one packet" send_packet
    /// call isn't reliable for more than the first frame.
    pub fn decode_mpeg_pixel_data(object: &DefaultDicomObject) -> Result<Vec<u8>, String> {
        ensure_ffmpeg_init()?;

        let ts_uid = transfer_syntax_uid(object);
        let codec_id = codec_id_for_transfer_syntax(&ts_uid)
            .ok_or_else(|| format!("unsupported video transfer syntax: {ts_uid}"))?;

        let fragments = object
            .element(tags::PIXEL_DATA)
            .map_err(|e| format!("missing PixelData: {e}"))?
            .fragments()
            .ok_or_else(|| "expected encapsulated video pixel data".to_owned())?;
        if fragments.is_empty() {
            return Err("no video data to decode".to_owned());
        }
        let mut bitstream = Vec::new();
        for fragment in fragments {
            bitstream.extend_from_slice(fragment);
        }

        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 dst_format = if samples_per_pixel == 1 {
            Pixel::GRAY8
        } else {
            Pixel::RGB24
        };

        let decoder_codec = ffmpeg::decoder::find(codec_id)
            .ok_or_else(|| format!("no {codec_id:?} decoder available in this FFmpeg build"))?;
        let mut decoder = ffmpeg::decoder::new()
            .open_as(decoder_codec)
            .map_err(|e| format!("failed to open {codec_id:?} decoder: {e}"))?
            .video()
            .map_err(|e| format!("{codec_id:?} decoder is not a video decoder: {e}"))?;

        let mut scaler: Option<scaling::Context> = None;
        let mut out = Vec::new();
        let mut raw = frame::Video::empty();

        let mut drain_frames = |decoder: &mut ffmpeg::decoder::Video| -> Result<(), String> {
            loop {
                match decoder.receive_frame(&mut raw) {
                    Ok(()) => {
                        if scaler.is_none() {
                            scaler = Some(
                                scaling::Context::get(
                                    decoder.format(),
                                    decoder.width(),
                                    decoder.height(),
                                    dst_format,
                                    u32::from(cols),
                                    u32::from(rows),
                                    scaling::flag::Flags::BILINEAR,
                                )
                                .map_err(|e| {
                                    format!("failed to create pixel format converter: {e}")
                                })?,
                            );
                        }
                        let mut converted = frame::Video::empty();
                        scaler
                            .as_mut()
                            .unwrap()
                            .run(&raw, &mut converted)
                            .map_err(|e| format!("pixel format conversion failed: {e}"))?;

                        let bytes_per_row = usize::from(cols) * usize::from(samples_per_pixel);
                        let stride = converted.stride(0);
                        let data = converted.data(0);
                        for y in 0..usize::from(rows) {
                            let start = y * stride;
                            out.extend_from_slice(&data[start..start + bytes_per_row]);
                        }
                    }
                    Err(ffmpeg::Error::Other { errno }) if errno == ffmpeg::error::EAGAIN => break,
                    Err(ffmpeg::Error::Eof) => break,
                    Err(e) => return Err(format!("video decode failed: {e}")),
                }
            }
            Ok(())
        };

        let decoder_context_ptr = unsafe { decoder.as_mut_ptr() };
        let access_units = split_into_access_units(codec_id, decoder_context_ptr, &bitstream)?;
        if access_units.is_empty() {
            return Err("bitstream parser found no access units to decode".to_owned());
        }
        for access_unit in &access_units {
            decoder
                .send_packet(&Packet::copy(access_unit))
                .map_err(|e| format!("failed to send video data to decoder: {e}"))?;
            drain_frames(&mut decoder)?;
        }
        decoder
            .send_eof()
            .map_err(|e| format!("failed to flush decoder: {e}"))?;
        drain_frames(&mut decoder)?;

        if out.is_empty() {
            return Err("no frames decoded".to_owned());
        }
        Ok(out)
    }

    /// Encode raw native pixel data to MPEG2/H.264/HEVC using FFmpeg's raw codec API, producing
    /// a single fragment holding the entire bitstream - the encoded-side mirror of
    /// `decode_mpeg_pixel_data`'s "one fragment, whole stream" convention (see its own doc
    /// comment for why).
    pub fn encode_mpeg_pixel_data(
        object: &DefaultDicomObject,
        target_uid: &str,
    ) -> Result<Vec<Vec<u8>>, String> {
        ensure_ffmpeg_init()?;

        let codec_id = codec_id_for_transfer_syntax(target_uid)
            .ok_or_else(|| format!("unsupported video transfer syntax: {target_uid}"))?;

        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())?;
        if bits_allocated != 8 {
            return Err(format!(
                "video encoding only supports 8-bit samples, got BitsAllocated={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 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}"))?
            .to_vec();

        let src_format = if samples_per_pixel == 1 {
            Pixel::GRAY8
        } else {
            Pixel::RGB24
        };
        let frame_len = usize::from(rows) * usize::from(cols) * usize::from(samples_per_pixel);
        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}: \
                 expected at least {expected_len} bytes, got {}",
                pixel_data.len()
            ));
        }

        let encoder_codec = ffmpeg::encoder::find(codec_id)
            .ok_or_else(|| format!("no {codec_id:?} encoder available in this FFmpeg build"))?;
        let fps = frames_per_second(object);
        let time_base = ffmpeg::Rational::new(1, (fps.round() as i32).max(1));

        let mut encoder = codec::context::Context::new_with_codec(encoder_codec)
            .encoder()
            .video()
            .map_err(|e| format!("failed to create {codec_id:?} encoder context: {e}"))?;
        encoder.set_width(u32::from(cols));
        encoder.set_height(u32::from(rows));
        // YUV 4:2:0 is what every target codec here actually negotiates/decodes correctly in
        // practice (RGB-native encoding profiles exist for some of these codecs but aren't what
        // real-world DICOM viewers expect); the scaler below converts from the source format.
        encoder.set_format(Pixel::YUV420P);
        encoder.set_time_base(time_base);
        encoder.set_frame_rate(Some(time_base.invert()));

        let mut encoder = encoder
            .open()
            .map_err(|e| format!("failed to open {codec_id:?} encoder: {e}"))?;

        let mut scaler = scaling::Context::get(
            src_format,
            u32::from(cols),
            u32::from(rows),
            Pixel::YUV420P,
            u32::from(cols),
            u32::from(rows),
            scaling::flag::Flags::BILINEAR,
        )
        .map_err(|e| format!("failed to create pixel format converter: {e}"))?;

        let mut bitstream = Vec::new();
        let mut encoded = Packet::empty();

        let mut drain_packets = |encoder: &mut ffmpeg::encoder::Video,
                                 bitstream: &mut Vec<u8>|
         -> Result<(), String> {
            loop {
                match encoder.receive_packet(&mut encoded) {
                    Ok(()) => {
                        if let Some(data) = encoded.data() {
                            bitstream.extend_from_slice(data);
                        }
                    }
                    Err(ffmpeg::Error::Other { errno }) if errno == ffmpeg::error::EAGAIN => break,
                    Err(ffmpeg::Error::Eof) => break,
                    Err(e) => return Err(format!("video encode failed: {e}")),
                }
            }
            Ok(())
        };

        for frame_index in 0..number_of_frames {
            let start = frame_index * frame_len;
            let frame_bytes = &pixel_data[start..start + frame_len];

            let mut src_frame = frame::Video::new(src_format, u32::from(cols), u32::from(rows));
            let src_bytes_per_row = usize::from(cols) * usize::from(samples_per_pixel);
            let src_stride = src_frame.stride(0);
            {
                let dst = src_frame.data_mut(0);
                for y in 0..usize::from(rows) {
                    let dst_start = y * src_stride;
                    let src_start = y * src_bytes_per_row;
                    dst[dst_start..dst_start + src_bytes_per_row]
                        .copy_from_slice(&frame_bytes[src_start..src_start + src_bytes_per_row]);
                }
            }

            let mut yuv_frame = frame::Video::empty();
            scaler
                .run(&src_frame, &mut yuv_frame)
                .map_err(|e| format!("pixel format conversion failed: {e}"))?;
            yuv_frame.set_pts(Some(frame_index as i64));

            encoder
                .send_frame(&yuv_frame)
                .map_err(|e| format!("failed to send frame {frame_index} to encoder: {e}"))?;
            drain_packets(&mut encoder, &mut bitstream)?;
        }

        encoder
            .send_eof()
            .map_err(|e| format!("failed to flush encoder: {e}"))?;
        drain_packets(&mut encoder, &mut bitstream)?;

        if bitstream.is_empty() {
            return Err("encoder produced no data".to_owned());
        }
        Ok(vec![bitstream])
    }
}

/// Video transfer syntaxes through the `ffmpeg` command on `PATH`, for builds without FFmpeg
/// linked in (the default). Nothing FFmpeg-related is compiled: the elementary stream goes to
/// `ffmpeg` on stdin and raw frames come back on stdout (or the reverse for encoding), so the
/// build stays fast and the binary starts on machines without FFmpeg. Only these transfer
/// syntaxes need it; when `ffmpeg` is missing they fail with an error saying how to install it.
///
/// The output matches the linked backend: frames scaled to Rows x Columns as GRAY8
/// (SamplesPerPixel 1) or RGB24, concatenated in display order; encoding takes 8-bit native
/// frames, converts them to YUV 4:2:0 and returns the whole bitstream as one fragment. `ffmpeg`'s
/// raw demuxers split the stream into access units themselves, and its default encoder for each
/// raw format is used (mpeg2video, and libx264 / libx265 when the installed FFmpeg has them).
#[cfg(not(feature = "ffmpeg-codec-linked"))]
pub mod mpeg_impl {
    use std::io::{ErrorKind, Read, Write};
    use std::process::{Command, Stdio};

    use dcmnorm_dictionary::tags;
    use dcmnorm_object::DefaultDicomObject;

    use super::{frames_per_second, transfer_syntax_uid};

    /// Shown whenever the `ffmpeg` command can't be started.
    pub const FFMPEG_NOT_FOUND: &str = "MPEG-2, MPEG-4 AVC/H.264 and HEVC transfer syntaxes need the `ffmpeg` command on PATH, \
         and it was not found. Install FFmpeg (for example `apt install ffmpeg`, `brew install ffmpeg` \
         or `winget install ffmpeg`) and try again.";

    /// `ffmpeg -f` name of the raw elementary stream format for a video transfer syntax (the
    /// same name works as the demuxer and the muxer, except MPEG-2's demuxer is `mpegvideo`).
    fn raw_format(uid: &str, demux: bool) -> Option<&'static str> {
        match uid {
            "1.2.840.10008.1.2.4.100" | "1.2.840.10008.1.2.4.101" => {
                Some(if demux { "mpegvideo" } else { "mpeg2video" })
            }
            "1.2.840.10008.1.2.4.102"
            | "1.2.840.10008.1.2.4.103"
            | "1.2.840.10008.1.2.4.104"
            | "1.2.840.10008.1.2.4.105"
            | "1.2.840.10008.1.2.4.106" => Some("h264"),
            "1.2.840.10008.1.2.4.107" | "1.2.840.10008.1.2.4.108" => Some("hevc"),
            _ => None,
        }
    }

    /// Whether `uid` is a video transfer syntax this backend encodes. Whether the installed
    /// `ffmpeg` has the encoder (libx264 / libx265 for H.264 / HEVC) only shows when encoding.
    pub fn can_encode_video(uid: &str) -> bool {
        raw_format(uid, false).is_some()
    }

    /// Runs `ffmpeg` with `args`, feeding `input` on stdin and returning stdout. stdin is
    /// written and stderr drained on their own threads so neither pipe can fill up and stall
    /// the other.
    fn run_ffmpeg(args: &[String], input: Vec<u8>) -> Result<Vec<u8>, String> {
        run_program("ffmpeg", args, input)
    }

    pub(super) fn run_program(
        program: &str,
        args: &[String],
        input: Vec<u8>,
    ) -> Result<Vec<u8>, String> {
        let mut child = Command::new(program)
            .args(["-hide_banner", "-loglevel", "error"])
            .args(args)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .map_err(|e| {
                if e.kind() == ErrorKind::NotFound {
                    FFMPEG_NOT_FOUND.to_owned()
                } else {
                    format!("could not start ffmpeg: {e}")
                }
            })?;

        let mut stdin = child.stdin.take().expect("stdin is piped");
        // A write error means ffmpeg exited early; its exit status and stderr say why.
        let writer = std::thread::spawn(move || {
            let _ = stdin.write_all(&input);
        });
        let mut stderr = child.stderr.take().expect("stderr is piped");
        let stderr_reader = std::thread::spawn(move || {
            let mut text = String::new();
            let _ = stderr.read_to_string(&mut text);
            text
        });

        let mut output = Vec::new();
        child
            .stdout
            .take()
            .expect("stdout is piped")
            .read_to_end(&mut output)
            .map_err(|e| format!("failed to read ffmpeg output: {e}"))?;
        let status = child
            .wait()
            .map_err(|e| format!("failed to wait for ffmpeg: {e}"))?;
        let _ = writer.join();
        let stderr_text = stderr_reader.join().unwrap_or_default();

        if !status.success() {
            let detail = stderr_text.trim();
            return Err(if detail.is_empty() {
                format!("ffmpeg failed ({status})")
            } else {
                format!("ffmpeg failed ({status}): {detail}")
            });
        }
        Ok(output)
    }

    fn raw_pixel_format(samples_per_pixel: u16) -> &'static str {
        if samples_per_pixel == 1 {
            "gray"
        } else {
            "rgb24"
        }
    }

    pub fn decode_mpeg_pixel_data(object: &DefaultDicomObject) -> Result<Vec<u8>, String> {
        let ts_uid = transfer_syntax_uid(object);
        let format = raw_format(&ts_uid, true)
            .ok_or_else(|| format!("unsupported video transfer syntax: {ts_uid}"))?;

        let fragments = object
            .element(tags::PIXEL_DATA)
            .map_err(|e| format!("missing PixelData: {e}"))?
            .fragments()
            .ok_or_else(|| "expected encapsulated video pixel data".to_owned())?;
        if fragments.is_empty() {
            return Err("no video data to decode".to_owned());
        }
        let mut bitstream = Vec::new();
        for fragment in fragments {
            bitstream.extend_from_slice(fragment);
        }

        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 args: Vec<String> = [
            "-f",
            format,
            "-i",
            "pipe:0",
            "-f",
            "rawvideo",
            "-pix_fmt",
            raw_pixel_format(samples_per_pixel),
            "-s",
            &format!("{cols}x{rows}"),
            "-sws_flags",
            "bilinear",
            "pipe:1",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        let out = run_ffmpeg(&args, bitstream)?;

        let frame_len = usize::from(rows) * usize::from(cols) * usize::from(samples_per_pixel);
        if out.is_empty() {
            return Err("no frames decoded".to_owned());
        }
        if frame_len == 0 || out.len() % frame_len != 0 {
            return Err(format!(
                "ffmpeg returned {} bytes, not a whole number of {cols}x{rows}x{samples_per_pixel} frames",
                out.len()
            ));
        }
        Ok(out)
    }

    pub fn encode_mpeg_pixel_data(
        object: &DefaultDicomObject,
        target_uid: &str,
    ) -> Result<Vec<Vec<u8>>, String> {
        let format = raw_format(target_uid, false)
            .ok_or_else(|| format!("unsupported video transfer syntax: {target_uid}"))?;

        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())?;
        if bits_allocated != 8 {
            return Err(format!(
                "video encoding only supports 8-bit samples, got BitsAllocated={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 mut 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}"))?
            .to_vec();
        let frame_len = usize::from(rows) * usize::from(cols) * usize::from(samples_per_pixel);
        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}: \
                 expected at least {expected_len} bytes, got {}",
                pixel_data.len()
            ));
        }
        // Even-length padding beyond the last frame isn't a frame.
        pixel_data.truncate(expected_len);

        let fps = (frames_per_second(object).round() as i64).max(1);
        let args: Vec<String> = [
            "-f",
            "rawvideo",
            "-pix_fmt",
            raw_pixel_format(samples_per_pixel),
            "-s",
            &format!("{cols}x{rows}"),
            "-framerate",
            &fps.to_string(),
            "-i",
            "pipe:0",
            "-pix_fmt",
            "yuv420p",
            "-sws_flags",
            "bilinear",
            "-f",
            format,
            "pipe:1",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        let bitstream = run_ffmpeg(&args, pixel_data)?;
        if bitstream.is_empty() {
            return Err("encoder produced no data".to_owned());
        }
        Ok(vec![bitstream])
    }
}

pub use mpeg_impl::{can_encode_video, decode_mpeg_pixel_data, encode_mpeg_pixel_data};

#[cfg(test)]
mod tests {
    use super::{decode_mpeg_pixel_data, encode_mpeg_pixel_data};
    use dcmnorm_core::value::PixelFragmentSequence;
    use dcmnorm_core::{DataElement, PrimitiveValue, VR};
    use dcmnorm_dictionary::tags;
    use dcmnorm_object::{DefaultDicomObject, FileMetaTableBuilder};

    const ROWS: u16 = 120;
    const COLS: u16 = 256;
    const FRAME_LEN: usize = ROWS as usize * COLS as usize * 3;

    /// FFmpeg linked in has no H.264/HEVC encoder (see `can_encode_video`); those round trips are
    /// skipped there (with a note) rather than failed.
    fn encoder_available(ts_uid: &str) -> bool {
        let available = super::can_encode_video(ts_uid);
        if !available {
            eprintln!("skipping {ts_uid}: this build has no encoder for it");
        }
        available
    }

    /// The round trips need a video codec: FFmpeg linked in, or the `ffmpeg` command for the
    /// default build. Without either they are skipped (with a note), not failed.
    fn video_codec_available() -> bool {
        if cfg!(feature = "ffmpeg-codec-linked") {
            return true;
        }
        let found = std::process::Command::new("ffmpeg")
            .arg("-version")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false);
        if !found {
            eprintln!("skipping: no ffmpeg on PATH");
        }
        found
    }

    /// A red band across the top `count` rows, black elsewhere - deliberately not something a
    /// real X-ray/ultrasound frame would ever look like, so any cross-frame bleed or reordering
    /// bug shows up as an obviously wrong ratio rather than a subtle pixel-value drift.
    fn solid_band_frame(band_rows_from_top: usize, color: [u8; 3]) -> Vec<u8> {
        let mut frame = vec![0u8; FRAME_LEN];
        for y in 0..band_rows_from_top {
            for x in 0..usize::from(COLS) {
                let i = (y * usize::from(COLS) + x) * 3;
                frame[i..i + 3].copy_from_slice(&color);
            }
        }
        frame
    }

    /// Fraction of the top 20 rows that are (approximately) the given color - lossy video
    /// compression means "exactly equal" isn't the right check.
    fn top_band_match_ratio(frame: &[u8], color: [u8; 3]) -> f64 {
        let mut matches = 0usize;
        let checked = 20 * usize::from(COLS);
        for i in 0..checked {
            let px = &frame[i * 3..i * 3 + 3];
            if (0..3).all(|c| (i32::from(px[c]) - i32::from(color[c])).abs() < 40) {
                matches += 1;
            }
        }
        matches as f64 / checked as f64
    }

    fn empty_object_with_transfer_syntax(ts_uid: &str) -> DefaultDicomObject {
        let meta = FileMetaTableBuilder::new()
            .transfer_syntax(ts_uid)
            .build()
            .expect("minimal meta table should build");
        DefaultDicomObject::new_empty_with_meta(meta)
    }

    fn native_rgb_object(number_of_frames: usize, pixel_data: Vec<u8>) -> DefaultDicomObject {
        // Native (uncompressed) source pixel data - the transfer syntax here doesn't matter to
        // encode_mpeg_pixel_data (it only reads the target UID passed to it separately), so
        // Explicit VR Little Endian just documents "this is native, not encapsulated".
        let mut object = empty_object_with_transfer_syntax("1.2.840.10008.1.2.1");
        for element in [
            DataElement::new(tags::ROWS, VR::US, PrimitiveValue::from(ROWS)),
            DataElement::new(tags::COLUMNS, VR::US, PrimitiveValue::from(COLS)),
            DataElement::new(tags::SAMPLES_PER_PIXEL, VR::US, PrimitiveValue::from(3u16)),
            DataElement::new(tags::BITS_ALLOCATED, VR::US, PrimitiveValue::from(8u16)),
            DataElement::new(
                tags::PIXEL_REPRESENTATION,
                VR::US,
                PrimitiveValue::from(0u16),
            ),
            DataElement::new(
                tags::PLANAR_CONFIGURATION,
                VR::US,
                PrimitiveValue::from(0u16),
            ),
            DataElement::new(
                tags::PHOTOMETRIC_INTERPRETATION,
                VR::CS,
                PrimitiveValue::from("RGB".to_owned()),
            ),
            DataElement::new(
                tags::NUMBER_OF_FRAMES,
                VR::IS,
                PrimitiveValue::from(number_of_frames.to_string()),
            ),
            DataElement::new(tags::PIXEL_DATA, VR::OW, PrimitiveValue::from(pixel_data)),
        ] {
            object.put(element);
        }
        object
    }

    /// `decode_mpeg_pixel_data` dispatches on `object.meta().transfer_syntax`, so the returned
    /// object's meta table must actually carry `ts_uid` - unlike the dataset elements, which are
    /// just cloned from `source` unchanged.
    fn encapsulated_video_object(
        source: &DefaultDicomObject,
        ts_uid: &str,
        bitstream: Vec<u8>,
    ) -> DefaultDicomObject {
        let mut object = empty_object_with_transfer_syntax(ts_uid);
        for element in source.iter() {
            object.put(element.clone());
        }
        object.put(DataElement::new(
            tags::PIXEL_DATA,
            VR::OB,
            PixelFragmentSequence::new(vec![0], vec![bitstream]),
        ));
        object
    }

    /// Three solid-color-band frames, each visually unambiguous, round-tripped through real
    /// libx264 encode and libavcodec decode (not mocked). This is the primary regression test
    /// for `split_into_access_units`: earlier in development, sending the whole 3-frame
    /// bitstream to the decoder as a single packet decoded frame 0 correctly and then failed
    /// with "decode_slice_header error" on every frame after - a bug a single-frame test can't
    /// catch, which is why this uses three.
    #[test]
    fn h264_multi_frame_round_trip_preserves_frame_content_and_order() {
        if !video_codec_available() || !encoder_available("1.2.840.10008.1.2.4.102") {
            return;
        }
        let frame0 = solid_band_frame(0, [0, 0, 0]);
        let frame1 = solid_band_frame(20, [255, 0, 0]);
        let frame2 = solid_band_frame(20, [0, 255, 0]);
        let mut pixel_data = Vec::with_capacity(FRAME_LEN * 3);
        pixel_data.extend_from_slice(&frame0);
        pixel_data.extend_from_slice(&frame1);
        pixel_data.extend_from_slice(&frame2);

        let source = native_rgb_object(3, pixel_data);
        let fragments = encode_mpeg_pixel_data(&source, "1.2.840.10008.1.2.4.102")
            .expect("H.264 encode should succeed");
        assert_eq!(
            fragments.len(),
            1,
            "PS3.5 requires the whole bitstream in one fragment"
        );

        let encoded =
            encapsulated_video_object(&source, "1.2.840.10008.1.2.4.102", fragments[0].clone());
        let decoded = decode_mpeg_pixel_data(&encoded).expect("H.264 decode should succeed");
        assert_eq!(decoded.len(), FRAME_LEN * 3, "expected all 3 frames back");

        let decoded_frames: Vec<&[u8]> = decoded.chunks_exact(FRAME_LEN).collect();
        assert!(
            top_band_match_ratio(decoded_frames[0], [0, 0, 0]) > 0.9,
            "frame 0 should stay black"
        );
        assert!(
            top_band_match_ratio(decoded_frames[1], [255, 0, 0]) > 0.9,
            "frame 1 should be red"
        );
        assert!(
            top_band_match_ratio(decoded_frames[2], [0, 255, 0]) > 0.9,
            "frame 2 should be green"
        );
    }

    /// Same multi-frame round trip for MPEG2 and HEVC, through the same shared
    /// `codec_id_for_transfer_syntax` dispatch H.264 uses above - HEVC in particular is worth
    /// covering separately since x265 (unlike this test's libx264 settings) does use B-frames by
    /// default, exercising the decoder's PTS-based frame reordering rather than just simple
    /// decode-order-equals-display-order sequences.
    #[test]
    fn mpeg2_and_hevc_multi_frame_round_trips_preserve_frame_order() {
        if !video_codec_available() {
            return;
        }
        let frame0 = solid_band_frame(0, [0, 0, 0]);
        let frame1 = solid_band_frame(20, [255, 0, 0]);
        let frame2 = solid_band_frame(20, [0, 255, 0]);
        let mut pixel_data = Vec::with_capacity(FRAME_LEN * 3);
        pixel_data.extend_from_slice(&frame0);
        pixel_data.extend_from_slice(&frame1);
        pixel_data.extend_from_slice(&frame2);
        let source = native_rgb_object(3, pixel_data);

        for ts_uid in ["1.2.840.10008.1.2.4.100", "1.2.840.10008.1.2.4.107"] {
            if !encoder_available(ts_uid) {
                continue;
            }
            let fragments = encode_mpeg_pixel_data(&source, ts_uid)
                .unwrap_or_else(|e| panic!("encode for {ts_uid} should succeed: {e}"));
            let encoded = encapsulated_video_object(&source, ts_uid, fragments[0].clone());
            let decoded = decode_mpeg_pixel_data(&encoded)
                .unwrap_or_else(|e| panic!("decode for {ts_uid} should succeed: {e}"));
            assert_eq!(
                decoded.len(),
                FRAME_LEN * 3,
                "{ts_uid}: expected all 3 frames back"
            );

            let decoded_frames: Vec<&[u8]> = decoded.chunks_exact(FRAME_LEN).collect();
            assert!(
                top_band_match_ratio(decoded_frames[0], [0, 0, 0]) > 0.85,
                "{ts_uid}: frame 0 should stay black"
            );
            assert!(
                top_band_match_ratio(decoded_frames[1], [255, 0, 0]) > 0.85,
                "{ts_uid}: frame 1 should be red"
            );
            assert!(
                top_band_match_ratio(decoded_frames[2], [0, 255, 0]) > 0.85,
                "{ts_uid}: frame 2 should be green"
            );
        }
    }

    #[test]
    fn encode_rejects_unsupported_transfer_syntax() {
        let source = native_rgb_object(1, vec![0u8; FRAME_LEN]);
        let result = encode_mpeg_pixel_data(&source, "1.2.840.10008.1.2.4.90");
        assert!(result.is_err(), "expected an error, got {result:?}");
    }

    /// Without FFmpeg linked in, a missing `ffmpeg` command is a clear, actionable error.
    #[cfg(not(feature = "ffmpeg-codec-linked"))]
    #[test]
    fn missing_ffmpeg_command_says_how_to_install_it() {
        let result = super::mpeg_impl::run_program("dcmnorm-test-no-such-ffmpeg", &[], Vec::new());
        assert_eq!(result.unwrap_err(), super::mpeg_impl::FFMPEG_NOT_FOUND);
    }

    /// MPEG-2 always encodes (FFmpeg's own mpeg2video encoder, or the ffmpeg command's).
    #[test]
    fn mpeg2_is_always_encodable() {
        assert!(super::can_encode_video("1.2.840.10008.1.2.4.100"));
        assert!(!super::can_encode_video("1.2.840.10008.1.2.4.90"));
    }
}