transmux 0.29.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, 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
//! AAC `AudioSpecificConfig` (ASC) — ISO/IEC 14496-3:2001 §1.6.2.1 Table 1.8.
//!
//! Bit-packed (`bslbf`/`uimsbf`, big-endian, MSB-first) audio decoder-config record
//! carried in an MP4 `mp4a` sample entry's `esds` `DecoderSpecificInfo` when
//! `objectTypeIndication == 0x40`, and the source for an ADTS header on TS→MP4
//! transmux.
//!
//! # ADTS↔ASC mapping
//!
//! | ADTS field              | ASC field                  | Relation                  |
//! |-------------------------|----------------------------|---------------------------|
//! | `profile` (2 bits)      | `audioObjectType`          | `ADTS.profile = AOT - 1` |
//! | `sampling_frequency_index` (4) | `samplingFrequencyIndex` | direct copy              |
//! | `channel_configuration` (4)    | `channelConfiguration`   | direct copy              |
//!
//! ## References
//!
//! - ISO/IEC 14496-3:2001, subpart 1 (`audioObjectType` §1.5.1.1 Table 1.1;
//!   `AudioSpecificConfig` §1.6.2.1 Table 1.8; `samplingFrequencyIndex` §1.6.3.3
//!   Table 1.10; `channelConfiguration` §1.6.3.4 Table 1.11).
//! - ADTS: ISO/IEC 13818-7:2003 §A.2.2.3 (Audio Data Transport Stream).

use crate::error::{Error, Result};
use alloc::string::String;
use alloc::vec::Vec;
use broadcast_common::{Parse, Serialize};

const ADTS_HEADER_SIZE: usize = 7;

/// Maximum `frame_length` an ADTS fixed header can carry: a 13-bit field
/// (ISO/IEC 13818-7:2003 §A.2.2.3, header size included) — `2^13 - 1`.
const ADTS_FRAME_LENGTH_MAX: u16 = 8191;

// --- AudioObjectType §1.5.1.1 ---
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum AudioObjectType {
    Null,
    AacMain,
    AacLc,
    AacSsr,
    AacLtp,
    Reserved(u8),
    AacScalable,
    TwinVq,
    Celp,
    Hvxc,
    Ttsi,
    MainSynthetic,
    WavetableSynthesis,
    GeneralMidi,
    AlgorithmicSynthesis,
    ErAacLc,
    ErAacLtp,
    ErAacScalable,
    ErTwinVq,
    ErBsac,
    ErAacLd,
    ErCelp,
    ErHvxc,
    ErHiln,
    ErParametric,
}
impl AudioObjectType {
    pub fn raw(self) -> u8 {
        match self {
            Self::Null => 0,
            Self::AacMain => 1,
            Self::AacLc => 2,
            Self::AacSsr => 3,
            Self::AacLtp => 4,
            Self::Reserved(r) => r & 0x1F,
            Self::AacScalable => 6,
            Self::TwinVq => 7,
            Self::Celp => 8,
            Self::Hvxc => 9,
            Self::Ttsi => 12,
            Self::MainSynthetic => 13,
            Self::WavetableSynthesis => 14,
            Self::GeneralMidi => 15,
            Self::AlgorithmicSynthesis => 16,
            Self::ErAacLc => 17,
            Self::ErAacLtp => 19,
            Self::ErAacScalable => 20,
            Self::ErTwinVq => 21,
            Self::ErBsac => 22,
            Self::ErAacLd => 23,
            Self::ErCelp => 24,
            Self::ErHvxc => 25,
            Self::ErHiln => 26,
            Self::ErParametric => 27,
        }
    }
    pub fn name(&self) -> &str {
        match self {
            Self::Null => "null",
            Self::AacMain => "AAC Main",
            Self::AacLc => "AAC LC",
            Self::AacSsr => "AAC SSR",
            Self::AacLtp => "AAC LTP",
            Self::Reserved(_) => "reserved",
            Self::AacScalable => "AAC Scalable",
            Self::TwinVq => "TwinVQ",
            Self::Celp => "CELP",
            Self::Hvxc => "HVXC",
            Self::Ttsi => "TTSI",
            Self::MainSynthetic => "Main synthetic",
            Self::WavetableSynthesis => "Wavetable synthesis",
            Self::GeneralMidi => "General MIDI",
            Self::AlgorithmicSynthesis => "Algorithmic Synthesis & Audio FX",
            Self::ErAacLc => "ER AAC LC",
            Self::ErAacLtp => "ER AAC LTP",
            Self::ErAacScalable => "ER AAC Scalable",
            Self::ErTwinVq => "ER TwinVQ",
            Self::ErBsac => "ER BSAC",
            Self::ErAacLd => "ER AAC LD",
            Self::ErCelp => "ER CELP",
            Self::ErHvxc => "ER HVXC",
            Self::ErHiln => "ER HILN",
            Self::ErParametric => "ER Parametric",
        }
    }
}
impl From<u8> for AudioObjectType {
    fn from(raw: u8) -> Self {
        match raw & 0x1F {
            0 => Self::Null,
            1 => Self::AacMain,
            2 => Self::AacLc,
            3 => Self::AacSsr,
            4 => Self::AacLtp,
            5 => Self::Reserved(5),
            6 => Self::AacScalable,
            7 => Self::TwinVq,
            8 => Self::Celp,
            9 => Self::Hvxc,
            10 | 11 => Self::Reserved(raw & 0x1F),
            12 => Self::Ttsi,
            13 => Self::MainSynthetic,
            14 => Self::WavetableSynthesis,
            15 => Self::GeneralMidi,
            16 => Self::AlgorithmicSynthesis,
            17 => Self::ErAacLc,
            18 => Self::Reserved(18),
            19 => Self::ErAacLtp,
            20 => Self::ErAacScalable,
            21 => Self::ErTwinVq,
            22 => Self::ErBsac,
            23 => Self::ErAacLd,
            24 => Self::ErCelp,
            25 => Self::ErHvxc,
            26 => Self::ErHiln,
            27 => Self::ErParametric,
            _ => Self::Reserved(raw & 0x1F),
        }
    }
}
broadcast_common::impl_spec_display!(AudioObjectType, Reserved);

