arcly-stream 0.1.7

An open-extensible live-media streaming kernel: lock-free zero-copy frame fan-out, instant-start GOP cache, a pluggable multi-protocol ingestion layer (RTMP, RTSP, SRT, WHIP/WHEP shipped), and a feature-gated pure-Rust media plane (MPEG-TS/HLS/fMP4) — runtime, config, and metrics free.
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
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
//! A native, dependency-free **fragmented-MP4 / CMAF** muxer (`feature = "fmp4"`).
//!
//! Implements the [`Muxer`](super::Muxer) trait, producing the two artifacts
//! LL-HLS fMP4 egress needs:
//!
//! * an **initialization segment** (`ftyp` + `moov`, carrying the decoder
//!   configuration, e.g. `avcC`/`hvcC`) via
//!   [`init_segment`](super::Muxer::init_segment), referenced once from the
//!   playlist with `#EXT-X-MAP`; and
//! * **media fragments** (`moof` + `mdat`) per segment, with a `trun` sample
//!   table, signed composition-time offsets, and a `tfdt` base-media-decode-time
//!   for seamless concatenation.
//!
//! The **fragment path here is codec-generic** — samples are length-prefixed and
//! described structurally — so the same `moof`/`mdat` machinery serves any
//! codec; only the init segment's sample entry is codec-specific. This release
//! builds init segments for **H.264 (`avc1`)** and, behind their codec features,
//! **H.265 (`hvc1`, `codec-h265`)**, **AV1 (`av01`, `codec-av1`)** and **VVC
//! (`vvc1`, `codec-vvc`)** — all via one shared box writer. For H.265 and VVC the
//! profile-tier-level is read from the SPS, so the `hvcC`/`vvcC` and the HLS
//! codec string carry real values.
//!
//! ```no_run
//! # #[cfg(feature = "storage-fs")]
//! # async fn demo(handle: arcly_stream::StreamHandle) -> arcly_stream::Result<()> {
//! use arcly_stream::packager::{Fmp4Muxer, HlsSegmenter, Packager};
//! use arcly_stream::storage::FsStorage;
//!
//! // 1s parts, 6 segments of LL-HLS, written as init.m4s + segN.m4s.
//! let mut seg = HlsSegmenter::new(Fmp4Muxer::new(), FsStorage::new("/var/hls"), "live/cam", 6, 5)
//!     .low_latency(1.0);
//! let mut sub = handle.subscribe_resilient();
//! while let Some(frame) = sub.recv().await { seg.push(&frame).await?; }
//! seg.finish().await?;
//! # Ok(())
//! # }
//! ```

use super::Muxer;
use crate::{CodecId, MediaFrame, Result, StreamError};
use bytes::Bytes;

const TIMESCALE: u32 = 1000; // milliseconds — matches MediaFrame pts/dts units.
const VIDEO_TRACK_ID: u32 = 1;
const AUDIO_TRACK_ID: u32 = 2;
const FALLBACK_DURATION: u64 = TIMESCALE as u64 / 30; // ~33 ms when unknown.

/// A buffered sample within the current fragment (stored length-prefixed / AVCC).
struct Sample {
    data: Bytes,
    dts: i64,
    cts: i32, // pts − dts (composition offset)
    is_key: bool,
    duration: Option<u64>,
}

/// The decoder-config-derived state of the muxer's audio (AAC) track.
struct AudioTrack {
    /// Prebuilt `mp4a` sample entry (with `esds`).
    entry: Vec<u8>,
    /// Buffered audio samples for the current fragment.
    samples: Vec<Sample>,
    /// Audio track base-media-decode-time, advanced per fragment.
    base_decode_time: u64,
    /// HLS `CODECS` token (e.g. `mp4a.40.2`).
    codec_str: String,
}

/// Native fragmented-MP4 muxer for a single video track.
///
/// Construct with [`new`](Self::new), hand to an
/// [`HlsSegmenter`](super::HlsSegmenter) (or drive the [`Muxer`] trait directly).
/// The init segment is built for **H.264** (`avc1`) and, behind their codec
/// features, **H.265** (`hvc1`), **AV1** (`av01`) and **VVC** (`vvc1`); the
/// `moof`/`mdat` fragment path is codec-generic.
/// `Send` — owned by a single segmenter task. Audio frames are skipped (use a
/// dedicated audio rendition).
pub struct Fmp4Muxer {
    codec: Option<CodecId>,
    width: u16,
    height: u16,
    codec_str: Option<String>,
    /// Prebuilt video sample entry (`avc1`/`hvc1`/`av01`/`vvc1`), once a video
    /// CONFIG has been ingested.
    video_entry: Option<Vec<u8>>,
    /// The AAC audio track, when an audio CONFIG was present at init time.
    audio: Option<AudioTrack>,
    seq: u32,
    base_decode_time: u64,
    samples: Vec<Sample>,
}

impl Default for Fmp4Muxer {
    fn default() -> Self {
        Self::new()
    }
}

impl Fmp4Muxer {
    /// A new muxer, awaiting the first CONFIG access unit to build its init
    /// segment.
    pub fn new() -> Self {
        Self {
            codec: None,
            width: 0,
            height: 0,
            codec_str: None,
            video_entry: None,
            audio: None,
            seq: 1,
            base_decode_time: 0,
            samples: Vec::new(),
        }
    }

    /// Build the `avc1` sample-entry box (with `avcC`) and codec string from an
    /// Annex-B SPS/PPS config.
    fn ingest_h264_config(&mut self, config_record: &[u8]) -> Result<Vec<u8>> {
        let mut sps: Option<&[u8]> = None;
        let mut pps: Option<&[u8]> = None;
        for nal in crate::codec::h264::iter_nals_annexb(config_record) {
            match nal.first().map(|b| b & 0x1f) {
                Some(t) if t == crate::codec::h264::NAL_SPS => sps = Some(nal),
                Some(t) if t == crate::codec::h264::NAL_PPS => pps = Some(nal),
                _ => {}
            }
        }
        let sps = sps.ok_or_else(|| StreamError::codec("fmp4: no SPS in H.264 config"))?;
        let pps = pps.ok_or_else(|| StreamError::codec("fmp4: no PPS in H.264 config"))?;
        if sps.len() < 4 {
            return Err(StreamError::codec("fmp4: truncated SPS"));
        }
        let info = crate::codec::h264::parse_sps(sps)
            .ok_or_else(|| StreamError::codec("fmp4: unparseable SPS"))?;
        self.width = info.width as u16;
        self.height = info.height as u16;
        // avc1.PPCCLL — profile / constraint flags / level, from the SPS bytes.
        self.codec_str = Some(format!("avc1.{:02X}{:02X}{:02X}", sps[1], sps[2], sps[3]));

        // avcC (AVCDecoderConfigurationRecord).
        let mut c = Vec::with_capacity(16 + sps.len() + pps.len());
        c.push(1); // configurationVersion
        c.push(sps[1]); // AVCProfileIndication
        c.push(sps[2]); // profile_compatibility
        c.push(sps[3]); // AVCLevelIndication
        c.push(0xFF); // 6 reserved bits | lengthSizeMinusOne = 3
        c.push(0xE1); // 3 reserved bits | numOfSPS = 1
        c.extend_from_slice(&(sps.len() as u16).to_be_bytes());
        c.extend_from_slice(sps);
        c.push(1); // numOfPPS
        c.extend_from_slice(&(pps.len() as u16).to_be_bytes());
        c.extend_from_slice(pps);
        Ok(build_avc1(self.width, self.height, &c))
    }

