oxideav-ac4 0.0.2

Pure-Rust Dolby AC-4 audio decoder foundation for oxideav โ€” sync, TOC, presentation and substream parsing
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
//! AC-4 Audio Spectral Frontend (ASF) substream baseline.
//!
//! This module implements the framing of an `ac4_substream()` element
//! (ETSI TS 103 190-1 ยง4.3.4) and the outer shell of the `audio_data()`
//! dispatcher (ยง4.2.5) for the mono and stereo channel modes. It parses
//! the top-level codec-mode flags, `asf_transform_info()` (ยง4.2.8.1 /
//! ยง4.3.6.1), and `asf_psy_info()` (ยง4.2.8.2 / ยง4.3.6.2) so the decoder
//! can describe which tools each substream uses (`SIMPLE` / `ASPX` /
//! `ASPX_ACPL_*`), what transform length is in play, how many MDCT
//! windows are present, the window grouping, and the per-group
//! `max_sfb`. It stops short of the actual spectral-coefficient decoding,
//! Huffman tables, and MDCT synthesis.
//!
//! What we deliberately do **not** do yet (and why):
//!
//! * `asf_section_data`, `asf_spectral_data`, `asf_scalefac_data`,
//!   `asf_snf_data` โ€” all Huffman-driven; Huffman tables (ยง5.1) have
//!   not been transcribed yet.
//! * `ssf_data` (Speech Spectral Frontend) โ€” gated by the same Huffman
//!   / arithmetic-coded layer.
//! * A-SPX (`aspx_config`, `aspx_data_*`) and A-CPL. These are the
//!   bandwidth-extension and inter-channel-coupling tools; each carries
//!   its own Huffman suites.
//!
//! Those components remain marked TODO and the substream walker simply
//! consumes opaque bits from the `audio_size` budget after the outer
//! `asf_transform_info()` is parsed. The decoder continues to emit
//! silence until the tools are filled in.
//!
//! Nothing in here panics on malformed input โ€” every read is
//! result-propagated.

use oxideav_core::bits::BitReader;
use oxideav_core::{Error, Result};

use crate::asf_data;
use crate::aspx;
use crate::sfb_offset;
use crate::tables;
use crate::toc::variable_bits;

/// `mono_codec_mode` values (Table 93).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MonoCodecMode {
    Simple,
    Aspx,
}

impl MonoCodecMode {
    pub fn from_bit(v: u32) -> Self {
        if v == 0 {
            Self::Simple
        } else {
            Self::Aspx
        }
    }
}

/// `stereo_codec_mode` values (Table 95).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StereoCodecMode {
    Simple,
    Aspx,
    AspxAcpl1,
    AspxAcpl2,
}

impl StereoCodecMode {
    pub fn from_u32(v: u32) -> Self {
        match v & 0b11 {
            0 => Self::Simple,
            1 => Self::Aspx,
            2 => Self::AspxAcpl1,
            _ => Self::AspxAcpl2,
        }
    }
}

/// `spec_frontend` values (Table 94).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpecFrontend {
    /// Audio Spectral Frontend โ€” MDCT-based.
    Asf,
    /// Speech Spectral Frontend โ€” arithmetic-coded MDCT with LPC envelope.
    Ssf,
}

impl SpecFrontend {
    pub fn from_bit(v: u32) -> Self {
        if v == 0 {
            Self::Asf
        } else {
            Self::Ssf
        }
    }
}

/// ASF transform-length info (`asf_transform_info()`, ยง4.2.8.1 + ยง4.3.6.1).
#[derive(Debug, Clone, Copy, Default)]
pub struct AsfTransformInfo {
    /// `b_long_frame` โ€” only meaningful when `frame_len_base >= 1536`.
    pub b_long_frame: bool,
    /// `transf_length[0]` / `transf_length[1]` โ€” 2-bit indices. For a
    /// long frame the two are implicitly equal and hold the long-frame
    /// transform length from Table 99. For `frame_len_base < 1536`
    /// there's only a single `transf_length` field; we mirror it into
    /// both slots.
    pub transf_length: [u32; 2],
    /// Resolved transform length in samples for `transf_length[0]`.
    pub transform_length_0: u32,
    /// Resolved transform length for `transf_length[1]`.
    pub transform_length_1: u32,
}

/// Parsed `asf_psy_info()` (ETSI TS 103 190-1 ยง4.2.8.2 + ยง4.3.6.2) โ€”
/// the scale-factor-band organisation for one or two transform-length
/// windows.
#[derive(Debug, Clone, Default)]
pub struct AsfPsyInfo {
    /// Derived from the spec: `transf_length[0]` differed from
    /// `transf_length[1]`, triggering the dual-window branch.
    pub b_different_framing: bool,
    /// `max_sfb[0]` or `max_sfb_side[0]` depending on `b_side_limited`.
    pub max_sfb_0: u32,
    /// `max_sfb_side[0]` when `b_dual_maxsfb` is set (else 0).
    pub max_sfb_side_0: u32,
    /// `max_sfb[1]` โ€” only populated when `b_different_framing`.
    pub max_sfb_1: u32,
    /// `max_sfb_side[1]` โ€” only populated when `b_different_framing`
    /// and `b_dual_maxsfb`.
    pub max_sfb_side_1: u32,
    /// Raw `scale_factor_grouping[i]` bits.
    pub scale_factor_grouping: Vec<u8>,
    /// Derived: `num_windows` (1 for long frames).
    pub num_windows: u32,
    /// Derived: `num_window_groups`.
    pub num_window_groups: u32,
}

/// Table 109 row lookup โ€” `n_grp_bits` for `frame_len_base โ‰ฅ 1536` and
/// `b_long_frame == 0`, keyed by `(transf_length[0], transf_length[1])`.
pub fn n_grp_bits_ge_1536(tl0: u32, tl1: u32) -> u32 {
    match (tl0 & 0b11, tl1 & 0b11) {
        (0, 0) => 15,
        (0, 1) => 10,
        (0, 2) => 8,
        (0, 3) => 7,
        (1, 0) => 10,
        (1, 1) => 7,
        (1, 2) => 4,
        (1, 3) => 3,
        (2, 0) => 8,
        (2, 1) => 4,
        (2, 2) => 3,
        (2, 3) => 1,
        (3, 0) => 7,
        (3, 1) => 3,
        (3, 2) => 1,
        (3, 3) => 1,
        _ => 0,
    }
}

/// Table 110 row lookup โ€” `n_grp_bits` for `frame_len_base < 1536`,
/// keyed by `(frame_len_base, transf_length)`. Returns 0 for unknown
/// combinations.
pub fn n_grp_bits_lt_1536(frame_len_base: u32, tl: u32) -> u32 {
    match (frame_len_base, tl & 0b11) {
        (1024, 0) | (960, 0) | (768, 0) => 7,
        (1024, 1) | (960, 1) | (768, 1) => 3,
        (1024, 2) | (960, 2) | (768, 2) => 1,
        (1024, 3) | (960, 3) | (768, 3) => 0,
        (512, 0) | (384, 0) => 3,
        (512, 1) | (384, 1) => 1,
        (512, 2) | (384, 2) => 0,
        _ => 0,
    }
}

/// Parse `asf_psy_info(b_dual_maxsfb, b_side_limited)` at the current
/// position. `transform_info` is the previously parsed
/// `asf_transform_info()` result; `frame_len_base` the TOC's
/// `frame_length` at the base rate.
///
/// Returns the scale-factor-band shape plus the parsed
/// `scale_factor_grouping[i]` bits. Derives `num_windows` /
/// `num_window_groups` per Pseudocode 3 in ยง4.3.6.2.6.
pub fn parse_asf_psy_info(
    br: &mut BitReader<'_>,
    transform_info: &AsfTransformInfo,
    frame_len_base: u32,
    b_dual_maxsfb: bool,
    b_side_limited: bool,
) -> Result<AsfPsyInfo> {
    // b_different_framing is derived, not coded.
    let b_different_framing = frame_len_base >= 1536
        && !transform_info.b_long_frame
        && transform_info.transf_length[0] != transform_info.transf_length[1];
    let mut info = AsfPsyInfo {
        b_different_framing,
        ..AsfPsyInfo::default()
    };

    // Resolve n_msfb_bits / n_side_bits from Table 106 for the primary
    // transform length.
    let (nm0, ns0, _nml0) = tables::n_msfb_bits_48(transform_info.transform_length_0)
        .ok_or_else(|| Error::invalid("ac4: asf_psy_info: unsupported transform_length[0]"))?;

    if b_side_limited {
        info.max_sfb_0 = br.read_u32(ns0)?;
    } else {
        info.max_sfb_0 = br.read_u32(nm0)?;
        if b_dual_maxsfb {
            info.max_sfb_side_0 = br.read_u32(nm0)?;
        }
    }

    if info.b_different_framing {
        let (nm1, ns1, _) = tables::n_msfb_bits_48(transform_info.transform_length_1)
            .ok_or_else(|| Error::invalid("ac4: asf_psy_info: unsupported transform_length[1]"))?;
        if b_side_limited {
            info.max_sfb_1 = br.read_u32(ns1)?;
        } else {
            info.max_sfb_1 = br.read_u32(nm1)?;
            if b_dual_maxsfb {
                info.max_sfb_side_1 = br.read_u32(nm1)?;
            }
        }
    }

    // Determine n_grp_bits per Table 109 / 110 and spec ยง4.3.6.2.4.
    let n_grp_bits = if transform_info.b_long_frame {
        // Long frames: no grouping bits.
        0
    } else if frame_len_base >= 1536 {
        n_grp_bits_ge_1536(
            transform_info.transf_length[0],
            transform_info.transf_length[1],
        )
    } else {
        n_grp_bits_lt_1536(frame_len_base, transform_info.transf_length[0])
    };

    // Read scale_factor_grouping[i] bits.
    let mut grouping = Vec::with_capacity(n_grp_bits as usize);
    for _ in 0..n_grp_bits {
        grouping.push(br.read_u32(1)? as u8);
    }
    info.scale_factor_grouping = grouping;

    // Derive num_windows / num_window_groups per Pseudocode 3 โ€”
    // simplified: for long frames it's 1/1; for non-long with equal
    // transform lengths, num_windows = n_grp_bits + 1.
    if transform_info.b_long_frame {
        info.num_windows = 1;
        info.num_window_groups = 1;
    } else {
        info.num_windows = n_grp_bits + 1;
        info.num_window_groups = 1;
        // For the equal-transform-length case each grouping==0 bit
        // starts a new group. For b_different_framing the pseudocode
        // inserts an unconditional boundary at the half-frame mark.
        for &b in &info.scale_factor_grouping {
            if b == 0 {
                info.num_window_groups += 1;
            }
        }
        // Safety cap โ€” malformed streams shouldn't explode.
        if info.num_windows == 0 {
            info.num_windows = 1;
        }
    }

    Ok(info)
}

