oxideav-aac 0.1.7

Pure-Rust AAC-LC decoder and encoder for oxideav — ADTS framing, Huffman books 1-11, IMDCT, M/S stereo, TNS, PNS
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
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
//! LATM / LOAS transport framing — ISO/IEC 14496-3 §1.7.
//!
//! LATM (Low-overhead MPEG-4 Audio Transport Multiplex) is the
//! multiplex layer that packs one or more MPEG-4 Audio payloads plus
//! their [`AudioSpecificConfig`] (ASC) into a single multiplexed
//! element ([`AudioMuxElement`], §1.7.3.1 Table 1.41). LOAS
//! (Low Overhead Audio Stream) is the synchronization layer above it
//! ([`AudioSyncStream`], §1.7.2.1 Table 1.36), which prefixes each
//! multiplexed element with a `0x2B7` syncword and a 13-bit byte
//! length so the multiplex can be recovered from a transmission
//! channel that carries no framing of its own.
//!
//! This module decodes the transport structure end to end for the AAC
//! case — the configuration ([`StreamMuxConfig`], Table 1.42), the
//! per-subframe payload lengths ([`PayloadLengthInfo`], Table 1.44),
//! and the multiplexed AAC access units ([`PayloadMux`], Table 1.45) —
//! and hands the recovered raw-data-block byte slices to the
//! [`crate::decode::StreamDecoder`] / [`crate::raw_data_block`] layer.
//!
//! ## Scope
//!
//! The decode path supports the configurations that carry AAC:
//! `audioMuxVersion ∈ {0, 1}` (the `audioMuxVersion == 1`
//! `taraBufferFullness` / per-ASC length-prefix extensions are parsed),
//! `allStreamsSameTimeFraming` in both states, and the per-layer
//! `frameLengthType` values `0` (variable-length, byte count carried
//! in `PayloadLengthInfo()`) and `1` (fixed `frameLength` bits in
//! `StreamMuxConfig()`). The CELP (`3`/`4`/`5`) and HVXC (`6`/`7`)
//! frame-length-table-indexed types are surfaced as
//! [`Error::LatmUnsupportedFrameLengthType`] — they index frame-length
//! tables for object types this AAC-focused crate does not decode. The
//! `audioMuxVersionA == 1` reserved branch is
//! [`Error::LatmAudioMuxVersionAReserved`]. The `EPMuxElement()`
//! error-protected variant (Table 1.40) and the
//! `EPAudioSyncStream()` FEC header (Table 1.37) are parsed at the
//! framing level but the EP-tool payload de-interleave is out of
//! scope.

use crate::asc::AudioSpecificConfig;
use crate::crc;
use crate::{Error, Result};
use oxideav_core::bits::BitReader;

/// §1.7.2.1 Table 1.36 `AudioSyncStream()` syncword (`0x2B7`, 11 bits).
pub const AUDIO_SYNC_STREAM_SYNCWORD: u32 = 0x2B7;

/// §1.7.2.1 Table 1.37 `EPAudioSyncStream()` syncword (`0x4DE1`,
/// 16 bits).
pub const EP_AUDIO_SYNC_STREAM_SYNCWORD: u32 = 0x4DE1;

/// §1.7.2.2.1: "The maximum byte-distance between two syncwords is
/// 8192 bytes", encoded in the 13-bit `audioMuxLengthBytes` field.
pub const MAX_AUDIO_MUX_LENGTH_BYTES: u32 = (1 << 13) - 1;

/// §1.7.3 signalling caps: `numProgram` is 4-bit (max program index
/// 15), `numLayer` is 3-bit (max layer index 7), `streamIndx` is
/// 4-bit (max 15 streams), `numChunk` is 4-bit.
const MAX_PROGRAM_INDEX: u32 = 15;
const MAX_LAYER_INDEX: u32 = 7;
const MAX_STREAM_COUNT: usize = 16;

/// One decoded scalable layer of a [`StreamMuxConfig`] program.
///
/// Mirrors the per-`streamID[prog][lay]` state the Table 1.42 loop
/// builds: the parsed [`AudioSpecificConfig`] (or `None` when
/// `useSameConfig` pointed at an earlier layer's config), the
/// `frameLengthType`, and the framing parameter that type selects
/// (`latmBufferFullness` for type 0, `frameLength` bits for type 1).
#[derive(Debug, Clone)]
pub struct LayerConfig {
    /// `progSIndx` — the program this layer belongs to.
    pub prog: u8,
    /// `laySIndx` — the layer index within the program.
    pub lay: u8,
    /// `streamID[prog][lay]` — the flat stream counter assigned in
    /// transmission order.
    pub stream_id: u8,
    /// The layer's [`AudioSpecificConfig`]. `None` ⇔ `useSameConfig`
    /// was set, meaning "apply the ASC most recently transmitted in a
    /// previous layer or program" (§1.7.3.2.3). [`StreamMuxConfig`]
    /// resolves this into [`LayerConfig::effective_asc`] on parse, so
    /// callers always have a concrete config there.
    pub asc: Option<AudioSpecificConfig>,
    /// The effective ASC after resolving `useSameConfig` back to the
    /// most recently transmitted config. Always populated.
    pub effective_asc: AudioSpecificConfig,
    /// `frameLengthType[streamID]` (§1.7.3.1 Table 1.42).
    pub frame_length_type: u8,
    /// `latmBufferFullness[streamID]` — present (8-bit) only for
    /// `frameLengthType == 0`.
    pub latm_buffer_fullness: Option<u8>,
    /// `coreFrameOffset` — present (6-bit) only for
    /// `frameLengthType == 0`, `!allStreamsSameTimeFraming`, and a
    /// CELP-core / AAC-enhancement layer pairing.
    pub core_frame_offset: Option<u8>,
    /// `frameLength[streamID]` — present (9-bit) only for
    /// `frameLengthType == 1`. The fixed payload length is
    /// `(frameLength + 20) * 8` bits per §1.7.3.2.3.
    pub frame_length: Option<u16>,
}

impl LayerConfig {
    /// §1.7.3.2.3: for `frameLengthType == 1` the fixed payload bit
    /// length is `(frameLength + 20) * 8`. Returns `None` for every
    /// other frame-length type (their length is carried in
    /// `PayloadLengthInfo()` or is table-indexed).
    pub fn fixed_payload_bits(&self) -> Option<u32> {
        if self.frame_length_type == 1 {
            self.frame_length
                .map(|fl| (u32::from(fl) + 20).saturating_mul(8))
        } else {
            None
        }
    }
}

/// Decoded `StreamMuxConfig()` — ISO/IEC 14496-3 §1.7.3.1 Table 1.42.
///
/// Carries the whole multiplex configuration: the version flags, the
/// time-framing mode, the per-program / per-layer [`LayerConfig`]
/// table, the `otherData` length, and the optional `crcCheckSum`.
#[derive(Debug, Clone)]
pub struct StreamMuxConfig {
    /// `audioMuxVersion` (1 bit).
    pub audio_mux_version: u8,
    /// `audioMuxVersionA` (1 bit; `0` unless `audioMuxVersion == 1`
    /// signalled it). A `1` here is the reserved `/* tbd */` branch,
    /// rejected on parse.
    pub audio_mux_version_a: u8,
    /// `taraBufferFullness` — present only for `audioMuxVersion == 1`.
    pub tara_buffer_fullness: Option<u32>,
    /// `allStreamsSameTimeFraming` (1 bit).
    pub all_streams_same_time_framing: bool,
    /// `numSubFrames` (6 bits). `numSubFrames + 1` PayloadMux frames
    /// are multiplexed.
    pub num_sub_frames: u8,
    /// `numProgram` (4 bits). `numProgram + 1` programs.
    pub num_program: u8,
    /// `numLayer[prog]` (3 bits) for each program — `num_layer[p] + 1`
    /// layers in program `p`.
    pub num_layer: Vec<u8>,
    /// The flat per-stream layer table, in transmission order.
    pub layers: Vec<LayerConfig>,
    /// `otherDataPresent` (1 bit).
    pub other_data_present: bool,
    /// `otherDataLenBits` — the decoded length of the trailing
    /// `otherData` field (in bits). `0` when `!otherDataPresent`.
    pub other_data_len_bits: u32,
    /// `crcCheckPresent` (1 bit).
    pub crc_check_present: bool,
    /// `crcCheckSum` (8 bits) when present.
    pub crc_check_sum: Option<u8>,
}

impl StreamMuxConfig {
    /// `streamID[prog][lay]` lookup, mirroring the Table 1.42
    /// `streamID` assignment (`prog`-major, `lay`-minor flat counter).
    pub fn stream_id(&self, prog: u8, lay: u8) -> Option<u8> {
        self.layers
            .iter()
            .find(|l| l.prog == prog && l.lay == lay)
            .map(|l| l.stream_id)
    }

    /// The [`LayerConfig`] for a given flat `streamID`.
    pub fn layer(&self, stream_id: u8) -> Option<&LayerConfig> {
        self.layers.iter().find(|l| l.stream_id == stream_id)
    }