    /// Build the `hvc1` sample-entry box (with `hvcC`) and codec string from an
    /// Annex-B VPS/SPS/PPS config access unit.
    #[cfg(feature = "codec-h265")]
    fn ingest_h265_config(&mut self, config_record: &[u8]) -> Result<Vec<u8>> {
        use crate::codec::{h265::H265, CodecParser};
        let (params, hvcc) = crate::codec::h265::hvcc_config_record(config_record)
            .ok_or_else(|| StreamError::codec("fmp4: no parsable SPS in H.265 config"))?;
        self.width = params.width as u16;
        self.height = params.height as u16;
        self.codec_str = Some(H265::hls_codec_string(&params));
        Ok(build_hvc1(self.width, self.height, &hvcc))
    }

    /// Build the `av01` sample-entry box (with `av1C`) and codec string from an
    /// AV1 sequence-header config access unit.
    #[cfg(feature = "codec-av1")]
    fn ingest_av1_config(&mut self, config_record: &[u8]) -> Result<Vec<u8>> {
        use crate::codec::{av1::Av1, CodecParser};
        let (params, av1c) = crate::codec::av1::av1c_config_record(config_record)
            .ok_or_else(|| StreamError::codec("fmp4: no AV1 sequence header in config"))?;
        self.width = params.width as u16;
        self.height = params.height as u16;
        self.codec_str = Some(Av1::hls_codec_string(&params));
        Ok(build_av01(self.width, self.height, &av1c))
    }

    /// Build the `vvc1` sample-entry box (with `vvcC`) and codec string from a
    /// VVC parameter-set config access unit.
    #[cfg(feature = "codec-vvc")]
    fn ingest_vvc_config(&mut self, config_record: &[u8]) -> Result<Vec<u8>> {
        use crate::codec::{vvc::Vvc, CodecParser};
        let (params, vvcc) =
            crate::codec::vvc::vvcc_config_record(config_record).ok_or_else(|| {
                StreamError::codec(
                    "fmp4: VVC config needs an SPS without a PTL block (parser limit)",
                )
            })?;
        self.width = params.width as u16;
        self.height = params.height as u16;
        self.codec_str = Some(Vvc::hls_codec_string(&params));
        Ok(build_vvc1(self.width, self.height, &vvcc))
    }

    /// Build the video sample entry for `codec` from its CONFIG access unit,
    /// recording the codec, dimensions, and prebuilt entry. Shared by
    /// `init_segment` (video-only) and `build_init_from` (with audio).
    fn ingest_video_config(&mut self, codec: CodecId, config_record: &[u8]) -> Result<Vec<u8>> {
        let entry = match codec {
            CodecId::H264 => self.ingest_h264_config(config_record)?,
            #[cfg(feature = "codec-h265")]
            CodecId::H265 => self.ingest_h265_config(config_record)?,
            #[cfg(feature = "codec-av1")]
            CodecId::AV1 => self.ingest_av1_config(config_record)?,
            #[cfg(feature = "codec-vvc")]
            CodecId::VVC => self.ingest_vvc_config(config_record)?,
            _ => {
                return Err(StreamError::UnsupportedCodec(format!(
                    "fmp4 init segment: {codec:?} not supported in this build"
                )))
            }
        };
        self.codec = Some(codec);
        self.video_entry = Some(entry.clone());
        Ok(entry)
    }

    /// Ingest an AAC `AudioSpecificConfig`, building the `mp4a` sample entry and
    /// the audio track that rides alongside the video in the same fMP4.
    fn set_audio_config(&mut self, asc: &[u8]) -> Result<()> {
        if asc.len() < 2 {
            return Err(StreamError::codec(
                "fmp4: truncated AAC AudioSpecificConfig",
            ));
        }
        // AudioSpecificConfig: 5-bit objectType, 4-bit freqIndex, 4-bit channels.
        let object_type = asc[0] >> 3;
        let freq_index = (((asc[0] & 0x07) << 1) | (asc[1] >> 7)) as usize;
        let channels = (asc[1] >> 3) & 0x0F;
        let sample_rate = AAC_SAMPLE_RATES.get(freq_index).copied().unwrap_or(48_000);
        self.audio = Some(AudioTrack {
            entry: build_mp4a(channels.max(1) as u16, sample_rate, asc),
            samples: Vec::new(),
            base_decode_time: 0,
            // mp4a.40.<objectType> — AAC-LC is mp4a.40.2.
            codec_str: format!("mp4a.40.{}", object_type.max(1)),
        });
        Ok(())
    }

    /// Build one `moof`+`mdat` fragment from the buffered video (and, when
    /// present, audio) samples — advancing each track's fragment sequence and
    /// base-media-decode-time — or `None` if no samples are buffered. Shared by
    /// `finish_segment` and `take_partial`.
    fn flush_fragment(&mut self) -> Option<Bytes> {
        let have_audio = self.audio.as_ref().is_some_and(|a| !a.samples.is_empty());
        if self.samples.is_empty() && !have_audio {
            return None;
        }

        // Assemble one TrackFrag per non-empty track (video first, then audio).
        let mut tracks: Vec<TrackFrag> = Vec::with_capacity(2);
        if !self.samples.is_empty() {
            let durations = sample_durations(&self.samples);
            tracks.push(TrackFrag {
                track_id: VIDEO_TRACK_ID,
                base_decode_time: self.base_decode_time,
                samples: &self.samples,
                durations,
            });
        }
        if let Some(audio) = self.audio.as_ref() {
            if !audio.samples.is_empty() {
                let durations = sample_durations(&audio.samples);
                tracks.push(TrackFrag {
                    track_id: AUDIO_TRACK_ID,
                    base_decode_time: audio.base_decode_time,
                    samples: &audio.samples,
                    durations,
                });
            }
        }

        let mut out = build_moof(self.seq, &tracks);
        // mdat: every track's sample data, in track order (matching the data
        // offsets patched into each `trun`).
        let mdat_len: usize = tracks
            .iter()
            .flat_map(|t| t.samples.iter())
            .map(|s| s.data.len())
            .sum();
        out.extend_from_slice(&((mdat_len + 8) as u32).to_be_bytes());
        out.extend_from_slice(b"mdat");
        for t in &tracks {
            for s in t.samples {
                out.extend_from_slice(&s.data);
            }
        }

        // Per-track fragment totals, captured before releasing the `tracks` borrow.
        let video_total: u64 = tracks
            .iter()
            .find(|t| t.track_id == VIDEO_TRACK_ID)
            .map(|t| t.durations.iter().sum())
            .unwrap_or(0);
        let audio_total: u64 = tracks
            .iter()
            .find(|t| t.track_id == AUDIO_TRACK_ID)
            .map(|t| t.durations.iter().sum())
            .unwrap_or(0);
        drop(tracks);

        self.base_decode_time += video_total;
        self.seq += 1;
        self.samples.clear();
        if let Some(audio) = self.audio.as_mut() {
            audio.base_decode_time += audio_total;
            audio.samples.clear();
        }
        Some(Bytes::from(out))
    }
}

