transmux 0.25.4

Any-to-any media container muxing hub: demux TS, fMP4/CMAF, MPEG-PS, WebM, FLV, or RTMP into one neutral IR and mux to CMAF/fMP4, progressive MP4, TS, DASH, low-latency DASH, HLS, low-latency HLS, Smooth Streaming, or RTMP. CENC/CBCS encrypt+decrypt, SSAI splice, RTP/RTCP, and an fMP4/CMAF conformance validator; parses codec config headers only, samples stay opaque. no_std + alloc, except the XML manifest paths (DASH/Smooth/PlayReady), which need the std feature.
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
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
//! AVC/HEVC sample entries and their config boxes — ISO/IEC 14496-15:2017 §5.4, §8.4.
//!
//! Sample entries live inside `stsd` and extend `VisualSampleEntry`. Each carries
//! a configuration box (`avcC` or `hvcC`) containing the decoder configuration record
//! with parameter sets (SPS/PPS/VPS).
//!
//! # Types
//!
//! | Sample entry | Four-CC | Params in sample entry | Params in-band |
//! |---------------|---------|----------------------|----------------|
//! | `avc1`        | avc1    | yes                   | no             |
//! | `avc3`        | avc3    | yes                   | yes            |
//! | `avc2`        | avc2    | yes (extractors)      | no             |
//! | `avc4`        | avc4    | yes (extractors)      | yes            |
//! | `hvc1`        | hvc1    | yes (`array_completeness=1`) | no      |
//! | `hev1`        | hev1    | yes                   | yes            |

use crate::avc_config::{AVCConfigurationBox, AVCDecoderConfigurationRecord};
use crate::error::{Error, Result};
use crate::hevc_config::{HEVCConfigurationBox, HEVCDecoderConfigurationRecord};
use alloc::vec::Vec;
use broadcast_common::Serialize;

/// Length of the VisualSampleEntry fixed fields (ISO/IEC 14496-12:2015 §12.1.3).
/// 6+2(data_ref_index)+8+2(width)+2(height)+4(horiz)+4(vert)+4(reserved)+2(frame_count)+
/// 32(compressorname)+2(depth)+2(predefined) = 78
const VISUAL_SAMPLE_ENTRY_SIZE: usize = 78;

/// Fewest bytes a bare `avc1`/`hvc1` entry can have: the 8-byte box header, the
/// fixed VisualSampleEntry fields, and the 8-byte header of its config box.
const BARE_ENTRY_MIN_LEN: usize = 8 + VISUAL_SAMPLE_ENTRY_SIZE + 8;

// ---------------------------------------------------------------------------
// VisualSampleEntry fields (common to all visual sample entries)
// ---------------------------------------------------------------------------

/// Fixed fields shared by all visual sample entries, per ISO/IEC 14496-12:2015 §12.1.3.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct VisualSampleEntryFields {
    /// Data reference index (SampleEntry field at body offset 6-7).
    pub data_reference_index: u16,
    /// Width in pixels.
    pub width: u16,
    /// Height in pixels.
    pub height: u16,
    /// Horizontal resolution (fixed-point 16.16, default 0x00480000 = 72 dpi).
    pub horizontal_resolution: u32,
    /// Vertical resolution (fixed-point 16.16).
    pub vertical_resolution: u32,
    /// Data size (reserved, 0).
    pub data_size: u32,
    /// Frame count (typically 1).
    pub frame_count: u16,
    /// Compressor name (32 bytes, zero-padded).
    pub compressorname: [u8; 32],
    /// Depth (typically 0x0018 = 24).
    pub depth: u16,
    /// Pre-defined (reserved, -1 = 0xFFFF).
    pub predefined: u16,
}

impl Default for VisualSampleEntryFields {
    fn default() -> Self {
        Self {
            data_reference_index: 1,
            width: 0,
            height: 0,
            horizontal_resolution: 0x00480000,
            vertical_resolution: 0x00480000,
            data_size: 0,
            frame_count: 1,
            compressorname: [0u8; 32],
            depth: 0x0018,
            predefined: 0xFFFF,
        }
    }
}

impl VisualSampleEntryFields {
    /// Number of bytes serialized (constant).
    pub const fn serialized_len() -> usize {
        VISUAL_SAMPLE_ENTRY_SIZE
    }

    /// Parse the VisualSampleEntry fixed fields from full box bytes (including the
    /// 8-byte box header). `what` names the box for error context.
    pub fn parse_body(bytes: &[u8], what: &'static str) -> Result<Self> {
        if bytes.len() < 8 + VISUAL_SAMPLE_ENTRY_SIZE {
            return Err(Error::BufferTooShort {
                need: 8 + VISUAL_SAMPLE_ENTRY_SIZE,
                have: bytes.len(),
                what,
            });
        }
        let body = &bytes[8..];
        Ok(Self {
            data_reference_index: u16::from_be_bytes([body[6], body[7]]),
            width: u16::from_be_bytes([body[24], body[25]]),
            height: u16::from_be_bytes([body[26], body[27]]),
            horizontal_resolution: u32::from_be_bytes([body[28], body[29], body[30], body[31]]),
            vertical_resolution: u32::from_be_bytes([body[32], body[33], body[34], body[35]]),
            data_size: u32::from_be_bytes([body[36], body[37], body[38], body[39]]),
            frame_count: u16::from_be_bytes([body[40], body[41]]),
            compressorname: {
                let mut c = [0u8; 32];
                c.copy_from_slice(&body[42..74]);
                c
            },
            depth: u16::from_be_bytes([body[74], body[75]]),
            predefined: u16::from_be_bytes([body[76], body[77]]),
        })
    }