// --- SamplingFrequencyIndex §1.6.3.3 ---
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum SamplingFrequencyIndex {
    Fs96000,
    Fs88200,
    Fs64000,
    Fs48000,
    Fs44100,
    Fs32000,
    Fs24000,
    Fs22050,
    Fs16000,
    Fs12000,
    Fs11025,
    Fs8000,
    Fs7350,
    Reserved(u8),
    Escape,
}
impl SamplingFrequencyIndex {
    /// The sampling rate in Hz this index denotes — ISO/IEC 14496-3 §1.6.3.3
    /// Table 1.10 ("samplingFrequencyIndex").
    ///
    /// This is the crate's **single** copy of Table 1.10, so the value a
    /// frequency index means cannot differ between the AAC
    /// `AudioSpecificConfig` parser, the FLV/RTMP demuxers and the SDP
    /// `config=` decoder. `None` for the reserved indices (13, 14) and for
    /// the explicit-rate escape (15), which carries its own value elsewhere.
    pub fn table_hz(self) -> Option<u32> {
        match self {
            Self::Fs96000 => Some(96_000),
            Self::Fs88200 => Some(88_200),
            Self::Fs64000 => Some(64_000),
            Self::Fs48000 => Some(48_000),
            Self::Fs44100 => Some(44_100),
            Self::Fs32000 => Some(32_000),
            Self::Fs24000 => Some(24_000),
            Self::Fs22050 => Some(22_050),
            Self::Fs16000 => Some(16_000),
            Self::Fs12000 => Some(12_000),
            Self::Fs11025 => Some(11_025),
            Self::Fs8000 => Some(8_000),
            Self::Fs7350 => Some(7_350),
            Self::Reserved(_) | Self::Escape => None,
        }
    }

    pub fn raw(self) -> u8 {
        match self {
            Self::Fs96000 => 0x0,
            Self::Fs88200 => 0x1,
            Self::Fs64000 => 0x2,
            Self::Fs48000 => 0x3,
            Self::Fs44100 => 0x4,
            Self::Fs32000 => 0x5,
            Self::Fs24000 => 0x6,
            Self::Fs22050 => 0x7,
            Self::Fs16000 => 0x8,
            Self::Fs12000 => 0x9,
            Self::Fs11025 => 0xA,
            Self::Fs8000 => 0xB,
            Self::Fs7350 => 0xC,
            Self::Reserved(r) => r & 0x0F,
            Self::Escape => 0xF,
        }
    }
    pub fn name(&self) -> &str {
        match self {
            Self::Fs96000 => "96000 Hz",
            Self::Fs88200 => "88200 Hz",
            Self::Fs64000 => "64000 Hz",
            Self::Fs48000 => "48000 Hz",
            Self::Fs44100 => "44100 Hz",
            Self::Fs32000 => "32000 Hz",
            Self::Fs24000 => "24000 Hz",
            Self::Fs22050 => "22050 Hz",
            Self::Fs16000 => "16000 Hz",
            Self::Fs12000 => "12000 Hz",
            Self::Fs11025 => "11025 Hz",
            Self::Fs8000 => "8000 Hz",
            Self::Fs7350 => "7350 Hz",
            Self::Reserved(_) => "reserved",
            Self::Escape => "escape",
        }
    }
}
impl From<u8> for SamplingFrequencyIndex {
    fn from(raw: u8) -> Self {
        match raw & 0x0F {
            0x0 => Self::Fs96000,
            0x1 => Self::Fs88200,
            0x2 => Self::Fs64000,
            0x3 => Self::Fs48000,
            0x4 => Self::Fs44100,
            0x5 => Self::Fs32000,
            0x6 => Self::Fs24000,
            0x7 => Self::Fs22050,
            0x8 => Self::Fs16000,
            0x9 => Self::Fs12000,
            0xA => Self::Fs11025,
            0xB => Self::Fs8000,
            0xC => Self::Fs7350,
            0xD | 0xE => Self::Reserved(raw & 0x0F),
            0xF => Self::Escape,
            _ => Self::Reserved(raw & 0x0F),
        }
    }
}
broadcast_common::impl_spec_display!(SamplingFrequencyIndex, Reserved);

// --- ChannelConfiguration §1.6.3.4 ---
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum ChannelConfiguration {
    InBand,
    Mono,
    Stereo,
    Ch3,
    Ch4,
    Ch5,
    Ch5_1,
    Ch7_1,
    Reserved(u8),
}
impl ChannelConfiguration {
    pub fn raw(self) -> u8 {
        match self {
            Self::InBand => 0,
            Self::Mono => 1,
            Self::Stereo => 2,
            Self::Ch3 => 3,
            Self::Ch4 => 4,
            Self::Ch5 => 5,
            Self::Ch5_1 => 6,
            Self::Ch7_1 => 7,
            Self::Reserved(r) => r & 0x0F,
        }
    }
    pub fn name(&self) -> &str {
        match self {
            Self::InBand => "in-band",
            Self::Mono => "mono",
            Self::Stereo => "stereo",
            Self::Ch3 => "3 channels",
            Self::Ch4 => "4 channels",
            Self::Ch5 => "5 channels",
            Self::Ch5_1 => "5.1 surround",
            Self::Ch7_1 => "7.1 surround",
            Self::Reserved(_) => "reserved",
        }
    }