/// Per-substream tool summary โ€” what the decoder can learn by walking
/// the outer layers of `audio_data()` without touching Huffman tables.
#[derive(Debug, Clone, Default)]
pub struct SubstreamTools {
    /// Channel mode that drove the `audio_data()` switch. Copied from
    /// the parent `ac4_substream_info()`.
    pub channel_mode_channels: u16,
    /// Mono codec mode for channel_mode == 0.
    pub mono_mode: Option<MonoCodecMode>,
    /// Stereo codec mode for channel_mode == 1.
    pub stereo_mode: Option<StereoCodecMode>,
    /// `spec_frontend` for the primary (mid / left / mono) channel.
    pub spec_frontend_primary: Option<SpecFrontend>,
    /// `spec_frontend` for the secondary (side / right) channel if the
    /// substream is dual-MDCT-frontend.
    pub spec_frontend_secondary: Option<SpecFrontend>,
    /// Parsed `asf_transform_info()` for the primary channel when
    /// spec_frontend == ASF.
    pub transform_info_primary: Option<AsfTransformInfo>,
    /// Parsed `asf_transform_info()` for the secondary channel.
    pub transform_info_secondary: Option<AsfTransformInfo>,
    /// Parsed `asf_psy_info()` for the primary channel.
    pub psy_info_primary: Option<AsfPsyInfo>,
    /// Parsed `asf_psy_info()` for the secondary channel.
    pub psy_info_secondary: Option<AsfPsyInfo>,
    /// `b_enable_mdct_stereo_proc` โ€” stereo MDCT joint processing flag.
    pub mdct_stereo_proc: bool,
    /// Dequantised + scaled spectral coefficients for the primary
    /// channel (length = `sfb_offset[max_sfb]`). `None` when the
    /// Huffman-driven data path didn't run (non-SIMPLE / non-ASF /
    /// short-frame grouping cases).
    pub scaled_spec_primary: Option<Vec<f32>>,
    /// Dequantised + scaled spectral coefficients for the secondary
    /// (right) channel in a stereo SIMPLE substream. `None` for mono
    /// or non-decoded stereo cases.
    pub scaled_spec_secondary: Option<Vec<f32>>,
    /// Per-scale-factor-band M/S flags (`ms_used[sfb]`). Populated for
    /// `b_enable_mdct_stereo_proc == 1` joint-stereo frames. `None`
    /// otherwise. Length equals the decoded `max_sfb` for the shared
    /// window.
    pub ms_used: Option<Vec<bool>>,
    /// Parsed `aspx_config()` when the substream's codec mode selected
    /// one of the A-SPX paths (mono ASPX or stereo ASPX / ASPX_ACPL_*)
    /// **and** the current frame is an I-frame. `aspx_config` is only
    /// present in I-frames (ยง4.2.6.1 / ยง4.2.6.3); predictive frames
    /// inherit the previous I-frame's config. For non-I-frames or for
    /// SIMPLE substreams this stays `None`.
    pub aspx_config: Option<aspx::AspxConfig>,
    /// Parsed `companding_control()` when the substream's codec mode
    /// is one of the ASPX paths. Captured from the bitstream in the
    /// outer `audio_data()` walker.
    pub companding: Option<aspx::CompandingControl>,
    /// Parsed `aspx_framing(0)` for the primary channel. Populated when
    /// the substream's codec mode is one of the ASPX paths and an
    /// `aspx_config` is in scope (either from this frame if it's an
    /// I-frame or carried over from a prior I-frame โ€” we only wire the
    /// I-frame path here so non-I-frame ASPX bitstreams stay at
    /// companding_control until config state plumbing arrives).
    pub aspx_framing_primary: Option<aspx::AspxFraming>,
    /// Parsed `aspx_framing(1)` for the secondary channel in a stereo
    /// ASPX substream. Only present when `aspx_balance == 0` (the
    /// secondary channel has its own framing per Table 52); when
    /// `aspx_balance == 1` the secondary envelope data reuses the
    /// primary's framing.
    pub aspx_framing_secondary: Option<aspx::AspxFraming>,
    /// `aspx_balance` โ€” 1-bit flag from `aspx_data_2ch()` (Table 52).
    /// Present only in stereo ASPX substreams; otherwise `None`.
    pub aspx_balance: Option<bool>,
    /// `aspx_xover_subband_offset` โ€” 3-bit I-frame-sticky field that
    /// leads `aspx_data_1ch` / `aspx_data_2ch` (Tables 51 / 52). Only
    /// populated for I-frames; carries the crossover-subband offset
    /// used to seed `sbx` in ยง5.7.6.3.1.2.
    pub aspx_xover_subband_offset: Option<u8>,
    /// `aspx_delta_dir(0)` โ€” per-envelope delta-direction bits for the
    /// primary channel (Table 54). Populated when the walker reaches
    /// `aspx_data_1ch() / aspx_data_2ch()` and the framing decoded
    /// successfully.
    pub aspx_delta_dir_primary: Option<aspx::AspxDeltaDir>,
    /// `aspx_delta_dir(1)` โ€” per-envelope delta-direction bits for
    /// the secondary channel in a stereo ASPX substream. `None` for
    /// mono.
    pub aspx_delta_dir_secondary: Option<aspx::AspxDeltaDir>,
    /// `aspx_qmode_env[0]` โ€” the effective envelope quant step for
    /// the primary channel after the `FIXFIX && num_env == 1`
    /// clamp-to-0 override in Tables 51 / 52.
    pub aspx_qmode_env_primary: Option<aspx::AspxQuantStep>,
    /// `aspx_qmode_env[1]` โ€” same, for the secondary channel.
    pub aspx_qmode_env_secondary: Option<aspx::AspxQuantStep>,
    /// Derived A-SPX frequency tables (ยง5.7.6.3.1). Populated on any
    /// I-frame ASPX substream that parses `aspx_config` plus
    /// `aspx_xover_subband_offset` without hitting a bailout.
    pub aspx_frequency_tables: Option<aspx::AspxFrequencyTables>,
    /// Parsed `aspx_hfgen_iwc_1ch()` for the mono ASPX path (Table 55).
    pub aspx_hfgen_iwc_1ch: Option<aspx::AspxHfgenIwc1Ch>,
    /// Parsed `aspx_hfgen_iwc_2ch()` for the stereo ASPX path (Table 56).
    pub aspx_hfgen_iwc_2ch: Option<aspx::AspxHfgenIwc2Ch>,
    /// `aspx_data_sig[0]` โ€” per-envelope Huffman-decoded signal
    /// envelopes for the primary channel.
    pub aspx_data_sig_primary: Option<Vec<aspx::AspxHuffEnv>>,
    /// `aspx_data_sig[1]` โ€” per-envelope signal envelopes for the
    /// secondary channel in a stereo ASPX substream.
    pub aspx_data_sig_secondary: Option<Vec<aspx::AspxHuffEnv>>,
    /// `aspx_data_noise[0]` โ€” per-envelope Huffman-decoded noise
    /// envelopes for the primary channel.
    pub aspx_data_noise_primary: Option<Vec<aspx::AspxHuffEnv>>,
    /// `aspx_data_noise[1]` โ€” per-envelope noise envelopes for the
    /// secondary channel.
    pub aspx_data_noise_secondary: Option<Vec<aspx::AspxHuffEnv>>,
}

/// Result of walking a single `ac4_substream()` payload.
#[derive(Debug, Clone, Default)]
pub struct Ac4SubstreamInfo {
    /// `audio_size_value` in bytes (post variable_bits extension).
    pub audio_size: u32,
    /// Byte position (relative to the start of `ac4_substream()`) where
    /// `audio_data()` begins.
    pub audio_data_offset: u32,
    /// Tool summary โ€” what we parsed from the outer `audio_data()`
    /// layers before bailing to opaque consumption.
    pub tools: SubstreamTools,
}

/// Resolve a `transf_length` index into an actual transform length in
/// samples for a given `frame_len_base` and base sample rate family.
///
/// Covers Tables 99 (long frames), 100 (non-long, 44.1/48 kHz,
/// `frame_len_base >= 1536`) and 103 (non-long, 44.1/48 kHz,
/// `frame_len_base < 1536`) for the base-rate path. 96 kHz and 192 kHz
/// (Tables 101 / 102 / 104 / 105) reach via HSF extension โ€” not wired
/// in this baseline.
pub fn resolve_transf_length(frame_len_base: u32, b_long_frame: bool, idx: u32) -> u32 {
    // Long-frame branch โ€” Table 99, 44.1/48 kHz column.
    if b_long_frame {
        return frame_len_base;
    }
    if frame_len_base >= 1536 {
        // Table 100 โ€” rows are frame_len_base, columns are transf_length[i].
        match (frame_len_base, idx & 0b11) {
            (2048, 0) => 128,
            (2048, 1) => 256,
            (2048, 2) => 512,
            (2048, 3) => 1024,
            (1920, 0) => 120,
            (1920, 1) => 240,
            (1920, 2) => 480,
            (1920, 3) => 960,
            (1536, 0) => 96,
            (1536, 1) => 192,
            (1536, 2) => 384,
            (1536, 3) => 768,
            _ => 0,
        }
    } else {
        // Table 103 โ€” short-ish frames.
        match (frame_len_base, idx & 0b11) {
            (1024, 0) => 128,
            (1024, 1) => 256,
            (1024, 2) => 512,
            (1024, 3) => 1024,
            (960, 0) => 120,
            (960, 1) => 240,
            (960, 2) => 480,
            (960, 3) => 960,
            (768, 0) => 96,
            (768, 1) => 192,
            (768, 2) => 384,
            (768, 3) => 768,
            (512, 0) => 128,
            (512, 1) => 256,
            (512, 2) => 512,
            (384, 0) => 96,
            (384, 1) => 192,
            (384, 2) => 384,
            _ => 0,
        }
    }
}