    /// Serialize the fixed fields into a buffer (public for external sample entries).
    pub fn serialize_body_into(&self, buf: &mut [u8]) -> Result<usize> {
        self.serialize_into(buf)
    }

    /// Serialize the fixed fields into a buffer.
    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        if buf.len() < VISUAL_SAMPLE_ENTRY_SIZE {
            return Err(Error::OutputBufferTooSmall {
                need: VISUAL_SAMPLE_ENTRY_SIZE,
                have: buf.len(),
            });
        }
        let mut cursor = 0usize;

        // 6 bytes reserved (zero) — SampleEntry part. Written explicitly rather
        // than skipped: the `Serialize` contract accepts any `&mut [u8]`, so a
        // reused/dirty buffer would otherwise keep garbage in the reserved
        // bytes (r04-W45).
        buf[cursor..cursor + 6].fill(0);
        cursor += 6;
        // data_reference_index (16)
        buf[cursor..cursor + 2].copy_from_slice(&self.data_reference_index.to_be_bytes());
        cursor += 2;
        // pre_defined(16) + reserved(16) + pre_defined[3]×32 = 16 bytes (zero) — §12.1.3
        buf[cursor..cursor + 16].fill(0);
        cursor += 16;
        // width (16)
        buf[cursor..cursor + 2].copy_from_slice(&self.width.to_be_bytes());
        cursor += 2;
        // height (16)
        buf[cursor..cursor + 2].copy_from_slice(&self.height.to_be_bytes());
        cursor += 2;
        // horizontal resolution (32, fixed-16.16)
        buf[cursor..cursor + 4].copy_from_slice(&self.horizontal_resolution.to_be_bytes());
        cursor += 4;
        // vertical resolution (32, fixed-16.16)
        buf[cursor..cursor + 4].copy_from_slice(&self.vertical_resolution.to_be_bytes());
        cursor += 4;
        // data size (32, reserved = 0)
        buf[cursor..cursor + 4].copy_from_slice(&self.data_size.to_be_bytes());
        cursor += 4;
        // frame count (16)
        buf[cursor..cursor + 2].copy_from_slice(&self.frame_count.to_be_bytes());
        cursor += 2;
        // compressorname (32 bytes)
        buf[cursor..cursor + 32].copy_from_slice(&self.compressorname);
        cursor += 32;
        // depth (16)
        buf[cursor..cursor + 2].copy_from_slice(&self.depth.to_be_bytes());
        cursor += 2;
        // predefined (16)
        buf[cursor..cursor + 2].copy_from_slice(&self.predefined.to_be_bytes());
        cursor += 2;

        Ok(cursor)
    }
}

/// An opaque box captured verbatim for round-trip.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct OpaqueBox {
    pub box_type: [u8; 4],
    pub data: Vec<u8>,
}

impl OpaqueBox {
    fn serialized_len(&self) -> usize {
        8 + self.data.len()
    }
    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let need = self.serialized_len();
        if buf.len() < need {
            return Err(Error::OutputBufferTooSmall {
                need,
                have: buf.len(),
            });
        }
        buf[..4].copy_from_slice(&(need as u32).to_be_bytes());
        buf[4..8].copy_from_slice(&self.box_type);
        buf[8..8 + self.data.len()].copy_from_slice(&self.data);
        Ok(need)
    }
}

/// Find a config box (e.g. `avcC`) inside the sample entry's config region.
/// Returns the full box bytes (including 8-byte header).
///
/// `size` is an untrusted wire `u32` (ISO/IEC 14496-12:2015 §4.2 `Box.size`),
/// so it is clamped against what actually remains in `region` before it is
/// used to slice — the same bound `init_segment::parse_stbl_children` applies
/// — rather than trusted outright: a child box declaring `size = 0xFFFFFFFF`
/// would otherwise panic on the out-of-bounds slice (audit finding #2).
pub(crate) fn find_config_box<'a>(region: &'a [u8], fourcc: &[u8; 4]) -> Option<&'a [u8]> {
    let mut off = 0usize;
    while off + 8 <= region.len() {
        let size = u32::from_be_bytes([
            region[off],
            region[off + 1],
            region[off + 2],
            region[off + 3],
        ]) as usize;
        if size < 8 {
            break;
        }
        let ty = &region[off + 4..off + 8];
        let clamped = size.min(region.len() - off);
        if ty == fourcc {
            return Some(&region[off..off + clamped]);
        }
        off += size;
    }
    None
}

/// Every child of a sample entry except the one named by `fourcc`, each as its
/// *whole* box bytes (header included) so a parse -> serialize re-emits it
/// verbatim.
///
/// A `vp09`/`av01` entry carries `pasp`, `btrt`, `colr` and friends alongside
/// its config box (ISO/IEC 14496-12:2015 §8.5.2.2, §12.1.5); modelling only
/// the config box dropped the rest (audit item 9).
/// One child of a `vp09`/`av01` sample entry, in wire order.
///
/// A sample entry's children (its config box plus `pasp`/`btrt`/`colr`/…) have
/// no order of their own in the struct, so the position of each is recorded
/// here: emitting the config box first unconditionally reordered a real entry
/// whose `pasp` preceded it (audit item 3, round 3).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum SampleEntryChild {
    /// The codec configuration box (`vpcC`/`av1C`) at its wire position.
    Config,
    /// Any other child, verbatim as its whole box bytes.
    Other(Vec<u8>),
}