    /// The number of audio channels this configuration's default channel
    /// mapping carries (ISO/IEC 14496-3 Table 1.19, "channelConfiguration").
    ///
    /// This is **not** the raw field value: configuration `7` is 8 channels
    /// (7.1), and `0` means the mapping is carried in-band by a
    /// `program_config_element` in the raw data stream, so the count is not
    /// known from the ASC — that (and a reserved value, 8..=15) returns
    /// `None` rather than a fabricated `0`. Reporting the raw field as a
    /// channel count made 7.1 look like 7 channels and a PCE-signalled stream
    /// look like 0.
    pub fn channel_count(&self) -> Option<u16> {
        match self {
            Self::InBand | Self::Reserved(_) => None,
            Self::Mono => Some(1),
            Self::Stereo => Some(2),
            Self::Ch3 => Some(3),
            Self::Ch4 => Some(4),
            Self::Ch5 => Some(5),
            Self::Ch5_1 => Some(6),
            // 7.1 = 3 front + 2 side + 2 back + LFE per Table 1.19.
            Self::Ch7_1 => Some(8),
        }
    }
}
impl From<u8> for ChannelConfiguration {
    fn from(raw: u8) -> Self {
        match raw & 0x0F {
            0 => Self::InBand,
            1 => Self::Mono,
            2 => Self::Stereo,
            3 => Self::Ch3,
            4 => Self::Ch4,
            5 => Self::Ch5,
            6 => Self::Ch5_1,
            7 => Self::Ch7_1,
            _ => Self::Reserved(raw & 0x0F),
        }
    }
}
broadcast_common::impl_spec_display!(ChannelConfiguration, Reserved);

// --- AudioSpecificConfig §1.6.2.1 ---
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct AudioSpecificConfig {
    pub audio_object_type: AudioObjectType,
    pub sampling_frequency_index: SamplingFrequencyIndex,
    pub sampling_frequency: Option<u32>,
    pub channel_configuration: ChannelConfiguration,
    /// Bytes following the byte that contains trailing data start.
    pub trailing: Vec<u8>,
    /// Bottom 3 bits of the partial byte shared with fixed fields.
    pub trailing_top: Option<u8>,
}

/// Explicit-signaling extension state (HE-AAC SBR / HE-AAC v2 PS) recovered from
/// an [`AudioSpecificConfig`] — ISO/IEC 14496-3 §1.6.2 (SBR: Amd 1, PS: Amd 2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct HeAacSignaling {
    /// SBR is explicitly signaled (`sbrPresentFlag == 1`, HE-AAC v1).
    pub sbr_present: bool,
    /// PS is explicitly signaled (`psPresentFlag == 1`, HE-AAC v2).
    pub ps_present: bool,
    /// The effective object type for RFC 6381: `29` (PS), `5` (SBR), or the core AOT.
    pub effective_aot: u8,
}

/// AudioObjectType raw value for SBR (HE-AAC v1).
const AOT_SBR: u8 = 5;
/// AudioObjectType raw value for PS (HE-AAC v2).
const AOT_PS: u8 = 29;
/// AAC backward-compatible SBR sync-extension type (11 bits).
const SYNC_EXT_SBR: u16 = 0x2B7;
/// AAC backward-compatible PS sync-extension type (11 bits).
const SYNC_EXT_PS: u16 = 0x548;
/// `frameLengthFlag` within the 3-bit `GASpecificConfig` head held in
/// `trailing_top` (ISO/IEC 14496-3 §4.4.1: frameLengthFlag is its first bit).
const FRAME_LENGTH_FLAG_MASK: u8 = 0b100;
/// Samples per AAC frame when `frameLengthFlag` is 0 (ISO/IEC 14496-3 §4.4.1).
const AAC_FRAME_SAMPLES_1024: u32 = 1024;
/// Samples per AAC frame when `frameLengthFlag` is 1 (ISO/IEC 14496-3 §4.4.1).
const AAC_FRAME_SAMPLES_960: u32 = 960;
/// `samplingFrequencyIndex` escape value (24-bit explicit rate follows).
const SFI_ESCAPE: u8 = 0x0F;

impl AudioSpecificConfig {
    /// Build the RFC 6381 `mp4a.40.<AOT>` codec string, honouring explicit HE-AAC
    /// SBR/PS signaling (`mp4a.40.5` / `mp4a.40.29`).
    pub fn rfc6381(&self) -> String {
        crate::sps::rfc6381_mp4a(self.heaac_signaling().effective_aot)
    }

    /// Recover the explicit HE-AAC SBR/PS signaling from the ASC bitstream.
    ///
    /// Handles both encodings from ISO/IEC 14496-3 §1.6.2:
    /// hierarchical (`audioObjectType == 5`/`29`) and the trailing
    /// backward-compatible sync extensions (`0x2B7` → SBR, `0x548` → PS).
    /// Read-only over the parsed fields — never mutates the round-trip bytes.
    pub fn heaac_signaling(&self) -> HeAacSignaling {
        self.with_serialized(detect_heaac_signaling)
            .unwrap_or(HeAacSignaling {
                sbr_present: false,
                ps_present: false,
                effective_aot: self.audio_object_type.raw(),
            })
    }

    /// The effective sampling rate in Hz: the explicit 24-bit rate when present,
    /// else the rate of the `samplingFrequencyIndex` (ISO/IEC 14496-3 Table
    /// 1.10). `None` for the reserved indices. The crate's one place that
    /// combines the two (audit r04-O5/r05-O6).
    pub fn effective_sampling_frequency(&self) -> Option<u32> {
        self.sampling_frequency
            .or_else(|| self.sampling_frequency_index.table_hz())
    }

    /// PCM samples per raw_data_block (one AAC access unit) declared by the
    /// `GASpecificConfig` `frameLengthFlag` — ISO/IEC 14496-3 §4.4.1: 1024
    /// when clear, 960 when set. `None` for object types without a
    /// `GASpecificConfig` this decodes (only AAC main/LC/SSR/LTP are handled),
    /// when the flag byte is absent, or when explicit HE-AAC SBR/PS signalling
    /// makes the access-unit span differ from the core frame.
    pub fn samples_per_frame(&self) -> Option<u32> {
        if !matches!(
            self.audio_object_type,
            AudioObjectType::AacMain
                | AudioObjectType::AacLc
                | AudioObjectType::AacSsr
                | AudioObjectType::AacLtp
        ) {
            return None;
        }
        let signaling = self.heaac_signaling();
        if signaling.sbr_present || signaling.ps_present {
            return None;
        }
        let ga_bits = self.trailing_top?;
        Some(if ga_bits & FRAME_LENGTH_FLAG_MASK != 0 {
            AAC_FRAME_SAMPLES_960
        } else {
            AAC_FRAME_SAMPLES_1024
        })
    }