/// Parse `asf_transform_info()` at the current reader position. The
/// `frame_len_base` comes from the TOC.
pub fn parse_asf_transform_info(
    br: &mut BitReader<'_>,
    frame_len_base: u32,
) -> Result<AsfTransformInfo> {
    // Table 37 / ยง4.3.6.1.
    if frame_len_base >= 1536 {
        let b_long_frame = br.read_bit()?;
        if b_long_frame {
            // Long-frame transform length equals frame_len_base (at the
            // base sample rate family).
            let tl = resolve_transf_length(frame_len_base, true, 0);
            Ok(AsfTransformInfo {
                b_long_frame: true,
                transf_length: [0, 0],
                transform_length_0: tl,
                transform_length_1: tl,
            })
        } else {
            let t0 = br.read_u32(2)?;
            let t1 = br.read_u32(2)?;
            Ok(AsfTransformInfo {
                b_long_frame: false,
                transf_length: [t0, t1],
                transform_length_0: resolve_transf_length(frame_len_base, false, t0),
                transform_length_1: resolve_transf_length(frame_len_base, false, t1),
            })
        }
    } else {
        let t0 = br.read_u32(2)?;
        let len = resolve_transf_length(frame_len_base, false, t0);
        Ok(AsfTransformInfo {
            b_long_frame: false,
            transf_length: [t0, t0],
            transform_length_0: len,
            transform_length_1: len,
        })
    }
}

/// Parse the outer layers of `audio_data(channel_mode, b_iframe)` for
/// the mono channel mode. Fills in `tools.mono_mode`,
/// `tools.spec_frontend_primary`, and `tools.transform_info_primary`
/// when the mode is SIMPLE/ASPX and the frontend is ASF.
///
/// Returns after parsing `sf_info` โ€” the `sf_data` payload is left
/// untouched for the caller to skip (via `audio_size`).
pub fn parse_mono_audio_data_outer(
    br: &mut BitReader<'_>,
    tools: &mut SubstreamTools,
    b_iframe: bool,
    frame_len_base: u32,
) -> Result<()> {
    // ยง4.2.6.1 single_channel_element(b_iframe):
    //   mono_codec_mode; 1 bit
    //   if (b_iframe && mono_codec_mode == ASPX) { aspx_config(); }
    //   if (mono_codec_mode == SIMPLE) {
    //       mono_data(0);
    //   } else {
    //       companding_control(1);
    //       mono_data(0);
    //       aspx_data_1ch();
    //   }
    let mode_bit = br.read_u32(1)?;
    let mode = MonoCodecMode::from_bit(mode_bit);
    tools.mono_mode = Some(mode);
    // ASPX path (ยง4.2.6.1): if b_iframe, read aspx_config(); then
    // companding_control(1); then mono_data(0); then aspx_data_1ch().
    // We stop after companding_control + mono_data(0) โ€” the aspx_data
    // Huffman body needs Annex A.2 tables we haven't transcribed.
    if mode != MonoCodecMode::Simple {
        if b_iframe {
            tools.aspx_config = Some(aspx::parse_aspx_config(br)?);
        }
        tools.companding = Some(aspx::parse_companding_control(br, 1)?);
        // Fall through into mono_data(0) โ€” same outer shell as SIMPLE.
    }
    // mono_data(b_lfe=0):
    //   spec_frontend;    1 bit
    //   sf_info(spec_frontend, 0, 0);
    //   sf_data(spec_frontend);
    let sf_bit = br.read_u32(1)?;
    let frontend = SpecFrontend::from_bit(sf_bit);
    tools.spec_frontend_primary = Some(frontend);
    if !b_iframe {
        // The transform-info for non-I-frames still runs on the first
        // I-frame's state but the syntax still reads it โ€” keep parsing.
    }
    if let SpecFrontend::Asf = frontend {
        let ti = parse_asf_transform_info(br, frame_len_base)?;
        tools.transform_info_primary = Some(ti);
        // asf_psy_info(b_dual_maxsfb=0, b_side_limited=0) for a mono
        // channel โ€” per sf_info(spec_frontend, 0, 0).
        if let Ok(psy) = parse_asf_psy_info(br, &ti, frame_len_base, false, false) {
            tools.psy_info_primary = Some(psy);
            // For the single-window-group / long-frame case we can now
            // walk asf_section_data + asf_spectral_data +
            // asf_scalefac_data + asf_snf_data and produce scaled
            // spectral coefficients.
            let mut body_ok = false;
            if ti.b_long_frame && tools.psy_info_primary.as_ref().unwrap().num_window_groups == 1 {
                let psy_ref = tools.psy_info_primary.as_ref().unwrap().clone();
                if let Some(scaled) = decode_asf_long_mono_body(br, &ti, &psy_ref) {
                    tools.scaled_spec_primary = Some(scaled);
                    body_ok = true;
                }
            }
            // ยง4.2.6.1: for the ASPX path, aspx_data_1ch() follows
            // mono_data(0). Parse its leading xover-subband-offset +
            // aspx_framing(0) here. Only runs when:
            //   * we're on an I-frame โ€” both xover-subband-offset and
            //     aspx_config (which drives aspx_framing) are I-frame-
            //     sticky;
            //   * mono_data(0) was fully decoded, so the bitreader sits
            //     at the start of aspx_data_1ch();
            //   * aspx_config was parsed into tools above.
            if mode != MonoCodecMode::Simple && b_iframe && body_ok {
                if let Some(cfg) = tools.aspx_config {
                    let xover = br.read_u32(3)? as u8;
                    tools.aspx_xover_subband_offset = Some(xover);
                    let nats = aspx::num_aspx_timeslots(frame_len_base);
                    let framing = aspx::parse_aspx_framing(br, &cfg, b_iframe, nats > 8)?;
                    // Per Table 51: `aspx_qmode_env[0] = aspx_quant_mode_env`
                    // by default, but FIXFIX with a single envelope drops
                    // back to 0 (1.5 dB / Fine) regardless of the config.
                    let qmode = if matches!(framing.int_class, aspx::AspxIntClass::FixFix)
                        && framing.num_env == 1
                    {
                        aspx::AspxQuantStep::Fine
                    } else {
                        cfg.quant_mode_env
                    };
                    tools.aspx_qmode_env_primary = Some(qmode);
                    // aspx_delta_dir(0) follows aspx_framing(0) per
                    // Table 51 โ€” fully determined by framing.num_env /
                    // num_noise.
                    let dd = aspx::parse_aspx_delta_dir(br, &framing)?;
                    // Derive the ยง5.7.6.3.1 frequency tables and use
                    // them to parse aspx_hfgen_iwc_1ch() (Table 55)
                    // then two aspx_ec_data() calls (SIGNAL + NOISE)
                    // per the aspx_data_1ch() body. Any derivation
                    // error silently skips this block without clearing
                    // the framing / delta_dir already stashed.
                    if let Ok(tables) = aspx::derive_aspx_frequency_tables(&cfg, xover as u32) {
                        let hfgen = aspx::parse_aspx_hfgen_iwc_1ch(
                            br,
                            cfg.num_noise_sbgroups(),
                            tables.counts.num_sbg_sig_highres,
                            nats,
                        )?;
                        tools.aspx_hfgen_iwc_1ch = Some(hfgen);
                        // Signal envelopes โ€” per Table 51, stereo_mode
                        // is LEVEL (literal `0` in the Table 51 body)
                        // for the 1-channel path.
                        let sig = aspx::parse_aspx_ec_data(
                            br,
                            aspx::AspxDataType::Signal,
                            framing.num_env,
                            &framing.freq_res,
                            qmode,
                            aspx::AspxStereoMode::Level,
                            &dd.sig_delta_dir,
                            tables.counts,
                        )?;
                        tools.aspx_data_sig_primary = Some(sig);
                        // Noise envelopes โ€” per Table 51 freq_res /
                        // qmode are `0` (both ignored by the NOISE
                        // branch of Pseudocode 79).
                        let noise = aspx::parse_aspx_ec_data(
                            br,
                            aspx::AspxDataType::Noise,
                            framing.num_noise,
                            &[],
                            aspx::AspxQuantStep::Fine,
                            aspx::AspxStereoMode::Level,
                            &dd.noise_delta_dir,
                            tables.counts,
                        )?;
                        tools.aspx_data_noise_primary = Some(noise);
                        tools.aspx_frequency_tables = Some(tables);
                    }
                    tools.aspx_delta_dir_primary = Some(dd);
                    tools.aspx_framing_primary = Some(framing);
                }
            }
        }
    }
    Ok(())
}

/// Decode the `sf_data` body for a mono, long-frame, single-window-
/// group ASF substream. Returns the dequantised + scaled spectral
/// coefficients for the frame.
///
/// On any Huffman / bitstream error we return `None` โ€” the caller
/// falls back to silence. Uses the decoder's own max_sfb (from
/// psy_info) rather than num_sfb_48 since the latter is only a cap.
fn decode_asf_long_mono_body(
    br: &mut BitReader<'_>,
    ti: &AsfTransformInfo,
    psy: &AsfPsyInfo,
) -> Option<Vec<f32>> {
    let tl = ti.transform_length_0;
    let tl_idx = ti.transf_length[0];
    let max_sfb_cap = tables::num_sfb_48(tl)?;
    let max_sfb = psy.max_sfb_0.min(max_sfb_cap);
    if max_sfb == 0 {
        return None;
    }
    let sfbo = sfb_offset::sfb_offset_48(tl)?;
    // asf_section_data.
    let sections = asf_data::parse_asf_section_data(br, tl_idx, tl, max_sfb).ok()?;
    // asf_spectral_data.
    let (qspec, mqi) = asf_data::parse_asf_spectral_data(br, &sections, sfbo, max_sfb).ok()?;
    // asf_scalefac_data.
    let sf_gain = asf_data::parse_asf_scalefac_data(br, &sections, &mqi, max_sfb, tl).ok()?;
    // asf_snf_data โ€” consume the bits but ignore the output for now
    // (noise fill to be added later).
    let _snf = asf_data::parse_asf_snf_data(br, &sections, &mqi, max_sfb, tl).ok()?;
    // Dequantise + scale.
    let scaled = asf_data::dequantise_and_scale(&qspec, &sf_gain, sfbo, max_sfb);
    Some(scaled)
}