/// Parse a sample entry's children in wire order, taking each child's bytes.
///
/// Errors on a truncated child rather than clamping it: the old code used
/// `min(len)` and kept a child whose declared size had fewer bytes behind it,
/// and `break`ed on a `size < 8` child, dropping every sibling after it (audit
/// item 3, round 3).
pub(crate) fn entry_children(region: &[u8], fourcc: &[u8; 4]) -> Result<Vec<SampleEntryChild>> {
    let mut out = Vec::new();
    let mut off = 0usize;
    while off < region.len() {
        let Some(rest) = region.get(off..) else {
            break;
        };
        let (bx, consumed) = crate::box_types::parse_box(rest)?;
        if bx.header.box_type.is(fourcc) {
            out.push(SampleEntryChild::Config);
        } else {
            out.push(SampleEntryChild::Other(rest[..consumed].to_vec()));
        }
        // A `size == 0` child consumes the rest of the entry by definition
        // (§4.2), so the walk ends there.
        if bx.header.size == 0 || consumed == 0 {
            break;
        }
        off += consumed;
    }
    Ok(out)
}

/// Serialize a sample entry's children in wire order, calling `write_config`
/// where the config box sits. Returns the number of bytes written.
pub(crate) fn serialize_entry_children(
    children: &[SampleEntryChild],
    write_config: impl Fn(&mut [u8], &mut usize) -> Result<()>,
    buf: &mut [u8],
    c: &mut usize,
) -> Result<()> {
    for child in children {
        match child {
            SampleEntryChild::Config => write_config(buf, c)?,
            SampleEntryChild::Other(bytes) => {
                buf[*c..*c + bytes.len()].copy_from_slice(bytes);
                *c += bytes.len();
            }
        }
    }
    Ok(())
}

/// The serialized length of a sample entry's children, given the config box's
/// own length.
pub(crate) fn entry_children_len(children: &[SampleEntryChild], config_len: usize) -> usize {
    children
        .iter()
        .map(|c| match c {
            SampleEntryChild::Config => config_len,
            SampleEntryChild::Other(bytes) => bytes.len(),
        })
        .sum()
}

// ---------------------------------------------------------------------------
// AVC Sample Entries: avc1 and avc3
// ---------------------------------------------------------------------------

/// H.264/AVC sample entry — ISO/IEC 14496-15:2017 §5.4.2.
///
/// Fields common to `avc1` and `avc3`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct AVCSampleEntry {
    /// The four-CC (avc1 or avc3).
    pub codec_type: [u8; 4],
    /// Visual sample entry fields.
    pub visual: VisualSampleEntryFields,
    /// AVC configuration box (avcC).
    pub config: AVCConfigurationBox,
    /// Additional config boxes (e.g. `pasp`, `btrt`) preserved verbatim.
    pub extra_boxes: Vec<OpaqueBox>,
}

impl AVCSampleEntry {
    /// Parse an AVC sample entry from full box bytes (including 8-byte header).
    pub fn bare_parse(bytes: &[u8]) -> Result<Self> {
        use crate::avc_config::AVCConfigurationBox;
        if bytes.len() < BARE_ENTRY_MIN_LEN {
            return Err(Error::BufferTooShort {
                need: BARE_ENTRY_MIN_LEN,
                have: bytes.len(),
                what: "avc1 bare",
            });
        }
        let codec_type = [bytes[4], bytes[5], bytes[6], bytes[7]];
        let body = &bytes[8..];
        let visual = VisualSampleEntryFields::parse_body(bytes, "avc1 bare")?;
        // Find avcC in the config region (after the fixed VisualSampleEntry fields)
        let config_region = &body[VISUAL_SAMPLE_ENTRY_SIZE..];
        if let Some(avcc) = find_config_box(config_region, b"avcC") {
            // avcc is the full box (header+body); parse_body expects only the body
            let config = if avcc.len() > 8 {
                AVCConfigurationBox::parse_body(&avcc[8..])?
            } else {
                return Err(Error::BufferTooShort {
                    need: 8,
                    have: avcc.len(),
                    what: "avcC body",
                });
            };
            // Every sibling box (colr/pasp/btrt/clli/mdcv/dvcC/dvvC …) — a
            // box *before* the config is kept too, not only the ones after it.
            let extra_boxes = capture_extra_boxes(config_region, &[b"avcC"]);
            Ok(Self {
                codec_type,
                visual,
                config,
                extra_boxes,
            })
        } else {
            Err(Error::BufferTooShort {
                need: 0,
                have: 0,
                what: "avc1 missing avcC",
            })
        }
    }

    /// Create a new avc1 sample entry.
    pub fn new_avc1(config: AVCDecoderConfigurationRecord) -> Self {
        let compressorname = {
            let mut c = [0u8; 32];
            c[0] = 11;
            c[1..11].copy_from_slice(b"AVC Coding");
            c
        };
        Self {
            codec_type: *b"avc1",
            visual: VisualSampleEntryFields {
                compressorname,
                ..VisualSampleEntryFields::default()
            },
            config: AVCConfigurationBox::new(config),
            extra_boxes: Vec::new(),
        }
    }

    /// Create a new avc3 sample entry.
    pub fn new_avc3(config: AVCDecoderConfigurationRecord) -> Self {
        let mut s = Self::new_avc1(config);
        s.codec_type = *b"avc3";
        s
    }
}

impl Serialize for AVCSampleEntry {
    type Error = Error;