    /// Run `f` over this ASC's serialized bytes without a heap allocation when
    /// they fit [`STACK_ASC_MAX`] (every real ASC does; the HE-AAC decode below
    /// reads well under 16 bytes), else over a `to_bytes` copy. Byte-identical
    /// input to `f` either way (audit r04-O2).
    fn with_serialized<R>(&self, f: impl FnOnce(&[u8]) -> R) -> R {
        let need = self.serialized_len();
        let mut stack = [0u8; STACK_ASC_MAX];
        if need <= STACK_ASC_MAX && self.serialize_into(&mut stack[..need]).is_ok() {
            return f(&stack[..need]);
        }
        // Serialization only fails for a value violating a wire constraint; an
        // empty input then yields the parsers' "no config" result rather than a panic.
        let bytes = self.try_to_bytes().unwrap_or_default();
        f(&bytes)
    }
}

/// Largest serialized ASC (bytes) handled on the stack by
/// [`AudioSpecificConfig::with_serialized`].
const STACK_ASC_MAX: usize = 64;

/// Read `n` MSB-first bits from `bytes` at `*bit`, advancing it. Returns `None`
/// if the buffer is exhausted.
///
/// Delegates to the shared [`crate::bitreader::read_bits_at`] cursor (`n` is
/// always <= 24 for every ASC field this module reads).
fn asc_read_bits(bytes: &[u8], bit: &mut usize, n: usize) -> Option<u32> {
    u32::try_from(crate::bitreader::read_bits_at(bytes, bit, n)?).ok()
}

/// `GetAudioObjectType()` — 5 bits, or `31 + 6` bits (ISO/IEC 14496-3 §1.5.1.1).
fn asc_get_aot(bytes: &[u8], bit: &mut usize) -> Option<u8> {
    let a = asc_read_bits(bytes, bit, 5)?;
    if a == 31 {
        Some((32 + asc_read_bits(bytes, bit, 6)?) as u8)
    } else {
        Some(a as u8)
    }
}

/// Bit-decode the ASC to detect explicit SBR/PS signaling.
fn detect_heaac_signaling(bytes: &[u8]) -> Option<HeAacSignaling> {
    let (core_aot, sbr_present, ps_present) = detect_heaac_core(bytes)?;
    let effective_aot = if ps_present {
        AOT_PS
    } else if sbr_present {
        AOT_SBR
    } else {
        core_aot
    };
    Some(HeAacSignaling {
        sbr_present,
        ps_present,
        effective_aot,
    })
}

/// Bit-decode the ASC and return `(core_aot, sbr_present, ps_present)`. The
/// core AOT is what an ADTS `profile` field must be derived from (C2, #1008):
/// with explicit hierarchical signaling (`audioObjectType == 5`/`29`) the
/// *first* AOT read is the extension type, not the codec's actual profile —
/// the real core AOT follows the extension sampling-rate field.
fn detect_heaac_core(bytes: &[u8]) -> Option<(u8, bool, bool)> {
    let mut bit = 0usize;
    let mut aot = asc_get_aot(bytes, &mut bit)?;
    let mut sbr_present = false;
    let mut ps_present = false;

    // samplingFrequencyIndex (+ 24-bit escape rate).
    let sfi = asc_read_bits(bytes, &mut bit, 4)? as u8;
    if sfi == SFI_ESCAPE {
        asc_read_bits(bytes, &mut bit, 24)?;
    }
    asc_read_bits(bytes, &mut bit, 4)?; // channelConfiguration

    // Hierarchical explicit signaling: AOT 5 (SBR) or 29 (PS).
    if aot == AOT_SBR || aot == AOT_PS {
        if aot == AOT_PS {
            ps_present = true;
        }
        sbr_present = true;
        let esfi = asc_read_bits(bytes, &mut bit, 4)? as u8;
        if esfi == SFI_ESCAPE {
            asc_read_bits(bytes, &mut bit, 24)?;
        }
        aot = asc_get_aot(bytes, &mut bit)?; // core AOT
    }

    // Trailing backward-compatible sync extension (best-effort; only for AAC-LC
    // core where GASpecificConfig is a fixed 3-bit tail with no PCE).
    if !sbr_present && aot == AudioObjectType::AacLc.raw() {
        // GASpecificConfig: frameLengthFlag(1) dependsOnCoreCoder(1) extensionFlag(1).
        asc_read_bits(bytes, &mut bit, 3);
        if let Some(sync) = asc_read_bits(bytes, &mut bit, 11) {
            if sync as u16 == SYNC_EXT_SBR {
                if let Some(ext_aot) = asc_get_aot(bytes, &mut bit)
                    && ext_aot == AOT_SBR
                    && let Some(flag) = asc_read_bits(bytes, &mut bit, 1)
                {
                    sbr_present = flag == 1;
                    if sbr_present {
                        let esfi = asc_read_bits(bytes, &mut bit, 4).unwrap_or(0) as u8;
                        if esfi == SFI_ESCAPE {
                            asc_read_bits(bytes, &mut bit, 24);
                        }
                        if let Some(sync2) = asc_read_bits(bytes, &mut bit, 11)
                            && sync2 as u16 == SYNC_EXT_PS
                        {
                            // The psPresentFlag(1) follows; when the ASC is
                            // byte-aligned it may be truncated, in which case
                            // the presence of the 0x548 sync itself signals PS.
                            ps_present = asc_read_bits(bytes, &mut bit, 1).unwrap_or(1) == 1;
                        }
                    }
                }
            } else if sync as u16 == SYNC_EXT_PS {
                ps_present = asc_read_bits(bytes, &mut bit, 1).unwrap_or(0) == 1;
            }
        }
    }

    Some((aot, sbr_present, ps_present))
}