/// Parse the outer layers of a stereo `audio_data()` element
/// (channel_pair_element / stereo_data).
///
/// Only the most common case โ€” `stereo_codec_mode == SIMPLE` with the
/// `stereo_data()` body โ€” is walked to the `sf_info` level. Other
/// modes (ASPX / ASPX_ACPL_1 / ASPX_ACPL_2) set the tool enum and stop.
pub fn parse_stereo_audio_data_outer(
    br: &mut BitReader<'_>,
    tools: &mut SubstreamTools,
    b_iframe: bool,
    frame_len_base: u32,
) -> Result<()> {
    // ยง4.2.6.3 channel_pair_element(b_iframe):
    //   stereo_codec_mode;        2 bits
    let mode_bits = br.read_u32(2)?;
    let mode = StereoCodecMode::from_u32(mode_bits);
    tools.stereo_mode = Some(mode);

    if mode != StereoCodecMode::Simple {
        // ยง4.2.6.3: for b_iframe all ASPX stereo modes start with an
        // aspx_config(); ASPX_ACPL_{1,2} also carry an acpl_config_1ch
        // (PARTIAL / FULL) right after โ€” acpl_config parsing isn't
        // implemented yet so we record the aspx_config only. Then each
        // stereo mode runs companding_control with a mode-specific
        // channel count (2 for ASPX, 1 for ASPX_ACPL_*), which we also
        // surface. The per-channel stereo_data / sf_data / aspx_data /
        // acpl_data bodies remain Huffman-gated and unhandled.
        if b_iframe {
            tools.aspx_config = Some(aspx::parse_aspx_config(br)?);
            // acpl_config_1ch(PARTIAL/FULL) bits are consumed opaquely โ€”
            // we don't have an A-CPL parser yet, so bail here instead of
            // misreading subsequent bits.
            if matches!(
                mode,
                StereoCodecMode::AspxAcpl1 | StereoCodecMode::AspxAcpl2
            ) {
                return Ok(());
            }
        }
        let nc = match mode {
            StereoCodecMode::Aspx => 2,
            _ => 1,
        };
        tools.companding = Some(aspx::parse_companding_control(br, nc)?);
        // For `StereoCodecMode::Aspx` (Table 22) the stereo_data()
        // body follows companding_control(2), then aspx_data_2ch()
        // closes the element. We parse stereo_data() with the same
        // shared decoder as SIMPLE, then attempt to read the leading
        // xover-offset + aspx_framing(0)[ + aspx_balance + framing(1)]
        // of aspx_data_2ch(). Only runs when:
        //   * we're on an I-frame, and
        //   * the stereo_data() body decoded cleanly (bitreader is at
        //     the right place).
        if matches!(mode, StereoCodecMode::Aspx) {
            let body_ok = parse_stereo_data_body(br, tools, frame_len_base);
            if b_iframe && body_ok {
                if let Some(cfg) = tools.aspx_config {
                    let xover = br.read_u32(3)? as u8;
                    tools.aspx_xover_subband_offset = Some(xover);
                    let nats = aspx::num_aspx_timeslots(frame_len_base);
                    let framing_ch0 = aspx::parse_aspx_framing(br, &cfg, b_iframe, nats > 8)?;
                    // Per Table 52: `aspx_qmode_env[0] = aspx_qmode_env[1]
                    // = aspx_quant_mode_env` then clamp to 0 on FIXFIX +
                    // num_env == 1.
                    let qmode_ch0 = if matches!(framing_ch0.int_class, aspx::AspxIntClass::FixFix)
                        && framing_ch0.num_env == 1
                    {
                        aspx::AspxQuantStep::Fine
                    } else {
                        cfg.quant_mode_env
                    };
                    tools.aspx_qmode_env_primary = Some(qmode_ch0);
                    // Table 52: aspx_balance (1 bit). If 0, aspx_framing(1)
                    // follows for channel 1; otherwise channel 1 reuses
                    // channel 0's framing.
                    let balance = br.read_bit()?;
                    tools.aspx_balance = Some(balance);
                    let framing_ch1_ref;
                    if !balance {
                        let framing_ch1 = aspx::parse_aspx_framing(br, &cfg, b_iframe, nats > 8)?;
                        // Per Table 52 the ch1 qmode is recomputed
                        // against the ch1 framing (and re-clamped on
                        // FIXFIX + num_env == 1).
                        let qmode_ch1 =
                            if matches!(framing_ch1.int_class, aspx::AspxIntClass::FixFix)
                                && framing_ch1.num_env == 1
                            {
                                aspx::AspxQuantStep::Fine
                            } else {
                                cfg.quant_mode_env
                            };
                        tools.aspx_qmode_env_secondary = Some(qmode_ch1);
                        tools.aspx_framing_secondary = Some(framing_ch1);
                        framing_ch1_ref = tools.aspx_framing_secondary.as_ref();
                    } else {
                        // Shared framing; copy the ch0 qmode across.
                        tools.aspx_qmode_env_secondary = Some(qmode_ch0);
                        framing_ch1_ref = Some(&framing_ch0);
                    }
                    // aspx_delta_dir(0) then aspx_delta_dir(1) per
                    // Table 52.
                    let dd0 = aspx::parse_aspx_delta_dir(br, &framing_ch0)?;
                    let f_ch1 = framing_ch1_ref.unwrap_or(&framing_ch0);
                    let dd1 = aspx::parse_aspx_delta_dir(br, f_ch1)?;
                    // ยง5.7.6.3.1 derivation feeds aspx_hfgen_iwc_2ch()
                    // (Table 56) then four aspx_ec_data() calls
                    // (ch0/ch1 SIGNAL, ch0/ch1 NOISE) per Table 52.
                    if let Ok(tables) = aspx::derive_aspx_frequency_tables(&cfg, xover as u32) {
                        let hfgen = aspx::parse_aspx_hfgen_iwc_2ch(
                            br,
                            balance,
                            cfg.num_noise_sbgroups(),
                            tables.counts.num_sbg_sig_highres,
                            nats,
                        )?;
                        tools.aspx_hfgen_iwc_2ch = Some(hfgen);
                        let qmode_ch1_effective =
                            tools.aspx_qmode_env_secondary.unwrap_or(qmode_ch0);
                        // ch0 SIGNAL: stereo_mode = LEVEL (Table 52).
                        let sig0 = aspx::parse_aspx_ec_data(
                            br,
                            aspx::AspxDataType::Signal,
                            framing_ch0.num_env,
                            &framing_ch0.freq_res,
                            qmode_ch0,
                            aspx::AspxStereoMode::Level,
                            &dd0.sig_delta_dir,
                            tables.counts,
                        )?;
                        tools.aspx_data_sig_primary = Some(sig0);
                        // ch1 SIGNAL: BALANCE when aspx_balance == 1
                        // else LEVEL (Table 52).
                        let sm_ch1 = if balance {
                            aspx::AspxStereoMode::Balance
                        } else {
                            aspx::AspxStereoMode::Level
                        };
                        let sig1 = aspx::parse_aspx_ec_data(
                            br,
                            aspx::AspxDataType::Signal,
                            f_ch1.num_env,
                            &f_ch1.freq_res,
                            qmode_ch1_effective,
                            sm_ch1,
                            &dd1.sig_delta_dir,
                            tables.counts,
                        )?;
                        tools.aspx_data_sig_secondary = Some(sig1);
                        // ch0 NOISE.
                        let noise0 = aspx::parse_aspx_ec_data(
                            br,
                            aspx::AspxDataType::Noise,
                            framing_ch0.num_noise,
                            &[],
                            aspx::AspxQuantStep::Fine,
                            aspx::AspxStereoMode::Level,
                            &dd0.noise_delta_dir,
                            tables.counts,
                        )?;
                        tools.aspx_data_noise_primary = Some(noise0);
                        // ch1 NOISE mirrors ch1 SIGNAL stereo_mode.
                        let noise1 = aspx::parse_aspx_ec_data(
                            br,
                            aspx::AspxDataType::Noise,
                            f_ch1.num_noise,
                            &[],
                            aspx::AspxQuantStep::Fine,
                            sm_ch1,
                            &dd1.noise_delta_dir,
                            tables.counts,
                        )?;
                        tools.aspx_data_noise_secondary = Some(noise1);
                        tools.aspx_frequency_tables = Some(tables);
                    }
                    tools.aspx_delta_dir_primary = Some(dd0);
                    tools.aspx_delta_dir_secondary = Some(dd1);
                    tools.aspx_framing_primary = Some(framing_ch0);
                }
            }
        }
        return Ok(());
    }

    // SIMPLE path: just `stereo_data()`.
    let _ = parse_stereo_data_body(br, tools, frame_len_base);
    let _ = b_iframe; // reserved for later Huffman-state keying.
    Ok(())
}