    fn serialized_len(&self) -> usize {
        let mut n = 8 + VisualSampleEntryFields::serialized_len() + self.config.serialized_len();
        for eb in &self.extra_boxes {
            n += eb.serialized_len();
        }
        n
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let need = self.serialized_len();
        if buf.len() < need {
            return Err(Error::OutputBufferTooSmall {
                need,
                have: buf.len(),
            });
        }
        let mut cursor = 0usize;
        let size32 = need as u32;
        buf[cursor..cursor + 4].copy_from_slice(&size32.to_be_bytes());
        cursor += 4;
        buf[cursor..cursor + 4].copy_from_slice(&self.codec_type);
        cursor += 4;
        cursor += self.visual.serialize_into(&mut buf[cursor..])?;
        cursor += self.config.serialize_into(&mut buf[cursor..])?;
        for eb in &self.extra_boxes {
            cursor += eb.serialize_into(&mut buf[cursor..])?;
        }
        Ok(cursor)
    }
}

// ---------------------------------------------------------------------------
// MPEG-4/MPEG-2 Visual Sample Entry: mp4v (esds-bearing)
// ---------------------------------------------------------------------------

/// MPEG visual sample entry (`mp4v`) — ISO/IEC 14496-12:2015 §12.1 /
/// ISO/IEC 14496-14 §5.6: a `VisualSampleEntry` followed by an `esds`
/// (`ES_Descriptor`) box and any extra child boxes (`pasp`, `fiel`, `btrt`).
///
/// Used to carry MPEG-2 video (H.262) with an `esds` whose ObjectTypeIndication
/// is 0x60–0x65 (ISO/IEC 14496-1 §7.2.6.6). Every trailing child box (starting
/// with `esds`) is preserved verbatim as an [`OpaqueBox`] so the sample entry
/// round-trips byte-identically.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Mp4vSampleEntry {
    /// Visual sample entry fixed fields.
    pub visual: VisualSampleEntryFields,
    /// Trailing child boxes (the `esds` first, then any `pasp`/`fiel`/`btrt`),
    /// each preserved verbatim (box header + body) for byte-exact round-trip.
    pub config_boxes: Vec<crate::init_segment::OpaqueBox>,
}

impl Mp4vSampleEntry {
    /// The four-CC of an MPEG visual sample entry.
    pub const FOURCC: [u8; 4] = *b"mp4v";

    /// Parse an `mp4v` sample entry from full box bytes (including 8-byte header).
    pub fn bare_parse(bytes: &[u8]) -> Result<Self> {
        let visual = VisualSampleEntryFields::parse_body(bytes, "mp4v")?;
        // Child boxes start after the 8-byte box header + visual fixed fields.
        let region = &bytes[8 + VISUAL_SAMPLE_ENTRY_SIZE..];
        let config_boxes = parse_trailing_boxes(region);
        Ok(Self {
            visual,
            config_boxes,
        })
    }
}

impl Serialize for Mp4vSampleEntry {
    type Error = Error;

    fn serialized_len(&self) -> usize {
        let mut n = 8 + VisualSampleEntryFields::serialized_len();
        for b in &self.config_boxes {
            n += b.serialized_len();
        }
        n
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let need = self.serialized_len();
        if buf.len() < need {
            return Err(Error::OutputBufferTooSmall {
                need,
                have: buf.len(),
            });
        }
        let mut cursor = 0usize;
        buf[cursor..cursor + 4].copy_from_slice(&(need as u32).to_be_bytes());
        cursor += 4;
        buf[cursor..cursor + 4].copy_from_slice(&Self::FOURCC);
        cursor += 4;
        cursor += self.visual.serialize_into(&mut buf[cursor..])?;
        for b in &self.config_boxes {
            cursor += b.serialize_into(&mut buf[cursor..])?;
        }
        Ok(cursor)
    }
}

/// Every child box of a visual sample entry's trailing region **except** the
/// config box(es) named in `skip`, in wire order.
///
/// A visual sample entry may carry `colr`, `pasp`, `btrt`, `clli`, `mdcv` and
/// Dolby Vision's `dvcC`/`dvvC` beside the codec config. Dropping them loses
/// HDR/DV signalling entirely: an HDR10 or Dolby Vision profile 8.1
/// (`hvc1` + `dvcC`) source comes out as SDR on an fMP4-to-fMP4 repackage
/// (r04-W37), so this is shared by the AVC, HEVC and VVC entries.
///
/// A malformed tail **ends the walk and is dropped**: a box whose declared size
/// is smaller than its own header, or runs past the region, cannot be sliced
/// safely, and everything already captured is kept. This is the same
/// stop-at-the-first-bad-length policy [`parse_trailing_boxes`] and
/// [`find_config_box`] use, so a truncated sample entry degrades to the boxes
/// before the damage rather than losing all of them or panicking. (The entry's
/// config box is located by [`find_config_box`] independently, so a truncated
/// tail never costs the codec config.)
fn capture_extra_boxes(region: &[u8], skip: &[&[u8; 4]]) -> Vec<OpaqueBox> {
    let mut out = Vec::new();
    let mut off = 0usize;
    while off + 8 <= region.len() {
        let sz = u32::from_be_bytes([
            region[off],
            region[off + 1],
            region[off + 2],
            region[off + 3],
        ]) as usize;
        // A malformed length ends the walk rather than losing earlier boxes.
        if sz < 8 || off + sz > region.len() {
            break;
        }
        let bt = [
            region[off + 4],
            region[off + 5],
            region[off + 6],
            region[off + 7],
        ];
        if !skip.iter().any(|k| **k == bt) {
            out.push(OpaqueBox {
                box_type: bt,
                data: region[off + 8..off + sz].to_vec(),
            });
        }
        off += sz;
    }
    out
}