impl Parse<'_> for AudioSpecificConfig {
    type Error = Error;
    fn parse(bytes: &[u8]) -> Result<Self> {
        if bytes.len() < 2 {
            return Err(Error::BufferTooShort {
                need: 2,
                have: bytes.len(),
                what: "ASC header",
            });
        }
        let b0 = bytes[0];
        let b1 = bytes[1];
        let aot = AudioObjectType::from(b0 >> 3);
        let sfi_raw = ((b0 & 7) << 1) | (b1 >> 7);
        let sfi = SamplingFrequencyIndex::from(sfi_raw);
        let sf = if sfi_raw == 0x0F {
            if bytes.len() < 5 {
                return Err(Error::BufferTooShort {
                    need: 5,
                    have: bytes.len(),
                    what: "ASC escape",
                });
            }
            Some(
                ((b1 as u32 & 0x7F) << 17)
                    | (bytes[2] as u32) << 9
                    | (bytes[3] as u32) << 1
                    | (bytes[4] as u32 & 1),
            )
        } else {
            None
        };
        let cc = if sfi_raw == 0x0F {
            if bytes.len() < 5 {
                return Err(Error::BufferTooShort {
                    need: 5,
                    have: bytes.len(),
                    what: "ASC cc esc",
                });
            }
            ChannelConfiguration::from((bytes[4] >> 3) & 0x0F)
        } else {
            ChannelConfiguration::from((b1 >> 3) & 0x0F)
        };
        // trailing stores bytes after the partial byte. trailing_top stores the GASpecific
        // bits from the partial byte (bottom 3 bits of byte 1 or byte 4).
        let (partial_idx, trailing_start) = if sfi_raw == 0x0F {
            (4, 5usize)
        } else {
            (1, 2usize)
        };
        let trailing_top = if partial_idx < bytes.len() {
            Some(bytes[partial_idx] & 7)
        } else {
            None
        };
        let trailing = if trailing_start < bytes.len() {
            bytes[trailing_start..].to_vec()
        } else {
            Vec::new()
        };
        Ok(Self {
            audio_object_type: aot,
            sampling_frequency_index: sfi,
            sampling_frequency: sf,
            channel_configuration: cc,
            trailing,
            trailing_top,
        })
    }
}

impl Serialize for AudioSpecificConfig {
    type Error = Error;
    fn serialized_len(&self) -> usize {
        let base = if self.sampling_frequency_index == SamplingFrequencyIndex::Escape {
            5
        } else {
            2
        };
        base + self.trailing.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(),
            });
        }
        // Only the region this config occupies: the `Serialize` contract lets a
        // caller serialize into a larger shared buffer, and a whole-buffer
        // `fill(0)` would zero their bytes past `need` (r04-W9).
        buf[..need].fill(0);
        let aot = self.audio_object_type.raw() & 0x1F;
        let sv = self.sampling_frequency_index.raw() & 0x0F;
        let cv = self.channel_configuration.raw() & 0x0F;
        let esc = self.sampling_frequency_index == SamplingFrequencyIndex::Escape;
        buf[0] = (aot << 3) | ((sv >> 1) & 7);
        if esc {
            let freq = self.sampling_frequency.unwrap_or(0) & 0xFF_FFFF;
            buf[1] = ((sv & 1) << 7) | ((freq >> 17) as u8 & 0x7F);
            buf[2] = (freq >> 9) as u8;
            buf[3] = (freq >> 1) as u8;
            let sf0 = (freq & 1) as u8;
            let tt = self.trailing_top.unwrap_or(0) & 7;
            buf[4] = (sf0 << 7) | (cv << 3) | tt;
            // `need` already covers `trailing` in full, and `buf.len() >= need`
            // was checked above, so the copy can never overrun.
            buf[5..need].copy_from_slice(&self.trailing);
        } else {
            let tt = self.trailing_top.unwrap_or(0) & 7;
            buf[1] = ((sv & 1) << 7) | (cv << 3) | tt;
            // As above: `need == 2 + trailing.len()`, already bounds-checked.
            buf[2..need].copy_from_slice(&self.trailing);
        }
        Ok(need)
    }
}

// --- ADTS header §A.2.2.3 ---
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct AdtsHeader {
    /// `protection_absent` (1 bit): `true` = no `adts_error_check()` CRC
    /// follows the fixed+variable header; `false` = a 16-bit `crc_check`
    /// (2 bytes) is present before the raw data block(s) — ISO/IEC 13818-7
    /// §6.2, `adts_frame()`. C11 (#1012): this was not read at all, so a
    /// CRC-protected ADTS frame's header was always treated as 7 bytes wide
    /// instead of 9, leaving the 2 CRC bytes inside the "sample" data.
    pub protection_absent: bool,
    pub profile: u8,
    pub sampling_frequency_index: u8,
    pub channel_configuration: u8,
    pub frame_length: u16,
    pub buffer_fullness: u16,
    pub num_raw_data_blocks: u8,
}

pub fn build_adts_header(profile: u8, sfi: u8, cc: u8, frame_len: u16) -> [u8; ADTS_HEADER_SIZE] {
    let mut h = [0u8; ADTS_HEADER_SIZE];
    h[0] = 0xFF;
    h[1] = 0xF1;
    // channel_configuration is a 3-bit field split across the byte boundary
    // (ISO/IEC 13818-7 §6.2 ADTS fixed header): its MSB is byte2 bit0, and its
    // low 2 bits are byte3 bits `[7:6]`.
    h[2] = (profile & 3) << 6 | (sfi & 0x0F) << 2 | (cc >> 2) & 1;
    h[3] = (cc & 3) << 6 | ((frame_len >> 11) & 3) as u8;
    h[4] = (frame_len >> 3) as u8;
    let bf: u16 = 0x7FF;
    h[5] = ((frame_len as u8 & 7) << 5) | ((bf >> 6) as u8 & 0x1F);
    h[6] = (bf as u8 & 0x3F) << 2;
    h
}