/// Per-sample durations: inter-DTS deltas, with the last sample falling back to
/// its declared frame duration (or the previous delta).
fn sample_durations(samples: &[Sample]) -> Vec<u64> {
    let n = samples.len();
    let mut out = Vec::with_capacity(n);
    for i in 0..n {
        let dur = if i + 1 < n {
            (samples[i + 1].dts - samples[i].dts).max(0) as u64
        } else {
            samples[i]
                .duration
                .or_else(|| out.last().copied())
                .unwrap_or(FALLBACK_DURATION)
        };
        out.push(dur);
    }
    out
}

impl Muxer for Fmp4Muxer {
    fn extension(&self) -> &'static str {
        "m4s"
    }

    fn start_segment(&mut self) -> Result<()> {
        self.samples.clear();
        Ok(())
    }

    fn write(&mut self, frame: &MediaFrame) -> Result<()> {
        // Audio: buffer AAC access units into the audio track when one exists
        // (its config was present at init). A CONFIG frame carries no media
        // sample, and a non-AAC codec has no track here — both are skipped.
        if frame.is_audio() {
            if frame.flags.contains(crate::FrameFlags::CONFIG) || frame.codec != CodecId::AAC {
                return Ok(());
            }
            if let Some(audio) = self.audio.as_mut() {
                let raw = strip_adts(&frame.data);
                if !raw.is_empty() {
                    audio.samples.push(Sample {
                        data: raw,
                        dts: frame.pts, // audio has no separate decode order
                        cts: 0,
                        is_key: true, // every AAC AU is independently decodable
                        duration: frame.duration,
                    });
                }
            }
            return Ok(());
        }
        if !frame.is_video() {
            return Ok(());
        }
        // NAL codecs (H.264, VVC) are length-prefixed (4-byte) in mp4, not
        // Annex-B; AV1 temporal units are already in the size-delimited form
        // mp4 carries.
        let is_nal = matches!(
            self.codec,
            Some(CodecId::H264) | Some(CodecId::H265) | Some(CodecId::VVC)
        );
        let data = if is_nal {
            crate::codec::h264::annexb_to_avcc(&frame.data) // codec-agnostic NAL → 4-byte length
        } else {
            frame.data.clone()
        };
        if data.is_empty() {
            return Ok(());
        }
        self.samples.push(Sample {
            data,
            dts: frame.dts,
            cts: (frame.pts - frame.dts) as i32,
            is_key: frame.is_keyframe(),
            duration: frame.duration,
        });
        Ok(())
    }

    fn finish_segment(&mut self) -> Result<Bytes> {
        Ok(self.flush_fragment().unwrap_or_default())
    }

    fn take_partial(&mut self) -> Result<Option<Bytes>> {
        // An fMP4 LL-HLS part is exactly one `moof`+`mdat` fragment — the same
        // shape `finish_segment` produces — so the concatenation of a segment's
        // parts is byte-identical to packaging it as one fragment.
        Ok(self.flush_fragment())
    }

    fn init_segment(&mut self, codec: CodecId, config_record: &[u8]) -> Result<Option<Bytes>> {
        let sample_entry = self.ingest_video_config(codec, config_record)?;
        let mut seg = build_ftyp();
        seg.extend_from_slice(&build_moov(self.width, self.height, &sample_entry, None));
        Ok(Some(Bytes::from(seg)))
    }

    fn build_init_from(&mut self, configs: &[(CodecId, Bytes)]) -> Result<Option<Bytes>> {
        let mut video_entry = None;
        for (codec, data) in configs {
            match codec {
                CodecId::AAC => self.set_audio_config(data)?,
                CodecId::Opus => {} // no fMP4 Opus track here (WebRTC-only for now)
                _ => video_entry = Some(self.ingest_video_config(*codec, data)?),
            }
        }
        // A video track is required (the audio track rides alongside it).
        let Some(entry) = video_entry else {
            return Ok(None);
        };
        let mut seg = build_ftyp();
        seg.extend_from_slice(&build_moov(
            self.width,
            self.height,
            &entry,
            self.audio.as_ref(),
        ));
        Ok(Some(Bytes::from(seg)))
    }

    fn codec_string(&self) -> Option<String> {
        // Advertise both codecs when audio is muxed in (HLS `CODECS` is a list).
        match (&self.codec_str, self.audio.as_ref()) {
            (Some(v), Some(a)) => Some(format!("{v},{}", a.codec_str)),
            (Some(v), None) => Some(v.clone()),
            (None, _) => None,
        }
    }
}

// ── ISO-BMFF box writers ─────────────────────────────────────────────────────

/// `size(4) + type(4) + body`.
fn bx(typ: &[u8; 4], body: &[u8]) -> Vec<u8> {
    let mut v = Vec::with_capacity(8 + body.len());
    v.extend_from_slice(&((body.len() + 8) as u32).to_be_bytes());
    v.extend_from_slice(typ);
    v.extend_from_slice(body);
    v
}

/// A FullBox: `size + type + (version<<24 | flags) + body`.
fn full(typ: &[u8; 4], version: u8, flags: u32, body: &[u8]) -> Vec<u8> {
    let mut b = Vec::with_capacity(4 + body.len());
    b.extend_from_slice(&(((version as u32) << 24) | (flags & 0x00FF_FFFF)).to_be_bytes());
    b.extend_from_slice(body);
    bx(typ, &b)
}

const MATRIX_IDENTITY: [u32; 9] = [0x0001_0000, 0, 0, 0, 0x0001_0000, 0, 0, 0, 0x4000_0000];

fn put_matrix(v: &mut Vec<u8>) {
    for m in MATRIX_IDENTITY {
        v.extend_from_slice(&m.to_be_bytes());
    }
}

fn build_ftyp() -> Vec<u8> {
    let mut b = Vec::new();
    b.extend_from_slice(b"iso5"); // major_brand
    b.extend_from_slice(&0u32.to_be_bytes()); // minor_version
    for brand in [b"iso5", b"iso6", b"mp41"] {
        b.extend_from_slice(brand);
    }
    bx(b"ftyp", &b)
}

/// Build `moov` around the prebuilt video sample entry, adding an audio `trak`
/// when an AAC track is present (so the fMP4 carries both video and audio).
fn build_moov(width: u16, height: u16, video_entry: &[u8], audio: Option<&AudioTrack>) -> Vec<u8> {
    let next_track_id = if audio.is_some() {
        AUDIO_TRACK_ID + 1
    } else {
        2
    };
    let mut body = Vec::new();
    body.extend_from_slice(&build_mvhd(next_track_id));
    body.extend_from_slice(&build_video_trak(width, height, video_entry));
    if let Some(a) = audio {
        body.extend_from_slice(&build_audio_trak(&a.entry));
    }
    body.extend_from_slice(&build_mvex(audio.is_some()));
    bx(b"moov", &body)
}