/// Split a sample entry's trailing child-box region into verbatim
/// [`init_segment::OpaqueBox`](crate::init_segment::OpaqueBox) entries (each
/// carrying the box body after its 8-byte header). Stops at the first malformed
/// length so a truncated tail does not lose earlier boxes.
fn parse_trailing_boxes(region: &[u8]) -> Vec<crate::init_segment::OpaqueBox> {
    let mut out = Vec::new();
    let mut off = 0usize;
    while off + 8 <= region.len() {
        let sz = u32::from_be_bytes([
            region[off],
            region[off + 1],
            region[off + 2],
            region[off + 3],
        ]) as usize;
        if sz < 8 || off + sz > region.len() {
            break;
        }
        let bt = [
            region[off + 4],
            region[off + 5],
            region[off + 6],
            region[off + 7],
        ];
        out.push(crate::init_segment::OpaqueBox::new(
            bt,
            region[off + 8..off + sz].to_vec(),
        ));
        off += sz;
    }
    out
}

// ---------------------------------------------------------------------------
// HEVC Sample Entries: hvc1 and hev1
// ---------------------------------------------------------------------------

/// H.265/HEVC sample entry — ISO/IEC 14496-15:2017 §8.4.1.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct HEVCSampleEntry {
    /// The four-CC (hvc1 or hev1).
    pub codec_type: [u8; 4],
    /// Visual sample entry fields.
    pub visual: VisualSampleEntryFields,
    /// HEVC configuration box (hvcC).
    pub config: HEVCConfigurationBox,
    /// Additional config boxes preserved verbatim.
    pub extra_boxes: Vec<OpaqueBox>,
}

impl HEVCSampleEntry {
    /// Parse an HEVC sample entry from full box bytes (including 8-byte header).
    pub fn bare_parse(bytes: &[u8]) -> Result<Self> {
        use crate::hevc_config::HEVCConfigurationBox;
        if bytes.len() < BARE_ENTRY_MIN_LEN {
            return Err(Error::BufferTooShort {
                need: BARE_ENTRY_MIN_LEN,
                have: bytes.len(),
                what: "hvc1 bare",
            });
        }
        let codec_type = [bytes[4], bytes[5], bytes[6], bytes[7]];
        let body = &bytes[8..];
        let visual = VisualSampleEntryFields::parse_body(bytes, "hvc1 bare")?;
        let config_region = &body[VISUAL_SAMPLE_ENTRY_SIZE..];
        if let Some(hvcc) = find_config_box(config_region, b"hvcC") {
            let config = if hvcc.len() > 8 {
                HEVCConfigurationBox::parse_body(&hvcc[8..])?
            } else {
                return Err(Error::BufferTooShort {
                    need: 8,
                    have: hvcc.len(),
                    what: "hvcC body",
                });
            };
            // Keep every sibling box (colr/pasp/btrt/clli/mdcv/dvcC/dvvC …):
            // dropping them loses HDR and Dolby Vision signalling on an
            // fMP4-to-fMP4 repackage (r04-W37).
            Ok(Self {
                codec_type,
                visual,
                config,
                extra_boxes: capture_extra_boxes(config_region, &[b"hvcC"]),
            })
        } else {
            Err(Error::BufferTooShort {
                need: 0,
                have: 0,
                what: "hvc1 missing hvcC",
            })
        }
    }

    /// Create a new hvc1 sample entry.
    pub fn new_hvc1(config: HEVCDecoderConfigurationRecord) -> Self {
        let compressorname = {
            let mut c = [0u8; 32];
            c[0] = 12;
            c[1..12].copy_from_slice(b"HEVC Coding");
            c
        };
        Self {
            codec_type: *b"hvc1",
            visual: VisualSampleEntryFields {
                compressorname,
                ..VisualSampleEntryFields::default()
            },
            config: HEVCConfigurationBox::new(config),
            extra_boxes: Vec::new(),
        }
    }

    /// Create a new hev1 sample entry.
    pub fn new_hev1(config: HEVCDecoderConfigurationRecord) -> Self {
        let mut s = Self::new_hvc1(config);
        s.codec_type = *b"hev1";
        s
    }
}

impl Serialize for HEVCSampleEntry {
    type Error = Error;

    fn serialized_len(&self) -> usize {
        let mut n = 8 + VisualSampleEntryFields::serialized_len() + self.config.serialized_len();
        for eb in &self.extra_boxes {
            n += eb.serialized_len();
        }
        n
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let need = self.serialized_len();
        if buf.len() < need {
            return Err(Error::OutputBufferTooSmall {
                need,
                have: buf.len(),
            });
        }
        let mut cursor = 0usize;
        let size32 = need as u32;
        buf[cursor..cursor + 4].copy_from_slice(&size32.to_be_bytes());
        cursor += 4;
        buf[cursor..cursor + 4].copy_from_slice(&self.codec_type);
        cursor += 4;
        cursor += self.visual.serialize_into(&mut buf[cursor..])?;
        cursor += self.config.serialize_into(&mut buf[cursor..])?;
        for eb in &self.extra_boxes {
            cursor += eb.serialize_into(&mut buf[cursor..])?;
        }
        Ok(cursor)
    }
}

// ---------------------------------------------------------------------------
// VVC Sample Entry: vvc1 / vvi1
// ---------------------------------------------------------------------------

/// H.266/VVC sample entry — ISO/IEC 14496-15:2022 §11.3.3.
///
/// `vvc1` carries the parameter sets in the sample entry's `vvcC`; `vvi1`
/// allows in-band parameter sets. The `codec_type` field records which FourCC
/// was parsed / is to be emitted.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct VVCSampleEntry {
    /// The four-CC (`vvc1` or `vvi1`).
    pub codec_type: [u8; 4],
    /// Visual sample entry fields.
    pub visual: VisualSampleEntryFields,
    /// VVC configuration box (`vvcC`).
    pub config: crate::vvc_config::VvcConfigurationBox,
    /// Additional config boxes preserved verbatim.
    pub extra_boxes: Vec<OpaqueBox>,
}