/// Walk `stereo_data()` (ยง4.2.6.3 / Table 22) into `tools`. Returns
/// `true` when the body decoded cleanly enough for the bitreader to sit
/// at the spec's end-of-body position (i.e. the caller is safe to
/// continue reading downstream elements like `aspx_data_2ch()`). A
/// return of `false` means some inner Huffman-gated decode bailed; the
/// bitreader position after the call is indeterminate.
fn parse_stereo_data_body(
    br: &mut BitReader<'_>,
    tools: &mut SubstreamTools,
    frame_len_base: u32,
) -> bool {
    // stereo_data():
    //   if (b_enable_mdct_stereo_proc) {
    //       spec_frontend_l = ASF; spec_frontend_r = ASF;
    //       sf_info(ASF, 0, 0);
    //       chparam_info();
    //   } else {
    //       spec_frontend_l;   1 bit
    //       sf_info(spec_frontend_l, 0, 0);
    //       spec_frontend_r;   1 bit
    //       sf_info(spec_frontend_r, 0, 0);
    //   }
    //   sf_data(spec_frontend_l);
    //   sf_data(spec_frontend_r);
    let b_mdct_stereo = match br.read_bit() {
        Ok(v) => v,
        Err(_) => return false,
    };
    tools.mdct_stereo_proc = b_mdct_stereo;
    if b_mdct_stereo {
        tools.spec_frontend_primary = Some(SpecFrontend::Asf);
        tools.spec_frontend_secondary = Some(SpecFrontend::Asf);
        let ti = match parse_asf_transform_info(br, frame_len_base) {
            Ok(t) => t,
            Err(_) => return false,
        };
        tools.transform_info_primary = Some(ti);
        tools.transform_info_secondary = Some(ti);
        // stereo_data() with b_enable_mdct_stereo_proc==1 calls
        // sf_info(ASF, 0, 0) which fires asf_psy_info(0, 0) over the
        // shared transform window.
        let psy = match parse_asf_psy_info(br, &ti, frame_len_base, false, false) {
            Ok(p) => p,
            Err(_) => return false,
        };
        tools.psy_info_primary = Some(psy.clone());
        // Joint-stereo MDCT path: one shared section / psy layout,
        // two residual channel spectra, followed by a per-sfb
        // ms_used[] flag array. Only walk the long-frame, single
        // window-group body; other shapes stay at outer-layer only.
        if ti.b_long_frame && psy.num_window_groups == 1 {
            match decode_asf_long_stereo_joint_body(br, &ti, &psy) {
                Some((l, r, ms)) => {
                    tools.scaled_spec_primary = Some(l);
                    tools.scaled_spec_secondary = Some(r);
                    tools.ms_used = Some(ms);
                    true
                }
                None => false,
            }
        } else {
            // Outer layers parsed but Huffman body not walked โ€” the
            // bitreader isn't at the end of stereo_data(), so downstream
            // elements aren't safe to parse.
            false
        }
    } else {
        let l = match br.read_u32(1) {
            Ok(v) => SpecFrontend::from_bit(v),
            Err(_) => return false,
        };
        tools.spec_frontend_primary = Some(l);
        let mut ti_l: Option<AsfTransformInfo> = None;
        let mut psy_l: Option<AsfPsyInfo> = None;
        if let SpecFrontend::Asf = l {
            let ti = match parse_asf_transform_info(br, frame_len_base) {
                Ok(t) => t,
                Err(_) => return false,
            };
            tools.transform_info_primary = Some(ti);
            ti_l = Some(ti);
            if let Ok(psy) = parse_asf_psy_info(br, &ti, frame_len_base, false, false) {
                tools.psy_info_primary = Some(psy.clone());
                psy_l = Some(psy);
            } else {
                return false;
            }
        }
        let r = match br.read_u32(1) {
            Ok(v) => SpecFrontend::from_bit(v),
            Err(_) => return false,
        };
        tools.spec_frontend_secondary = Some(r);
        let mut ti_r: Option<AsfTransformInfo> = None;
        let mut psy_r: Option<AsfPsyInfo> = None;
        if let SpecFrontend::Asf = r {
            let ti = match parse_asf_transform_info(br, frame_len_base) {
                Ok(t) => t,
                Err(_) => return false,
            };
            tools.transform_info_secondary = Some(ti);
            ti_r = Some(ti);
            if let Ok(psy) = parse_asf_psy_info(br, &ti, frame_len_base, false, false) {
                tools.psy_info_secondary = Some(psy.clone());
                psy_r = Some(psy);
            } else {
                return false;
            }
        }
        // Split-MDCT stereo: two independent ASF spectra. Decode each if
        // long-frame + single-window-group. Any malformed body is
        // surfaced as a decode miss (None) rather than a hard error.
        let mut body_ok = true;
        if let (Some(ti), Some(psy)) = (ti_l, psy_l.as_ref()) {
            if ti.b_long_frame && psy.num_window_groups == 1 {
                tools.scaled_spec_primary = decode_asf_long_mono_body(br, &ti, psy);
                if tools.scaled_spec_primary.is_none() {
                    body_ok = false;
                }
            } else {
                body_ok = false;
            }
        }
        if let (Some(ti), Some(psy)) = (ti_r, psy_r.as_ref()) {
            if ti.b_long_frame && psy.num_window_groups == 1 {
                tools.scaled_spec_secondary = decode_asf_long_mono_body(br, &ti, psy);
                if tools.scaled_spec_secondary.is_none() {
                    body_ok = false;
                }
            } else {
                body_ok = false;
            }
        }
        body_ok
    }
}

/// Decode the `sf_data` body for a stereo, long-frame, single-window-
/// group ASF substream with `b_enable_mdct_stereo_proc == 1` (joint
/// MDCT processing โ€” ยง7.4 / ยง7.5).
///
/// Layout inferred from the spec:
///   - shared asf_section_data (one section partition drives both
///     channels' codebook assignment).
///   - two asf_spectral_data bodies (residuals for channel L and R,
///     which are actually M and S when ms_used is set).
///   - shared asf_scalefac_data (the scalefactors are shared so the
///     joint quant step is uniform across both channels).
///   - per-sfb ms_used[sfb] flag โ€” one bit per active band.
///   - asf_snf_data consumed but not injected.
///
/// Returns `(left_scaled, right_scaled, ms_used)` on success.
fn decode_asf_long_stereo_joint_body(
    br: &mut BitReader<'_>,
    ti: &AsfTransformInfo,
    psy: &AsfPsyInfo,
) -> Option<(Vec<f32>, Vec<f32>, Vec<bool>)> {
    let tl = ti.transform_length_0;
    let tl_idx = ti.transf_length[0];
    let max_sfb_cap = tables::num_sfb_48(tl)?;
    let max_sfb = psy.max_sfb_0.min(max_sfb_cap);
    if max_sfb == 0 {
        return None;
    }
    let sfbo = sfb_offset::sfb_offset_48(tl)?;
    // Shared asf_section_data.
    let sections = asf_data::parse_asf_section_data(br, tl_idx, tl, max_sfb).ok()?;
    // L / M channel residuals.
    let (q_l, mqi_l) = asf_data::parse_asf_spectral_data(br, &sections, sfbo, max_sfb).ok()?;
    // R / S channel residuals.
    let (q_r, mqi_r) = asf_data::parse_asf_spectral_data(br, &sections, sfbo, max_sfb).ok()?;
    // Shared scalefactors โ€” compute max_quant_idx as the band-wise max
    // over both channels so the scalefactor DPCM state tracks bands
    // that have any energy at all.
    let mqi: Vec<u32> = mqi_l
        .iter()
        .zip(mqi_r.iter())
        .map(|(a, b)| (*a).max(*b))
        .collect();
    let sf_gain = asf_data::parse_asf_scalefac_data(br, &sections, &mqi, max_sfb, tl).ok()?;
    // Per-sfb ms_used flag array. Only active bands (cb != 0 and
    // max_quant_idx > 0) carry a bit per ยง7.5 Pseudocode 77; other
    // bands default to false.
    let mut ms_used = vec![false; max_sfb as usize];
    for sfb in 0..max_sfb as usize {
        let cb = sections.sfb_cb[sfb];
        if cb == 0 || mqi[sfb] == 0 {
            continue;
        }
        ms_used[sfb] = br.read_bit().ok()?;
    }
    // asf_snf_data consumed but not currently injected.
    let _ = asf_data::parse_asf_snf_data(br, &sections, &mqi, max_sfb, tl).ok()?;
    // Dequantise + scale both channels with the shared gain.
    let mut scaled_l = asf_data::dequantise_and_scale(&q_l, &sf_gain, sfbo, max_sfb);
    let mut scaled_r = asf_data::dequantise_and_scale(&q_r, &sf_gain, sfbo, max_sfb);
    // Apply inverse M/S per ยง7.5: L = M + S, R = M - S for bands with
    // ms_used == true.
    for (sfb, &used) in ms_used.iter().enumerate() {
        if !used {
            continue;
        }
        let a = sfbo[sfb] as usize;
        let b = sfbo[sfb + 1] as usize;
        let bmax = b.min(scaled_l.len()).min(scaled_r.len());
        for k in a..bmax {
            let m = scaled_l[k];
            let s = scaled_r[k];
            scaled_l[k] = m + s;
            scaled_r[k] = m - s;
        }
    }
    Some((scaled_l, scaled_r, ms_used))
}