    /// Parse a `StreamMuxConfig()` from `reader` (Table 1.42).
    ///
    /// `data` is the byte slice that backs `reader` (the same slice it
    /// was constructed over); it is used only to re-read the config
    /// prefix for CRC recomputation when `crcCheckPresent` is set.
    ///
    /// The reader is positioned at the `audioMuxVersion` bit and is
    /// advanced to the bit after the configuration (the `crcCheckSum`,
    /// or the last config bit when no CRC is present). The optional
    /// `crcCheckSum` is recomputed against the configuration prefix and
    /// validated; a mismatch is [`Error::LatmCrcMismatch`].
    pub fn parse(reader: &mut BitReader<'_>, data: &[u8]) -> Result<Self> {
        let start_bit = reader.bit_position();

        let audio_mux_version = read_u8(reader, 1)?;
        let audio_mux_version_a = if audio_mux_version == 1 {
            read_u8(reader, 1)?
        } else {
            0
        };

        if audio_mux_version_a != 0 {
            // The Table 1.42 `else { /* tbd */ }` branch — no defined
            // syntax.
            return Err(Error::LatmAudioMuxVersionAReserved);
        }

        let tara_buffer_fullness = if audio_mux_version == 1 {
            Some(latm_get_value(reader)?)
        } else {
            None
        };

        let all_streams_same_time_framing = read_bit(reader)?;
        let num_sub_frames = read_u8(reader, 6)?;
        let num_program = read_u8(reader, 4)?;
        if u32::from(num_program) > MAX_PROGRAM_INDEX {
            return Err(Error::LatmConfigOutOfRange);
        }

        let mut num_layer: Vec<u8> = Vec::with_capacity(usize::from(num_program) + 1);
        let mut layers: Vec<LayerConfig> = Vec::new();
        // The "most recently transmitted" ASC, threaded across layers
        // for `useSameConfig` resolution (§1.7.3.2.3).
        let mut last_asc: Option<AudioSpecificConfig> = None;
        let mut stream_cnt: u32 = 0;

        for prog in 0..=u32::from(num_program) {
            let n_layer = read_u8(reader, 3)?;
            if u32::from(n_layer) > MAX_LAYER_INDEX {
                return Err(Error::LatmConfigOutOfRange);
            }
            num_layer.push(n_layer);

            for lay in 0..=u32::from(n_layer) {
                if stream_cnt as usize >= MAX_STREAM_COUNT {
                    return Err(Error::LatmConfigOutOfRange);
                }
                let stream_id = stream_cnt as u8;
                stream_cnt += 1;

                // useSameConfig — never present for the (0,0) layer.
                let use_same_config = if prog == 0 && lay == 0 {
                    false
                } else {
                    read_bit(reader)?
                };

                let asc = if use_same_config {
                    None
                } else if audio_mux_version == 0 {
                    // audioMuxVersion == 0: the ASC has no explicit
                    // length prefix; it is parsed in place and its
                    // bit-length is implied by the ASC syntax.
                    let asc = AudioSpecificConfig::parse_bits(reader, start_bit)?;
                    Some(asc)
                } else {
                    // audioMuxVersion == 1: `ascLen = LatmGetValue();
                    // ascLen -= AudioSpecificConfig(); fillBits(ascLen)`.
                    // The ASC is length-prefixed, so we know the exact
                    // bit bound and can apply the §1.6.5 trailing
                    // implicit-SBR probe.
                    let asc_len = latm_get_value(reader)?;
                    let asc_start = reader.bit_position();
                    let asc = AudioSpecificConfig::parse_bits_bounded(
                        reader,
                        asc_start,
                        u64::from(asc_len),
                    )?;
                    let consumed = reader.bit_position().saturating_sub(asc_start);
                    // fillBits = ascLen - (bits the ASC consumed).
                    let fill = u64::from(asc_len).saturating_sub(consumed);
                    if fill > 0 {
                        skip_bits(reader, fill)?;
                    }
                    Some(asc)
                };

                // Resolve useSameConfig into a concrete effective ASC.
                let effective_asc = if let Some(a) = &asc {
                    last_asc = Some(a.clone());
                    a.clone()
                } else {
                    last_asc.clone().ok_or(Error::LatmNoPreviousMuxConfig)?
                };

                let frame_length_type = read_u8(reader, 3)?;
                let mut latm_buffer_fullness = None;
                let mut core_frame_offset = None;
                let mut frame_length = None;

                match frame_length_type {
                    0 => {
                        latm_buffer_fullness = Some(read_u8(reader, 8)?);
                        if !all_streams_same_time_framing {
                            // The CELP-core / AAC-enhancement pairing
                            // (§1.7.3.1 Table 1.42): AOT 6/20 (AAC SSR
                            // / ER AAC Scalable) layered above AOT 8/24
                            // (CELP / ER CELP).
                            let this_aot = effective_asc.aot;
                            let prev_aot = layers.last().map(|l| l.effective_asc.aot);
                            let pairs = (this_aot == 6 || this_aot == 20)
                                && matches!(prev_aot, Some(8) | Some(24));
                            if pairs {
                                core_frame_offset = Some(read_u8(reader, 6)?);
                            }
                        }
                    }
                    1 => {
                        frame_length = Some(read_u16(reader, 9)?);
                    }
                    other => {
                        // `2` is reserved; `3`/`4`/`5` are CELP and
                        // `6`/`7` are HVXC, all table-indexed framing
                        // this AAC-focused decoder does not carry.
                        return Err(Error::LatmUnsupportedFrameLengthType(other));
                    }
                }

                layers.push(LayerConfig {
                    prog: prog as u8,
                    lay: lay as u8,
                    stream_id,
                    asc,
                    effective_asc,
                    frame_length_type,
                    latm_buffer_fullness,
                    core_frame_offset,
                    frame_length,
                });
            }
        }

        // otherDataPresent / otherDataLenBits.
        let other_data_present = read_bit(reader)?;
        let other_data_len_bits = if other_data_present {
            if audio_mux_version == 1 {
                latm_get_value(reader)?
            } else {
                // do { otherDataLenBits *= 256; esc; tmp(8);
                // otherDataLenBits += tmp; } while (esc);
                let mut acc: u32 = 0;
                loop {
                    acc = acc.wrapping_mul(256);
                    let esc = read_bit(reader)?;
                    let tmp = read_u8(reader, 8)?;
                    acc = acc.wrapping_add(u32::from(tmp));
                    if !esc {
                        break;
                    }
                }
                acc
            }
        } else {
            0
        };

        // crcCheckPresent / crcCheckSum. The CRC covers the whole
        // StreamMuxConfig() from `audioMuxVersion` up to but excluding
        // crcCheckPresent — capture that prefix before reading the
        // flag.
        let crc_end_bit = reader.bit_position();
        let crc_check_present = read_bit(reader)?;
        let crc_check_sum = if crc_check_present {
            let sum = read_u8(reader, 8)?;
            // Recompute over the config prefix and validate.
            let prefix = read_back_bits(data, start_bit, crc_end_bit)?;
            let expected = crc::stream_mux_config_crc(&prefix);
            if expected != sum {
                return Err(Error::LatmCrcMismatch);
            }
            Some(sum)
        } else {
            None
        };

        Ok(StreamMuxConfig {
            audio_mux_version,
            audio_mux_version_a,
            tara_buffer_fullness,
            all_streams_same_time_framing,
            num_sub_frames,
            num_program,
            num_layer,
            layers,
            other_data_present,
            other_data_len_bits,
            crc_check_present,
            crc_check_sum,
        })
    }
}

/// §1.7.3 signalling cap: `numChunk` is 4-bit (max chunk index 15).
const MAX_NUM_CHUNK_INDEX: u32 = 15;

/// One recovered MPEG-4 Audio payload from a [`PayloadMux`] — the raw
/// access-unit bytes for a single `(subframe, prog, lay)` slot. For an
/// AAC layer these bytes are the §4.4.2.1 `raw_data_block()` that the
/// [`crate::decode::StreamDecoder`] / [`crate::raw_data_block`] layer
/// consumes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MuxPayload {
    /// Subframe index (`0 ..= numSubFrames`).
    pub sub_frame: u8,
    /// `prog` — the program this payload belongs to.
    pub prog: u8,
    /// `lay` — the layer within the program.
    pub lay: u8,
    /// `streamID[prog][lay]`.
    pub stream_id: u8,
    /// The raw payload bytes (one complete access unit for
    /// `frameLengthType == 0`).
    pub data: Vec<u8>,
}

/// `MuxSlotLengthBytes[streamID]` decoded for one payload slot of a
/// [`PayloadLengthInfo`] (Table 1.44). For `frameLengthType == 0` this
/// is the running 8-bit-escape byte count; the bit length for
/// `frameLengthType == 1` comes from the layer's fixed `frameLength`.
#[derive(Debug, Clone, Copy)]
struct SlotLength {
    prog: u8,
    lay: u8,
    stream_id: u8,
    /// Payload length in **bits**. For type-0 this is `bytes * 8`; for
    /// type-1 it is `(frameLength + 20) * 8`.
    bits: u32,
}

/// Decoded `AudioMuxElement()` — ISO/IEC 14496-3 §1.7.3.1 Table 1.41.
///
/// Holds the (possibly inherited) [`StreamMuxConfig`] and the recovered
/// per-subframe payloads. Parsing supports `audioMuxVersionA == 0`
/// (the only defined branch) and `allStreamsSameTimeFraming` in both
/// states; non-same-time-framing uses the `numChunk` chunk layout of
/// Tables 1.44 / 1.45.
#[derive(Debug, Clone)]
pub struct AudioMuxElement {
    /// `useSameStreamMux` (only present when `muxConfigPresent`). When
    /// `true`, [`AudioMuxElement::config`] was inherited from the
    /// previous element rather than parsed here.
    pub use_same_stream_mux: bool,
    /// The active multiplex configuration for this element.
    pub config: StreamMuxConfig,
    /// The recovered payloads in transmission order.
    pub payloads: Vec<MuxPayload>,
}

impl AudioMuxElement {
    /// Parse an `AudioMuxElement()` (Table 1.41) from `reader`.
    ///
    /// `data` is the byte slice backing `reader` (forwarded to
    /// [`StreamMuxConfig::parse`] for CRC recomputation).
    /// `mux_config_present` is the `muxConfigPresent` flag the calling
    /// layer supplies (LOAS [`AudioSyncStream`] passes `1`; an
    /// out-of-band-configured transport passes `0`). `prev_config` is
    /// the configuration decoded on the previous element, used when
    /// `useSameStreamMux` is set or when `muxConfigPresent == 0`.
    pub fn parse(
        reader: &mut BitReader<'_>,
        data: &[u8],
        mux_config_present: bool,
        prev_config: Option<&StreamMuxConfig>,
    ) -> Result<Self> {
        let (use_same_stream_mux, config) = if mux_config_present {
            let use_same = read_bit(reader)?;
            if use_same {
                let cfg = prev_config.cloned().ok_or(Error::LatmNoPreviousMuxConfig)?;
                (true, cfg)
            } else {
                (false, StreamMuxConfig::parse(reader, data)?)
            }
        } else {
            // Out-of-band StreamMuxConfig(): apply the previous one.
            let cfg = prev_config.cloned().ok_or(Error::LatmNoPreviousMuxConfig)?;
            (false, cfg)
        };

        if config.audio_mux_version_a != 0 {
            return Err(Error::LatmAudioMuxVersionAReserved);
        }

        let mut payloads = Vec::new();
        for sub_frame in 0..=u32::from(config.num_sub_frames) {
            let slots = payload_length_info(reader, &config)?;
            payload_mux(reader, &config, sub_frame as u8, &slots, &mut payloads)?;
        }

        // otherData: skip otherDataLenBits bits.
        if config.other_data_present {
            skip_bits(reader, u64::from(config.other_data_len_bits))?;
        }

        // ByteAlign().
        reader.align_to_byte();

        Ok(AudioMuxElement {
            use_same_stream_mux,
            config,
            payloads,
        })
    }
}