fn build_mvhd(next_track_id: u32) -> Vec<u8> {
    let mut b = Vec::new();
    b.extend_from_slice(&0u32.to_be_bytes()); // creation_time
    b.extend_from_slice(&0u32.to_be_bytes()); // modification_time
    b.extend_from_slice(&TIMESCALE.to_be_bytes());
    b.extend_from_slice(&0u32.to_be_bytes()); // duration (fragmented → 0)
    b.extend_from_slice(&0x0001_0000u32.to_be_bytes()); // rate 1.0
    b.extend_from_slice(&0x0100u16.to_be_bytes()); // volume 1.0
    b.extend_from_slice(&0u16.to_be_bytes()); // reserved
    b.extend_from_slice(&[0u8; 8]); // reserved
    put_matrix(&mut b);
    b.extend_from_slice(&[0u8; 24]); // pre_defined
    b.extend_from_slice(&next_track_id.to_be_bytes());
    full(b"mvhd", 0, 0, &b)
}

fn build_video_trak(width: u16, height: u16, entry: &[u8]) -> Vec<u8> {
    let mut b = Vec::new();
    b.extend_from_slice(&build_tkhd(VIDEO_TRACK_ID, width, height, 0));
    b.extend_from_slice(&build_mdia(
        b"vide",
        b"VideoHandler\0",
        &build_video_minf(entry),
    ));
    bx(b"trak", &b)
}

fn build_audio_trak(entry: &[u8]) -> Vec<u8> {
    let mut b = Vec::new();
    // Volume 1.0 (0x0100) for audio; width/height 0.
    b.extend_from_slice(&build_tkhd(AUDIO_TRACK_ID, 0, 0, 0x0100));
    b.extend_from_slice(&build_mdia(
        b"soun",
        b"SoundHandler\0",
        &build_audio_minf(entry),
    ));
    bx(b"trak", &b)
}

fn build_tkhd(track_id: u32, width: u16, height: u16, volume: u16) -> Vec<u8> {
    let mut b = Vec::new();
    b.extend_from_slice(&0u32.to_be_bytes()); // creation_time
    b.extend_from_slice(&0u32.to_be_bytes()); // modification_time
    b.extend_from_slice(&track_id.to_be_bytes());
    b.extend_from_slice(&0u32.to_be_bytes()); // reserved
    b.extend_from_slice(&0u32.to_be_bytes()); // duration
    b.extend_from_slice(&[0u8; 8]); // reserved
    b.extend_from_slice(&0u16.to_be_bytes()); // layer
    b.extend_from_slice(&0u16.to_be_bytes()); // alternate_group
    b.extend_from_slice(&volume.to_be_bytes()); // volume (0 video, 0x0100 audio)
    b.extend_from_slice(&0u16.to_be_bytes()); // reserved
    put_matrix(&mut b);
    b.extend_from_slice(&((width as u32) << 16).to_be_bytes()); // 16.16 width
    b.extend_from_slice(&((height as u32) << 16).to_be_bytes()); // 16.16 height
    full(b"tkhd", 0, 0x0000_0007, &b) // enabled | in_movie | in_preview
}

fn build_mdia(handler: &[u8; 4], name: &[u8], minf: &[u8]) -> Vec<u8> {
    let mut b = Vec::new();
    b.extend_from_slice(&build_mdhd());
    b.extend_from_slice(&build_hdlr(handler, name));
    b.extend_from_slice(minf);
    bx(b"mdia", &b)
}

fn build_mdhd() -> Vec<u8> {
    let mut b = Vec::new();
    b.extend_from_slice(&0u32.to_be_bytes()); // creation_time
    b.extend_from_slice(&0u32.to_be_bytes()); // modification_time
    b.extend_from_slice(&TIMESCALE.to_be_bytes());
    b.extend_from_slice(&0u32.to_be_bytes()); // duration
    b.extend_from_slice(&0x55C4u16.to_be_bytes()); // language 'und'
    b.extend_from_slice(&0u16.to_be_bytes()); // pre_defined
    full(b"mdhd", 0, 0, &b)
}

fn build_hdlr(handler_type: &[u8; 4], name: &[u8]) -> Vec<u8> {
    let mut b = Vec::new();
    b.extend_from_slice(&0u32.to_be_bytes()); // pre_defined
    b.extend_from_slice(handler_type);
    b.extend_from_slice(&[0u8; 12]); // reserved
    b.extend_from_slice(name);
    full(b"hdlr", 0, 0, &b)
}

fn build_video_minf(entry: &[u8]) -> Vec<u8> {
    let mut b = Vec::new();
    b.extend_from_slice(&full(b"vmhd", 0, 1, &[0u8; 8])); // graphicsmode + opcolor
    b.extend_from_slice(&build_dinf());
    b.extend_from_slice(&build_stbl(entry));
    bx(b"minf", &b)
}

fn build_audio_minf(entry: &[u8]) -> Vec<u8> {
    let mut b = Vec::new();
    // smhd: balance (0) + reserved.
    b.extend_from_slice(&full(b"smhd", 0, 0, &[0u8; 4]));
    b.extend_from_slice(&build_dinf());
    b.extend_from_slice(&build_stbl(entry));
    bx(b"minf", &b)
}

fn build_dinf() -> Vec<u8> {
    // dref with a single self-contained 'url ' entry (flags = 1).
    let url = full(b"url ", 0, 1, &[]);
    let mut dref_body = Vec::new();
    dref_body.extend_from_slice(&1u32.to_be_bytes()); // entry_count
    dref_body.extend_from_slice(&url);
    let dref = full(b"dref", 0, 0, &dref_body);
    bx(b"dinf", &dref)
}

fn build_stbl(entry: &[u8]) -> Vec<u8> {
    let mut b = Vec::new();
    b.extend_from_slice(&build_stsd(entry));
    b.extend_from_slice(&full(b"stts", 0, 0, &0u32.to_be_bytes())); // entry_count 0
    b.extend_from_slice(&full(b"stsc", 0, 0, &0u32.to_be_bytes()));
    let mut stsz = Vec::new();
    stsz.extend_from_slice(&0u32.to_be_bytes()); // sample_size
    stsz.extend_from_slice(&0u32.to_be_bytes()); // sample_count
    b.extend_from_slice(&full(b"stsz", 0, 0, &stsz));
    b.extend_from_slice(&full(b"stco", 0, 0, &0u32.to_be_bytes()));
    bx(b"stbl", &b)
}

fn build_stsd(entry: &[u8]) -> Vec<u8> {
    let mut b = Vec::new();
    b.extend_from_slice(&1u32.to_be_bytes()); // entry_count
    b.extend_from_slice(entry);
    full(b"stsd", 0, 0, &b)
}