/// Walk an `ac4_substream()` payload. `substream_bytes` is the slice
/// covering the substream as pointed to by `substream_index_table()`.
/// The walker reads the outer framing and the initial `audio_data()`
/// flags; on success returns an [`Ac4SubstreamInfo`] with the tool
/// summary. On malformed input โ€” which for a stub walker mostly means
/// running off the end of the bitstream โ€” the function returns a
/// best-effort info with whatever was parsed before the error.
///
/// `channels` is the channel count taken from the parent
/// `ac4_substream_info()`. `b_iframe` likewise. `frame_len_base` is
/// `frame_length` at the base sample rate (i.e. the TOC's
/// `frame_length` entry for 48 kHz and 44.1 kHz).
pub fn walk_ac4_substream(
    substream_bytes: &[u8],
    channels: u16,
    b_iframe: bool,
    frame_len_base: u32,
) -> Result<Ac4SubstreamInfo> {
    if substream_bytes.is_empty() {
        return Err(Error::invalid("ac4: empty substream"));
    }
    let mut br = BitReader::new(substream_bytes);

    // ยง4.3.4.1 audio_size_value โ€” 15-bit value, optional variable_bits(7)
    // extension gated by b_more_bits.
    let audio_size_short = br.read_u32(15)?;
    let b_more_bits = br.read_bit()?;
    let audio_size = if b_more_bits {
        audio_size_short + (variable_bits(&mut br, 7)? << 15)
    } else {
        audio_size_short
    };

    // byte_align to enter audio_data().
    br.align_to_byte();
    let audio_data_offset = br.byte_position() as u32;

    // Parse the outer layers of audio_data(channel_mode, b_iframe).
    let mut tools = SubstreamTools {
        channel_mode_channels: channels,
        ..Default::default()
    };
    match channels {
        1 => parse_mono_audio_data_outer(&mut br, &mut tools, b_iframe, frame_len_base)?,
        2 => parse_stereo_audio_data_outer(&mut br, &mut tools, b_iframe, frame_len_base)?,
        // 3.0 / 5.0 / 5.1 / 7.x paths are coding-config-dependent; their
        // outer walkers live behind the same Huffman gate as ASF's
        // spectral data. For the baseline we record the channel count
        // and bail.
        _ => {}
    }

    Ok(Ac4SubstreamInfo {
        audio_size,
        audio_data_offset,
        tools,
    })
}

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

    #[test]
    fn resolve_transf_length_long_frame_table_99() {
        // Long frame at 44.1/48 kHz returns frame_len_base directly.
        assert_eq!(resolve_transf_length(2048, true, 0), 2048);
        assert_eq!(resolve_transf_length(1920, true, 3), 1920);
    }

    #[test]
    fn resolve_transf_length_table_100_rows() {
        assert_eq!(resolve_transf_length(2048, false, 0), 128);
        assert_eq!(resolve_transf_length(2048, false, 1), 256);
        assert_eq!(resolve_transf_length(2048, false, 2), 512);
        assert_eq!(resolve_transf_length(2048, false, 3), 1024);
        assert_eq!(resolve_transf_length(1920, false, 2), 480);
        assert_eq!(resolve_transf_length(1536, false, 1), 192);
    }

    #[test]
    fn resolve_transf_length_table_103_rows() {
        assert_eq!(resolve_transf_length(1024, false, 3), 1024);
        assert_eq!(resolve_transf_length(960, false, 2), 480);
        assert_eq!(resolve_transf_length(512, false, 0), 128);
        assert_eq!(resolve_transf_length(384, false, 2), 384);
    }

    #[test]
    fn asf_transform_info_long_frame_path() {
        // frame_len_base = 1920, b_long_frame = 1.
        let mut bw = BitWriter::new();
        bw.write_bit(true); // b_long_frame
        bw.align_to_byte();
        let bytes = bw.finish();
        let mut br = BitReader::new(&bytes);
        let ti = parse_asf_transform_info(&mut br, 1920).unwrap();
        assert!(ti.b_long_frame);
        assert_eq!(ti.transform_length_0, 1920);
        assert_eq!(ti.transform_length_1, 1920);
    }

    #[test]
    fn asf_transform_info_short_pair() {
        // frame_len_base = 1920, b_long_frame = 0, transf_length[0] = 2,
        // transf_length[1] = 3. -> transform lengths 480, 960.
        let mut bw = BitWriter::new();
        bw.write_bit(false); // b_long_frame
        bw.write_u32(2, 2);
        bw.write_u32(3, 2);
        bw.align_to_byte();
        let bytes = bw.finish();
        let mut br = BitReader::new(&bytes);
        let ti = parse_asf_transform_info(&mut br, 1920).unwrap();
        assert!(!ti.b_long_frame);
        assert_eq!(ti.transf_length, [2, 3]);
        assert_eq!(ti.transform_length_0, 480);
        assert_eq!(ti.transform_length_1, 960);
    }

    fn build_mono_substream() -> Vec<u8> {
        // Minimal ac4_substream() body: audio_size = 10, no extension,
        // byte_align, then audio_data() for channel_mode=mono,
        // b_iframe=1: mono_codec_mode=0 (SIMPLE), spec_frontend=0 (ASF),
        // asf_transform_info() for frame_len_base=1920 long-frame.
        let mut bw = BitWriter::new();
        // audio_size_value (15 bits) = 10.
        bw.write_u32(10, 15);
        // b_more_bits = 0.
        bw.write_bit(false);
        // byte_align to enter audio_data.
        bw.align_to_byte();
        // mono_codec_mode = 0 (SIMPLE).
        bw.write_u32(0, 1);
        // mono_data(0) body:
        //   spec_frontend = 0 (ASF).
        bw.write_u32(0, 1);
        //   sf_info(ASF, 0, 0) -> asf_transform_info():
        //     frame_len_base >= 1536 path; b_long_frame = 1.
        bw.write_bit(true);
        //   asf_psy_info(b_dual_maxsfb=0, b_side_limited=0):
        //   long-frame @ 1920 => n_msfb_bits = 6; max_sfb[0] = 40.
        bw.write_u32(40, 6);
        //   asf_section_data / spectral / scalefac / snf left opaque.
        bw.align_to_byte();
        // Pad up to "audio_size"-worth of bytes.
        while bw.byte_len() < 32 {
            bw.write_u32(0, 8);
        }
        bw.finish()
    }

    #[test]
    fn walk_mono_asf_substream_extracts_tools() {
        let bytes = build_mono_substream();
        let info = walk_ac4_substream(&bytes, 1, true, 1920).unwrap();
        assert_eq!(info.audio_size, 10);
        assert_eq!(info.tools.mono_mode, Some(MonoCodecMode::Simple));
        assert_eq!(info.tools.spec_frontend_primary, Some(SpecFrontend::Asf));
        let ti = info.tools.transform_info_primary.unwrap();
        assert!(ti.b_long_frame);
        assert_eq!(ti.transform_length_0, 1920);
        let psy = info.tools.psy_info_primary.as_ref().unwrap();
        assert_eq!(psy.max_sfb_0, 40);
        assert_eq!(psy.num_windows, 1);
        assert_eq!(psy.num_window_groups, 1);
    }

    fn build_stereo_simple_substream() -> Vec<u8> {
        let mut bw = BitWriter::new();
        // audio_size = 20.
        bw.write_u32(20, 15);
        bw.write_bit(false);
        bw.align_to_byte();
        // stereo_codec_mode = SIMPLE (0b00).
        bw.write_u32(0, 2);
        // stereo_data(): b_enable_mdct_stereo_proc = 0.
        bw.write_bit(false);
        // spec_frontend_l = 0 (ASF), long-frame, max_sfb[0] = 30.
        bw.write_u32(0, 1);
        bw.write_bit(true); // b_long_frame
        bw.write_u32(30, 6);
        // spec_frontend_r = 0 (ASF), long-frame, max_sfb[0] = 32.
        bw.write_u32(0, 1);
        bw.write_bit(true);
        bw.write_u32(32, 6);
        bw.align_to_byte();
        while bw.byte_len() < 32 {
            bw.write_u32(0, 8);
        }
        bw.finish()
    }

    #[test]
    fn walk_stereo_simple_substream_extracts_two_frontends() {
        let bytes = build_stereo_simple_substream();
        let info = walk_ac4_substream(&bytes, 2, true, 1920).unwrap();
        assert_eq!(info.audio_size, 20);
        assert_eq!(info.tools.stereo_mode, Some(StereoCodecMode::Simple));
        assert!(!info.tools.mdct_stereo_proc);
        assert_eq!(info.tools.spec_frontend_primary, Some(SpecFrontend::Asf));
        assert_eq!(info.tools.spec_frontend_secondary, Some(SpecFrontend::Asf));
        assert!(info.tools.transform_info_primary.is_some());
        assert!(info.tools.transform_info_secondary.is_some());
        let psy_l = info.tools.psy_info_primary.as_ref().unwrap();
        let psy_r = info.tools.psy_info_secondary.as_ref().unwrap();
        assert_eq!(psy_l.max_sfb_0, 30);
        assert_eq!(psy_r.max_sfb_0, 32);
    }

    #[test]
    fn walk_stereo_mdct_joint_shares_transform_info() {
        let mut bw = BitWriter::new();
        bw.write_u32(20, 15);
        bw.write_bit(false);
        bw.align_to_byte();
        bw.write_u32(0, 2); // SIMPLE
        bw.write_bit(true); // b_enable_mdct_stereo_proc
        bw.write_bit(true); // long-frame
        bw.write_u32(25, 6); // max_sfb[0] = 25.
        bw.align_to_byte();
        while bw.byte_len() < 32 {
            bw.write_u32(0, 8);
        }
        let bytes = bw.finish();
        let info = walk_ac4_substream(&bytes, 2, true, 1920).unwrap();
        assert!(info.tools.mdct_stereo_proc);
        assert_eq!(info.tools.spec_frontend_primary, Some(SpecFrontend::Asf));
        assert_eq!(info.tools.spec_frontend_secondary, Some(SpecFrontend::Asf));
        assert_eq!(
            info.tools
                .transform_info_primary
                .unwrap()
                .transform_length_0,
            info.tools
                .transform_info_secondary
                .unwrap()
                .transform_length_0
        );
        let psy = info.tools.psy_info_primary.as_ref().unwrap();
        assert_eq!(psy.max_sfb_0, 25);
    }

    #[test]
    fn asf_psy_info_long_frame_path() {
        // Manually drive parse_asf_psy_info with a known transform_info.
        let ti = AsfTransformInfo {
            b_long_frame: true,
            transf_length: [0, 0],
            transform_length_0: 1920,
            transform_length_1: 1920,
        };
        let mut bw = BitWriter::new();
        bw.write_u32(50, 6); // max_sfb[0]
        bw.align_to_byte();
        let bytes = bw.finish();
        let mut br = BitReader::new(&bytes);
        let psy = parse_asf_psy_info(&mut br, &ti, 1920, false, false).unwrap();
        assert!(!psy.b_different_framing);
        assert_eq!(psy.max_sfb_0, 50);
        assert_eq!(psy.num_windows, 1);
        assert_eq!(psy.num_window_groups, 1);
        assert!(psy.scale_factor_grouping.is_empty());
    }

    #[test]
    fn asf_psy_info_short_pair_with_grouping() {
        // frame_len_base = 1920, transf_length = [2, 2] (480 both).
        // From Table 109: n_grp_bits = 3. n_msfb_bits at 480 = 6.
        let ti = AsfTransformInfo {
            b_long_frame: false,
            transf_length: [2, 2],
            transform_length_0: 480,
            transform_length_1: 480,
        };
        let mut bw = BitWriter::new();
        bw.write_u32(20, 6); // max_sfb[0]
                             // scale_factor_grouping bits (3): 1, 0, 1 => one new group at bit 1.
        bw.write_u32(1, 1);
        bw.write_u32(0, 1);
        bw.write_u32(1, 1);
        bw.align_to_byte();
        let bytes = bw.finish();
        let mut br = BitReader::new(&bytes);
        let psy = parse_asf_psy_info(&mut br, &ti, 1920, false, false).unwrap();
        // b_different_framing = false (transf_length[0] == transf_length[1]).
        assert!(!psy.b_different_framing);
        assert_eq!(psy.max_sfb_0, 20);
        assert_eq!(psy.scale_factor_grouping, vec![1, 0, 1]);
        // num_windows = n_grp_bits + 1 = 4; one zero-bit => 2 groups.
        assert_eq!(psy.num_windows, 4);
        assert_eq!(psy.num_window_groups, 2);
    }

    #[test]
    fn asf_psy_info_different_framing_path() {
        // transf_length[0] = 1 (240 @ 1920), transf_length[1] = 2 (480).
        // n_grp_bits (Table 109) = 4.
        let ti = AsfTransformInfo {
            b_long_frame: false,
            transf_length: [1, 2],
            transform_length_0: 240,
            transform_length_1: 480,
        };
        let mut bw = BitWriter::new();
        // n_msfb_bits at 240 = 5 (Table 106).
        bw.write_u32(10, 5); // max_sfb[0]
                             // b_different_framing triggers:
                             // n_msfb_bits at 480 = 6.
        bw.write_u32(15, 6); // max_sfb[1]
                             // scale_factor_grouping bits (4): 0,0,0,0
        bw.write_u32(0, 4);
        bw.align_to_byte();
        let bytes = bw.finish();
        let mut br = BitReader::new(&bytes);
        let psy = parse_asf_psy_info(&mut br, &ti, 1920, false, false).unwrap();
        assert!(psy.b_different_framing);
        assert_eq!(psy.max_sfb_0, 10);
        assert_eq!(psy.max_sfb_1, 15);
        assert_eq!(psy.num_windows, 5);
    }

    #[test]
    fn walk_mono_aspx_substream_parses_config_and_companding() {
        // mono_codec_mode = 1 (ASPX) on an I-frame: the walker now
        // consumes aspx_config() (15 bits) and companding_control(1).
        let mut bw = BitWriter::new();
        bw.write_u32(5, 15); // audio_size = 5
        bw.write_bit(false); // b_more_bits = 0
        bw.align_to_byte();
        // mono_codec_mode = 1 (ASPX)
        bw.write_u32(1, 1);
        // aspx_config: quant_mode=0, start=3, stop=1, scale=1, interp=1,
        // preflat=0, limiter=1, noise_sbg=2, num_env_bits_fixfix=0,
        // freq_res_mode=0.
        bw.write_u32(0, 1);
        bw.write_u32(3, 3);
        bw.write_u32(1, 2);
        bw.write_u32(1, 1);
        bw.write_bit(true);
        bw.write_bit(false);
        bw.write_bit(true);
        bw.write_u32(2, 2);
        bw.write_u32(0, 1);
        bw.write_u32(0, 2);
        // companding_control(1): no sync_flag; compand_on[0] = 1.
        bw.write_bit(true);
        bw.align_to_byte();
        while bw.byte_len() < 32 {
            bw.write_u32(0, 8);
        }
        let bytes = bw.finish();
        let info = walk_ac4_substream(&bytes, 1, true, 1920).unwrap();
        assert_eq!(info.tools.mono_mode, Some(MonoCodecMode::Aspx));
        // aspx_config captured.
        let cfg = info.tools.aspx_config.unwrap();
        assert_eq!(cfg.start_freq, 3);
        assert_eq!(cfg.stop_freq, 1);
        assert_eq!(cfg.noise_sbg, 2);
        assert_eq!(cfg.num_noise_sbgroups(), 3);
        assert!(cfg.interpolation);
        assert!(!cfg.preflat);
        assert!(cfg.limiter);
        assert!(cfg.signals_freq_res());
        // companding captured.
        let cc = info.tools.companding.as_ref().unwrap();
        assert_eq!(cc.compand_on, vec![true]);
        assert!(cc.sync_flag.is_none());
        assert!(cc.compand_avg.is_none());
    }

    #[test]
    fn walk_stereo_aspx_substream_parses_config() {
        // stereo_codec_mode = 01 (ASPX) on an I-frame: read
        // aspx_config() then companding_control(2).
        let mut bw = BitWriter::new();
        bw.write_u32(5, 15);
        bw.write_bit(false);
        bw.align_to_byte();
        bw.write_u32(0b01, 2); // ASPX
                               // aspx_config: all-zero fields.
        bw.write_u32(0, 15);
        // companding_control(2): sync_flag=0, compand_on=[1,1].
        bw.write_bit(false);
        bw.write_bit(true);
        bw.write_bit(true);
        bw.align_to_byte();
        while bw.byte_len() < 32 {
            bw.write_u32(0, 8);
        }
        let bytes = bw.finish();
        let info = walk_ac4_substream(&bytes, 2, true, 1920).unwrap();
        assert_eq!(info.tools.stereo_mode, Some(StereoCodecMode::Aspx));
        let cfg = info.tools.aspx_config.unwrap();
        assert_eq!(cfg.start_freq, 0);
        let cc = info.tools.companding.as_ref().unwrap();
        assert_eq!(cc.sync_flag, Some(false));
        assert_eq!(cc.compand_on, vec![true, true]);
    }

    #[test]
    fn walk_stereo_aspx_non_iframe_skips_config() {
        // Predictive (b_iframe = 0) ASPX frame: aspx_config not present;
        // we go straight to companding_control.
        let mut bw = BitWriter::new();
        bw.write_u32(5, 15);
        bw.write_bit(false);
        bw.align_to_byte();
        bw.write_u32(0b01, 2); // ASPX
                               // No aspx_config โ€” go straight to companding_control(2).
        bw.write_bit(true); // sync_flag = 1 -> single compand_on
        bw.write_bit(true); // compand_on[0] = 1
        bw.align_to_byte();
        while bw.byte_len() < 32 {
            bw.write_u32(0, 8);
        }
        let bytes = bw.finish();
        let info = walk_ac4_substream(&bytes, 2, false, 1920).unwrap();
        assert_eq!(info.tools.stereo_mode, Some(StereoCodecMode::Aspx));
        assert!(info.tools.aspx_config.is_none());
        let cc = info.tools.companding.as_ref().unwrap();
        assert_eq!(cc.sync_flag, Some(true));
        assert_eq!(cc.compand_on, vec![true]);
    }

    /// Write sect_len_incr per ยง4.2.7.1 Table 80 (section-length
    /// expansion). Duplicated from `decoder.rs` tests for crate-local use.
    fn write_sect_len_incr(bw: &mut BitWriter, sect_len: u32, n_sect_bits: u32, esc: u32) {
        let base = sect_len.saturating_sub(1);
        let k = base / esc;
        let incr = base % esc;
        for _ in 0..k {
            bw.write_u32(esc, n_sect_bits);
        }
        bw.write_u32(incr, n_sect_bits);
    }

    #[test]
    fn walk_mono_aspx_iframe_reads_framing_after_mono_data() {
        // Full-path mono ASPX I-frame substream:
        //   audio_size_value (15), b_more_bits (1), byte_align.
        //   mono_codec_mode = 1 (ASPX)
        //   aspx_config() โ€” 15 bits.
        //   companding_control(1) โ€” 1 bit.
        //   mono_data(0):
        //     spec_frontend = 0 (ASF)
        //     asf_transform_info(): b_long_frame = 1
        //     asf_psy_info(): max_sfb[0] = 10 (6 bits)
        //     sf_data body (section + spectral zeros + scalefac 120 + snf off)
        //   aspx_data_1ch():
        //     aspx_xover_subband_offset = 3 (3 bits)
        //     aspx_framing(0): FIXFIX (1 bit) + tmp_num_env=1 (1 bit since
        //     aspx_num_env_bits_fixfix=0) -> num_env = 2.
        // We set aspx_freq_res_mode to High (not Signalled) so no
        // freq_res bits follow, keeping the fixture small.
        use crate::huffman;
        let mut bw = BitWriter::new();
        bw.write_u32(200, 15);
        bw.write_bit(false);
        bw.align_to_byte();
        // mono_codec_mode = ASPX
        bw.write_u32(1, 1);
        // aspx_config(): quant_mode=0, start=0, stop=0, scale=0,
        // interp=0, preflat=0, limiter=0, noise_sbg=0,
        // num_env_bits_fixfix=0, freq_res_mode=3 (High -> not signalled).
        bw.write_u32(0, 1); // quant_mode_env
        bw.write_u32(0, 3); // start_freq
        bw.write_u32(0, 2); // stop_freq
        bw.write_u32(0, 1); // master_freq_scale
        bw.write_bit(false); // interpolation
        bw.write_bit(false); // preflat
        bw.write_bit(false); // limiter
        bw.write_u32(0, 2); // noise_sbg
        bw.write_u32(0, 1); // num_env_bits_fixfix = 0 -> 1-bit tmp_num_env
        bw.write_u32(3, 2); // freq_res_mode = 3 (High)
                            // companding_control(1): compand_on[0] = 1, no avg.
        bw.write_bit(true);
        // mono_data(0): spec_frontend = 0 (ASF).
        bw.write_u32(0, 1);
        // asf_transform_info: b_long_frame = 1.
        bw.write_bit(true);
        // asf_psy_info: max_sfb[0] = 10 in 6 bits.
        bw.write_u32(10, 6);
        // sf_data body (all-zero spectra):
        //   section: cb_idx = 5 (4 bits) + sect_len for max_sfb=10 via
        //   n_sect_bits=3 (long frame at 1920), esc=7.
        bw.write_u32(5, 4);
        write_sect_len_incr(&mut bw, 10, 3, 7);
        // spectral pairs โ€” cb 5 is dim=2, so pairs = end_line / 2.
        // sfb_offset_48 @ 1920 index 10 = ?
        let sfbo = crate::sfb_offset::sfb_offset_48(1920).unwrap();
        let end_line = sfbo[10] as u32;
        let hcb = huffman::asf_hcb(5).unwrap();
        let pairs = end_line / 2;
        for _ in 0..pairs {
            bw.write_u32(hcb.cw[40], hcb.len[40] as u32); // zero pair
        }
        // scalefac: reference = 120 (8 bits). All bands are empty, so
        // no dpcm follows.
        bw.write_u32(120, 8);
        // snf: b_snf_data_exists = 0.
        bw.write_u32(0, 1);
        // aspx_data_1ch():
        //   aspx_xover_subband_offset = 3 (3 bits).
        bw.write_u32(3, 3);
        //   aspx_framing(0): FIXFIX = '0' (1 bit); tmp_num_env = 1
        //   (1 bit) -> num_env = 1 << 1 = 2.
        bw.write_bit(false); // FIXFIX
        bw.write_bit(true); // tmp_num_env = 1
        bw.align_to_byte();
        while bw.byte_len() < 220 {
            bw.write_u32(0, 8);
        }
        let bytes = bw.finish();
        let info = walk_ac4_substream(&bytes, 1, true, 1920).unwrap();
        // Sanity: we got through the outer layers.
        assert_eq!(info.tools.mono_mode, Some(MonoCodecMode::Aspx));
        assert!(info.tools.aspx_config.is_some());
        assert!(info.tools.companding.is_some());
        assert!(info.tools.transform_info_primary.is_some());
        // aspx_data_1ch path fired:
        assert_eq!(info.tools.aspx_xover_subband_offset, Some(3));
        let framing = info.tools.aspx_framing_primary.expect("framing");
        assert_eq!(framing.int_class, aspx::AspxIntClass::FixFix);
        assert_eq!(framing.num_env, 2);
        assert_eq!(framing.num_noise, 2);
        assert!(framing.freq_res.is_empty()); // freq_res_mode = High
                                              // Stereo sidecar untouched on mono.
        assert!(info.tools.aspx_framing_secondary.is_none());
        assert!(info.tools.aspx_balance.is_none());
        // aspx_delta_dir(0) followed on the same path: consumed
        // num_env + num_noise = 4 bits โ€” all zeros from the padding.
        let dd = info.tools.aspx_delta_dir_primary.expect("delta dir");
        assert_eq!(dd.sig_delta_dir, vec![false; 2]);
        assert_eq!(dd.noise_delta_dir, vec![false; 2]);
        // FIXFIX + num_env > 1, so the config's quant_mode_env carries
        // through (and the config had it as Fine).
        assert_eq!(
            info.tools.aspx_qmode_env_primary,
            Some(aspx::AspxQuantStep::Fine)
        );
    }

    #[test]
    fn walk_mono_aspx_non_iframe_does_not_emit_framing() {
        // Non-I-frame ASPX substream: no aspx_config in the bitstream,
        // so the walker cannot safely consume aspx_data_1ch (xover
        // offset is also I-frame-sticky). Framing stays None.
        use crate::huffman;
        let mut bw = BitWriter::new();
        bw.write_u32(200, 15);
        bw.write_bit(false);
        bw.align_to_byte();
        bw.write_u32(1, 1); // mono_codec_mode = ASPX
                            // No aspx_config (b_iframe = false).
        bw.write_bit(true); // companding_control(1): compand_on[0] = 1.
        bw.write_u32(0, 1); // spec_frontend = ASF
        bw.write_bit(true); // b_long_frame = 1
        bw.write_u32(10, 6); // max_sfb
        bw.write_u32(5, 4); // cb
        write_sect_len_incr(&mut bw, 10, 3, 7);
        let sfbo = crate::sfb_offset::sfb_offset_48(1920).unwrap();
        let end_line = sfbo[10] as u32;
        let hcb = huffman::asf_hcb(5).unwrap();
        for _ in 0..(end_line / 2) {
            bw.write_u32(hcb.cw[40], hcb.len[40] as u32);
        }
        bw.write_u32(120, 8);
        bw.write_u32(0, 1);
        bw.align_to_byte();
        while bw.byte_len() < 220 {
            bw.write_u32(0, 8);
        }
        let bytes = bw.finish();
        let info = walk_ac4_substream(&bytes, 1, false, 1920).unwrap();
        assert_eq!(info.tools.mono_mode, Some(MonoCodecMode::Aspx));
        // No aspx_config (non-I-frame), so no framing either.
        assert!(info.tools.aspx_config.is_none());
        assert!(info.tools.aspx_framing_primary.is_none());
        assert!(info.tools.aspx_xover_subband_offset.is_none());
    }

    /// End-to-end mono ASPX I-frame substream: hand-build
    /// aspx_hfgen_iwc_1ch plus two aspx_ec_data() payloads and verify
    /// the walker captures them. This is the round-6 acceptance test
    /// for parse_aspx_ec_data's wiring through ยง5.7.6.3.1 derivation.
    #[test]
    fn walk_mono_aspx_iframe_reads_ec_data_end_to_end() {
        use crate::aspx::{
            ASPX_HCB_ENV_LEVEL_15_DF, ASPX_HCB_ENV_LEVEL_15_F0, ASPX_HCB_NOISE_LEVEL_F0,
        };
        use crate::huffman;
        let mut bw = BitWriter::new();
        bw.write_u32(500, 15);
        bw.write_bit(false);
        bw.align_to_byte();
        bw.write_u32(1, 1); // mono_codec_mode = ASPX
                            // aspx_config(): quant_mode=0, start=3, stop=3, scale=1
                            // (highres -> 22 - 6 - 6 = 10 master groups), freq_res_mode=3
                            // (High -> no per-env freq_res bits), other flags zero.
        bw.write_u32(0, 1); // quant_mode_env
        bw.write_u32(3, 3); // start_freq
        bw.write_u32(3, 2); // stop_freq
        bw.write_u32(1, 1); // master_freq_scale = HighRes
        bw.write_bit(false); // interpolation
        bw.write_bit(false); // preflat
        bw.write_bit(false); // limiter
        bw.write_u32(0, 2); // noise_sbg
        bw.write_u32(0, 1); // num_env_bits_fixfix
        bw.write_u32(3, 2); // freq_res_mode = High
                            // companding_control(1): compand_on[0] = 1.
        bw.write_bit(true);
        // mono_data(0): ASF frontend, long frame, max_sfb=10, zero
        // spectra + scalefac 120 + no snf.
        bw.write_u32(0, 1); // spec_frontend = ASF
        bw.write_bit(true); // b_long_frame
        bw.write_u32(10, 6); // max_sfb
        bw.write_u32(5, 4);
        write_sect_len_incr(&mut bw, 10, 3, 7);
        let sfbo = crate::sfb_offset::sfb_offset_48(1920).unwrap();
        let end_line = sfbo[10] as u32;
        let hcb = huffman::asf_hcb(5).unwrap();
        for _ in 0..(end_line / 2) {
            bw.write_u32(hcb.cw[40], hcb.len[40] as u32);
        }
        bw.write_u32(120, 8); // reference scalefac
        bw.write_u32(0, 1); // b_snf_data_exists
                            // aspx_data_1ch(): xover=7 -> num_sbg_sig_highres = 10 - 7 = 3
                            // and num_sbg_sig_lowres = 2. num_sbg_noise clamps to 1 since
                            // aspx_noise_sbg = 0. FIXFIX + tmp_num_env=0 -> num_env = 1.
        bw.write_u32(7, 3); // aspx_xover_subband_offset
        bw.write_bit(false); // FIXFIX
        bw.write_bit(false); // tmp_num_env = 0
                             // aspx_delta_dir(0): sig[0]=0, noise[0]=0 (FREQ for both).
        bw.write_bit(false);
        bw.write_bit(false);
        // aspx_hfgen_iwc_1ch: tna_mode[0] = 0 (2 bits), ah_present=0,
        // fic_present=0, tic_present=0 (3 bits).
        bw.write_u32(0, 2);
        bw.write_bit(false);
        bw.write_bit(false);
        bw.write_bit(false);
        // aspx_data_sig[0]: num_env=1, high-res (3 subband groups).
        // F0 symbol 30 + two DF zero-deltas (index 70).
        let f0_cb = &ASPX_HCB_ENV_LEVEL_15_F0;
        let df_cb = &ASPX_HCB_ENV_LEVEL_15_DF;
        bw.write_u32(f0_cb.cw[30], f0_cb.len[30] as u32);
        bw.write_u32(df_cb.cw[70], df_cb.len[70] as u32);
        bw.write_u32(df_cb.cw[70], df_cb.len[70] as u32);
        // aspx_data_noise[0]: num_noise=1 (since num_env==1), num_sbg_noise=1.
        // One F0 codeword from the NOISE_LEVEL_F0 table.
        let noise_f0 = &ASPX_HCB_NOISE_LEVEL_F0;
        bw.write_u32(noise_f0.cw[6], noise_f0.len[6] as u32);
        bw.align_to_byte();
        while bw.byte_len() < 520 {
            bw.write_u32(0, 8);
        }
        let bytes = bw.finish();
        let info = walk_ac4_substream(&bytes, 1, true, 1920).unwrap();
        // ยง5.7.6.3.1 derivation results.
        let tables = info.tools.aspx_frequency_tables.as_ref().expect("tables");
        assert_eq!(tables.num_sbg_master, 10);
        assert_eq!(tables.sba, 24);
        assert_eq!(tables.sbz, 44);
        assert_eq!(tables.counts.num_sbg_sig_highres, 3);
        assert_eq!(tables.counts.num_sbg_sig_lowres, 2);
        assert_eq!(tables.counts.num_sbg_noise, 1);
        // hfgen: all gates off.
        let hfgen = info.tools.aspx_hfgen_iwc_1ch.as_ref().expect("hfgen");
        assert_eq!(hfgen.tna_mode, vec![0]);
        assert!(!hfgen.ah_present);
        assert!(!hfgen.fic_present);
        assert!(!hfgen.tic_present);
        // Signal envelope: F0=30, DF=0, DF=0.
        let sig = info.tools.aspx_data_sig_primary.as_ref().expect("sig");
        assert_eq!(sig.len(), 1);
        assert_eq!(sig[0].values, vec![30, 0, 0]);
        assert!(!sig[0].direction_time);
        // Noise envelope: single F0 with delta = 6.
        let noise = info.tools.aspx_data_noise_primary.as_ref().expect("noise");
        assert_eq!(noise.len(), 1);
        assert_eq!(noise[0].values, vec![6]);
        assert!(!noise[0].direction_time);
    }

    #[test]
    fn walk_stereo_aspx_acpl1_reads_config_and_stops_before_acpl() {
        // stereo_codec_mode = 10 (ASPX_ACPL_1): aspx_config present on
        // I-frames; acpl_config_1ch follows but isn't parsed โ€” we bail
        // after aspx_config rather than misread bits.
        let mut bw = BitWriter::new();
        bw.write_u32(5, 15);
        bw.write_bit(false);
        bw.align_to_byte();
        bw.write_u32(0b10, 2); // ASPX_ACPL_1
        bw.write_u32(0, 15); // aspx_config (all zero)
        bw.align_to_byte();
        while bw.byte_len() < 32 {
            bw.write_u32(0, 8);
        }
        let bytes = bw.finish();
        let info = walk_ac4_substream(&bytes, 2, true, 1920).unwrap();
        assert_eq!(info.tools.stereo_mode, Some(StereoCodecMode::AspxAcpl1));
        assert!(info.tools.aspx_config.is_some());
        // We explicitly stop before acpl_config_1ch so companding stays
        // None for the ACPL path.
        assert!(info.tools.companding.is_none());
    }
}