pub fn parse_adts_header(bytes: &[u8]) -> Result<AdtsHeader> {
    if bytes.len() < ADTS_HEADER_SIZE {
        return Err(Error::BufferTooShort {
            need: ADTS_HEADER_SIZE,
            have: bytes.len(),
            what: "ADTS",
        });
    }
    if bytes[0] != 0xFF || (bytes[1] & 0xF0) != 0xF0 {
        return Err(Error::InvalidValue {
            field: "adts_syncword",
            value: ((bytes[0] as u64) << 8) | (bytes[1] as u64),
            reason: "must be 0xFFF",
        });
    }
    let (b2, b3, b4, b5, b6) = (bytes[2], bytes[3], bytes[4], bytes[5], bytes[6]);
    Ok(AdtsHeader {
        protection_absent: (bytes[1] & 0x01) != 0,
        profile: (b2 >> 6) & 3,
        sampling_frequency_index: (b2 >> 2) & 0x0F,
        channel_configuration: ((b2 & 1) << 2) | ((b3 >> 6) & 3),
        frame_length: (((b3 & 3) as u16) << 11) | ((b4 as u16) << 3) | ((b5 >> 5) as u16),
        buffer_fullness: (((b5 & 0x1F) as u16) << 6) | ((b6 >> 2) as u16),
        num_raw_data_blocks: b6 & 3,
    })
}

impl AudioSpecificConfig {
    pub fn to_adts_header(&self, frame_len: u16) -> Result<[u8; ADTS_HEADER_SIZE]> {
        if frame_len < ADTS_HEADER_SIZE as u16 {
            return Err(Error::InvalidValue {
                field: "frame_len",
                value: frame_len as u64,
                reason: "too small",
            });
        }
        if frame_len > ADTS_FRAME_LENGTH_MAX {
            return Err(Error::InvalidValue {
                field: "frame_len",
                value: frame_len as u64,
                reason: "exceeds ADTS 13-bit frame_length maximum (8191)",
            });
        }
        if self.sampling_frequency_index == SamplingFrequencyIndex::Escape {
            return Err(Error::InvalidValue {
                field: "sampling_frequency_index",
                value: self.sampling_frequency_index.raw() as u64,
                reason: "escape (explicit rate) is not representable in ADTS's 4-bit field",
            });
        }
        // C2 (#1008): with explicit hierarchical HE-AAC/HE-AACv2 signaling
        // (`audioObjectType == 5`/`29`), the ASC's *first* AOT is the SBR/PS
        // extension type, not the codec's actual core profile — the real
        // core AOT follows the extension sfi. `self.audio_object_type` is
        // that first AOT, so it must not be used directly as the ADTS
        // `profile` source; decode the core AOT the same way `heaac_signaling`
        // does. ADTS `profile` (2 bits, `= AOT - 1`) can only represent core
        // AOT 1..=4 (Main/LC/SSR/LTP); anything else is rejected rather than
        // silently wrapped into an unrelated profile.
        let core_aot = self
            .with_serialized(detect_heaac_core)
            .map(|(aot, _, _)| aot)
            .unwrap_or(self.audio_object_type.raw());
        if !(1..=4).contains(&core_aot) {
            return Err(Error::InvalidValue {
                field: "audio_object_type",
                value: core_aot as u64,
                reason: "core AOT is not representable in ADTS's 2-bit profile field (must be Main/LC/SSR/LTP, 1..=4)",
            });
        }
        Ok(build_adts_header(
            core_aot - 1,
            self.sampling_frequency_index.raw(),
            self.channel_configuration.raw(),
            frame_len,
        ))
    }
    pub fn from_adts_header(adts: &AdtsHeader) -> Self {
        Self {
            audio_object_type: AudioObjectType::from((adts.profile + 1) & 0x1F),
            sampling_frequency_index: SamplingFrequencyIndex::from(adts.sampling_frequency_index),
            sampling_frequency: None,
            channel_configuration: ChannelConfiguration::from(adts.channel_configuration),
            trailing: Vec::new(),
            trailing_top: None,
        }
    }
}

/// HE-AAC flavour to signal explicitly in an `AudioSpecificConfig`: the
/// hierarchical SBR (`audioObjectType` 5, HE-AAC v1) or PS (`audioObjectType`
/// 29, HE-AAC v2) form of ISO/IEC 14496-3 §1.6.2, which Apple's HLS authoring
/// rules require for HE-AAC in fMP4 instead of an implicit ADTS-derived config.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum HeAacProfile {
    /// HE-AAC v1: AAC-LC core + SBR.
    V1,
    /// HE-AAC v2: AAC-LC core + SBR + Parametric Stereo.
    V2,
}

impl HeAacProfile {
    /// The `audioObjectType` that opens the hierarchical ASC for this profile.
    pub fn audio_object_type(self) -> u8 {
        match self {
            Self::V1 => AOT_SBR,
            Self::V2 => AOT_PS,
        }
    }

    /// Spec-token label.
    pub fn name(&self) -> &'static str {
        match self {
            Self::V1 => "HE-AAC v1 (SBR)",
            Self::V2 => "HE-AAC v2 (SBR+PS)",
        }
    }
}

broadcast_common::impl_spec_display!(HeAacProfile);