/// `PayloadLengthInfo()` — §1.7.3.1 Table 1.44. Returns the decoded
/// per-slot payload bit-lengths in the order `PayloadMux()` will emit
/// them.
fn payload_length_info(
    reader: &mut BitReader<'_>,
    config: &StreamMuxConfig,
) -> Result<Vec<SlotLength>> {
    let mut slots = Vec::new();
    if config.all_streams_same_time_framing {
        for prog in 0..=u32::from(config.num_program) {
            let n_layer = config.num_layer[prog as usize];
            for lay in 0..=u32::from(n_layer) {
                let stream_id = config
                    .stream_id(prog as u8, lay as u8)
                    .ok_or(Error::LatmConfigOutOfRange)?;
                let layer = config.layer(stream_id).ok_or(Error::LatmConfigOutOfRange)?;
                let bits = slot_bits(reader, layer)?;
                slots.push(SlotLength {
                    prog: prog as u8,
                    lay: lay as u8,
                    stream_id,
                    bits,
                });
            }
        }
    } else {
        let num_chunk = read_u8(reader, 4)?;
        if u32::from(num_chunk) > MAX_NUM_CHUNK_INDEX {
            return Err(Error::LatmConfigOutOfRange);
        }
        for _ in 0..=u32::from(num_chunk) {
            let stream_indx = read_u8(reader, 4)?;
            let layer = config
                .layer(stream_indx)
                .ok_or(Error::LatmConfigOutOfRange)?;
            let prog = layer.prog;
            let lay = layer.lay;
            let stream_id = layer.stream_id;
            let frame_length_type = layer.frame_length_type;
            let bits = slot_bits(reader, layer)?;
            // For frameLengthType == 0 in the chunk layout the spec
            // appends an AuEndFlag bit after MuxSlotLengthBytes.
            if frame_length_type == 0 {
                let _au_end_flag = read_bit(reader)?;
            }
            slots.push(SlotLength {
                prog,
                lay,
                stream_id,
                bits,
            });
        }
    }
    Ok(slots)
}

/// Decode the payload bit-length for one slot per its
/// `frameLengthType` (Table 1.44 inner body): the 8-bit-escape running
/// `MuxSlotLengthBytes` for type 0, or the fixed `(frameLength+20)*8`
/// for type 1. CELP/HVXC `MuxSlotLengthCoded` table indices are out of
/// scope and were already rejected when the config was parsed.
fn slot_bits(reader: &mut BitReader<'_>, layer: &LayerConfig) -> Result<u32> {
    match layer.frame_length_type {
        0 => {
            let mut bytes: u32 = 0;
            loop {
                let tmp = read_u8(reader, 8)?;
                bytes = bytes.wrapping_add(u32::from(tmp));
                if tmp != 255 {
                    break;
                }
            }
            Ok(bytes.saturating_mul(8))
        }
        1 => layer
            .fixed_payload_bits()
            .ok_or(Error::LatmConfigOutOfRange),
        other => Err(Error::LatmUnsupportedFrameLengthType(other)),
    }
}

/// `PayloadMux()` — §1.7.3.1 Table 1.45. Reads each slot's payload
/// bytes in the same order `PayloadLengthInfo()` emitted them, pushing
/// one [`MuxPayload`] per slot. Payloads are byte-extracted; the spec
/// guarantees `frameLengthType == 0` payloads are an integer number of
/// bytes, and `AudioMuxElement()` byte-aligns the reader at each
/// subframe boundary in the common AAC case.
fn payload_mux(
    reader: &mut BitReader<'_>,
    config: &StreamMuxConfig,
    sub_frame: u8,
    slots: &[SlotLength],
    out: &mut Vec<MuxPayload>,
) -> Result<()> {
    // Walk in the order PayloadLengthInfo built the slots, which is the
    // same program/layer (or chunk) order PayloadMux uses.
    let _ = config;
    for slot in slots {
        let data = read_payload_bytes(reader, slot.bits)?;
        out.push(MuxPayload {
            sub_frame,
            prog: slot.prog,
            lay: slot.lay,
            stream_id: slot.stream_id,
            data,
        });
    }
    Ok(())
}

/// Read `bits` bits of payload as a byte vector. The common AAC case
/// (`frameLengthType == 0`, byte-aligned reader) is a fast `read_bytes`
/// path; a non-byte-multiple length or non-aligned reader falls back to
/// bit-by-bit assembly (MSB-first), with the trailing partial byte
/// left-justified.
fn read_payload_bytes(reader: &mut BitReader<'_>, bits: u32) -> Result<Vec<u8>> {
    if bits % 8 == 0 && reader.is_byte_aligned() {
        let n = (bits / 8) as usize;
        return reader.read_bytes(n).map_err(|_| Error::UnexpectedEnd);
    }
    let full = bits / 8;
    let rem = bits % 8;
    let mut out = Vec::with_capacity((full + u32::from(rem != 0)) as usize);
    for _ in 0..full {
        out.push(read_u8(reader, 8)?);
    }
    if rem > 0 {
        let v = read_u8(reader, rem)?;
        out.push(v << (8 - rem));
    }
    Ok(out)
}

/// §1.7.3.1 Table 1.43 `LatmGetValue()`: a variable-length unsigned
/// integer carried as `bytesForValue` (2 bits) followed by
/// `bytesForValue + 1` bytes, big-endian.
pub fn latm_get_value(reader: &mut BitReader<'_>) -> Result<u32> {
    let bytes_for_value = read_u8(reader, 2)?;
    let mut value: u32 = 0;
    for _ in 0..=u32::from(bytes_for_value) {
        value = value.wrapping_mul(256);
        let byte = read_u8(reader, 8)?;
        value = value.wrapping_add(u32::from(byte));
    }
    Ok(value)
}

/// One decoded LOAS sync frame — ISO/IEC 14496-3 §1.7.2.1.
///
/// Carries the framed `audioMuxLengthBytes` length, the recovered
/// [`AudioMuxElement`], and (for `EPAudioSyncStream`) the FEC header
/// fields. The byte offset of the frame within the LOAS buffer is also
/// recorded so callers can resume the sync search.
#[derive(Debug, Clone)]
pub struct LoasFrame {
    /// `audioMuxLengthBytes` (13 bits) — the byte length of the framed
    /// multiplexed element.
    pub audio_mux_length_bytes: u16,
    /// The recovered multiplexed element.
    pub element: AudioMuxElement,
    /// `frameCounter` (5 bits) — present only for `EPAudioSyncStream`.
    pub frame_counter: Option<u8>,
    /// Byte offset of the syncword within the LOAS buffer.
    pub offset: usize,
    /// Byte offset of the first byte after this sync frame.
    pub next_offset: usize,
}

/// LOAS `AudioSyncStream()` walker — ISO/IEC 14496-3 §1.7.2.1
/// Table 1.36.
///
/// Scans `data` for the 11-bit `0x2B7` syncword, then for each frame
/// reads the 13-bit `audioMuxLengthBytes` and decodes the byte-aligned
/// `AudioMuxElement(1)` over the next `audioMuxLengthBytes` bytes. The
/// syncword is searched on byte boundaries (AudioSyncStream frames are
/// byte-aligned per §1.7.2.2.1).
#[derive(Debug)]
pub struct AudioSyncStream<'a> {
    data: &'a [u8],
    pos: usize,
    /// The most recently decoded [`StreamMuxConfig`], threaded across
    /// frames for `useSameStreamMux` inheritance.
    prev_config: Option<StreamMuxConfig>,
}

impl<'a> AudioSyncStream<'a> {
    /// Create a walker over a LOAS `AudioSyncStream()` byte buffer.
    pub fn new(data: &'a [u8]) -> Self {
        AudioSyncStream {
            data,
            pos: 0,
            prev_config: None,
        }
    }

    /// Decode the next `AudioSyncStream()` sync frame, advancing past
    /// it. Returns `Ok(None)` at end of stream (no further syncword).
    ///
    /// On a successful decode the frame's [`StreamMuxConfig`] is
    /// retained so a subsequent frame carrying `useSameStreamMux` can
    /// inherit it.
    pub fn next_frame(&mut self) -> Result<Option<LoasFrame>> {
        let Some(sync_off) = self.find_syncword(AUDIO_SYNC_STREAM_SYNCWORD, 11) else {
            self.pos = self.data.len();
            return Ok(None);
        };

        // Read audioMuxLengthBytes (13 bits) starting after the 11-bit
        // syncword.
        let mut reader = BitReader::new(&self.data[sync_off..]);
        reader.skip(11).map_err(|_| Error::LoasSyncInvalid)?;
        let audio_mux_length_bytes =
            reader.read_u32(13).map_err(|_| Error::LoasSyncInvalid)? as u16;

        // The AudioMuxElement(1) follows; it is byte-aligned because
        // 11 + 13 = 24 bits = 3 whole bytes.
        debug_assert_eq!(reader.bit_position(), 24);
        let element_byte_start = sync_off + 3;
        let element_byte_end = element_byte_start + usize::from(audio_mux_length_bytes);
        if element_byte_end > self.data.len() {
            return Err(Error::LoasSyncInvalid);
        }
        let element_bytes = &self.data[element_byte_start..element_byte_end];
        let mut elem_reader = BitReader::new(element_bytes);
        let element = AudioMuxElement::parse(
            &mut elem_reader,
            element_bytes,
            true,
            self.prev_config.as_ref(),
        )?;

        self.prev_config = Some(element.config.clone());
        self.pos = element_byte_end;

        Ok(Some(LoasFrame {
            audio_mux_length_bytes,
            element,
            frame_counter: None,
            offset: sync_off,
            next_offset: element_byte_end,
        }))
    }