/// The common `VisualSampleEntry` header shared by `avc1` / `av01`, ending with
/// the codec-specific configuration box (`avcC` / `av1C`).
fn visual_sample_entry(typ: &[u8; 4], width: u16, height: u16, config_box: &[u8]) -> Vec<u8> {
    let mut b = Vec::new();
    b.extend_from_slice(&[0u8; 6]); // reserved
    b.extend_from_slice(&1u16.to_be_bytes()); // data_reference_index
    b.extend_from_slice(&0u16.to_be_bytes()); // pre_defined
    b.extend_from_slice(&0u16.to_be_bytes()); // reserved
    b.extend_from_slice(&[0u8; 12]); // pre_defined[3]
    b.extend_from_slice(&width.to_be_bytes());
    b.extend_from_slice(&height.to_be_bytes());
    b.extend_from_slice(&0x0048_0000u32.to_be_bytes()); // horizresolution 72dpi
    b.extend_from_slice(&0x0048_0000u32.to_be_bytes()); // vertresolution 72dpi
    b.extend_from_slice(&0u32.to_be_bytes()); // reserved
    b.extend_from_slice(&1u16.to_be_bytes()); // frame_count
    b.extend_from_slice(&[0u8; 32]); // compressorname
    b.extend_from_slice(&0x0018u16.to_be_bytes()); // depth
    b.extend_from_slice(&0xFFFFu16.to_be_bytes()); // pre_defined = -1
    b.extend_from_slice(config_box);
    bx(typ, &b)
}

/// `avc1` sample entry wrapping an `avcC` (AVCDecoderConfigurationRecord) body.
fn build_avc1(width: u16, height: u16, avcc: &[u8]) -> Vec<u8> {
    visual_sample_entry(b"avc1", width, height, &bx(b"avcC", avcc))
}

/// `av01` sample entry wrapping an `av1C` (AV1CodecConfigurationRecord) body.
#[cfg(feature = "codec-av1")]
fn build_av01(width: u16, height: u16, av1c: &[u8]) -> Vec<u8> {
    visual_sample_entry(b"av01", width, height, &bx(b"av1C", av1c))
}

/// `vvc1` sample entry wrapping a `vvcC` (VvcDecoderConfigurationRecord) body.
#[cfg(feature = "codec-vvc")]
fn build_vvc1(width: u16, height: u16, vvcc: &[u8]) -> Vec<u8> {
    visual_sample_entry(b"vvc1", width, height, &bx(b"vvcC", vvcc))
}

/// `hvc1` sample entry wrapping an `hvcC` (HEVCDecoderConfigurationRecord) body.
#[cfg(feature = "codec-h265")]
fn build_hvc1(width: u16, height: u16, hvcc: &[u8]) -> Vec<u8> {
    visual_sample_entry(b"hvc1", width, height, &bx(b"hvcC", hvcc))
}

/// `mvex` with one `trex` per track (video, and audio when present).
fn build_mvex(has_audio: bool) -> Vec<u8> {
    let trex = |track_id: u32| {
        let mut t = Vec::new();
        t.extend_from_slice(&track_id.to_be_bytes());
        t.extend_from_slice(&1u32.to_be_bytes()); // default_sample_description_index
        t.extend_from_slice(&0u32.to_be_bytes()); // default_sample_duration
        t.extend_from_slice(&0u32.to_be_bytes()); // default_sample_size
        t.extend_from_slice(&0u32.to_be_bytes()); // default_sample_flags
        full(b"trex", 0, 0, &t)
    };
    let mut body = trex(VIDEO_TRACK_ID);
    if has_audio {
        body.extend_from_slice(&trex(AUDIO_TRACK_ID));
    }
    bx(b"mvex", &body)
}

/// MPEG-4 sampling-frequency table indexed by `samplingFrequencyIndex`.
const AAC_SAMPLE_RATES: [u32; 13] = [
    96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350,
];

/// Strip an ADTS header from an AAC access unit if present, returning the raw
/// AU bytes mp4 carries (mp4 `mp4a` samples are raw AAC, never ADTS-framed).
fn strip_adts(data: &[u8]) -> Bytes {
    // ADTS syncword: 0xFFF in the top 12 bits.
    if data.len() > 7 && data[0] == 0xFF && (data[1] & 0xF6) == 0xF0 {
        // protection_absent (bit 0 of byte 1): 0 → 2-byte CRC → 9-byte header.
        let header = if data[1] & 0x01 == 0 { 9 } else { 7 };
        if data.len() > header {
            return Bytes::copy_from_slice(&data[header..]);
        }
    }
    Bytes::copy_from_slice(data)
}

/// An `mp4a` audio sample entry wrapping an `esds` (AAC `AudioSpecificConfig`).
fn build_mp4a(channels: u16, sample_rate: u32, asc: &[u8]) -> Vec<u8> {
    let mut b = Vec::new();
    b.extend_from_slice(&[0u8; 6]); // reserved
    b.extend_from_slice(&1u16.to_be_bytes()); // data_reference_index
    b.extend_from_slice(&[0u8; 8]); // reserved (2× u32)
    b.extend_from_slice(&channels.to_be_bytes()); // channelcount
    b.extend_from_slice(&16u16.to_be_bytes()); // samplesize
    b.extend_from_slice(&0u16.to_be_bytes()); // pre_defined
    b.extend_from_slice(&0u16.to_be_bytes()); // reserved
    b.extend_from_slice(&(sample_rate << 16).to_be_bytes()); // 16.16 samplerate
    b.extend_from_slice(&build_esds(asc));
    bx(b"mp4a", &b)
}

/// One MPEG-4 descriptor: `tag + length(1 byte) + body` (lengths here are small).
fn descriptor(tag: u8, body: &[u8]) -> Vec<u8> {
    let mut v = Vec::with_capacity(2 + body.len());
    v.push(tag);
    v.push(body.len() as u8);
    v.extend_from_slice(body);
    v
}

/// The `esds` box: ES_Descriptor → DecoderConfigDescriptor (AAC) →
/// DecoderSpecificInfo (the AudioSpecificConfig) → SLConfigDescriptor.
fn build_esds(asc: &[u8]) -> Vec<u8> {
    let dsi = descriptor(0x05, asc); // DecoderSpecificInfo
    let mut dcd = Vec::new();
    dcd.push(0x40); // objectTypeIndication = AAC
    dcd.push(0x15); // streamType = audio(5)<<2 | upstream(0)<<1 | reserved(1)
    dcd.extend_from_slice(&[0, 0, 0]); // bufferSizeDB
    dcd.extend_from_slice(&0u32.to_be_bytes()); // maxBitrate
    dcd.extend_from_slice(&0u32.to_be_bytes()); // avgBitrate
    dcd.extend_from_slice(&dsi);
    let dcd = descriptor(0x04, &dcd); // DecoderConfigDescriptor

    let mut es = Vec::new();
    es.extend_from_slice(&0u16.to_be_bytes()); // ES_ID
    es.push(0); // flags
    es.extend_from_slice(&dcd);
    es.extend_from_slice(&descriptor(0x06, &[0x02])); // SLConfigDescriptor (predefined=2)
    let es = descriptor(0x03, &es); // ES_Descriptor
    full(b"esds", 0, 0, &es)
}

/// Sync sample (keyframe) flags vs. a non-sync delta sample.
fn sample_flags(is_key: bool) -> u32 {
    if is_key {
        0x0200_0000 // sample_depends_on = 2 (I-frame), is_non_sync = 0
    } else {
        0x0101_0000 // sample_depends_on = 1, sample_is_non_sync_sample = 1
    }
}

/// One track's contribution to a fragment: its samples + per-sample durations.
struct TrackFrag<'a> {
    track_id: u32,
    base_decode_time: u64,
    samples: &'a [Sample],
    durations: Vec<u64>,
}