/// Extension rate is the core rate times this (SBR doubles the output rate,
/// ISO/IEC 14496-3 §4.6.18).
const SBR_RATE_FACTOR: u32 = 2;
/// Highest raw `samplingFrequencyIndex` that names a table rate (Table 1.10).
const SFI_TABLE_LAST: u8 = 0x0C;
/// Core `audioObjectType` of an AAC-LC stream (Table 1.1).
const AOT_AAC_LC: u8 = 2;
/// Width of `audioObjectType` in the ASC.
const AOT_BITS: u32 = 5;
/// Width of the `GASpecificConfig` head (frameLengthFlag, dependsOnCoreCoder,
/// extensionFlag) that follows the core object type.
const GA_HEAD_BITS: u32 = 3;
/// Width of `samplingFrequencyIndex`.
const SFI_BITS: u32 = 4;
/// Width of `channelConfiguration`.
const CHANNEL_CONFIG_BITS: usize = 4;
/// Width of an explicit `samplingFrequency` escape value.
const SFI_ESCAPE_BITS: usize = 24;
/// Bits of the hierarchical tail that share the byte holding the fixed
/// `channelConfiguration` field.
const TAIL_BITS_IN_SHARED_BYTE: u32 = 3;
/// Width of the hierarchical tail after `channelConfiguration`.
const TAIL_BITS: u32 = SFI_BITS + AOT_BITS + GA_HEAD_BITS;
/// Bits of the tail that follow the shared byte.
const TAIL_SPILL_BITS: u32 = TAIL_BITS - TAIL_BITS_IN_SHARED_BYTE;
/// Bits in the two bytes the spill is left-aligned into.
const SPILL_FIELD_BITS: u32 = 16;

impl AudioSpecificConfig {
    /// Re-express an AAC-LC config as explicit hierarchical HE-AAC signalling
    /// (ISO/IEC 14496-3 §1.6.2): `audioObjectType` 5 (v1) or 29 (v2), the
    /// core rate in `samplingFrequencyIndex`, twice that rate in
    /// `extensionSamplingFrequencyIndex`, then the underlying AAC-LC object
    /// type and its `GASpecificConfig`.
    ///
    /// A config already in exactly this hierarchical form is re-expressed for
    /// `profile` (so an explicit v1 can become v2 and back). Fails for any
    /// other config: not AAC-LC, explicit-rate escape, a non-default
    /// `GASpecificConfig`, trailing extension data, or a doubled core rate
    /// with no Table 1.10 index.
    pub fn with_explicit_he_aac(&self, profile: HeAacProfile) -> Result<Self> {
        let raw_aot = self.audio_object_type.raw();
        let current = match raw_aot {
            AOT_SBR => Some(HeAacProfile::V1),
            AOT_PS => Some(HeAacProfile::V2),
            _ => None,
        };
        if let Some(current) = current {
            let derived = self.with_plain_core().build_explicit_he_aac(current)?;
            if derived.trailing_top != self.trailing_top || derived.trailing != self.trailing {
                return Err(Error::InvalidValue {
                    field: "trailing",
                    value: self.trailing.len() as u64,
                    reason: "hierarchical config is not the default AAC-LC form",
                });
            }
        } else if self.audio_object_type != AudioObjectType::AacLc {
            return Err(Error::InvalidValue {
                field: "audio_object_type",
                value: u64::from(raw_aot),
                reason: "explicit HE-AAC signalling needs an AAC-LC core",
            });
        } else if !self.trailing.is_empty() || self.trailing_top.is_some_and(|t| t != 0) {
            return Err(Error::InvalidValue {
                field: "trailing",
                value: self.trailing.len() as u64,
                reason: "config already carries GASpecificConfig/extension data",
            });
        }
        let base = if current.is_some() {
            self.with_plain_core()
        } else {
            self.clone()
        };
        base.build_explicit_he_aac(profile)
    }

    fn with_plain_core(&self) -> Self {
        Self {
            audio_object_type: AudioObjectType::AacLc,
            sampling_frequency_index: self.sampling_frequency_index,
            sampling_frequency: None,
            channel_configuration: self.channel_configuration,
            trailing: Vec::new(),
            trailing_top: None,
        }
    }

    fn build_explicit_he_aac(&self, profile: HeAacProfile) -> Result<Self> {
        let core_hz = self
            .sampling_frequency_index
            .table_hz()
            .ok_or(Error::InvalidValue {
                field: "sampling_frequency_index",
                value: u64::from(self.sampling_frequency_index.raw()),
                reason: "core rate is not a Table 1.10 rate",
            })?;
        let ext_hz = core_hz.saturating_mul(SBR_RATE_FACTOR);
        let ext_index = extension_index_for(ext_hz).ok_or(Error::InvalidValue {
            field: "extension_sampling_frequency_index",
            value: u64::from(ext_hz),
            reason: "doubled core rate has no Table 1.10 index",
        })?;
        let tail = (u16::from(ext_index.raw()) << (AOT_BITS + GA_HEAD_BITS))
            | (u16::from(AOT_AAC_LC) << GA_HEAD_BITS);
        let top = (tail >> TAIL_SPILL_BITS) as u8;
        let spill_mask = (1u16 << TAIL_SPILL_BITS) - 1;
        let spill = ((tail & spill_mask) << (SPILL_FIELD_BITS - TAIL_SPILL_BITS)).to_be_bytes();
        Ok(Self {
            audio_object_type: AudioObjectType::from(profile.audio_object_type()),
            sampling_frequency_index: self.sampling_frequency_index,
            sampling_frequency: None,
            channel_configuration: self.channel_configuration,
            trailing: spill.to_vec(),
            trailing_top: Some(top),
        })
    }

    /// The underlying codec's object type: for hierarchical HE-AAC signalling
    /// (`audioObjectType` 5/29 first) the one that follows the extension rate
    /// (normally AAC-LC), otherwise [`Self::audio_object_type`].
    pub fn core_audio_object_type(&self) -> AudioObjectType {
        self.with_serialized(detect_heaac_core)
            .map_or(self.audio_object_type, |(aot, _, _)| {
                AudioObjectType::from(aot)
            })
    }