    /// Search for an `n`-bit syncword on byte boundaries from the
    /// current position. Returns the byte offset of the syncword's
    /// first byte, or `None` if not found before end of buffer. The
    /// 11-bit `0x2B7` and 16-bit `0x4DE1` syncwords both begin on a
    /// byte boundary in their respective frame layouts.
    fn find_syncword(&self, syncword: u32, n: u32) -> Option<usize> {
        let bytes_needed = n.div_ceil(8) as usize;
        let mut off = self.pos;
        while off + bytes_needed <= self.data.len() {
            let mut r = BitReader::new(&self.data[off..]);
            if let Ok(v) = r.read_u32(n) {
                if v == syncword {
                    return Some(off);
                }
            }
            off += 1;
        }
        None
    }
}

impl Iterator for AudioSyncStream<'_> {
    type Item = Result<LoasFrame>;

    fn next(&mut self) -> Option<Self::Item> {
        match self.next_frame() {
            Ok(Some(frame)) => Some(Ok(frame)),
            Ok(None) => None,
            Err(e) => {
                // Stop iterating after surfacing the error.
                self.pos = self.data.len();
                Some(Err(e))
            }
        }
    }
}

/// Decoded `EPAudioSyncStream()` FEC header — ISO/IEC 14496-3 §1.7.2.1
/// Table 1.37.
///
/// Parses the 16-bit `0x4DE1` syncword, the 4-bit `futureUse`, the
/// 13-bit `audioMuxLengthBytes`, the 5-bit `frameCounter`, and the
/// 18-bit `headerParity`. The body is an `EPMuxElement(1, 1)` whose
/// EP-tool de-interleave is out of scope; this struct captures the
/// header so callers can frame the stream and recover the (byte-aligned)
/// element body bounds.
#[derive(Debug, Clone)]
pub struct EpAudioSyncHeader {
    /// `futureUse` (4 bits).
    pub future_use: u8,
    /// `audioMuxLengthBytes` (13 bits).
    pub audio_mux_length_bytes: u16,
    /// `frameCounter` (5 bits).
    pub frame_counter: u8,
    /// `headerParity` (18 bits).
    pub header_parity: u32,
    /// Byte offset of the syncword.
    pub offset: usize,
    /// Byte offset of the first byte of the `EPMuxElement(1, 1)` body
    /// (the header is `16 + 4 + 13 + 5 + 18 = 56` bits = 7 bytes, so the
    /// body is byte-aligned).
    pub body_offset: usize,
}

impl EpAudioSyncHeader {
    /// Parse one `EPAudioSyncStream()` FEC header from `data` starting
    /// at `pos`, scanning for the `0x4DE1` syncword on byte boundaries.
    /// Returns `Ok(None)` if no syncword is found.
    pub fn parse(data: &[u8], pos: usize) -> Result<Option<Self>> {
        let walker = AudioSyncStream {
            data,
            pos,
            prev_config: None,
        };
        let Some(sync_off) = walker.find_syncword(EP_AUDIO_SYNC_STREAM_SYNCWORD, 16) else {
            return Ok(None);
        };
        let mut reader = BitReader::new(&data[sync_off..]);
        reader.skip(16).map_err(|_| Error::LoasSyncInvalid)?; // syncword
        let future_use = read_u8(&mut reader, 4)?;
        let audio_mux_length_bytes = read_u16(&mut reader, 13)?;
        let frame_counter = read_u8(&mut reader, 5)?;
        let header_parity = reader.read_u32(18).map_err(|_| Error::UnexpectedEnd)?;
        debug_assert_eq!(reader.bit_position(), 56);
        Ok(Some(EpAudioSyncHeader {
            future_use,
            audio_mux_length_bytes,
            frame_counter,
            header_parity,
            offset: sync_off,
            body_offset: sync_off + 7,
        }))
    }
}

/// Generator polynomial of the `EPAudioSyncStream()` `headerParity`
/// BCH(36,18) code (§1.7.2.2.2):
/// x¹⁸+x¹⁷+x¹⁶+x¹⁵+x⁹+x⁷+x⁶+x³+x²+x+1, stored without the leading
/// x¹⁸ term.
const EP_SYNC_BCH_GEN: u32 = (1 << 17)
    | (1 << 16)
    | (1 << 15)
    | (1 << 9)
    | (1 << 7)
    | (1 << 6)
    | (1 << 3)
    | (1 << 2)
    | (1 << 1)
    | 1;

/// Compute the §1.7.2.2.2 `headerParity` — the 18 parity bits of the
/// shortened BCH(36,18) over `audioMuxLengthBytes` (13 bits) followed
/// by `frameCounter` (5 bits), `R(x)` of `M(x)·x¹⁸ mod G(x)` per
/// §1.8.4.3.
pub fn ep_sync_header_parity(audio_mux_length_bytes: u16, frame_counter: u8) -> u32 {
    let msg: u32 =
        (u32::from(audio_mux_length_bytes & 0x1FFF) << 5) | u32::from(frame_counter & 0x1F);
    let mut reg: u32 = 0;
    let top = 1u32 << 17;
    let feed = |reg: &mut u32, bit: bool| {
        let high = *reg & top != 0;
        *reg = (*reg << 1) & 0x3FFFF;
        if high {
            *reg ^= EP_SYNC_BCH_GEN;
        }
        if bit {
            *reg ^= 1;
        }
    };
    for i in (0..18).rev() {
        feed(&mut reg, msg & (1 << i) != 0);
    }
    for _ in 0..18 {
        let high = reg & top != 0;
        reg = (reg << 1) & 0x3FFFF;
        if high {
            reg ^= EP_SYNC_BCH_GEN;
        }
    }
    reg
}

impl EpAudioSyncHeader {
    /// Verify the §1.7.2.2.2 BCH(36,18) `headerParity` against the
    /// received `audioMuxLengthBytes` / `frameCounter`.
    pub fn parity_ok(&self) -> bool {
        ep_sync_header_parity(self.audio_mux_length_bytes, self.frame_counter) == self.header_parity
    }
}

/// Threaded cross-frame state of an `EPMuxElement()` stream: the
/// active EP-tool configuration and the previous `StreamMuxConfig`.
#[derive(Debug, Default)]
pub struct EpMuxState {
    /// The active `ErrorProtectionSpecificConfig()` (threaded across
    /// `epUsePreviousMuxConfig == 1` elements).
    pub ep_config: Option<crate::ep_config::ErrorProtectionSpecificConfig>,
    /// The previous `StreamMuxConfig` for `useSameStreamMux`.
    pub prev_config: Option<StreamMuxConfig>,
}

/// A decoded `EPMuxElement(1, 1)` (§1.7.3.1 Table 1.40): the EP-tool
/// configuration in force plus the recovered (error-corrected)
/// `AudioMuxElement()`.
#[derive(Debug)]
pub struct EpMuxElement {
    /// `epUsePreviousMuxConfig` (majority-decoded).
    pub use_previous_mux_config: bool,
    /// The recovered inner `AudioMuxElement()`.
    pub element: AudioMuxElement,
}

impl EpMuxElement {
    /// Parse an `EPMuxElement(epDataPresent = 1, muxConfigPresent = 1)`
    /// from `data` (the whole element, byte-aligned), threading
    /// `state` across elements.
    ///
    /// Layout per Table 1.40: `epUsePreviousMuxConfig` + its 2-bit
    /// repetition parity (majority decides, §1.7.3.2.1); when clear,
    /// the 10-bit `epSpecificConfigLength` protected by the Table 1.59
    /// Golay(23,12) 11-bit parity, then
    /// `ErrorProtectionSpecificConfig()` + its Table 1.59 parity;
    /// `ByteAlign()`; then `EPAudioMuxElement(1)` — the EP-tool
    /// `ep_frame()` whose decoded class concatenation is the plain
    /// `AudioMuxElement(1)` bit stream (the §1.7.3.2.1 sensitivity
    /// category instances ride in syntax order).
    pub fn parse(data: &[u8], state: &mut EpMuxState) -> Result<Self> {
        let mut reader = BitReader::new(data);
        // epUsePreviousMuxConfig + 2-bit repetition parity.
        let b0 = read_bit(&mut reader)?;
        let b1 = read_bit(&mut reader)?;
        let b2 = read_bit(&mut reader)?;
        let use_prev = (u8::from(b0) + u8::from(b1) + u8::from(b2)) >= 2;
        if !use_prev {
            // epSpecificConfigLength (10) + Golay parity (11).
            let mut len_bits_field = [false; 10];
            for b in len_bits_field.iter_mut() {
                *b = read_bit(&mut reader)?;
            }
            let mut parity = [false; 11];
            for b in parity.iter_mut() {
                *b = read_bit(&mut reader)?;
            }
            let corrected = crate::ep_fec::header_fec_decode(&len_bits_field, &parity)?;
            let mut cfg_len = 0usize;
            for &b in &corrected {
                cfg_len = (cfg_len << 1) | usize::from(b);
            }
            // ErrorProtectionSpecificConfig() (self-terminating) +
            // Table 1.59 parity over its bits.
            let cfg_start = reader.bit_position();
            let epsc = crate::ep_config::ErrorProtectionSpecificConfig::parse(&mut reader)?;
            let consumed = (reader.bit_position() - cfg_start) as usize;
            // `epSpecificConfigLength` indicates the size of the
            // config; validate in bits (with a byte-unit fallback —
            // the staged text does not name the unit).
            if cfg_len != consumed && cfg_len != consumed.div_ceil(8) {
                return Err(Error::EpFrameInvalid);
            }
            let cfg_bits = read_back_bits(data, cfg_start, cfg_start + consumed as u64)?;
            let parity_len = crate::ep_fec::HeaderFec::for_len(consumed)?.parity_bits(consumed)?;
            let mut cfg_parity = Vec::with_capacity(parity_len);
            for _ in 0..parity_len {
                cfg_parity.push(read_bit(&mut reader)?);
            }
            let corrected_cfg = crate::ep_fec::header_fec_decode(&cfg_bits, &cfg_parity)?;
            if corrected_cfg != cfg_bits {
                // The FEC corrected config bits: re-parse from the
                // corrected sequence.
                let mut bytes = vec![0u8; corrected_cfg.len().div_ceil(8)];
                for (i, &b) in corrected_cfg.iter().enumerate() {
                    if b {
                        bytes[i / 8] |= 0x80 >> (i % 8);
                    }
                }
                let mut r2 = BitReader::new(&bytes);
                state.ep_config = Some(crate::ep_config::ErrorProtectionSpecificConfig::parse(
                    &mut r2,
                )?);
            } else {
                state.ep_config = Some(epsc);
            }
        }
        // ByteAlign().
        reader.align_to_byte();
        let epsc = state.ep_config.clone().ok_or(Error::EpFrameInvalid)?;
        let codec = crate::ep_frame::EpFrameCodec::new(epsc)?;
        let body = crate::ep_frame::read_remaining_bytes(&mut reader, data.len())?;
        let frame = codec.decode(&body)?;
        // The class concatenation is the AudioMuxElement(1) bits.
        let mut au_bits: Vec<bool> = Vec::new();
        for c in &frame.classes {
            au_bits.extend_from_slice(c);
        }
        let mut au_bytes = vec![0u8; au_bits.len().div_ceil(8)];
        for (i, &b) in au_bits.iter().enumerate() {
            if b {
                au_bytes[i / 8] |= 0x80 >> (i % 8);
            }
        }
        let mut au_reader = BitReader::new(&au_bytes);
        let element =
            AudioMuxElement::parse(&mut au_reader, &au_bytes, true, state.prev_config.as_ref())?;
        state.prev_config = Some(element.config.clone());
        Ok(EpMuxElement {
            use_previous_mux_config: use_prev,
            element,
        })
    }
}

