transmux 0.19.0

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.
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
//! 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;

// ---------------------------------------------------------------------------
// 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
        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
        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).
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];
        if ty == fourcc {
            return Some(&region[off..off + size]);
        }
        off += size;
    }
    None
}

// ---------------------------------------------------------------------------
// 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() < 8 + 78 + 8 {
            return Err(Error::BufferTooShort {
                need: 8 + 78 + 8,
                have: bytes.len(),
                what: "avc1 bare",
            });
        }
        let codec_type = [bytes[4], bytes[5], bytes[6], bytes[7]];
        let body = &bytes[8..];
        // SampleEntry: reserved(6) + data_reference_index(2) = body[0..7]
        let data_reference_index = u16::from_be_bytes([body[6], body[7]]);
        // VisualSampleEntry (§12.1.3): 16 reserved bytes (pre_defined(16) +
        // reserved(16) + pre_defined[3]) precede width → width at body[24].
        let width = u16::from_be_bytes([body[24], body[25]]);
        let height = u16::from_be_bytes([body[26], body[27]]);
        let horizontal_resolution = u32::from_be_bytes([body[28], body[29], body[30], body[31]]);
        let vertical_resolution = u32::from_be_bytes([body[32], body[33], body[34], body[35]]);
        let data_size = u32::from_be_bytes([body[36], body[37], body[38], body[39]]);
        let frame_count = u16::from_be_bytes([body[40], body[41]]);
        let mut compressorname = [0u8; 32];
        compressorname.copy_from_slice(&body[42..74]);
        let depth = u16::from_be_bytes([body[74], body[75]]);
        let predefined = u16::from_be_bytes([body[76], body[77]]);
        let visual = VisualSampleEntryFields {
            data_reference_index,
            width,
            height,
            horizontal_resolution,
            vertical_resolution,
            data_size,
            frame_count,
            compressorname,
            depth,
            predefined,
        };
        // Find avcC in the config region (starting at body[78] since visual fixed = 78 bytes)
        let config_region = &body[78..];
        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",
                });
            };
            // Capture extra boxes after avcC (e.g. pasp, btrt)
            let avcc_start = avcc.as_ptr() as usize - config_region.as_ptr() as usize;
            let avcc_end = avcc_start + avcc.len();
            let mut extra_boxes = Vec::new();
            let mut eb_off = avcc_end;
            while eb_off + 8 <= config_region.len() {
                let eb_sz = u32::from_be_bytes([
                    config_region[eb_off],
                    config_region[eb_off + 1],
                    config_region[eb_off + 2],
                    config_region[eb_off + 3],
                ]) as usize;
                if eb_sz < 8 {
                    break;
                }
                let bt = [
                    config_region[eb_off + 4],
                    config_region[eb_off + 5],
                    config_region[eb_off + 6],
                    config_region[eb_off + 7],
                ];
                let d = config_region[eb_off + 8..eb_off + eb_sz.min(config_region.len() - eb_off)]
                    .to_vec();
                extra_boxes.push(OpaqueBox {
                    box_type: bt,
                    data: d,
                });
                eb_off += eb_sz;
            }
            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)
    }
}

/// 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() < 8 + 78 + 8 {
            return Err(Error::BufferTooShort {
                need: 8 + 80 + 8,
                have: bytes.len(),
                what: "hvc1 bare",
            });
        }
        let codec_type = [bytes[4], bytes[5], bytes[6], bytes[7]];
        let body = &bytes[8..];
        // SampleEntry: reserved(6) + data_reference_index(2) = body[0..7].
        let data_reference_index = u16::from_be_bytes([body[6], body[7]]);
        // VisualSampleEntry (§12.1.3): 16 reserved bytes (pre_defined(16) +
        // reserved(16) + pre_defined[3]) precede width → width at body[24]
        // (matching `VisualSampleEntryFields::parse_body` and the AVC entry).
        let width = u16::from_be_bytes([body[24], body[25]]);
        let height = u16::from_be_bytes([body[26], body[27]]);
        let horizontal_resolution = u32::from_be_bytes([body[28], body[29], body[30], body[31]]);
        let vertical_resolution = u32::from_be_bytes([body[32], body[33], body[34], body[35]]);
        let data_size = u32::from_be_bytes([body[36], body[37], body[38], body[39]]);
        let frame_count = u16::from_be_bytes([body[40], body[41]]);
        let mut compressorname = [0u8; 32];
        compressorname.copy_from_slice(&body[42..74]);
        let depth = u16::from_be_bytes([body[74], body[75]]);
        let predefined = u16::from_be_bytes([body[76], body[77]]);
        let visual = VisualSampleEntryFields {
            data_reference_index,
            width,
            height,
            horizontal_resolution,
            vertical_resolution,
            data_size,
            frame_count,
            compressorname,
            depth,
            predefined,
        };
        let config_region = &body[78..];
        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",
                });
            };
            Ok(Self {
                codec_type,
                visual,
                config,
                extra_boxes: Vec::new(),
            })
        } 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",
                });
            };
            Ok(Self {
                codec_type,
                visual,
                config,
                extra_boxes: Vec::new(),
            })
        } 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
                ])],
            }],
        }
    }

    #[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");
    }
}