impl VVCSampleEntry {
    /// Parse a VVC sample entry from full box bytes (including 8-byte header).
    pub fn bare_parse(bytes: &[u8]) -> Result<Self> {
        use crate::vvc_config::VvcConfigurationBox;
        if bytes.len() < 8 + 78 + 8 {
            return Err(Error::BufferTooShort {
                need: 8 + 80 + 8,
                have: bytes.len(),
                what: "vvc1 bare",
            });
        }
        let codec_type = [bytes[4], bytes[5], bytes[6], bytes[7]];
        let visual = VisualSampleEntryFields::parse_body(bytes, "vvc1")?;
        let config_region = &bytes[8 + VISUAL_SAMPLE_ENTRY_SIZE..];
        if let Some(vvcc) = find_config_box(config_region, b"vvcC") {
            let config = if vvcc.len() > 8 {
                VvcConfigurationBox::parse_body(&vvcc[8..])?
            } else {
                return Err(Error::BufferTooShort {
                    need: 8,
                    have: vvcc.len(),
                    what: "vvcC body",
                });
            };
            // As for HEVC: keep every sibling box (colr/pasp/btrt/clli/mdcv …),
            // not just the config (r04-W37).
            Ok(Self {
                codec_type,
                visual,
                config,
                extra_boxes: capture_extra_boxes(config_region, &[b"vvcC"]),
            })
        } else {
            Err(Error::BufferTooShort {
                need: 0,
                have: 0,
                what: "vvc1 missing vvcC",
            })
        }
    }

    /// Create a new `vvc1` sample entry.
    pub fn new_vvc1(config: crate::vvc_config::VvcConfigurationBox) -> Self {
        let compressorname = {
            let mut c = [0u8; 32];
            c[0] = 10;
            c[1..11].copy_from_slice(b"VVC Coding");
            c
        };
        Self {
            codec_type: *b"vvc1",
            visual: VisualSampleEntryFields {
                compressorname,
                ..VisualSampleEntryFields::default()
            },
            config,
            extra_boxes: Vec::new(),
        }
    }

    /// Create a new `vvi1` sample entry (in-band parameter sets).
    pub fn new_vvi1(config: crate::vvc_config::VvcConfigurationBox) -> Self {
        let mut s = Self::new_vvc1(config);
        s.codec_type = *b"vvi1";
        s
    }
}

impl Serialize for VVCSampleEntry {
    type Error = Error;