// ---- bit helpers -----------------------------------------------------

fn read_u8(reader: &mut BitReader<'_>, n: u32) -> Result<u8> {
    Ok(reader.read_u32(n).map_err(|_| Error::UnexpectedEnd)? as u8)
}

fn read_u16(reader: &mut BitReader<'_>, n: u32) -> Result<u16> {
    Ok(reader.read_u32(n).map_err(|_| Error::UnexpectedEnd)? as u16)
}

fn read_bit(reader: &mut BitReader<'_>) -> Result<bool> {
    reader.read_bit().map_err(|_| Error::UnexpectedEnd)
}

fn skip_bits(reader: &mut BitReader<'_>, n: u64) -> Result<()> {
    // BitReader::skip takes a u32; chunk for safety on large fill runs.
    let mut remaining = n;
    while remaining > 0 {
        let chunk = remaining.min(u64::from(u32::MAX)) as u32;
        reader.skip(chunk).map_err(|_| Error::UnexpectedEnd)?;
        remaining -= u64::from(chunk);
    }
    Ok(())
}

/// Re-read the bits of an already-consumed `[from_bit, to_bit)` range
/// of `data` as a `Vec<bool>` in MSB-first transmission order, for CRC
/// recomputation. A fresh reader is created over the backing buffer so
/// the original reader's position is untouched.
fn read_back_bits(data: &[u8], from_bit: u64, to_bit: u64) -> Result<Vec<bool>> {
    debug_assert!(to_bit >= from_bit);
    let count = (to_bit - from_bit) as usize;
    let mut scratch = BitReader::new(data);
    skip_bits(&mut scratch, from_bit)?;
    let mut out = Vec::with_capacity(count);
    for _ in 0..count {
        out.push(scratch.read_bit().map_err(|_| Error::UnexpectedEnd)?);
    }
    Ok(out)
}

// ---- LOAS → PCM decode driver ----------------------------------------

use std::collections::HashMap;

use crate::decode::{DecodedFrame, StreamDecoder};

/// Whole-stream LATM/LOAS → PCM decoder.
///
/// Walks a LOAS `AudioSyncStream()` byte buffer ([`AudioSyncStream`]),
/// and for every recovered access unit ([`MuxPayload`]) drives the
/// payload's §4.4.2.1 `raw_data_block()` through the
/// [`crate::decode::StreamDecoder`] core
/// ([`StreamDecoder::decode_raw_data_block`]) using the configuration the
/// LATM `StreamMuxConfig` carried in the layer's
/// [`AudioSpecificConfig`].
///
/// The LATM multiplex can carry several streams (`streamID[prog][lay]`);
/// each is given its own [`StreamDecoder`] so the per-stream filterbank
/// overlap-add tail, LTP history, and predictor state thread across the
/// frames of that stream independently. For the common single-program /
/// single-layer AAC case there is exactly one stream.
///
/// ## Scope
///
/// Targets the core (AAC-LC / Main / LTP) tool chain the
/// [`StreamDecoder`] covers, **plus §4.6.18 SBR (HE-AAC v1)** — the
/// shared `decode_raw_data_block` core auto-detects the `EXT_SBR_DATA`
/// FIL payloads in-band and doubles the output rate (or keeps the core
/// rate in the §4.6.18.4.3 downsampled mode), and a PS payload renders
/// stereo through the subpart-8 tool (HE-AAC v2). The
/// `audioObjectType` carried by the ASC must be a General Audio
/// type whose `raw_data_block()` the core driver understands; otherwise
/// the underlying decode surfaces its own element-level error.
#[derive(Debug, Default)]
pub struct LoasDecoder {
    /// One [`StreamDecoder`] per `streamID`, so each multiplexed stream's
    /// inter-frame state stays independent.
    streams: HashMap<u8, StreamDecoder>,
    /// One §4.5.2.2 [`crate::scalable::ScalableDecoder`] per *program*
    /// for the scalable object types (AOTs 6 / 20), whose layers ride
    /// separate `streamID`s but decode to one combined output.
    scalable: HashMap<u8, crate::scalable::ScalableDecoder>,
    /// Per-program buffer collecting the current subframe's scalable
    /// layer payloads (in layer order) until the stack is complete.
    scalable_pending: HashMap<u8, Vec<Vec<u8>>>,
    /// Caller-forced §4.6.18.4.3 downsampled SBR output (see
    /// [`Self::set_sbr_downsampled`]); an explicitly signalled ASC
    /// whose extension sampling frequency equals the core rate selects
    /// the mode per stream regardless.
    sbr_downsampled: bool,
    /// Caller-forced §4.6.18.8 low-power SBR mode (see
    /// [`Self::set_sbr_low_power`]).
    sbr_low_power: bool,
}

impl LoasDecoder {
    /// A fresh LOAS decoder with no per-stream state.
    #[must_use]
    pub fn new() -> Self {
        LoasDecoder::default()
    }

    /// Force the §4.6.18.4.3 downsampled SBR output mode on every
    /// stream decoder this LOAS driver creates: SBR-active streams are
    /// emitted at the core sampling rate. Independent of the forced
    /// mode, a layer whose explicitly signalled `AudioSpecificConfig`
    /// carries `extensionSamplingFrequency == samplingFrequency`
    /// selects the mode by itself (the SBR output rate the ASC
    /// declares *is* the core rate). Select before decoding.
    pub fn set_sbr_downsampled(&mut self, downsampled: bool) {
        self.sbr_downsampled = downsampled;
    }

    /// Force the §4.6.18.8 low-power SBR mode on every stream decoder
    /// this LOAS driver creates (real-valued filterbanks + the LP
    /// adjustment chain; PS streams are rejected in this mode). Select
    /// before decoding.
    pub fn set_sbr_low_power(&mut self, low_power: bool) {
        self.sbr_low_power = low_power;
    }

    /// Decode a whole LOAS `AudioSyncStream()` byte buffer to a vector of
    /// per-access-unit interleaved PCM frames, in transmission order.
    ///
    /// Each [`LoasFrame`]'s `AudioMuxElement` may carry several
    /// subframes / payloads; every payload is decoded and pushed in the
    /// order [`AudioMuxElement::payloads`] presents them. A frame that
    /// yields no channel element (fill-only) still contributes its
    /// (empty) [`DecodedFrame`].
    pub fn decode_all(&mut self, data: &[u8]) -> Result<Vec<DecodedFrame>> {
        let mut out = Vec::new();
        let mut walker = AudioSyncStream::new(data);
        while let Some(frame) = walker.next_frame()? {
            for payload in &frame.element.payloads {
                // A scalable (AOT 6 / 20) layer joins its program's
                // pending stack; the stack decodes as one combined
                // access unit when the last layer arrives (§4.5.2.2:
                // one elementary stream per layer, one output).
                let config = &frame.element.config;
                let layer = config
                    .layer(payload.stream_id)
                    .ok_or(Error::LatmConfigOutOfRange)?;
                if layer.effective_asc.aot == 6 || layer.effective_asc.aot == 20 {
                    if let Some(decoded) = self.push_scalable_payload(config, payload)? {
                        out.push(decoded);
                    }
                    continue;
                }
                let decoded = self.decode_payload(config, payload)?;
                out.push(decoded);
            }
        }
        Ok(out)
    }

    /// Feed one scalable-program layer payload; returns the combined
    /// [`DecodedFrame`] when the payload completes the program's layer
    /// stack for the current access unit, `None` while the stack is
    /// still filling.
    ///
    /// Layers must arrive in layer order within each access unit
    /// (which is how `AudioMuxElement()` multiplexes them under
    /// `allStreamsSameTimeFraming`); an out-of-order layer surfaces
    /// [`Error::ScalableInvalid`].
    pub fn push_scalable_payload(
        &mut self,
        config: &StreamMuxConfig,
        payload: &MuxPayload,
    ) -> Result<Option<DecodedFrame>> {
        let layer = config
            .layer(payload.stream_id)
            .ok_or(Error::LatmConfigOutOfRange)?;
        let prog = layer.prog;
        let n_layers = usize::from(
            *config
                .num_layer
                .get(usize::from(prog))
                .ok_or(Error::LatmConfigOutOfRange)?,
        ) + 1;
        let pending = self.scalable_pending.entry(prog).or_default();
        if usize::from(layer.lay) != pending.len() {
            self.scalable_pending.remove(&prog);
            return Err(Error::ScalableInvalid);
        }
        pending.push(payload.data.clone());
        if pending.len() < n_layers {
            return Ok(None);
        }
        let payloads = self.scalable_pending.remove(&prog).unwrap_or_default();

        // Resolve the program's ScalableConfig from the layer ASCs.
        let mut ascs: Vec<&crate::asc::AudioSpecificConfig> = Vec::with_capacity(n_layers);
        for lay in 0..n_layers {
            let sid = config
                .stream_id(prog, lay as u8)
                .ok_or(Error::LatmConfigOutOfRange)?;
            let lc = config.layer(sid).ok_or(Error::LatmConfigOutOfRange)?;
            ascs.push(&lc.effective_asc);
        }
        let cfg = crate::scalable::ScalableConfig::from_layer_ascs(&ascs)?;
        // Reuse the persistent decoder while the configuration holds;
        // a mid-stream StreamMuxConfig change rebuilds it (the
        // overlap/LTP state is geometry-shaped).
        let rebuild = !matches!(self.scalable.get(&prog), Some(d) if d.config() == &cfg);
        if rebuild {
            self.scalable
                .insert(prog, crate::scalable::ScalableDecoder::new(cfg)?);
        }
        let dec = self.scalable.get_mut(&prog).expect("just inserted");
        let refs: Vec<&[u8]> = payloads.iter().map(Vec::as_slice).collect();
        dec.decode_frame(&refs).map(Some)
    }