/// Build a `moof` with one `traf`/`trun` per track, patching each `trun`'s
/// `data_offset` to point at that track's region of the following `mdat` (tracks
/// are laid out in order, so each starts after the previous track's bytes).
fn build_moof(seq: u32, tracks: &[TrackFrag]) -> Vec<u8> {
    let mfhd = full(b"mfhd", 0, 0, &seq.to_be_bytes());
    let mut moof_body = Vec::new();
    moof_body.extend_from_slice(&mfhd);

    // Absolute position (within moof_body) of each track's trun data_offset field.
    let mut data_offset_positions = Vec::with_capacity(tracks.len());

    for t in tracks {
        // tfhd: default-base-is-moof so data_offset is relative to the moof start.
        let tfhd = full(b"tfhd", 0, 0x0002_0000, &t.track_id.to_be_bytes());
        let tfdt = full(b"tfdt", 1, 0, &t.base_decode_time.to_be_bytes());

        let trun_flags: u32 = 0x0001 | 0x0100 | 0x0200 | 0x0400 | 0x0800;
        let mut trun_body = Vec::new();
        trun_body.extend_from_slice(&(t.samples.len() as u32).to_be_bytes());
        let data_offset_pos_in_body = trun_body.len();
        trun_body.extend_from_slice(&0i32.to_be_bytes()); // data_offset (patched below)
        for (s, &dur) in t.samples.iter().zip(&t.durations) {
            trun_body.extend_from_slice(&(dur as u32).to_be_bytes());
            trun_body.extend_from_slice(&(s.data.len() as u32).to_be_bytes());
            trun_body.extend_from_slice(&sample_flags(s.is_key).to_be_bytes());
            trun_body.extend_from_slice(&s.cts.to_be_bytes());
        }
        let trun = full(b"trun", 1, trun_flags, &trun_body);

        let mut traf_body = Vec::new();
        traf_body.extend_from_slice(&tfhd);
        traf_body.extend_from_slice(&tfdt);
        let trun_pos_in_traf_body = traf_body.len();
        traf_body.extend_from_slice(&trun);
        let traf = bx(b"traf", &traf_body);

        let traf_pos_in_moof_body = moof_body.len();
        moof_body.extend_from_slice(&traf);
        // data_offset field = traf header(8) + trun_pos + trun header+fullbox(12)
        //   + data_offset_pos_in_body, all relative to moof_body.
        data_offset_positions
            .push(traf_pos_in_moof_body + 8 + trun_pos_in_traf_body + 12 + data_offset_pos_in_body);
    }

    let mut moof = bx(b"moof", &moof_body);
    let mdat_data_start = moof.len() + 8; // moof + mdat header

    // Patch each track's data_offset: cumulative sample bytes precede each track.
    let mut cumulative = 0usize;
    for (i, t) in tracks.iter().enumerate() {
        let abs = 8 + data_offset_positions[i]; // +8 for the moof box header
        let data_offset = (mdat_data_start + cumulative) as i32;
        moof[abs..abs + 4].copy_from_slice(&data_offset.to_be_bytes());
        cumulative += t.samples.iter().map(|s| s.data.len()).sum::<usize>();
    }
    moof
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{CodecId, FrameFlags, MediaFrame};
    use bytes::Bytes;

    // A real baseline SPS (profile 66, level 31) + a minimal PPS, Annex-B framed.
    fn h264_config() -> Vec<u8> {
        let sps = [0x67u8, 0x42, 0x00, 0x1F, 0xF4, 0x02, 0x80, 0x2D, 0x80];
        let pps = [0x68u8, 0xCE, 0x3C, 0x80];
        let mut v = vec![0, 0, 0, 1];
        v.extend_from_slice(&sps);
        v.extend_from_slice(&[0, 0, 0, 1]);
        v.extend_from_slice(&pps);
        v
    }

    fn annexb_frame(pts: i64, is_key: bool) -> MediaFrame {
        let nal_type = if is_key { 0x65 } else { 0x41 }; // IDR vs non-IDR slice
        let data = Bytes::from(vec![0, 0, 0, 1, nal_type, 0xAA, 0xBB]);
        MediaFrame::new_video(pts, pts, data, CodecId::H264, is_key)
    }

    /// Walk the top-level boxes and assert their sizes tile the buffer exactly.
    fn box_types(buf: &[u8]) -> Vec<String> {
        let mut types = Vec::new();
        let mut i = 0;
        while i + 8 <= buf.len() {
            let size = u32::from_be_bytes(buf[i..i + 4].try_into().unwrap()) as usize;
            let typ = String::from_utf8_lossy(&buf[i + 4..i + 8]).to_string();
            types.push(typ);
            assert!(size >= 8 && i + size <= buf.len(), "box size out of range");
            i += size;
        }
        assert_eq!(i, buf.len(), "boxes must tile the buffer exactly");
        types
    }

    #[test]
    fn init_segment_has_ftyp_moov_and_codec_string() {
        let mut m = Fmp4Muxer::new();
        let init = m
            .init_segment(CodecId::H264, &h264_config())
            .unwrap()
            .expect("init segment");
        assert_eq!(box_types(&init), vec!["ftyp", "moov"]);
        // Sample entry + decoder config present.
        assert!(find(&init, b"avc1"));
        assert!(find(&init, b"avcC"));
        assert!(find(&init, b"mvex"));
        assert_eq!(m.codec_string().as_deref(), Some("avc1.42001F"));
    }

    #[test]
    fn unsupported_codec_init_is_rejected() {
        let mut m = Fmp4Muxer::new();
        // VP9 has no fMP4 init-segment support in this release.
        assert!(m.init_segment(CodecId::VP9, &[0, 0]).is_err());
    }

    #[cfg(feature = "codec-h265")]
    #[test]
    fn h265_init_segment_has_hvc1_and_hvcc() {
        use crate::codec::testutil::BitWriter;

        // Minimal HEVC SPS for 1920x1088 (Main, level 4.0), mirroring the codec
        // module's fixture, plus a VPS and PPS so the hvcC carries all arrays.
        let mut w = BitWriter::default();
        w.bits(0, 4); // sps_video_parameter_set_id
        w.bits(0, 3); // sps_max_sub_layers_minus1
        w.bit(0); // sps_temporal_id_nesting_flag
        w.bits(0, 2); // general_profile_space
        w.bit(0); // general_tier_flag
        w.bits(1, 5); // general_profile_idc = Main
        w.bits(0, 32); // compatibility flags
        w.bits(0, 32); // constraint (hi)
        w.bits(0, 16); // constraint (lo)
        w.bits(120, 8); // general_level_idc
        w.ue(0); // sps_seq_parameter_set_id
        w.ue(1); // chroma_format_idc
        w.ue(1920); // pic_width
        w.ue(1080); // pic_height
        w.bit(0); // conformance_window_flag
        let mut sps = vec![0x42u8, 0x01];
        sps.extend_from_slice(&w.bytes());

        let mut config = vec![0, 0, 0, 1, 0x40, 0x01, 0xAA]; // VPS
        config.extend_from_slice(&[0, 0, 0, 1]);
        config.extend_from_slice(&sps);
        config.extend_from_slice(&[0, 0, 0, 1, 0x44, 0x01, 0xBB]); // PPS

        let mut m = Fmp4Muxer::new();
        let init = m
            .init_segment(CodecId::H265, &config)
            .unwrap()
            .expect("init segment");
        assert_eq!(box_types(&init), vec!["ftyp", "moov"]);
        assert!(find(&init, b"hvc1"), "hvc1 sample entry present");
        assert!(find(&init, b"hvcC"), "hvcC decoder config present");
        assert!(
            m.codec_string()
                .as_deref()
                .is_some_and(|s| s.starts_with("hvc1.")),
            "HEVC codec string"
        );
    }

    #[cfg(feature = "codec-av1")]
    #[test]
    fn av1_init_segment_has_av01_and_av1c() {
        use crate::codec::testutil::BitWriter;

        // A sequence-header OBU for 1920x1080, profile 0 (mirrors the AV1 parser
        // test), wrapped as a size-delimited temporal unit.
        let mut w = BitWriter::default();
        w.bits(0, 3); // seq_profile
        w.bit(0); // still_picture
        w.bit(0); // reduced_still_picture_header
        w.bit(0); // timing_info_present_flag
        w.bit(0); // initial_display_delay_present_flag
        w.bits(0, 5); // operating_points_cnt_minus1
        w.bits(0, 12); // operating_point_idc[0]
        w.bits(1, 5); // seq_level_idx[0]
        w.bits(11, 4); // frame_width_bits_minus_1
        w.bits(11, 4); // frame_height_bits_minus_1
        w.bits(1919, 12);
        w.bits(1079, 12);
        w.align();
        let payload = w.bytes();
        let mut config = vec![0x0A, payload.len() as u8];
        config.extend_from_slice(&payload);

        let mut m = Fmp4Muxer::new();
        let init = m
            .init_segment(CodecId::AV1, &config)
            .unwrap()
            .expect("av1 init segment");
        assert_eq!(box_types(&init), vec!["ftyp", "moov"]);
        assert!(find(&init, b"av01"), "av01 sample entry");
        assert!(find(&init, b"av1C"), "av1C config box");
        assert_eq!(m.codec_string().as_deref(), Some("av01.0.01M.08"));

        // AV1 temporal units are muxed verbatim (no Annex-B → AVCC rewrite).
        m.start_segment().unwrap();
        let mut frame = MediaFrame::new_video(
            0,
            0,
            Bytes::from(vec![0x32, 0x02, 0xAA, 0xBB]), // OBU_FRAME
            CodecId::AV1,
            true,
        );
        frame.duration = Some(33);
        m.write(&frame).unwrap();
        let frag = m.finish_segment().unwrap();
        assert_eq!(box_types(&frag), vec!["moof", "mdat"]);
        // mdat carries the OBU bytes unchanged.
        assert!(find(&frag, &[0x32, 0x02, 0xAA, 0xBB]));
    }

    #[test]
    fn fragment_has_moof_mdat_and_correct_sample_count() {
        let mut m = Fmp4Muxer::new();
        m.init_segment(CodecId::H264, &h264_config()).unwrap();
        m.start_segment().unwrap();
        m.write(&annexb_frame(0, true)).unwrap();
        m.write(&annexb_frame(40, false)).unwrap();
        m.write(&annexb_frame(80, false)).unwrap();
        // An audio frame is skipped, not muxed into the video track.
        let audio = MediaFrame::new_audio(80, Bytes::from_static(b"aac"), CodecId::AAC);
        m.write(&audio).unwrap();

        let frag = m.finish_segment().unwrap();
        assert_eq!(box_types(&frag), vec!["moof", "mdat"]);
        assert!(find(&frag, b"tfdt"));
        assert!(find(&frag, b"trun"));

        // sample_count is the u32 right after the trun full-box header.
        let trun_at = position(&frag, b"trun").expect("trun present");
        let count = u32::from_be_bytes(frag[trun_at + 8..trun_at + 12].try_into().unwrap());
        assert_eq!(count, 3, "three video samples, audio skipped");
    }

    #[test]
    fn base_decode_time_advances_across_fragments() {
        let mut m = Fmp4Muxer::new();
        m.init_segment(CodecId::H264, &h264_config()).unwrap();

        m.start_segment().unwrap();
        m.write(&annexb_frame(0, true)).unwrap();
        m.write(&annexb_frame(40, false)).unwrap();
        let _ = m.finish_segment().unwrap();
        // Sample 0 = 40ms (DTS delta); last sample falls back to the prior delta
        // (40ms) → fragment total 80ms.
        assert_eq!(m.base_decode_time, 80);

        m.start_segment().unwrap();
        m.write(&annexb_frame(80, true)).unwrap();
        let frag2 = m.finish_segment().unwrap();
        // tfdt in fragment 2 carries the advanced base decode time.
        let tfdt_at = position(&frag2, b"tfdt").unwrap();
        let base = u64::from_be_bytes(frag2[tfdt_at + 8..tfdt_at + 16].try_into().unwrap());
        assert_eq!(base, 80);
    }

    #[cfg(feature = "codec-vvc")]
    #[test]
    fn vvc_init_segment_has_vvc1_and_vvcc() {
        use crate::codec::testutil::BitWriter;

        // VVC SPS for 1920x1080, 4:2:0, PTL block absent (mirrors the VVC test).
        let mut w = BitWriter::default();
        w.bits(0, 4); // sps_seq_parameter_set_id
        w.bits(0, 4); // sps_video_parameter_set_id
        w.bits(0, 3); // sps_max_sublayers_minus1
        w.bits(1, 2); // chroma_format_idc = 4:2:0
        w.bits(0, 2); // sps_log2_ctu_size_minus5
        w.bit(0); // sps_ptl_dpb_hrd_params_present_flag = 0
        w.bit(0); // sps_gdr_enabled_flag
        w.bit(0); // sps_ref_pic_resampling_enabled_flag
        w.ue(1920);
        w.ue(1080);
        w.bit(0); // sps_conformance_window_flag
        let mut sps = vec![0x00u8, 0x79]; // NAL header: nuh_unit_type 15 (SPS)
        sps.extend_from_slice(&w.bytes());

        let mut config = vec![0, 0, 0, 1];
        config.extend_from_slice(&sps);

        let mut m = Fmp4Muxer::new();
        let init = m
            .init_segment(CodecId::VVC, &config)
            .unwrap()
            .expect("vvc init segment");
        assert_eq!(box_types(&init), vec!["ftyp", "moov"]);
        assert!(find(&init, b"vvc1"), "vvc1 sample entry");
        assert!(find(&init, b"vvcC"), "vvcC config box");
        assert_eq!(m.codec_string().as_deref(), Some("vvc1.0.L0"));

        // VVC samples are length-prefixed (4-byte) like H.264.
        m.start_segment().unwrap();
        let mut frame = MediaFrame::new_video(
            0,
            0,
            Bytes::from(vec![0, 0, 0, 1, 0x00, 0x39, 0xAA]), // IDR_W_RADL Annex-B
            CodecId::VVC,
            true,
        );
        frame.duration = Some(40);
        m.write(&frame).unwrap();
        let frag = m.finish_segment().unwrap();
        assert_eq!(box_types(&frag), vec!["moof", "mdat"]);
        // The NAL was rewritten to a 4-byte length prefix (len 3 → 00 00 00 03).
        assert!(find(&frag, &[0x00, 0x00, 0x00, 0x03, 0x00, 0x39, 0xAA]));
    }

    // AAC-LC AudioSpecificConfig: objectType 2, freqIndex 4 (44100), 2 channels.
    fn aac_asc() -> Vec<u8> {
        vec![0x12, 0x10]
    }

    #[test]
    fn init_with_audio_has_video_and_audio_traks() {
        let mut m = Fmp4Muxer::new();
        let configs = [
            (CodecId::H264, Bytes::from(h264_config())),
            (CodecId::AAC, Bytes::from(aac_asc())),
        ];
        let init = m.build_init_from(&configs).unwrap().expect("init segment");
        assert_eq!(box_types(&init), vec!["ftyp", "moov"]);
        // Video + audio sample entries and their config boxes are present.
        assert!(find(&init, b"avc1") && find(&init, b"avcC"), "video entry");
        assert!(find(&init, b"mp4a") && find(&init, b"esds"), "audio entry");
        assert!(find(&init, b"SoundHandler"), "audio handler");
        assert!(find(&init, b"VideoHandler"), "video handler");
        // Two `trak` boxes and two `trex` entries in mvex.
        assert_eq!(
            init.windows(4).filter(|w| *w == b"trak").count(),
            2,
            "two traks"
        );
        assert_eq!(init.windows(4).filter(|w| *w == b"trex").count(), 2);
        // CODECS lists both.
        let cs = m.codec_string().unwrap();
        assert!(
            cs.contains("avc1.") && cs.contains("mp4a.40.2"),
            "codecs: {cs}"
        );
    }

    #[test]
    fn fragment_muxes_audio_alongside_video() {
        let mut m = Fmp4Muxer::new();
        m.build_init_from(&[
            (CodecId::H264, Bytes::from(h264_config())),
            (CodecId::AAC, Bytes::from(aac_asc())),
        ])
        .unwrap();
        m.start_segment().unwrap();
        m.write(&annexb_frame(0, true)).unwrap();
        m.write(&annexb_frame(40, false)).unwrap();
        // Two AAC audio frames (raw AU; mp4a samples are not ADTS-framed).
        m.write(&MediaFrame::new_audio(
            0,
            Bytes::from_static(&[0x01, 0x02, 0x03]),
            CodecId::AAC,
        ))
        .unwrap();
        m.write(&MediaFrame::new_audio(
            21,
            Bytes::from_static(&[0x04, 0x05]),
            CodecId::AAC,
        ))
        .unwrap();

        let frag = m.finish_segment().unwrap();
        assert_eq!(box_types(&frag), vec!["moof", "mdat"]);
        // One traf per track (video + audio).
        assert_eq!(
            frag.windows(4).filter(|w| *w == b"traf").count(),
            2,
            "two trafs"
        );
        // The audio AU bytes are carried in the mdat.
        assert!(find(&frag, &[0x01, 0x02, 0x03]), "audio sample 1 in mdat");
        assert!(find(&frag, &[0x04, 0x05]), "audio sample 2 in mdat");
    }

    #[test]
    fn strip_adts_removes_header() {
        // A 7-byte ADTS header (protection_absent=1) + payload.
        let adts = [0xFF, 0xF1, 0x50, 0x80, 0x00, 0x1F, 0xFC, 0xAA, 0xBB];
        assert_eq!(&strip_adts(&adts)[..], &[0xAA, 0xBB]);
        // Raw AAC (no syncword) is passed through unchanged.
        assert_eq!(&strip_adts(&[0x01, 0x02])[..], &[0x01, 0x02]);
    }

    #[test]
    fn config_without_sps_errors() {
        let mut m = Fmp4Muxer::new();
        // PPS only — no SPS.
        let cfg = vec![0, 0, 0, 1, 0x68, 0xCE, 0x3C, 0x80];
        assert!(m.init_segment(CodecId::H264, &cfg).is_err());
    }

    #[test]
    fn empty_fragment_yields_no_bytes() {
        let mut m = Fmp4Muxer::new();
        m.start_segment().unwrap();
        assert!(m.finish_segment().unwrap().is_empty());
    }

    fn find(buf: &[u8], needle: &[u8]) -> bool {
        position(buf, needle).is_some()
    }
    fn position(buf: &[u8], needle: &[u8]) -> Option<usize> {
        buf.windows(needle.len()).position(|w| w == needle)
    }

    #[test]
    fn integrates_with_segmenter_via_ext_x_map() {
        use crate::packager::{HlsSegmenter, Packager};
        use crate::testing::InMemoryStorage;
        use crate::traits::StorageBackend;

        tokio_test_block(async {
            let store = InMemoryStorage::new();
            let mut seg = HlsSegmenter::new(Fmp4Muxer::new(), store.clone(), "live/fmp4", 2, 5);

            let mut cfg =
                MediaFrame::new_video(0, 0, Bytes::from(h264_config()), CodecId::H264, true);
            cfg.flags |= FrameFlags::CONFIG;
            seg.push(&cfg).await.unwrap();
            for i in 0..6 {
                seg.push(&annexb_frame(i * 1000, true)).await.unwrap();
            }
            seg.finish().await.unwrap();

            assert!(store.get("live/fmp4/init.m4s").await.is_ok());
            let pl = String::from_utf8(store.get("live/fmp4/index.m3u8").await.unwrap().to_vec())
                .unwrap();
            assert!(pl.contains("#EXT-X-MAP:URI=\"init.m4s\""));
        });
    }

    #[test]
    fn segmenter_builds_init_with_audio_from_both_configs() {
        use crate::packager::{HlsSegmenter, Packager};
        use crate::testing::InMemoryStorage;
        use crate::traits::StorageBackend;

        tokio_test_block(async {
            let store = InMemoryStorage::new();
            let mut seg = HlsSegmenter::new(Fmp4Muxer::new(), store.clone(), "live/av", 2, 5);

            // Video CONFIG then audio CONFIG (the cached-config replay order),
            // both before any media sample.
            let mut vcfg =
                MediaFrame::new_video(0, 0, Bytes::from(h264_config()), CodecId::H264, true);
            vcfg.flags |= FrameFlags::CONFIG;
            seg.push(&vcfg).await.unwrap();
            let mut acfg = MediaFrame::new_audio(0, Bytes::from(aac_asc()), CodecId::AAC);
            acfg.flags |= FrameFlags::CONFIG;
            seg.push(&acfg).await.unwrap();

            // Media: keyframes + audio AUs.
            for i in 0..6 {
                seg.push(&annexb_frame(i * 1000, true)).await.unwrap();
                seg.push(&MediaFrame::new_audio(
                    i * 1000,
                    Bytes::from_static(&[0xAA, 0xBB]),
                    CodecId::AAC,
                ))
                .await
                .unwrap();
            }
            seg.finish().await.unwrap();

            // The deferred init segment carries both tracks.
            let init = store.get("live/av/init.m4s").await.expect("init written");
            assert!(find(&init, b"mp4a"), "init has the audio sample entry");
            assert!(find(&init, b"avc1"), "init has the video sample entry");
        });
    }

    fn tokio_test_block<F: std::future::Future>(fut: F) -> F::Output {
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap()
            .block_on(fut)
    }
}