    fn serialized_len(&self) -> usize {
        let mut n = 8 + VisualSampleEntryFields::serialized_len() + self.config.serialized_len();
        for eb in &self.extra_boxes {
            n += eb.serialized_len();
        }
        n
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let need = self.serialized_len();
        if buf.len() < need {
            return Err(Error::OutputBufferTooSmall {
                need,
                have: buf.len(),
            });
        }
        let mut cursor = 0usize;
        let size32 = need as u32;
        buf[cursor..cursor + 4].copy_from_slice(&size32.to_be_bytes());
        cursor += 4;
        buf[cursor..cursor + 4].copy_from_slice(&self.codec_type);
        cursor += 4;
        cursor += self.visual.serialize_into(&mut buf[cursor..])?;
        cursor += self.config.serialize_into(&mut buf[cursor..])?;
        for eb in &self.extra_boxes {
            cursor += eb.serialize_into(&mut buf[cursor..])?;
        }
        Ok(cursor)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::avc_config::AVCDecoderConfigurationRecord;
    use crate::hevc_config::HEVCDecoderConfigurationRecord;
    use alloc::vec;
    use broadcast_common::Serialize;

    fn make_avc_config() -> AVCDecoderConfigurationRecord {
        AVCDecoderConfigurationRecord {
            configuration_version: 1,
            profile_indication: 100,
            profile_compatibility: 0,
            level_indication: 30,
            length_size_minus_one: 3,
            sps: alloc::vec![crate::nalu_types::AvcSps(vec![0x67, 0x64, 0x00, 0x1E])],
            pps: alloc::vec![crate::nalu_types::AvcPps(vec![0x68, 0xEE, 0x3C])],
            chroma_format: Some(1),
            bit_depth_luma_minus8: Some(0),
            bit_depth_chroma_minus8: Some(0),
            sps_ext: alloc::vec![],
        }
    }

    fn make_hevc_config() -> HEVCDecoderConfigurationRecord {
        HEVCDecoderConfigurationRecord {
            configuration_version: 1,
            general_profile_space: 0,
            general_tier_flag: false,
            general_profile_idc: 1,
            general_profile_compatibility_flags: 0,
            general_constraint_indicator_flags: 0,
            general_level_idc: 93,
            min_spatial_segmentation_idc: 0,
            parallelism_type: 0,
            chroma_format_idc: 1,
            bit_depth_luma_minus8: 0,
            bit_depth_chroma_minus8: 0,
            avg_frame_rate: 0,
            constant_frame_rate: 0,
            num_temporal_layers: 1,
            temporal_id_nested: false,
            length_size_minus_one: 3,
            arrays: alloc::vec![crate::nalu_types::HevcNalArray {
                array_completeness: true,
                nal_unit_type: 32,
                nalus: alloc::vec![crate::nalu_types::HevcNalUnit(vec![
                    0x40, 0x01, 0x0C, 0x01, 0xFF
                ])],
            }],
        }
    }

    /// Audit finding #2: a config-region child box declaring a wire `size`
    /// (ISO/IEC 14496-12:2015 §4.2 `Box.size`) far larger than the region
    /// actually holding it used to panic slicing `&region[off..off + size]`.
    /// Must clamp to what the region can hold, not panic — same discipline
    /// `init_segment::parse_stbl_children` already applies to its own child
    /// walk.
    /// r04-W37: `hvc1`/`hev1`/`vvc1` parsing must keep every sibling box, not
    /// just the codec config — `colr`, `pasp`, `clli`, `mdcv` and Dolby Vision's
    /// `dvcC`/`dvvC`. Unfixed, an HDR10 or Dolby Vision profile 8.1
    /// (`hvc1` + `dvcC`) source lost its colour signalling on an fMP4-to-fMP4
    /// repackage and played as SDR.
    #[test]
    fn hevc_entry_keeps_every_sibling_box() {
        let entry = HEVCSampleEntry::new_hvc1(make_hevc_config());
        let mut bytes = entry.to_bytes();
        // Append a `colr` (nclx) and a `dvcC` box after the entry's hvcC.
        let colr: [u8; 19] = [
            0x00, 0x00, 0x00, 0x13, b'c', b'o', b'l', b'r', b'n', b'c', b'l', b'x', 0x00, 0x09,
            0x00, 0x10, 0x00, 0x09, 0x80,
        ];
        let dvc_cfg: [u8; 12] = [
            0x00, 0x00, 0x00, 0x0C, b'd', b'v', b'c', b'C', 0x01, 0x00, 0x00, 0x00,
        ];
        bytes.extend_from_slice(&colr);
        bytes.extend_from_slice(&dvc_cfg);
        let total = bytes.len() as u32;
        bytes[0..4].copy_from_slice(&total.to_be_bytes());

        let parsed = HEVCSampleEntry::bare_parse(&bytes).unwrap();
        let types: alloc::vec::Vec<[u8; 4]> =
            parsed.extra_boxes.iter().map(|b| b.box_type).collect();
        assert!(
            types.contains(b"colr") && types.contains(b"dvcC"),
            "colr and dvcC must be captured, got {types:?}"
        );
        // And the whole entry re-serializes byte-for-byte.
        assert_eq!(parsed.to_bytes(), bytes);
    }

    /// The same for the VVC sample entry.
    #[test]
    fn vvc_entry_keeps_every_sibling_box() {
        use crate::vvc_config::VvcConfigurationBox;
        use crate::vvc_config::VvcDecoderConfigurationRecord;
        let entry =
            VVCSampleEntry::new_vvc1(VvcConfigurationBox::new(VvcDecoderConfigurationRecord {
                length_size_minus_one: 3,
                ptl_present: false,
                ols_idx: 0,
                num_sublayers: 1,
                constant_frame_rate: 0,
                chroma_format_idc: 1,
                bit_depth_minus8: 0,
                ptl: None,
                max_picture_width: 0,
                max_picture_height: 0,
                avg_frame_rate: 0,
                arrays: alloc::vec![],
            }));
        let mut bytes = entry.to_bytes();
        let colr: [u8; 19] = [
            0x00, 0x00, 0x00, 0x13, b'c', b'o', b'l', b'r', b'n', b'c', b'l', b'x', 0x00, 0x09,
            0x00, 0x10, 0x00, 0x09, 0x80,
        ];
        bytes.extend_from_slice(&colr);
        let total = bytes.len() as u32;
        bytes[0..4].copy_from_slice(&total.to_be_bytes());

        let parsed = VVCSampleEntry::bare_parse(&bytes).unwrap();
        assert!(
            parsed.extra_boxes.iter().any(|b| b.box_type == *b"colr"),
            "vvc1 must capture colr"
        );
        assert_eq!(parsed.to_bytes(), bytes);
    }

    /// A malformed trailing child box ends the walk and is dropped, keeping
    /// everything captured before it: `capture_extra_boxes` cannot slice a box
    /// whose declared size is under its own header length or past the region.
    /// The entry's config box is located independently, so it is never lost.
    #[test]
    fn capture_extra_boxes_stops_at_a_truncated_tail() {
        // A well-formed `colr`, then a box declaring a 0xFFFF size it cannot
        // possibly have.
        let mut region = alloc::vec::Vec::new();
        region.extend_from_slice(&[
            0x00, 0x00, 0x00, 0x0C, b'c', b'o', b'l', b'r', 0x01, 0x02, 0x03, 0x04,
        ]);
        let after = region.len();
        region.extend_from_slice(&[0x00, 0x00, 0xFF, 0xFF, b'b', b't', b'r', b't']);
        // A box after the damage is not reachable either — the walk stopped.
        region.extend_from_slice(&[0x00, 0x00, 0x00, 0x0C, b'c', b'l', b'l', b'i', 9, 9, 9, 9]);
        let boxes = capture_extra_boxes(&region, &[]);
        assert_eq!(boxes.len(), 1, "only the box before the damage is kept");
        assert_eq!(boxes[0].box_type, *b"colr");
        assert_eq!(boxes[0].data, vec![0x01, 0x02, 0x03, 0x04]);
        assert_eq!(after, 12);
        // A size below the 8-byte header is likewise rejected.
        let mut under = alloc::vec::Vec::new();
        under.extend_from_slice(&[0x00, 0x00, 0x00, 0x04, b'z', b'z', b'z', b'z']);
        assert!(capture_extra_boxes(&under, &[]).is_empty());
        // An exact-fit box is accepted (the boundary is `size >= 8 && off+size <= len`).
        let mut exact = alloc::vec::Vec::new();
        exact.extend_from_slice(&[0x00, 0x00, 0x00, 0x08, b'p', b'a', b's', b'p']);
        assert_eq!(capture_extra_boxes(&exact, &[]).len(), 1);
    }

    /// A sibling box placed *before* the config is captured too (the pre-fix
    /// AVC path only walked forward from `avcC`). The entry serializer writes
    /// the config box first, so the assertion is on capture, not on order.
    #[test]
    fn avc_entry_keeps_boxes_before_the_config() {
        let entry = AVCSampleEntry::new_avc1(make_avc_config());
        let bytes = entry.to_bytes();
        // Rebuild with a `pasp` box inserted before the avcC.
        let avcc_at = bytes.windows(4).position(|w| w == b"avcC").unwrap() - 4;
        let pasp: [u8; 16] = [
            0x00, 0x00, 0x00, 0x10, b'p', b'a', b's', b'p', 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
            0x00, 0x01,
        ];
        let mut with_pasp = alloc::vec::Vec::new();
        with_pasp.extend_from_slice(&bytes[..avcc_at]);
        with_pasp.extend_from_slice(&pasp);
        with_pasp.extend_from_slice(&bytes[avcc_at..]);
        let total = with_pasp.len() as u32;
        with_pasp[0..4].copy_from_slice(&total.to_be_bytes());

        let parsed = AVCSampleEntry::bare_parse(&with_pasp).unwrap();
        assert!(
            parsed.extra_boxes.iter().any(|b| b.box_type == *b"pasp"),
            "pasp before avcC must be captured"
        );
        // The re-serialized entry still carries exactly one `pasp`, with the
        // same body, and parses back to the same struct.
        let re = parsed.to_bytes();
        let pasp_at = re.windows(4).position(|w| w == b"pasp").unwrap();
        assert_eq!(&re[pasp_at..pasp_at + 12], &pasp[4..]);
        assert_eq!(AVCSampleEntry::bare_parse(&re).unwrap(), parsed);
        assert_eq!(re.len(), with_pasp.len(), "same total length");
    }

    /// A hostile (`0xFFFF_FFFF`) declared size must not panic the config-box
    /// search: the returned slice is clamped to the region that actually
    /// exists, so a caller slicing by the (unclamped) size cannot overrun.
    #[test]
    fn find_config_box_hostile_size_does_not_panic() {
        let mut region = alloc::vec![0u8; 8];
        region[0..4].copy_from_slice(&0xFFFF_FFFFu32.to_be_bytes());
        region[4..8].copy_from_slice(b"avcC");

        let found = find_config_box(&region, b"avcC").expect("fourcc matches at offset 0");
        assert_eq!(
            found.len(),
            region.len(),
            "hostile size must clamp to the region's actual remaining length"
        );
    }

    /// A hostile size on a box whose fourcc does *not* match the one being
    /// searched for must not panic either (the `off += size` advance uses
    /// the raw, unclamped size, which is fine as long as nothing slices with
    /// it — this pins that nothing does).
    #[test]
    fn find_config_box_hostile_size_non_matching_fourcc_does_not_panic() {
        let mut region = alloc::vec![0u8; 8];
        region[0..4].copy_from_slice(&0xFFFF_FFFFu32.to_be_bytes());
        region[4..8].copy_from_slice(b"zzzz");

        assert!(find_config_box(&region, b"avcC").is_none());
    }

    #[test]
    fn test_avc1_serialize() {
        let config = make_avc_config();
        let entry = AVCSampleEntry::new_avc1(config);
        let bytes = entry.to_bytes();
        assert!(bytes.len() > 8);
        assert_eq!(&bytes[4..8], b"avc1");
        assert!(bytes.windows(4).any(|w| w == b"avcC"));
    }

    #[test]
    fn test_avc3_serialize() {
        let config = make_avc_config();
        let entry = AVCSampleEntry::new_avc3(config);
        let bytes = entry.to_bytes();
        assert_eq!(&bytes[4..8], b"avc3");
    }

    #[test]
    fn test_hvc1_serialize() {
        let config = make_hevc_config();
        let entry = HEVCSampleEntry::new_hvc1(config);
        let bytes = entry.to_bytes();
        assert_eq!(&bytes[4..8], b"hvc1");
        assert!(bytes.windows(4).any(|w| w == b"hvcC"));
    }

    #[test]
    fn test_hev1_serialize() {
        let config = make_hevc_config();
        let entry = HEVCSampleEntry::new_hev1(config);
        let bytes = entry.to_bytes();
        assert_eq!(&bytes[4..8], b"hev1");
    }

    /// r04-W45: the `VisualSampleEntry` reserved fields (6 bytes after the box
    /// header, then `pre_defined(16) + reserved(16) + pre_defined[3]×32`) must be
    /// written as zeros, not skipped — `Serialize` accepts any `&mut [u8]`, so a
    /// dirty caller buffer would otherwise leak garbage into a conformance-gated
    /// field. Serializing into a 0xFF-filled buffer must equal `to_bytes()`.
    #[test]
    fn reserved_fields_written_as_zeros_into_a_dirty_buffer() {
        let entry = AVCSampleEntry::new_avc1(make_avc_config());
        let clean = entry.to_bytes();
        let mut dirty = vec![0xFFu8; clean.len()];
        let written = entry
            .serialize_into(&mut dirty)
            .expect("serialize into a correctly-sized buffer");
        assert_eq!(written, clean.len());
        assert_eq!(
            dirty, clean,
            "a 0xFF-filled buffer must yield the same bytes as to_bytes()"
        );
        // The reserved bytes are literally zero in the output.
        assert_eq!(
            &clean[8..14],
            &[0u8; 6],
            "6 reserved bytes after the header"
        );
        assert_eq!(
            &clean[16..32],
            &[0u8; 16],
            "pre_defined(16)+reserved(16) after data_reference_index"
        );
    }
}