    /// Decode a whole `EPAudioSyncStream()` byte buffer (§1.7.2.1
    /// Table 1.37) to per-access-unit PCM frames: every `0x4DE1` sync
    /// frame's BCH(36,18)-verified header is walked, its
    /// `EPMuxElement(1, 1)` is EP-decoded ([`EpMuxElement::parse`] —
    /// FEC-corrected, CRC-checked, de-interleaved) and the recovered
    /// `AudioMuxElement()` payloads decode exactly as on the plain
    /// LOAS path (scalable programs included).
    pub fn decode_all_ep(&mut self, data: &[u8]) -> Result<Vec<DecodedFrame>> {
        let mut out = Vec::new();
        let mut ep_state = EpMuxState::default();
        let mut pos = 0usize;
        while let Some(header) = EpAudioSyncHeader::parse(data, pos)? {
            if !header.parity_ok() {
                return Err(Error::EpFrameInvalid);
            }
            let body_end = header
                .body_offset
                .checked_add(usize::from(header.audio_mux_length_bytes))
                .ok_or(Error::UnexpectedEnd)?;
            if body_end > data.len() {
                return Err(Error::UnexpectedEnd);
            }
            let mux = EpMuxElement::parse(&data[header.body_offset..body_end], &mut ep_state)?;
            for payload in &mux.element.payloads {
                let config = &mux.element.config;
                let layer = config
                    .layer(payload.stream_id)
                    .ok_or(Error::LatmConfigOutOfRange)?;
                if layer.effective_asc.aot == 6 || layer.effective_asc.aot == 20 {
                    if let Some(decoded) = self.push_scalable_payload(config, payload)? {
                        out.push(decoded);
                    }
                    continue;
                }
                out.push(self.decode_payload(config, payload)?);
            }
            pos = body_end;
        }
        Ok(out)
    }