    /// The explicit SBR output rate in Hz declared by a hierarchical
    /// (`audioObjectType` 5/29) config; `None` otherwise.
    pub fn extension_sampling_frequency(&self) -> Option<u32> {
        self.with_serialized(|bytes| {
            let mut bit = 0usize;
            let aot = asc_get_aot(bytes, &mut bit)?;
            if aot != AOT_SBR && aot != AOT_PS {
                return None;
            }
            let sfi = asc_read_bits(bytes, &mut bit, SFI_BITS as usize)? as u8;
            if sfi == SFI_ESCAPE {
                asc_read_bits(bytes, &mut bit, SFI_ESCAPE_BITS)?;
            }
            asc_read_bits(bytes, &mut bit, CHANNEL_CONFIG_BITS)?;
            let esfi = asc_read_bits(bytes, &mut bit, SFI_BITS as usize)? as u8;
            if esfi == SFI_ESCAPE {
                return asc_read_bits(bytes, &mut bit, SFI_ESCAPE_BITS);
            }
            SamplingFrequencyIndex::from(esfi).table_hz()
        })
    }
}

fn extension_index_for(hz: u32) -> Option<SamplingFrequencyIndex> {
    (0..=SFI_TABLE_LAST)
        .map(SamplingFrequencyIndex::from)
        .find(|i| i.table_hz() == Some(hz))
}

#[cfg(test)]
mod tests {
    use super::*;
    use broadcast_common::Serialize;
    const KNOWN: [u8; 5] = [0x12, 0x08, 0x56, 0xe5, 0x00];

    #[test]
    fn parse_real_fixture() {
        let a = AudioSpecificConfig::parse(&KNOWN).unwrap();
        assert_eq!(a.audio_object_type, AudioObjectType::AacLc);
        assert_eq!(a.sampling_frequency_index, SamplingFrequencyIndex::Fs44100);
        assert_eq!(a.channel_configuration, ChannelConfiguration::Mono);
        assert!(a.sampling_frequency.is_none());
    }
    #[test]
    fn serialize_byte_identical() {
        let out = AudioSpecificConfig::parse(&KNOWN)
            .unwrap()
            .try_to_bytes()
            .unwrap();
        assert_eq!(out.as_slice(), KNOWN.as_slice());
    }

    /// r04-W9: serializing into a larger shared buffer must leave the caller's
    /// bytes past `serialized_len()` untouched. Unfixed, `buf.fill(0)` zeroed
    /// the entire slice, so a caller batching several configs into one buffer
    /// lost everything it had already written after this point.
    #[test]
    fn serialize_does_not_zero_bytes_past_need() {
        let asc = AudioSpecificConfig::parse(&KNOWN).unwrap();
        let need = asc.serialized_len();
        let mut buf = alloc::vec![0xAAu8; need + 32];
        let n = asc.serialize_into(&mut buf).unwrap();
        assert_eq!(n, need);
        assert_eq!(&buf[..need], KNOWN.as_slice());
        assert!(
            buf[need..].iter().all(|&b| b == 0xAA),
            "bytes past `need` must be untouched, got {:02x?}",
            &buf[need..]
        );
    }

    /// The same for the Escape (explicit sampling frequency) form, whose
    /// trailing region starts at a different offset.
    #[test]
    fn serialize_escape_form_keeps_the_tail_intact() {
        let asc = AudioSpecificConfig {
            sampling_frequency_index: SamplingFrequencyIndex::Escape,
            sampling_frequency: Some(44100),
            trailing: alloc::vec![0x01, 0x02],
            ..AudioSpecificConfig::parse(&KNOWN).unwrap()
        };
        let need = asc.serialized_len();
        assert_eq!(need, 7);
        let mut buf = alloc::vec![0x55u8; need + 16];
        asc.serialize_into(&mut buf).unwrap();
        assert_eq!(&buf[5..7], &[0x01, 0x02]);
        assert!(buf[need..].iter().all(|&b| b == 0x55));
        // And the written region round-trips byte-exactly.
        let back = AudioSpecificConfig::parse(&buf[..need]).unwrap();
        assert_eq!(
            back.serialize_into(&mut alloc::vec![0u8; need]).unwrap(),
            need
        );
        assert_eq!(back.try_to_bytes().unwrap(), buf[..need]);
    }
    #[test]
    fn adts_round_trip() {
        let a = AudioSpecificConfig::parse(&KNOWN).unwrap();
        let h = a.to_adts_header(200).unwrap();
        let p = parse_adts_header(&h).unwrap();
        assert_eq!(p.profile, 1);
        assert_eq!(p.sampling_frequency_index, 4);
        assert_eq!(p.channel_configuration, 1);
        assert_eq!(p.frame_length, 200);
        let a2 = AudioSpecificConfig::from_adts_header(&p);
        assert_eq!(a.audio_object_type, a2.audio_object_type);
        assert_eq!(a.sampling_frequency_index, a2.sampling_frequency_index);
        assert_eq!(a.channel_configuration, a2.channel_configuration);
    }
    #[test]
    fn adts_build_parse() {
        let p = parse_adts_header(&build_adts_header(1, 4, 2, 300)).unwrap();
        assert_eq!(p.profile, 1);
        assert_eq!(p.sampling_frequency_index, 4);
        assert_eq!(p.channel_configuration, 2);
        assert_eq!(p.frame_length, 300);
    }
    #[test]
    fn escape_round_trip() {
        let mut a = AudioSpecificConfig::parse(&KNOWN).unwrap();
        a.sampling_frequency_index = SamplingFrequencyIndex::Escape;
        a.sampling_frequency = Some(48000);
        a.channel_configuration = ChannelConfiguration::Stereo;
        let bytes = a.try_to_bytes().unwrap();
        assert!(bytes.len() >= 5);
        let a2 = AudioSpecificConfig::parse(&bytes).unwrap();
        assert_eq!(a2.sampling_frequency_index, SamplingFrequencyIndex::Escape);
        assert_eq!(a2.sampling_frequency, Some(48000));
        assert_eq!(a2.channel_configuration, ChannelConfiguration::Stereo);
    }
    #[test]
    fn mutate_config_changes_bytes() {
        let o = AudioSpecificConfig::parse(&KNOWN)
            .unwrap()
            .try_to_bytes()
            .unwrap();
        let mut b = AudioSpecificConfig::parse(&KNOWN).unwrap();
        b.channel_configuration = ChannelConfiguration::Stereo;
        assert_ne!(o, b.try_to_bytes().unwrap());
    }
}