    /// Decode one recovered [`MuxPayload`] to PCM, routing it to the
    /// per-`streamID` [`StreamDecoder`] and configuring the decode from
    /// the payload's layer [`AudioSpecificConfig`].
    pub fn decode_payload(
        &mut self,
        config: &StreamMuxConfig,
        payload: &MuxPayload,
    ) -> Result<DecodedFrame> {
        let layer = config
            .layer(payload.stream_id)
            .ok_or(Error::LatmConfigOutOfRange)?;
        let asc = &layer.effective_asc;
        // The scalable object types decode per *program*, not per
        // stream: route through the layer-stack collector. While a
        // multi-layer stack is still filling, an empty frame (0
        // channels) is returned — [`Self::decode_all`] instead calls
        // [`Self::push_scalable_payload`] directly and skips these.
        if asc.aot == 6 || asc.aot == 20 {
            let sample_rate = asc.sample_rate;
            return Ok(self
                .push_scalable_payload(config, payload)?
                .unwrap_or(DecodedFrame {
                    pcm: Vec::new(),
                    channels: 0,
                    sample_rate,
                }));
        }
        // An SBR-signalling ASC (explicit AOT 5 wrapper or the implicit
        // trailing probe) needs no pre-rejection: the shared
        // `decode_raw_data_block` core auto-detects the `EXT_SBR_DATA`
        // FIL payloads in-band and doubles the output rate (§4.6.18).
        // The decode runs at the *core* configuration (`asc.aot` is the
        // unwrapped core object type, `asc.sample_rate` the core rate);
        // a PS payload renders stereo through the subpart-8 tool.
        // §4.5.1.1 — resolve the frame-length family from the layer's
        // ASC (`frameLengthFlag` semantics depend on the AOT: 1024/960
        // lines for the general GA types, 512/480 for ER AAC LD).
        let family = crate::swb_offset::FrameFamily::from_aot_and_flag(
            asc.aot,
            asc.ga_body.frame_length == crate::asc::FrameLength::Long960,
        );
        let dec = self.streams.entry(payload.stream_id).or_insert_with({
            let force_down = self.sbr_downsampled;
            let force_lp = self.sbr_low_power;
            move || {
                let mut d = StreamDecoder::new();
                d.set_sbr_downsampled(force_down);
                d.set_sbr_low_power(force_lp);
                d.set_frame_family(family);
                d
            }
        });
        // A mid-stream StreamMuxConfig replacement can change the
        // layer's frame family; the per-element overlap/LTP state is
        // family-shaped, so a mismatched decoder is rebuilt from
        // scratch rather than fed the wrong geometry.
        if dec.frame_family() != family {
            let mut d = StreamDecoder::new();
            d.set_sbr_downsampled(self.sbr_downsampled);
            d.set_sbr_low_power(self.sbr_low_power);
            d.set_frame_family(family);
            *dec = d;
        }
        // §4.6.18.2.6: FsSBR is twice the core rate; an explicit SBR
        // ASC whose extensionSamplingFrequency equals the core rate is
        // therefore declaring the §4.6.18.4.3 downsampled output.
        if asc.sbr_present && asc.extension_sample_rate == Some(asc.sample_rate) {
            dec.set_sbr_downsampled(true);
        }
        // A channelConfiguration-0 layer carries its layout in the
        // ASC's inline program_config_element(); install it so the
        // §8.5.2.2 canonical output reorder applies (an in-band PCE in
        // a later raw_data_block() still supersedes it).
        if asc.channel_configuration == 0 {
            if let Some(pce) = &asc.ga_body.pce {
                dec.set_program_config(pce.clone());
            }
        }
        // The ER General-Audio object types use the §4.4.2.3 Table 4.19
        // fixed-sequence er_raw_data_block() instead of the tagged
        // element walk; route AOT 17 (ER AAC LC), AOT 19 (ER AAC LTP —
        // the §4.6.7 LTP tool over the same Table 4.19 walk) and
        // AOT 23 (ER AAC LD, §4.6.17 — the 512/480-line family
        // installed above) there with the ASC's resilience triplet.
        if asc.aot == 17 || asc.aot == 19 || asc.aot == 23 {
            let resilience = asc
                .ga_body
                .extension_body
                .as_ref()
                .and_then(|ext| ext.resilience)
                .unwrap_or_default();
            return dec.decode_er_raw_data_block(
                asc.aot,
                asc.sampling_frequency_index,
                asc.sample_rate,
                asc.channel_configuration,
                resilience,
                &payload.data,
            );
        }
        // LATM carries exactly one raw_data_block() per payload.
        dec.decode_raw_data_block(
            asc.aot,
            asc.sampling_frequency_index,
            asc.sample_rate,
            asc.channel_configuration,
            1,
            &payload.data,
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use oxideav_core::bits::BitWriter;

    /// AAC-LC, 44.1 kHz (samplingFrequencyIndex 4), stereo
    /// (channelConfiguration 2): AOT=2 (5 bits `00010`), freqIdx=4
    /// (`0100`), chanConfig=2 (`0010`), then GASpecificConfig
    /// `frameLengthFlag=0 dependsOnCoreCoder=0 extensionFlag=0`
    /// (`000`). 16 bits total = `0x12 0x10`.
    const AAC_LC_ASC: [u8; 2] = [0x12, 0x10];

    /// Append the §1.7.3 AAC-LC ASC bit-for-bit into `w`.
    fn write_aac_lc_asc(w: &mut BitWriter) {
        // 16 bits, MSB-first, exactly as AAC_LC_ASC encodes.
        w.write_u32(u32::from(u16::from_be_bytes(AAC_LC_ASC)), 16);
    }

    #[test]
    fn latm_get_value_single_byte() {
        // bytesForValue = 0 -> one byte. value = 0xFF.
        let mut w = BitWriter::new();
        w.write_u32(0, 2); // bytesForValue
        w.write_u32(0xFF, 8);
        let bytes = w.finish();
        let mut r = BitReader::new(&bytes);
        assert_eq!(latm_get_value(&mut r).unwrap(), 0xFF);
    }

    #[test]
    fn latm_get_value_multi_byte() {
        // bytesForValue = 2 -> three bytes, big-endian: 0x010203.
        let mut w = BitWriter::new();
        w.write_u32(2, 2);
        w.write_u32(0x01, 8);
        w.write_u32(0x02, 8);
        w.write_u32(0x03, 8);
        let bytes = w.finish();
        let mut r = BitReader::new(&bytes);
        assert_eq!(latm_get_value(&mut r).unwrap(), 0x01_02_03);
    }

    /// Build a minimal `audioMuxVersion == 0` AAC-LC StreamMuxConfig:
    /// one program, one layer, allStreamsSameTimeFraming,
    /// frameLengthType 0, latmBufferFullness 0xFF, no otherData, no
    /// CRC.
    fn build_min_smc() -> Vec<u8> {
        let mut w = BitWriter::new();
        w.write_bit(false); // audioMuxVersion = 0
        w.write_bit(true); // allStreamsSameTimeFraming = 1
        w.write_u32(0, 6); // numSubFrames = 0
        w.write_u32(0, 4); // numProgram = 0
        w.write_u32(0, 3); // numLayer = 0
                           // (prog 0, lay 0): no useSameConfig bit; ASC inline.
        write_aac_lc_asc(&mut w);
        w.write_u32(0, 3); // frameLengthType = 0
        w.write_u32(0xFF, 8); // latmBufferFullness = 0xFF
        w.write_bit(false); // otherDataPresent = 0
        w.write_bit(false); // crcCheckPresent = 0
        w.finish()
    }

    #[test]
    fn stream_mux_config_minimal_aac_lc() {
        let bytes = build_min_smc();
        let mut r = BitReader::new(&bytes);
        let smc = StreamMuxConfig::parse(&mut r, &bytes).unwrap();
        assert_eq!(smc.audio_mux_version, 0);
        assert_eq!(smc.audio_mux_version_a, 0);
        assert!(smc.all_streams_same_time_framing);
        assert_eq!(smc.num_sub_frames, 0);
        assert_eq!(smc.num_program, 0);
        assert_eq!(smc.num_layer, vec![0]);
        assert_eq!(smc.layers.len(), 1);
        let lay = &smc.layers[0];
        assert_eq!(lay.stream_id, 0);
        assert_eq!(lay.frame_length_type, 0);
        assert_eq!(lay.latm_buffer_fullness, Some(0xFF));
        assert_eq!(lay.effective_asc.aot, 2);
        assert_eq!(lay.effective_asc.sampling_frequency_index, 4);
        assert_eq!(lay.effective_asc.channel_configuration, 2);
        assert!(!smc.other_data_present);
        assert!(!smc.crc_check_present);
        assert_eq!(smc.stream_id(0, 0), Some(0));
    }

    /// Push the low `n` bits of `v` (MSB-first) onto a bool vector,
    /// mirroring `BitWriter::write_u32` so the test can hold the config
    /// prefix as bits for an independent CRC recomputation.
    fn push_bits(out: &mut Vec<bool>, v: u32, n: u32) {
        for i in (0..n).rev() {
            out.push((v >> i) & 1 == 1);
        }
    }

    #[test]
    fn stream_mux_config_with_valid_crc() {
        // Build the config prefix as a bit vector, compute its CRC, then
        // emit prefix + crcCheckPresent + crcCheckSum.
        let mut prefix: Vec<bool> = Vec::new();
        push_bits(&mut prefix, 0, 1); // audioMuxVersion = 0
        push_bits(&mut prefix, 1, 1); // allStreamsSameTimeFraming
        push_bits(&mut prefix, 0, 6); // numSubFrames
        push_bits(&mut prefix, 0, 4); // numProgram
        push_bits(&mut prefix, 0, 3); // numLayer
        push_bits(&mut prefix, u32::from(u16::from_be_bytes(AAC_LC_ASC)), 16);
        push_bits(&mut prefix, 0, 3); // frameLengthType
        push_bits(&mut prefix, 0xFF, 8); // latmBufferFullness
        push_bits(&mut prefix, 0, 1); // otherDataPresent
        let sum = crc::stream_mux_config_crc(&prefix);

        let mut w = BitWriter::new();
        for &b in &prefix {
            w.write_bit(b);
        }
        w.write_bit(true); // crcCheckPresent
        w.write_u32(u32::from(sum), 8); // crcCheckSum
        let bytes = w.finish();

        let mut r = BitReader::new(&bytes);
        let smc = StreamMuxConfig::parse(&mut r, &bytes).unwrap();
        assert!(smc.crc_check_present);
        assert_eq!(smc.crc_check_sum, Some(sum));
    }

    #[test]
    fn stream_mux_config_bad_crc_rejected() {
        let mut w = BitWriter::new();
        w.write_bit(false);
        w.write_bit(true);
        w.write_u32(0, 6);
        w.write_u32(0, 4);
        w.write_u32(0, 3);
        write_aac_lc_asc(&mut w);
        w.write_u32(0, 3);
        w.write_u32(0xFF, 8);
        w.write_bit(false);
        w.write_bit(true); // crcCheckPresent
        w.write_u32(0x00, 8); // deliberately wrong crcCheckSum
        let bytes = w.finish();
        let mut r = BitReader::new(&bytes);
        assert!(matches!(
            StreamMuxConfig::parse(&mut r, &bytes),
            Err(Error::LatmCrcMismatch)
        ));
    }

    #[test]
    fn stream_mux_config_two_layers_use_same_config() {
        // One program, two layers; the second layer sets
        // useSameConfig, so it must inherit the first layer's ASC.
        let mut w = BitWriter::new();
        w.write_bit(false); // audioMuxVersion = 0
        w.write_bit(true); // allStreamsSameTimeFraming
        w.write_u32(0, 6); // numSubFrames
        w.write_u32(0, 4); // numProgram = 0
        w.write_u32(1, 3); // numLayer = 1 -> two layers
                           // layer 0: no useSameConfig bit; inline ASC.
        write_aac_lc_asc(&mut w);
        w.write_u32(0, 3); // frameLengthType 0
        w.write_u32(0xFF, 8); // latmBufferFullness
                              // layer 1: useSameConfig = 1.
        w.write_bit(true); // useSameConfig
        w.write_u32(0, 3); // frameLengthType 0
        w.write_u32(0xFF, 8); // latmBufferFullness
        w.write_bit(false); // otherDataPresent
        w.write_bit(false); // crcCheckPresent
        let bytes = w.finish();

        let mut r = BitReader::new(&bytes);
        let smc = StreamMuxConfig::parse(&mut r, &bytes).unwrap();
        assert_eq!(smc.layers.len(), 2);
        assert!(smc.layers[0].asc.is_some());
        assert!(smc.layers[1].asc.is_none());
        // The inherited effective ASC matches the first layer.
        assert_eq!(
            smc.layers[1].effective_asc.aot,
            smc.layers[0].effective_asc.aot
        );
        assert_eq!(smc.stream_id(0, 1), Some(1));
    }

    #[test]
    fn stream_mux_config_unsupported_frame_length_type() {
        // frameLengthType = 3 (CELP) must be rejected.
        let mut w = BitWriter::new();
        w.write_bit(false);
        w.write_bit(true);
        w.write_u32(0, 6);
        w.write_u32(0, 4);
        w.write_u32(0, 3);
        write_aac_lc_asc(&mut w);
        w.write_u32(3, 3); // frameLengthType = 3 (CELP)
        let bytes = w.finish();
        let mut r = BitReader::new(&bytes);
        assert!(matches!(
            StreamMuxConfig::parse(&mut r, &bytes),
            Err(Error::LatmUnsupportedFrameLengthType(3))
        ));
    }

    #[test]
    fn stream_mux_config_version1_reserved_a_rejected() {
        // audioMuxVersion = 1, audioMuxVersionA = 1 -> reserved.
        let mut w = BitWriter::new();
        w.write_bit(true); // audioMuxVersion = 1
        w.write_bit(true); // audioMuxVersionA = 1
        let bytes = w.finish();
        let mut r = BitReader::new(&bytes);
        assert!(matches!(
            StreamMuxConfig::parse(&mut r, &bytes),
            Err(Error::LatmAudioMuxVersionAReserved)
        ));
    }

    #[test]
    fn stream_mux_config_frame_length_type1_fixed_bits() {
        // frameLengthType = 1, frameLength = 100 -> (100+20)*8 bits.
        let mut w = BitWriter::new();
        w.write_bit(false);
        w.write_bit(true);
        w.write_u32(0, 6);
        w.write_u32(0, 4);
        w.write_u32(0, 3);
        write_aac_lc_asc(&mut w);
        w.write_u32(1, 3); // frameLengthType = 1
        w.write_u32(100, 9); // frameLength = 100
        w.write_bit(false); // otherDataPresent
        w.write_bit(false); // crcCheckPresent
        let bytes = w.finish();
        let mut r = BitReader::new(&bytes);
        let smc = StreamMuxConfig::parse(&mut r, &bytes).unwrap();
        let lay = &smc.layers[0];
        assert_eq!(lay.frame_length_type, 1);
        assert_eq!(lay.frame_length, Some(100));
        assert_eq!(lay.fixed_payload_bits(), Some((100 + 20) * 8));
    }

    /// Write the minimal `audioMuxVersion == 0` AAC-LC StreamMuxConfig
    /// (one prog, one layer, frameLengthType 0, no CRC) into `w`
    /// without finishing — for embedding inside an AudioMuxElement.
    fn write_min_smc_into(w: &mut BitWriter) {
        w.write_bit(false); // audioMuxVersion = 0
        w.write_bit(true); // allStreamsSameTimeFraming
        w.write_u32(0, 6); // numSubFrames = 0
        w.write_u32(0, 4); // numProgram = 0
        w.write_u32(0, 3); // numLayer = 0
        write_aac_lc_asc(w);
        w.write_u32(0, 3); // frameLengthType = 0
        w.write_u32(0xFF, 8); // latmBufferFullness
        w.write_bit(false); // otherDataPresent
        w.write_bit(false); // crcCheckPresent
    }

    #[test]
    fn audio_mux_element_in_band_single_payload() {
        // muxConfigPresent=1, useSameStreamMux=0, inline minimal SMC,
        // one subframe carrying a 4-byte payload.
        let payload: [u8; 4] = [0xDE, 0xAD, 0xBE, 0xEF];
        let mut w = BitWriter::new();
        w.write_bit(false); // useSameStreamMux = 0
        write_min_smc_into(&mut w);
        // PayloadLengthInfo: MuxSlotLengthBytes = 4 (single byte, < 255).
        w.write_u32(4, 8);
        // PayloadMux: 4 payload bytes.
        for &b in &payload {
            w.write_byte(b);
        }
        // otherDataPresent was 0; ByteAlign() pads.
        let bytes = w.finish();

        let mut r = BitReader::new(&bytes);
        let ame = AudioMuxElement::parse(&mut r, &bytes, true, None).unwrap();
        assert!(!ame.use_same_stream_mux);
        assert_eq!(ame.payloads.len(), 1);
        let p = &ame.payloads[0];
        assert_eq!(p.sub_frame, 0);
        assert_eq!(p.prog, 0);
        assert_eq!(p.lay, 0);
        assert_eq!(p.stream_id, 0);
        assert_eq!(p.data, payload.to_vec());
    }

    #[test]
    fn audio_mux_element_escape_length() {
        // MuxSlotLengthBytes with one 0xFF escape: 255 + 3 = 258 bytes.
        let len = 258usize;
        let payload: Vec<u8> = (0..len).map(|i| (i & 0xFF) as u8).collect();
        let mut w = BitWriter::new();
        w.write_bit(false); // useSameStreamMux
        write_min_smc_into(&mut w);
        w.write_u32(255, 8); // escape
        w.write_u32(3, 8); // + 3 = 258
        for &b in &payload {
            w.write_byte(b);
        }
        let bytes = w.finish();

        let mut r = BitReader::new(&bytes);
        let ame = AudioMuxElement::parse(&mut r, &bytes, true, None).unwrap();
        assert_eq!(ame.payloads.len(), 1);
        assert_eq!(ame.payloads[0].data, payload);
    }

    #[test]
    fn audio_mux_element_use_same_stream_mux_inherits() {
        // First element carries the config; second sets
        // useSameStreamMux and inherits it.
        let mut w0 = BitWriter::new();
        w0.write_bit(false); // useSameStreamMux = 0
        write_min_smc_into(&mut w0);
        w0.write_u32(2, 8); // 2-byte payload
        w0.write_byte(0x11);
        w0.write_byte(0x22);
        let bytes0 = w0.finish();
        let mut r0 = BitReader::new(&bytes0);
        let first = AudioMuxElement::parse(&mut r0, &bytes0, true, None).unwrap();

        let mut w1 = BitWriter::new();
        w1.write_bit(true); // useSameStreamMux = 1
        w1.write_u32(3, 8); // 3-byte payload
        w1.write_byte(0xAA);
        w1.write_byte(0xBB);
        w1.write_byte(0xCC);
        let bytes1 = w1.finish();
        let mut r1 = BitReader::new(&bytes1);
        let second = AudioMuxElement::parse(&mut r1, &bytes1, true, Some(&first.config)).unwrap();
        assert!(second.use_same_stream_mux);
        assert_eq!(second.payloads.len(), 1);
        assert_eq!(second.payloads[0].data, vec![0xAA, 0xBB, 0xCC]);
    }

    #[test]
    fn audio_mux_element_use_same_without_prev_rejected() {
        let mut w = BitWriter::new();
        w.write_bit(true); // useSameStreamMux = 1, but no prev config
        let bytes = w.finish();
        let mut r = BitReader::new(&bytes);
        assert!(matches!(
            AudioMuxElement::parse(&mut r, &bytes, true, None),
            Err(Error::LatmNoPreviousMuxConfig)
        ));
    }

    #[test]
    fn audio_mux_element_multiple_subframes() {
        // numSubFrames = 1 -> two PayloadMux frames, each a separate
        // PayloadLengthInfo + payload.
        let mut w = BitWriter::new();
        w.write_bit(false); // useSameStreamMux
                            // StreamMuxConfig with numSubFrames = 1.
        w.write_bit(false); // audioMuxVersion = 0
        w.write_bit(true); // allStreamsSameTimeFraming
        w.write_u32(1, 6); // numSubFrames = 1
        w.write_u32(0, 4); // numProgram = 0
        w.write_u32(0, 3); // numLayer = 0
        write_aac_lc_asc(&mut w);
        w.write_u32(0, 3); // frameLengthType = 0
        w.write_u32(0xFF, 8); // latmBufferFullness
        w.write_bit(false); // otherDataPresent
        w.write_bit(false); // crcCheckPresent
                            // subframe 0: 2 bytes.
        w.write_u32(2, 8);
        w.write_byte(0x01);
        w.write_byte(0x02);
        // subframe 1: 1 byte.
        w.write_u32(1, 8);
        w.write_byte(0x03);
        let bytes = w.finish();

        let mut r = BitReader::new(&bytes);
        let ame = AudioMuxElement::parse(&mut r, &bytes, true, None).unwrap();
        assert_eq!(ame.payloads.len(), 2);
        assert_eq!(ame.payloads[0].sub_frame, 0);
        assert_eq!(ame.payloads[0].data, vec![0x01, 0x02]);
        assert_eq!(ame.payloads[1].sub_frame, 1);
        assert_eq!(ame.payloads[1].data, vec![0x03]);
    }

    /// Build the byte body of a minimal in-band AudioMuxElement(1)
    /// carrying `payload` (one subframe, frameLengthType 0). The
    /// returned bytes are exactly the `audioMuxLengthBytes` body that a
    /// LOAS frame wraps.
    fn build_min_audio_mux_element(payload: &[u8]) -> Vec<u8> {
        let mut w = BitWriter::new();
        w.write_bit(false); // useSameStreamMux = 0
        write_min_smc_into(&mut w);
        // MuxSlotLengthBytes for payload.len() (< 255).
        assert!(payload.len() < 255);
        w.write_u32(payload.len() as u32, 8);
        for &b in payload {
            w.write_byte(b);
        }
        w.finish()
    }

    #[test]
    fn audio_sync_stream_single_frame() {
        let payload: [u8; 5] = [0x21, 0x00, 0x03, 0x40, 0x80];
        let body = build_min_audio_mux_element(&payload);

        // AudioSyncStream frame: 0x2B7 (11 bits) + audioMuxLengthBytes
        // (13 bits) + body. 11 + 13 = 24 bits = 3 bytes, so the body is
        // byte-aligned.
        let mut w = BitWriter::new();
        w.write_u32(AUDIO_SYNC_STREAM_SYNCWORD, 11);
        w.write_u32(body.len() as u32, 13);
        w.write_bytes(&body);
        let stream = w.finish();

        let mut walker = AudioSyncStream::new(&stream);
        let frame = walker.next_frame().unwrap().unwrap();
        assert_eq!(frame.offset, 0);
        assert_eq!(usize::from(frame.audio_mux_length_bytes), body.len());
        assert_eq!(frame.element.payloads.len(), 1);
        assert_eq!(frame.element.payloads[0].data, payload.to_vec());
        // No more frames.
        assert!(walker.next_frame().unwrap().is_none());
    }

    #[test]
    fn audio_sync_stream_skips_leading_garbage() {
        let payload: [u8; 2] = [0xAB, 0xCD];
        let body = build_min_audio_mux_element(&payload);
        let mut w = BitWriter::new();
        w.write_u32(AUDIO_SYNC_STREAM_SYNCWORD, 11);
        w.write_u32(body.len() as u32, 13);
        w.write_bytes(&body);
        let frame_bytes = w.finish();

        // Prepend non-syncword garbage bytes.
        let mut stream = vec![0x00, 0xAA, 0x55];
        stream.extend_from_slice(&frame_bytes);

        let mut walker = AudioSyncStream::new(&stream);
        let frame = walker.next_frame().unwrap().unwrap();
        assert_eq!(frame.offset, 3);
        assert_eq!(frame.element.payloads[0].data, payload.to_vec());
    }

    #[test]
    fn audio_sync_stream_two_frames_via_iterator() {
        let p0: [u8; 2] = [0x10, 0x20];
        let p1: [u8; 3] = [0x30, 0x40, 0x50];

        let build = |payload: &[u8]| {
            // First frame carries config inline; second uses
            // useSameStreamMux to inherit it.
            let body = build_min_audio_mux_element(payload);
            let mut w = BitWriter::new();
            w.write_u32(AUDIO_SYNC_STREAM_SYNCWORD, 11);
            w.write_u32(body.len() as u32, 13);
            w.write_bytes(&body);
            w.finish()
        };

        let mut stream = build(&p0);
        // Second frame: useSameStreamMux = 1 body.
        let body1 = {
            let mut w = BitWriter::new();
            w.write_bit(true); // useSameStreamMux = 1
            w.write_u32(p1.len() as u32, 8); // MuxSlotLengthBytes
            for &b in &p1 {
                w.write_byte(b);
            }
            w.finish()
        };
        let mut w1 = BitWriter::new();
        w1.write_u32(AUDIO_SYNC_STREAM_SYNCWORD, 11);
        w1.write_u32(body1.len() as u32, 13);
        w1.write_bytes(&body1);
        stream.extend_from_slice(&w1.finish());

        let frames: Vec<_> = AudioSyncStream::new(&stream)
            .collect::<Result<Vec<_>>>()
            .unwrap();
        assert_eq!(frames.len(), 2);
        assert_eq!(frames[0].element.payloads[0].data, p0.to_vec());
        assert_eq!(frames[1].element.payloads[0].data, p1.to_vec());
        // The second frame inherited the first frame's config.
        assert!(frames[1].element.use_same_stream_mux);
    }

    #[test]
    fn audio_sync_stream_truncated_body_rejected() {
        let payload: [u8; 4] = [0x01, 0x02, 0x03, 0x04];
        let body = build_min_audio_mux_element(&payload);
        let mut w = BitWriter::new();
        w.write_u32(AUDIO_SYNC_STREAM_SYNCWORD, 11);
        // Claim a longer body than is present.
        w.write_u32((body.len() + 10) as u32, 13);
        w.write_bytes(&body);
        let stream = w.finish();

        let mut walker = AudioSyncStream::new(&stream);
        assert!(matches!(walker.next_frame(), Err(Error::LoasSyncInvalid)));
    }

    #[test]
    fn ep_audio_sync_header_parse() {
        // 0x4DE1 (16) + futureUse(4)=0x5 + audioMuxLengthBytes(13)=100
        // + frameCounter(5)=7 + headerParity(18)=0x12345.
        let mut w = BitWriter::new();
        w.write_u32(EP_AUDIO_SYNC_STREAM_SYNCWORD, 16);
        w.write_u32(0x5, 4);
        w.write_u32(100, 13);
        w.write_u32(7, 5);
        w.write_u32(0x12345, 18);
        // A few body bytes (not parsed).
        w.write_bytes(&[0xAA, 0xBB]);
        let stream = w.finish();

        let hdr = EpAudioSyncHeader::parse(&stream, 0).unwrap().unwrap();
        assert_eq!(hdr.offset, 0);
        assert_eq!(hdr.future_use, 0x5);
        assert_eq!(hdr.audio_mux_length_bytes, 100);
        assert_eq!(hdr.frame_counter, 7);
        assert_eq!(hdr.header_parity, 0x12345);
        assert_eq!(hdr.body_offset, 7);
    }

    #[test]
    fn ep_audio_sync_header_not_found() {
        let stream = [0x00u8, 0x11, 0x22, 0x33];
        assert!(EpAudioSyncHeader::parse(&stream, 0).unwrap().is_none());
    }
}