scarletbook 1.0.1

Clean-room reader for Super Audio CD (Scarletbook) disc images
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
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
// SPDX-License-Identifier: MIT OR Apache-2.0

//! DST frame decoding (specification 5).
//!
//! A frame is decoded independently of every other frame. Each rule of 5.6 that makes a
//! frame invalid is reported as a [`DstError`]; on SACD an invalid frame is replaced by
//! 0x55 bytes (specification 4, 4.6), which [`crate::audio::TrackAudio`] does.

use crate::audio::FRAME_BYTES_PER_CHANNEL;
use crate::dispatch::{self, Isa};

/// Bits (samples) per channel per frame, `NB` (specification 5, 5.1.2).
pub const NB: usize = 37_632;

/// [`audio::MAX_CHANNELS`](crate::audio::MAX_CHANNELS) for array sizes and indexes, `Nch`.
const MAX_NCH: usize = crate::audio::MAX_CHANNELS as usize;

const MAX_ORDER: usize = 128;
const MAX_PTABLE_LEN: usize = 64;
const HISTORY_BYTES: usize = MAX_ORDER / 8;

/// Why a DST frame is invalid: the rules of specification 5, 5.6, plus caller errors.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, thiserror::Error)]
#[non_exhaustive]
pub enum DstError {
    /// Rule 1: `FB <= 1`.
    #[error("frame-too-short")]
    FrameTooShort,
    /// Rule 2: a plain frame with non-zero stuffing bits.
    #[error("stuffing")]
    Stuffing,
    /// Rule 3: the header needs more bits than the frame has.
    #[error("header-truncated")]
    HeaderTruncated,
    /// Rule 4: segment resolution 0 or too large.
    #[error("resolution")]
    Resolution,
    /// Rule 5: an explicit segment too short or too long.
    #[error("segment-length")]
    SegmentLength,
    /// Rule 6: too many explicit segment lengths.
    #[error("too-many-segments")]
    TooManySegments,
    /// Rule 7: a table index greater than the running count.
    #[error("table-number")]
    TableNumber,
    /// Rule 8: more than `2 x Nch` filters or ptables.
    #[error("too-many-tables")]
    TooManyTables,
    /// Rule 9: a shared mapping with unequal segment counts.
    #[error("channel-mapping")]
    ChannelMapping,
    /// Rule 10: a copied mapping with different filter and ptable segment counts.
    #[error("segment-count-mismatch")]
    SegmentCountMismatch,
    /// Rule 11: coefficient coding method 3, or its order not below the filter order.
    #[error("coefficient-coding")]
    CoefficientCoding,
    /// Rule 12: a reconstructed coefficient outside -256 to 255.
    #[error("coefficient-range")]
    CoefficientRange,
    /// Rule 13: ptable coding method 3, or its order not below the table length.
    #[error("ptable-coding")]
    PtableCoding,
    /// Rule 14: a reconstructed ptable entry outside 1 to 128.
    #[error("ptable-range")]
    PtableRange,
    /// Rule 15: the first code bit is 1.
    #[error("arithmetic-code")]
    ArithmeticCode,
    /// Rule 16: more than 7 code bits left unread.
    #[error("unread-code-bits")]
    UnreadCodeBits,
    /// Rule 17: the initial code value is 4095.
    #[error("code-out-of-range")]
    CodeOutOfRange,
    /// Not a frame rule: the channel count is not 1 to 6 or the output has the wrong size.
    #[error("invalid decoder arguments")]
    InvalidArguments,
}

impl DstError {
    /// The rule number of specification 5, 5.6 (0 for [`DstError::InvalidArguments`]).
    pub fn rule(self) -> u8 {
        match self {
            DstError::FrameTooShort => 1,
            DstError::Stuffing => 2,
            DstError::HeaderTruncated => 3,
            DstError::Resolution => 4,
            DstError::SegmentLength => 5,
            DstError::TooManySegments => 6,
            DstError::TableNumber => 7,
            DstError::TooManyTables => 8,
            DstError::ChannelMapping => 9,
            DstError::SegmentCountMismatch => 10,
            DstError::CoefficientCoding => 11,
            DstError::CoefficientRange => 12,
            DstError::PtableCoding => 13,
            DstError::PtableRange => 14,
            DstError::ArithmeticCode => 15,
            DstError::UnreadCodeBits => 16,
            DstError::CodeOutOfRange => 17,
            DstError::InvalidArguments => 0,
        }
    }
}

/// `bitlen(x)`: the smallest y with 2^y > x (specification 5, 5.1.3).
fn bitlen(x: u32) -> u32 {
    32 - x.leading_zeros()
}

/// Reads bits MSB first (specification 5, 5.1.4). Reads past the end fail with
/// `HeaderTruncated`; only the header is read through it.
struct Bits<'a> {
    data: &'a [u8],
    pos: usize,
    len: usize,
}

impl<'a> Bits<'a> {
    fn new(data: &'a [u8]) -> Self {
        Bits { data, pos: 0, len: data.len().saturating_mul(8) }
    }

    fn bit_at(data: &[u8], i: usize) -> u32 {
        data.get(i / 8).map_or(0, |b| u32::from((b >> (7 - i % 8)) & 1))
    }

    fn bit(&mut self) -> Result<u32, DstError> {
        if self.pos >= self.len {
            return Err(DstError::HeaderTruncated);
        }
        let b = Self::bit_at(self.data, self.pos);
        self.pos += 1;
        Ok(b)
    }

    fn read(&mut self, n: u32) -> Result<u32, DstError> {
        let n = n as usize;
        if self.len - self.pos < n {
            return Err(DstError::HeaderTruncated);
        }
        let mut v = 0u32;
        for _ in 0..n {
            v = (v << 1) | Self::bit_at(self.data, self.pos);
            self.pos += 1;
        }
        Ok(v)
    }

    /// `tcimsbf(9)`.
    fn read_tc9(&mut self) -> Result<i32, DstError> {
        let v = self.read(9)? as i32;
        Ok(if v >= 256 { v - 512 } else { v })
    }

    /// A Rice-coded signed integer (specification 5, 5.3.8).
    fn rice(&mut self, m: u32) -> Result<i64, DstError> {
        let mut q: i64 = 0;
        while self.bit()? == 0 {
            q += 1;
        }
        let lsb = i64::from(self.read(m)?);
        let u = (q << m) + lsb;
        if u == 0 {
            return Ok(0);
        }
        Ok(if self.bit()? == 1 { -u } else { u })
    }
}

/// One segmentation: per channel, the start bit of each segment.
#[derive(Clone, Debug, Default)]
struct Segmentation {
    starts: [Vec<u32>; MAX_NCH],
}

impl Segmentation {
    fn count(&self, c: usize) -> usize {
        self.starts.get(c).map_or(0, Vec::len)
    }
}

#[derive(Clone, Copy)]
enum Kind {
    Filter,
    Ptable,
}

impl Kind {
    fn lmin_bytes(self) -> u32 {
        match self {
            Kind::Filter => 128,
            Kind::Ptable => 4,
        }
    }

    fn max_explicit(self, shared: bool) -> usize {
        match (self, shared) {
            (Kind::Filter, true) => 4,
            (Kind::Filter, false) => 3,
            (Kind::Ptable, _) => 7,
        }
    }
}

/// `table_segmentation(kind)` (specification 5, 5.3.2).
fn read_segmentation(bits: &mut Bits<'_>, kind: Kind, nch: usize) -> Result<Segmentation, DstError> {
    let shared = bits.bit()? == 1;
    let lmin = kind.lmin_bytes();
    let rmax = FRAME_BYTES_PER_CHANNEL as u32 - lmin;
    let mut resolution: Option<u32> = None;
    let mut seg = Segmentation::default();
    let read_channels = if shared { 1 } else { nch };
    for c in 0..read_channels {
        let mut rem = rmax;
        let mut starts = vec![0u32];
        let mut pos = 0u32;
        loop {
            if bits.bit()? == 1 {
                break;
            }
            if starts.len() > kind.max_explicit(shared) {
                return Err(DstError::TooManySegments);
            }
            let r = match resolution {
                Some(r) => r,
                None => {
                    let r = bits.read(bitlen(rmax))?;
                    if r == 0 || r > rmax {
                        return Err(DstError::Resolution);
                    }
                    resolution = Some(r);
                    r
                }
            };
            let l = bits.read(bitlen(rem / r))?;
            // r <= 4700 and l < 2^13: no overflow.
            let bytes = r * l;
            if bytes < lmin || bytes > rem {
                return Err(DstError::SegmentLength);
            }
            rem -= bytes;
            pos += 8 * bytes;
            starts.push(pos);
        }
        if let Some(slot) = seg.starts.get_mut(c) {
            *slot = starts;
        }
    }
    if shared {
        let first = seg.starts[0].clone();
        for c in 1..nch {
            seg.starts[c].clone_from(&first);
        }
    }
    Ok(seg)
}

/// `table_mapping` (specification 5, 5.3.3): per channel and segment, a table number.
fn read_mapping(
    bits: &mut Bits<'_>,
    seg: &Segmentation,
    nch: usize,
) -> Result<(Vec<Vec<u8>>, usize), DstError> {
    let shared = bits.bit()? == 1;
    let mut t: u32 = 1;
    let mut index = |bits: &mut Bits<'_>| -> Result<u8, DstError> {
        let v = bits.read(bitlen(t))?;
        if v > t {
            return Err(DstError::TableNumber);
        }
        if v == t {
            t += 1;
        }
        // t is at most the total number of segments (48).
        Ok(v as u8)
    };
    let mut map: Vec<Vec<u8>> = Vec::with_capacity(nch);
    if shared {
        let mut first = vec![0u8];
        for _ in 1..seg.count(0) {
            first.push(index(bits)?);
        }
        for c in 0..nch {
            if seg.count(c) != seg.count(0) {
                return Err(DstError::ChannelMapping);
            }
            map.push(first.clone());
        }
    } else {
        for c in 0..nch {
            let mut m = Vec::with_capacity(seg.count(c));
            for j in 0..seg.count(c) {
                m.push(if c == 0 && j == 0 { 0 } else { index(bits)? });
            }
            map.push(m);
        }
    }
    let count = t as usize;
    if count > 2 * nch {
        return Err(DstError::TooManyTables);
    }
    Ok((map, count))
}

const COEF_PRED: [[i64; 3]; 3] = [[-8, 0, 0], [-16, 8, 0], [-9, -5, 6]];
const PTABLE_PRED: [[i64; 3]; 3] = [[-8, 0, 0], [-16, 8, 0], [-24, 24, -8]];

/// `floor((x + 4) / 8)`.
fn round8(x: i64) -> i64 {
    (x + 4).div_euclid(8)
}

/// A decoded filter: its prediction order and coefficients (zero beyond the order).
#[derive(Clone, Debug)]
struct Filter {
    order: usize,
    coefs: [i32; MAX_ORDER],
}

/// Eight prediction terms, one for each bit position of the byte being decoded.
type Row = [i16; 8];

/// For one complete history byte and each of its 256 values, its share of the prediction at
/// each bit position of the byte being decoded.
type ByteTable = [Row; 256];

/// The tables of a filter's history bytes beyond its order, and of channels not decoded.
static ZERO_TABLES: [ByteTable; HISTORY_BYTES] = [[[0; 8]; 256]; HISTORY_BYTES];

/// The initial history (5.5.2) as complete bytes (`h[8d + 7]` the most significant bit of
/// byte d, `h[8d]` the least): `h[i]` is 1 for odd i.
const HISTORY_FILL: u8 = 0xAA;

/// Bytes of history read for one byte of every channel, at most: [`HISTORY_BYTES`] bytes
/// of [`MAX_NCH`] channels, interleaved.
const WINDOW: usize = HISTORY_BYTES * MAX_NCH;

/// Most frames [`DstDecoder::decode_many`] decodes in lockstep; it decodes more in groups
/// of this many.
///
/// This is also the largest count [`crate::audio::TrackAudioCursor::with_dst_lanes`] accepts.
/// The name is covered by semantic versioning, but the value is a tuning value and is not: it
/// may change in any release. Read it instead of relying on a number.
pub const MAX_LANES: usize = 4;

/// How many frames of `channels` channels to pass to [`DstDecoder::decode_many`] at once
/// for the most frames per second on one thread (1 if `channels` is not 1 to 6).
///
/// This function is covered by semantic versioning, but the number it returns is a tuning
/// value and is not: it may change in any release, and may differ per build, per CPU and
/// with any setting that affects decoding. Call it instead of relying on a number. It never
/// affects the decoded output.
///
/// Chosen by measurement for each build (see the commit that added it): the decoder is
/// bound by the serial chain of the arithmetic decoder, which more frames overlap until
/// the 16 general registers of x86-64 run out and the state spills. Builds with
/// AVX-512 (`avx512cd`) have more registers, but the compiler pairs the steps of
/// two frames into vector operations there, which is much slower for 6 channels, so 3
/// frames are used.
///
/// The 1-, 3- and 4-channel choices were measured on generated frames; their output is
/// checked by the corpus's 1-, 3- and 4-channel DST cases (sacd-spec#15).
///
/// [`crate::TrackAudioCursor::with_dst_lanes`] chooses another count for one cursor.
pub fn lanes(channels: u8) -> usize {
    let avx512 = cfg!(target_feature = "avx512cd");
    match channels {
        1 => {
            if avx512 {
                3
            } else {
                4
            }
        }
        3 if !avx512 => 3,
        6 if avx512 => 3,
        2..=6 => 2,
        _ => 1,
    }
}

/// The buffers of one frame being decoded, reused from frame to frame.
#[derive(Debug, Default)]
struct Lane {
    /// Per filter, `HISTORY_BYTES` byte tables (see [`Lane::build_tables`]), zero beyond
    /// the filter's order.
    tables: Vec<ByteTable>,
    /// Per filter, how many of its tables may be non-zero.
    filled: Vec<usize>,
    /// Per filter, the share of the bits already decoded in the current byte, indexed by
    /// `2^r | bits` for `r` bits.
    partial: Vec<[i16; 256]>,
    /// Per ptable, its probability for each value of |Spred| / 8 ([`Lut`]).
    luts: Vec<Lut>,
    /// Per channel, the partial shares and probabilities [`run`] decodes it with.
    probes: Vec<Probe>,
    /// The frame's code bits, realigned.
    code: Vec<u8>,
    /// The history and output of every channel, interleaved: `HISTORY_BYTES` bytes of
    /// initial history per channel, then the output frame, then `WINDOW` spare bytes.
    hist: Vec<u8>,
}

/// Decodes DST frames, reusing its buffers between frames.
#[derive(Debug)]
pub struct DstDecoder {
    /// One per frame decoded at once.
    lanes: Vec<Lane>,
    /// The instruction set the decoder runs with, detected once (`dispatch`).
    isa: Isa,
}

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

impl DstDecoder {
    /// A new decoder.
    pub fn new() -> Self {
        DstDecoder { lanes: Vec::new(), isa: Isa::detect() }
    }

    /// A decoder that runs with `isa` instead of the detected instruction set.
    #[cfg(test)]
    pub(crate) fn with_isa(isa: Isa) -> Self {
        DstDecoder { lanes: Vec::new(), isa }
    }

    /// Decodes one frame of `channels` channels into `out` (`channels x 4704` bytes, in
    /// interleaved layout).
    ///
    /// On error `out` holds unspecified bytes.
    ///
    /// # Errors
    ///
    /// The rule of specification 5, 5.6 that makes the frame invalid, or
    /// [`DstError::InvalidArguments`].
    pub fn decode(&mut self, frame: &[u8], channels: u8, out: &mut [u8]) -> Result<(), DstError> {
        let mut result = [Ok(())];
        self.decode_group(&[frame], channels, &mut [out], &mut result);
        result[0]
    }

    /// Decodes `frames[i]` into `outs[i]` for every `i`, as [`DstDecoder::decode`] would
    /// one by one, with the same results, but a few frames at a time in
    /// lockstep on the calling thread: frames are independent (specification 5, 5.1.1), so
    /// the processor overlaps their arithmetic decoders, whose steps otherwise wait for each
    /// other. It takes any number of frames, and splits them into groups itself. [`lanes`]
    /// is the best number of frames to pass at once.
    ///
    /// The result has one entry per frame; a frame without an output buffer (when `outs` is
    /// shorter) is [`DstError::InvalidArguments`].
    pub fn decode_many(
        &mut self,
        frames: &[&[u8]],
        channels: u8,
        outs: &mut [&mut [u8]],
    ) -> Vec<Result<(), DstError>> {
        let mut results = vec![Err(DstError::InvalidArguments); frames.len()];
        let n = frames.len().min(outs.len());
        let groups = frames[..n].chunks(MAX_LANES).zip(outs[..n].chunks_mut(MAX_LANES));
        for ((frames, outs), results) in groups.zip(results.chunks_mut(MAX_LANES)) {
            self.decode_group(frames, channels, outs, results);
        }
        results
    }

    /// Decodes at most [`MAX_LANES`] frames in lockstep with the decoder's instruction set
    /// ([`DstDecoder::group`]).
    fn decode_group(
        &mut self,
        frames: &[&[u8]],
        channels: u8,
        outs: &mut [&mut [u8]],
        results: &mut [Result<(), DstError>],
    ) {
        dispatch::decode_group(self.isa, self, frames, channels, outs, results);
    }

    /// Decodes at most [`MAX_LANES`] frames in lockstep: every frame's header first, then
    /// the code byte by byte of every frame in turn. A frame whose header is invalid, or
    /// that is plain, drops out at once; one whose next chunk holds the end of a
    /// half-probability region decodes that chunk alone.
    ///
    /// Always inlined, so that `dispatch` builds it, and with `INLINE_RUN` every [`run`]
    /// it calls, with the features of its caller. Without `INLINE_RUN` each `run` stays a
    /// function of its own, as compiled.
    #[inline(always)]
    pub(crate) fn group<const INLINE_RUN: bool>(
        &mut self,
        frames: &[&[u8]],
        channels: u8,
        outs: &mut [&mut [u8]],
        results: &mut [Result<(), DstError>],
    ) {
        self.group_with::<INLINE_RUN, Native>(frames, channels, outs, results);
    }

    /// [`DstDecoder::decode_many`] with the arithmetic decoder in `W` instead of [`Native`],
    /// without run-time features: the same output and results (#369).
    #[cfg(test)]
    pub(crate) fn decode_many_with<W: Word>(
        &mut self,
        frames: &[&[u8]],
        channels: u8,
        outs: &mut [&mut [u8]],
    ) -> Vec<Result<(), DstError>> {
        let mut results = Vec::with_capacity(frames.len());
        for (frames, outs) in frames.chunks(MAX_LANES).zip(outs.chunks_mut(MAX_LANES)) {
            let mut group = vec![Ok(()); frames.len()];
            if frames.len() != outs.len() {
                group.fill(Err(DstError::InvalidArguments));
            } else {
                self.group_with::<false, W>(frames, channels, outs, &mut group);
            }
            results.extend(group);
        }
        results
    }

    /// [`DstDecoder::group`] with the arithmetic decoder in `W`.
    #[inline(always)]
    fn group_with<const INLINE_RUN: bool, W: Word>(
        &mut self,
        frames: &[&[u8]],
        channels: u8,
        outs: &mut [&mut [u8]],
        results: &mut [Result<(), DstError>],
    ) {
        if self.lanes.len() < frames.len() {
            self.lanes.resize_with(frames.len(), Lane::default);
        }
        let nch = usize::from(channels);
        let mut live: Vec<Live<'_, '_, W>> = Vec::with_capacity(frames.len());
        let lanes = self.lanes.iter_mut().zip(frames).zip(outs.iter_mut());
        for ((i, ((lane, frame), out)), result) in lanes.enumerate().zip(results.iter_mut()) {
            match Coded::<W>::start(lane, frame, nch, out) {
                Ok(Some(coded)) => live.push(Live { index: i, coded, out }),
                Ok(None) => *result = Ok(()),
                Err(e) => *result = Err(e),
            }
        }
        let mut spans: Vec<Span<'_>> = Vec::with_capacity(live.len());
        loop {
            // Frames at their end leave; a frame whose next chunk is in a half-probability
            // region decodes it alone (it lies in the first 16 bytes).
            let mut i = 0;
            spans.clear();
            while let Some(lv) = live.get_mut(i) {
                if lv.coded.n >= NB {
                    let lv = live.swap_remove(i);
                    results[lv.index] = lv.coded.finish(lv.out);
                    continue;
                }
                let span = lv.coded.span();
                if span.half {
                    lv.coded.run_general(&span);
                } else {
                    spans.push(span);
                    i += 1;
                }
            }
            if live.is_empty() {
                break;
            }
            // Then every frame for as many bytes as all of them keep their tables, with as
            // many history bytes (4, 8 or 16) as the longest filter needs.
            let bytes = live.iter().zip(&spans).map(|(lv, s)| (s.end - lv.coded.n) / 8).min().unwrap_or(0);
            let used = spans.iter().map(|s| s.most).max().unwrap_or(0);
            let mut runs: Vec<LaneRun<'_, '_, W>> =
                live.iter_mut().zip(&spans).map(|(lv, s)| lv.coded.lane_run(s)).collect();
            macro_rules! by_tables {
                ($k:literal, $n:literal) => {
                    match (used, INLINE_RUN) {
                        (0..=4, false) => run::<$k, $n, 4, W>(&mut runs, bytes),
                        (5..=8, false) => run::<$k, $n, 8, W>(&mut runs, bytes),
                        (_, false) => run::<$k, $n, 16, W>(&mut runs, bytes),
                        // One copy for every `used` where the byte is unrolled (see
                        // `run_inline`).
                        (_, true) if const { $k * $n <= UNROLL_BYTE } => {
                            run_inline::<$k, $n, W>(&mut runs, bytes, used)
                        }
                        (0..=4, true) => run_inline::<$k, $n, W>(&mut runs, bytes, 4),
                        (5..=8, true) => run_inline::<$k, $n, W>(&mut runs, bytes, 8),
                        (_, true) => run_inline::<$k, $n, W>(&mut runs, bytes, 16),
                    }
                };
            }
            macro_rules! by_channels {
                ($k:literal) => {
                    match nch {
                        1 => by_tables!($k, 1),
                        2 => by_tables!($k, 2),
                        3 => by_tables!($k, 3),
                        4 => by_tables!($k, 4),
                        5 => by_tables!($k, 5),
                        _ => by_tables!($k, 6),
                    }
                };
            }
            match runs.len() {
                1 => by_channels!(1),
                2 => by_channels!(2),
                3 => by_channels!(3),
                _ => by_channels!(4),
            }
            drop(runs);
            for lv in &mut live {
                lv.coded.advance(lv.coded.n + 8 * bytes);
            }
        }
    }
}

impl Lane {
    /// Splits the prediction of 5.5.3 by history byte. At bit `r` (0 to 7) of a byte, the
    /// history is the `r` bits already decoded in that byte (bit 0 of `partial`'s index
    /// the newest), then the complete bytes before it: bit `b` (0 the newest) of complete
    /// byte `d` (0 the newest) is history bit `8d + r + b`. Table `d` of a filter holds, for
    /// each byte value, its share at each of the 8 values of `r`.
    fn build_tables(&mut self, filters: &[Filter]) {
        // Tables beyond a filter's order are zero; only those a previous frame filled are
        // cleared again. The slots of filters no previous frame had are appended, each
        // table written once (#383): filling them with zeros first, then computing over
        // them, wrote a new decoder's tables twice.
        let had = self.filled.len();
        if filters.len() > had {
            self.tables.reserve_exact((filters.len() - had) * HISTORY_BYTES);
            self.partial.reserve_exact(filters.len() - had);
        }
        for (f, filter) in filters.iter().enumerate() {
            // Coefficients beyond the order (and beyond 127) are 0; every |a_i| <= 256.
            let a = |i: usize| filter.coefs.get(i).map_or(0, |&v| v as i16);
            let used = filter.order.div_ceil(8);
            if f < had {
                for d in 0..used {
                    byte_table(&mut self.tables[f * HISTORY_BYTES + d], d, a);
                }
                for d in used..self.filled[f] {
                    self.tables[f * HISTORY_BYTES + d] = [[0; 8]; 256];
                }
                self.filled[f] = used;
            } else {
                for d in 0..HISTORY_BYTES {
                    self.tables.push([[0; 8]; 256]);
                    if d < used {
                        if let Some(table) = self.tables.last_mut() {
                            byte_table(table, d, a);
                        }
                    }
                }
                self.filled.push(used);
                self.partial.push([0; 256]);
            }
            // The newest r bits of the current byte, at most 7 terms.
            let partial = &mut self.partial[f];
            for r in 0..8 {
                for bits in 0..1usize << r {
                    partial[(1 << r) | bits] =
                        (0..r).map(|i| if (bits >> i) & 1 == 1 { a(i) } else { -a(i) }).sum();
                }
            }
        }
    }

    fn build_luts(&mut self, ptables: &[Vec<u32>]) {
        // The tables of ptables no previous frame had are appended, each written once.
        let had = self.luts.len();
        self.luts.reserve_exact(ptables.len().saturating_sub(had));
        for (q, p) in ptables.iter().enumerate() {
            // In place; entries past 4096 are never read and keep whatever they hold.
            // Entries are 1 to 128 (5.3.6); a ptable has 1 to 64, and the last one repeats.
            let last = p.last().copied().unwrap_or(128) as u8;
            let lut = if q < had {
                let lut = &mut self.luts[q];
                lut[..LUT_USED].fill(last);
                lut
            } else {
                self.luts.push([last; LUT_LEN]);
                let Some(lut) = self.luts.last_mut() else { return };
                lut
            };
            for (slot, &v) in lut.iter_mut().zip(p) {
                *slot = v as u8;
            }
        }
    }
}

/// Builds table `d` of a filter with coefficients `a` (see [`Lane::build_tables`]) into
/// `table`, overwriting every entry.
#[inline(always)]
fn byte_table(table: &mut ByteTable, d: usize, a: impl Fn(usize) -> i16) {
    // A history bit of 1 contributes +a_i and 0 contributes -a_i: entry 0 is minus the sum
    // over the byte's bits, and setting bit b adds 2 a_i. Every entry is at most 8 x 256 in
    // magnitude.
    let mut first = [0i16; 8];
    let mut cols = [[0i16; 8]; 8];
    for (r, f) in first.iter_mut().enumerate() {
        for (b, col) in cols.iter_mut().enumerate() {
            let v = a(8 * d + r + b);
            *f -= v;
            col[r] = 2 * v;
        }
    }
    table[0] = first;
    for byte in 1..256usize {
        let col = &cols[byte.trailing_zeros() as usize];
        let prev = table[byte & (byte - 1)];
        table[byte] = core::array::from_fn(|r| prev[r].wrapping_add(col[r]));
    }
}

/// A coded frame of [`DstDecoder::decode_group`] still being decoded, and its output.
struct Live<'b, 'o, W: Word> {
    /// Its position in the group.
    index: usize,
    coded: Coded<'b, W>,
    out: &'o mut [u8],
}

/// A coded frame whose header has been read, decoded up to bit `n` of every channel.
struct Coded<'b, W: Word> {
    nch: usize,
    fseg: Segmentation,
    pseg: Segmentation,
    fmap: Vec<Vec<u8>>,
    pmap: Vec<Vec<u8>>,
    /// Each filter's prediction order.
    orders: Vec<usize>,
    /// Per channel, the half-probability length `NH` (5.4).
    nh: [usize; MAX_NCH],
    tables: &'b [ByteTable],
    partial: &'b [[i16; 256]],
    luts: &'b [Lut],
    /// See [`Lane::probes`], and per channel the filter and ptable they hold.
    probes: &'b mut [Probe],
    keys: [(usize, usize); MAX_NCH],
    arith: Arith<'b, W>,
    /// See [`Lane::hist`].
    hist: &'b mut [u8],
    /// Per channel, the current filter and ptable segment.
    fidx: [usize; MAX_NCH],
    pidx: [usize; MAX_NCH],
    n: usize,
    /// The number of code bits, `fs`.
    fs: usize,
}

/// Bytes `n / 8 .. end / 8` of every channel of a frame (`n` its position), with a fixed
/// filter and ptable per channel.
#[derive(Clone, Copy)]
struct Span<'t> {
    end: usize,
    /// Whether the span holds bits of some channel's half-probability region.
    half: bool,
    /// Per channel, the history bytes its filter uses, and the most of any channel.
    used: [usize; MAX_NCH],
    most: usize,
    tabs: [&'t [ByteTable; HISTORY_BYTES]; MAX_NCH],
    partial: [&'t [i16; 256]; MAX_NCH],
    luts: [&'t Lut; MAX_NCH],
    /// Per channel, the filter and ptable.
    keys: [(usize, usize); MAX_NCH],
}

impl<'b, W: Word> Coded<'b, W> {
    /// Reads the header of `frame` (`nch` channels) and prepares `lane` for its code, up
    /// to the coded X bit. A plain frame is copied to `out` at once (`Ok(None)`).
    fn start(lane: &'b mut Lane, frame: &[u8], nch: usize, out: &mut [u8]) -> Result<Option<Self>, DstError> {
        if !(1..=MAX_NCH).contains(&nch) || out.len() != nch * FRAME_BYTES_PER_CHANNEL {
            return Err(DstError::InvalidArguments);
        }
        if frame.len() <= 1 {
            return Err(DstError::FrameTooShort);
        }
        if frame[0] & 0x80 == 0 {
            return plain(frame, out).map(|()| None);
        }
        let mut bits = Bits::new(frame);
        bits.pos = 1;

        // Segmentation and mapping (5.3.1 to 5.3.3).
        let same_segmentation = bits.bit()? == 1;
        let fseg = read_segmentation(&mut bits, Kind::Filter, nch)?;
        let pseg =
            if same_segmentation { fseg.clone() } else { read_segmentation(&mut bits, Kind::Ptable, nch)? };
        let same_mapping = bits.bit()? == 1;
        let (fmap, nf) = read_mapping(&mut bits, &fseg, nch)?;
        let (pmap, np) = if same_mapping {
            for c in 0..nch {
                if pseg.count(c) != fseg.count(c) {
                    return Err(DstError::SegmentCountMismatch);
                }
            }
            (fmap.clone(), nf)
        } else {
            read_mapping(&mut bits, &pseg, nch)?
        };

        // Half probability (5.3.4).
        let mut half = [false; MAX_NCH];
        for h in half.iter_mut().take(nch) {
            *h = bits.bit()? == 1;
        }

        // Filters (5.3.5).
        let mut filters = Vec::with_capacity(nf);
        for _ in 0..nf {
            filters.push(read_filter(&mut bits)?);
        }

        // Ptables (5.3.6).
        let mut ptables: Vec<Vec<u32>> = Vec::with_capacity(np);
        for _ in 0..np {
            ptables.push(read_ptable(&mut bits)?);
        }

        // Arithmetic code (5.3.7).
        let header = bits.pos;
        let total = frame.len().saturating_mul(8);
        let fs = total - header;
        if fs > 0 && Bits::bit_at(frame, header) == 1 {
            return Err(DstError::ArithmeticCode);
        }
        lane.build_tables(&filters);
        lane.build_luts(&ptables);
        // Initial history (5.5.2).
        lane.hist.resize((HISTORY_BYTES + FRAME_BYTES_PER_CHANNEL) * nch + WINDOW, 0);
        lane.hist[..HISTORY_BYTES * nch].fill(HISTORY_FILL);
        lane.probes.resize(MAX_NCH, NO_PROBE);
        let Lane { tables, partial, luts, probes, code, hist, .. } = lane;
        let mut code = CodeBits::new(code, frame, header + 1, fs.saturating_sub(1));

        // Decoder initialisation (5.5.7): C is cb[1] .. cb[12].
        let c = code.take12();
        if c == 4095 {
            return Err(DstError::CodeOutOfRange);
        }
        let mut arith = Arith { a: W::from_u32(4095) << W::SCALE, x: W::from_u32(c) << W::SCALE, code };

        // Coded X bit (5.5.8), decoded and discarded.
        let a0 = filters.first().map_or(0, |f| f.coefs[0]);
        let px = u32::from(((a0 & 0x7F) as u8).reverse_bits() >> 1) + 1;
        arith.refill();
        let _ = arith.decode(px);

        // Half-probability lengths (5.4).
        let mut nh = [0usize; MAX_NCH];
        for ch in 0..nch {
            if half[ch] {
                nh[ch] = filters[usize::from(fmap[ch][0])].order;
            }
        }
        Ok(Some(Coded {
            nch,
            fseg,
            pseg,
            fmap,
            pmap,
            orders: filters.iter().map(|f| f.order).collect(),
            nh,
            tables,
            partial,
            luts,
            probes,
            keys: [(usize::MAX, usize::MAX); MAX_NCH],
            arith,
            hist,
            fidx: [0; MAX_NCH],
            pidx: [0; MAX_NCH],
            n: 0,
            fs,
        }))
    }

    /// The next chunk: whole bytes within which, for every channel, the filter and the
    /// ptable are fixed (segment boundaries are multiples of 8), ending at the end of a
    /// half-probability region if it holds one.
    fn span(&self) -> Span<'b> {
        let segment_end = |starts: &[u32], idx: usize| starts.get(idx + 1).map_or(NB, |&b| b as usize);
        let mut span = Span {
            end: NB,
            half: false,
            used: [0; MAX_NCH],
            most: 0,
            tabs: [&ZERO_TABLES; MAX_NCH],
            partial: [&[0; 256]; MAX_NCH],
            luts: [&NO_LUT; MAX_NCH],
            keys: [(0, 0); MAX_NCH],
        };
        for ch in 0..self.nch {
            span.end = span.end.min(segment_end(&self.fseg.starts[ch], self.fidx[ch]));
            span.end = span.end.min(segment_end(&self.pseg.starts[ch], self.pidx[ch]));
            if self.n < self.nh[ch] {
                span.half = true;
                span.end = span.end.min(self.nh[ch].next_multiple_of(8));
            }
            let q = usize::from(self.pmap[ch][self.pidx[ch]]);
            span.luts[ch] = &self.luts[q];
            let f = usize::from(self.fmap[ch][self.fidx[ch]]);
            span.keys[ch] = (f, q);
            span.used[ch] = self.orders[f].div_ceil(8);
            span.most = span.most.max(span.used[ch]);
            let tabs = self.tables.get(f * HISTORY_BYTES..(f + 1) * HISTORY_BYTES);
            span.tabs[ch] = tabs.and_then(|t| t.try_into().ok()).unwrap_or(&ZERO_TABLES);
            span.partial[ch] = &self.partial[f];
        }
        span
    }

    /// Moves to bit `n`, at most the end of the current span, and to the next segments of
    /// the channels that end there.
    fn advance(&mut self, n: usize) {
        let segment_end = |starts: &[u32], idx: usize| starts.get(idx + 1).map_or(NB, |&b| b as usize);
        self.n = n;
        for ch in 0..self.nch {
            if segment_end(&self.fseg.starts[ch], self.fidx[ch]) == n {
                self.fidx[ch] += 1;
            }
            if segment_end(&self.pseg.starts[ch], self.pidx[ch]) == n {
                self.pidx[ch] += 1;
            }
        }
    }

    /// Decodes `span` (the next chunk) through the general loop.
    fn run_general(&mut self, span: &Span<'_>) {
        run_general(self.n, span, self.nch, &self.nh, &mut self.arith, self.hist);
        self.advance(span.end);
    }

    /// The state [`run`] decodes `span` (the next chunk) with.
    fn lane_run<'r>(&'r mut self, span: &Span<'b>) -> LaneRun<'r, 'b, W> {
        for ch in 0..self.nch {
            if self.keys[ch] != span.keys[ch] {
                if let Some(p) = self.probes.get_mut(ch) {
                    p.fill(span.partial[ch], span.luts[ch], byte_lut(self.nch));
                }
                self.keys[ch] = span.keys[ch];
            }
        }
        LaneRun {
            start: self.n / 8,
            tabs: span.tabs,
            probes: self.probes.get(..MAX_NCH).and_then(|p| p.try_into().ok()).unwrap_or(&NO_PROBES),
            arith: &mut self.arith,
            hist: self.hist,
        }
    }

    /// The end-of-frame check of 5.5.7, after the last symbol, and the output.
    fn finish(self, out: &mut [u8]) -> Result<(), DstError> {
        // `ptr` is the index of the next code bit.
        let ptr = 1 + self.arith.code.consumed();
        if self.fs > ptr + 7 {
            return Err(DstError::UnreadCodeBits);
        }
        let first = HISTORY_BYTES * self.nch;
        if let Some(audio) = self.hist.get(first..first + out.len()) {
            out.copy_from_slice(audio);
        }
        Ok(())
    }
}

/// The machine word the arithmetic decoder of 5.5.7 keeps A and C in: `u64` (scale 2^52) or
/// `u32` (scale 2^20). Both give the same symbols, the same renormalisation and the same
/// code position to the bit: A and C are 12-bit integers either way, and the bits below
/// the scale are only the look-ahead of the code bits, which `u32` refills more often. The
/// 32-bit form is for 32-bit targets, where every operation on a `u64` takes a register
/// pair (#369); both are built everywhere, and the tests compare them.
pub(crate) trait Word:
    Copy
    + Ord
    + core::fmt::Debug
    + core::ops::Shl<u32, Output = Self>
    + core::ops::Shr<u32, Output = Self>
    + core::ops::BitOr<Output = Self>
    + core::ops::BitOrAssign
{
    /// The scale of A and C, 2^SCALE: the word's bits but the top 12.
    const SCALE: u32;
    /// How many symbols [`Arith::refill`] provides for: at most 8 code bits each.
    const PER_REFILL: usize = (Self::SCALE / 8) as usize;
    fn from_u32(v: u32) -> Self;
    /// The top 5 bits of A x 2^SCALE (A is below 4096).
    fn top5(self) -> usize;
    /// The word stored big-endian at `bytes[at..]`, or 0 if `bytes` ends before it.
    fn load(bytes: &[u8], at: usize) -> Self;
    fn wrapping_sub(self, b: Self) -> Self;
    fn wrapping_mul(self, b: Self) -> Self;
    fn wrapping_shl(self, k: u32) -> Self;
    fn leading_zeros(self) -> u32;
    fn q(probe: &Probe) -> &QTable<Self>;
    fn scaled(probe: &Probe) -> &ScaledLut<Self>;
}

macro_rules! word {
    ($t:ty, $q:ident, $scaled:ident) => {
        impl Word for $t {
            const SCALE: u32 = <$t>::BITS - 12;
            #[inline(always)]
            fn from_u32(v: u32) -> Self {
                v as $t
            }
            #[inline(always)]
            fn top5(self) -> usize {
                (self >> (Self::SCALE + 7)) as usize
            }
            #[inline(always)]
            fn load(bytes: &[u8], at: usize) -> Self {
                const N: usize = core::mem::size_of::<$t>();
                bytes.get(at..at + N).map_or(0, |w| {
                    let mut b = [0u8; N];
                    b.copy_from_slice(w);
                    <$t>::from_be_bytes(b)
                })
            }
            #[inline(always)]
            fn wrapping_sub(self, b: Self) -> Self {
                <$t>::wrapping_sub(self, b)
            }
            #[inline(always)]
            fn wrapping_mul(self, b: Self) -> Self {
                <$t>::wrapping_mul(self, b)
            }
            #[inline(always)]
            fn wrapping_shl(self, k: u32) -> Self {
                <$t>::wrapping_shl(self, k)
            }
            #[inline(always)]
            fn leading_zeros(self) -> u32 {
                <$t>::leading_zeros(self)
            }
            #[inline(always)]
            fn q(probe: &Probe) -> &QTable<Self> {
                &probe.$q
            }
            #[inline(always)]
            fn scaled(probe: &Probe) -> &ScaledLut<Self> {
                &probe.$scaled
            }
        }
    };
}
word!(u64, q, scaled);
word!(u32, q32, scaled32);

/// The [`Word`] the decoder uses: the target's pointer width (#369).
#[cfg(target_pointer_width = "64")]
pub(crate) type Native = u64;
/// The [`Word`] the decoder uses: the target's pointer width (#369).
#[cfg(not(target_pointer_width = "64"))]
pub(crate) type Native = u32;

/// The arithmetic decoder of 5.5.7.
///
/// A and C are kept x 2^S (S = [`Word::SCALE`], 52 or 20): A as `a`, and C as the top 12
/// bits of `x`; below it are the code bits that follow (from `code.pos` on), of which
/// [`Arith::refill`] makes at least S valid. A symbol takes at most 8 bits, so up to
/// [`Word::PER_REFILL`] symbols (6 or 2) can be decoded per refill: shifting `x` left by the
/// renormalisation count then both doubles C and appends the next bits.
#[derive(Clone, Copy)]
struct Arith<'a, W: Word> {
    a: W,
    x: W,
    code: CodeBits<'a>,
}

impl<W: Word> Arith<'_, W> {
    /// Fills the S bits below C with the code bits from `code.pos` on. Bits already there
    /// are the same code bits, and those shifted in are 0, so an OR does it.
    #[inline(always)]
    fn refill(&mut self) {
        self.x |= self.code.peek::<W>() >> 12;
    }

    /// Decodes one symbol with probability `p` (1 to 128) and renormalises by the whole
    /// shift count at once (A < 2048 doubles until bit 11 is set). At most 6 calls per
    /// [`Arith::refill`].
    #[inline(always)]
    fn decode(&mut self, p: u32) -> u32 {
        // A is 2048 to 4095 here (4095 at the start, then renormalised), so Q is 8 to 15
        // and Q x p is at most A / 2 + 128 < A: nothing below wraps, and the wrapping
        // forms only spare the hot loop the overflow checks. Everything is x 2^S, like C.
        // Q is floor(A / 256) with bit 0 ORed with bit 7 of A: from t = floor(A / 128). Worked
        // out at the scale of 1, it holds no constant in a register.
        let a = self.a;
        let t = a.top5() as u32;
        let q = (t >> 1) | (t & 1);
        let w0 = W::from_u32(q.wrapping_mul(p)) << W::SCALE;
        let w1 = a.wrapping_sub(w0);
        let zero = self.x >= w1;
        // C - W1 if that does not wrap, else C: the smaller of the two.
        let x = self.x.wrapping_sub(w1).min(self.x);
        let a = if zero { w0 } else { w1 };
        // A is 8 to 4095 here (w0 >= 8, w1 >= 128), so the shift is 0 to 8; C stays
        // below A, so nothing leaves the top of x.
        let k = a.leading_zeros();
        self.a = a.wrapping_shl(k);
        self.x = x.wrapping_shl(k);
        self.code.skip(k);
        u32::from(!zero)
    }

    /// [`Arith::decode`] with Q from `q`, a [`QTable`] the caller reaches without another
    /// register. The same to the bit.
    #[inline(always)]
    fn decode_table(&mut self, p: u32, q: &QTable<W>) -> u32 {
        // A is 2048 to 4095, so its top 5 bits are below 32. Nothing wraps; see `decode`.
        let a = self.a;
        let w0 = q[a.top5()].wrapping_mul(W::from_u32(p));
        let w1 = a.wrapping_sub(w0);
        let zero = self.x >= w1;
        // C - W1 if that does not wrap, else C: the smaller of the two.
        let x = self.x.wrapping_sub(w1).min(self.x);
        let a = if zero { w0 } else { w1 };
        let k = a.leading_zeros();
        self.a = a.wrapping_shl(k);
        self.x = x.wrapping_shl(k);
        self.code.skip(k);
        u32::from(!zero)
    }

    /// [`Arith::decode`] with `p` given x 2^S (a [`ScaledLut`] entry), the same to the
    /// bit: Q x p is one multiply from the top 5 bits of A.
    #[inline(always)]
    fn decode_scaled(&mut self, p: W) -> u32 {
        // Q is floor(A / 256) with bit 0 ORed with bit 7 of A: from t = floor(A / 128).
        let t = self.a.top5() as u32;
        let q = W::from_u32((t >> 1) | (t & 1));
        let w0 = q.wrapping_mul(p);
        let w1 = self.a.wrapping_sub(w0);
        let zero = self.x >= w1;
        // C - W1 if that does not wrap, else C: the smaller of the two.
        let x = self.x.wrapping_sub(w1).min(self.x);
        let a = if zero { w0 } else { w1 };
        let k = a.leading_zeros();
        self.a = a.wrapping_shl(k);
        self.x = x.wrapping_shl(k);
        self.code.skip(k);
        u32::from(!zero)
    }
}

/// Decodes one symbol for [`run_general`]: the prediction from the shares of the
/// complete bytes (`base`) and of the bits already decoded in the byte
/// (`partial[2^r | bits]`), the probability (128 in the half-probability region, 5.5.5),
/// and the output bit.
#[inline(always)]
fn symbol<W: Word>(
    ar: &mut Arith<'_, W>,
    base: i16,
    partial: &[i16; 256],
    idx: u32,
    lut: &Lut,
    half: bool,
) -> u32 {
    // The wrapping sum is S reduced as 5.5.3 does (32768 becomes -32768).
    let spred = base.wrapping_add(partial[(idx & 0xFF) as usize]);
    let sign = u32::from(spred < 0);
    // Probability (5.5.4).
    let p = if half { 128 } else { probability(spred, lut).0 };
    sign ^ ar.decode(p)
}

/// The probability (5.5.4) and sign indicator (5.5.3) of a prediction outside the
/// half-probability region.
#[inline(always)]
fn probability(spred: i16, lut: &Lut) -> (u32, u32) {
    // |Spred| / 8 is at most 4096, and the table needs no clamp to `M_q - 1` (5.5.4).
    (u32::from(lut[usize::from(spred.unsigned_abs() >> 3)]), u32::from(spred < 0))
}

/// [`probability`] from a [`ScaledLut`], p x 2^S.
#[inline(always)]
fn probability_scaled<W: Word>(spred: i16, lut: &ScaledLut<W>) -> (W, u32) {
    // 5.5.4's `min(|Spred| / 8, M_q - 1)`, with the last entry repeated up to 64.
    let j = usize::from(spred.unsigned_abs() >> 3).min(MAX_PTABLE_LEN - 1);
    (lut[j], u32::from(spred < 0))
}

/// The `WINDOW` bytes of [`Lane::hist`] from the history of byte `m` of `nch` channels on:
/// complete byte `d` (0 the newest) of channel c is at `(HISTORY_BYTES - 1 - d) x nch + c`.
#[inline(always)]
fn window(hist: &[u8], m: usize, nch: usize) -> &[u8; WINDOW] {
    // `hist` always holds them (it has `WINDOW` spare bytes after the output).
    hist.get(m * nch..m * nch + WINDOW).and_then(|w| w.try_into().ok()).unwrap_or(&[HISTORY_FILL; WINDOW])
}

/// The sum of the rows of tables `FROM..U` of channel `ch` (of `NCH`) for the byte
/// `FROM` after the one whose history is `w`: table d takes complete byte `d - FROM`.
#[inline(always)]
fn rows<const NCH: usize, const U: usize, const FROM: usize>(
    tables: &[ByteTable; HISTORY_BYTES],
    w: &[u8; WINDOW],
    ch: usize,
) -> Row {
    let mut sum = [0i16; 8];
    add_rows::<NCH, FROM, FROM, U>(&mut sum, tables, w, ch);
    sum
}

/// Adds the rows of tables `LO..HI` (`LO >= FROM`) to `sum`, as [`rows`] sums them.
#[inline(always)]
fn add_rows<const NCH: usize, const FROM: usize, const LO: usize, const HI: usize>(
    sum: &mut Row,
    tables: &[ByteTable; HISTORY_BYTES],
    w: &[u8; WINDOW],
    ch: usize,
) {
    // A loop over constant bounds, which is unrolled with each byte's position known.
    #[allow(clippy::needless_range_loop)]
    for d in LO..HI.min(HISTORY_BYTES) {
        let byte = w[(HISTORY_BYTES - 1 + FROM - d) * NCH + ch];
        let row = &tables[d][usize::from(byte)];
        for r in 0..8 {
            // 16 rows of at most 2048 and a partial share: the sum can wrap only as 5.5.3
            // reduces S.
            sum[r] = sum[r].wrapping_add(row[r]);
        }
    }
}

/// Most symbols per bit position (frames x channels) for which [`run`] unrolls a whole
/// byte; beyond, the loop body would outgrow the instruction caches (inferred: no front-end
/// counters were taken). Measured on Zen 2 (#203): at 10, 5 channels in 2 frames run fewer
/// instructions unrolled but take more cycles.
const UNROLL_BYTE: usize = 9;

/// A row on the stack of [`run`], aligned so that no vector access of it splits a cache line.
#[derive(Clone, Copy)]
#[repr(align(16))]
struct Aligned([i16; 8]);

/// One frame's part in [`run`]: its chunk from byte `start` on and its decoding state.
struct LaneRun<'r, 'b, W: Word> {
    start: usize,
    tabs: [&'b [ByteTable; HISTORY_BYTES]; MAX_NCH],
    probes: &'r [Probe; MAX_NCH],
    arith: &'r mut Arith<'b, W>,
    hist: &'r mut [u8],
}

/// Decodes `bytes` bytes of every channel of `K` frames (exactly `K` lanes) of `NCH`
/// channels (1 to 6), each from its own start, outside any half-probability region, with
/// the first `U` history bytes (the tables beyond a filter's order are zero). Each
/// frame's symbols are in the order of 5.5.1; the frames take turns symbol by symbol, so
/// that their arithmetic decoders, which are independent, overlap.
///
/// A function of its own, for the build without run-time features; `dispatch` inlines
/// [`run_inline`] instead.
#[inline(never)]
fn run<const K: usize, const NCH: usize, const U: usize, W: Word>(
    lanes: &mut [LaneRun<'_, '_, W>],
    bytes: usize,
) {
    run_inline::<K, NCH, W>(lanes, bytes, U);
}

/// The shares of the first `u` tables (4, 8 or 16; [`rows`]) of every frame and channel of
/// [`run_inline`], for the byte `FROM` after byte `at` of each frame's chunk. Tables 4 to 7
/// and 8 to 15 are added only when `u` reaches them, so that one copy serves every `u`;
/// with `u` a constant, the optimiser drops the tests.
#[inline(always)]
#[allow(clippy::needless_range_loop)]
fn shares<const K: usize, const NCH: usize, const FROM: usize, W: Word>(
    out: &mut [[Aligned; NCH]; K],
    lanes: &[LaneRun<'_, '_, W>; K],
    tabs: &[[&[ByteTable; HISTORY_BYTES]; NCH]; K],
    at: usize,
    u: usize,
) {
    let windows: [&[u8; WINDOW]; K] =
        core::array::from_fn(|l| window(lanes[l].hist, lanes[l].start + at, NCH));
    for l in 0..K {
        for ch in 0..NCH {
            out[l][ch] = Aligned(rows::<NCH, 4, FROM>(tabs[l][ch], windows[l], ch));
        }
    }
    if u > 4 {
        for l in 0..K {
            for ch in 0..NCH {
                add_rows::<NCH, FROM, 4, 8>(&mut out[l][ch].0, tabs[l][ch], windows[l], ch);
            }
        }
    }
    if u > 8 {
        for l in 0..K {
            for ch in 0..NCH {
                add_rows::<NCH, FROM, 8, 16>(&mut out[l][ch].0, tabs[l][ch], windows[l], ch);
            }
        }
    }
}

/// [`run`] with the first `u` history bytes (4, 8 or 16), always inlined.
///
/// `u` is an argument rather than a const parameter so that [`DstDecoder::group`] can inline
/// one copy of the symbol loop for all three: without optimisation every inlined copy keeps
/// its own stack slots, and the 72 copies of `K`, `NCH` and `u` made the frame of each
/// function that inlines them about 1 MiB, more than half of a new thread's stack (#336).
/// Only the rows ([`shares`]) then depend on `u`, which they test byte by byte. `group`
/// passes `u` so where the byte is unrolled (`K x NCH <= UNROLL_BYTE`), whose copies are the
/// large ones, and elsewhere as a constant, which the optimiser folds: measured on Zen 2
/// (3950X, #336), with `u` tested in the loop there, 6 channels in 2 frames took about 1 %
/// longer in the generic build.
#[inline(always)]
#[allow(clippy::needless_range_loop)]
fn run_inline<const K: usize, const NCH: usize, W: Word>(
    lanes: &mut [LaneRun<'_, '_, W>],
    bytes: usize,
    u: usize,
) {
    let Ok(lanes) = <&mut [LaneRun<'_, '_, W>; K]>::try_from(lanes) else {
        return;
    };
    let mut ar: [Arith<'_, W>; K] = core::array::from_fn(|l| *lanes[l].arith);
    let tabs: [[&[ByteTable; HISTORY_BYTES]; NCH]; K] =
        core::array::from_fn(|l| core::array::from_fn(|ch| lanes[l].tabs[ch]));
    let probes: [&[Probe; MAX_NCH]; K] = core::array::from_fn(|l| lanes[l].probes);
    // Per frame and channel, the shares of the complete bytes at each bit of the current
    // byte.
    let mut base = [[Aligned([0i16; 8]); NCH]; K];
    shares::<K, NCH, 0, W>(&mut base, lanes, &tabs, 0, u);
    for i in 0..bytes {
        // The shares at the next byte of every complete byte but the newest (which is
        // the current byte).
        let mut rest = [[Aligned([0i16; 8]); NCH]; K];
        shares::<K, NCH, 1, W>(&mut rest, lanes, &tabs, i, u);
        // The bits of the byte so far. The loop that does not unroll the bit position starts
        // them from a marker bit, so that they are the index `2^r | bits` of `Probe::partial`
        // as they stand; 8 shifts move the marker out of the low byte, which is all that is
        // read after the loop.
        let mut cur = [[if K * NCH <= UNROLL_BYTE { 0u32 } else { 1 }; NCH]; K];
        // A refill waits for the position after the previous symbol, so it is done as
        // rarely as allowed: before every `W::PER_REFILL` symbols, counted from the byte's
        // first.
        macro_rules! symbol {
            ($r:literal, $ch:literal, $l:literal) => {
                if $ch < NCH && $l < K {
                    if ($r * NCH + $ch) % W::PER_REFILL == 0 {
                        ar[$l].refill();
                    }
                    let idx = ((1 << $r) | cur[$l][$ch]) as usize & 0xFF;
                    let probe = &probes[$l][$ch];
                    let spred = base[$l][$ch].0[$r].wrapping_add(probe.partial[idx]);
                    let y = if const { byte_lut(NCH) } {
                        let (p, sign) = probability(spred, &probe.lut);
                        // One frame alone (K = 1) of 5 or 6 channels takes Q by shifts, the
                        // same to the bit: with no other frame to overlap with, the table's
                        // load lengthens its serial chain (#378). Measured on Zen 2: 4 to
                        // 5 % faster for 5 and 6 channels, 1 to 4 % slower for 1 and 2.
                        if K == 1 && NCH >= 5 {
                            sign ^ ar[$l].decode(p)
                        } else {
                            sign ^ ar[$l].decode_table(p, W::q(&probes[$l][0]))
                        }
                    } else {
                        let (p, sign) = probability_scaled(spred, W::scaled(probe));
                        sign ^ ar[$l].decode_scaled(p)
                    };
                    cur[$l][$ch] = (cur[$l][$ch] << 1) | y;
                }
            };
        }
        // Frames and channels unrolled by hand, so that their state stays in registers.
        macro_rules! lanes {
            ($r:literal, $ch:literal) => {
                symbol!($r, $ch, 0);
                symbol!($r, $ch, 1);
                symbol!($r, $ch, 2);
                symbol!($r, $ch, 3);
            };
        }
        macro_rules! bit {
            ($r:literal) => {
                lanes!($r, 0);
                lanes!($r, 1);
                lanes!($r, 2);
                lanes!($r, 3);
                lanes!($r, 4);
                lanes!($r, 5);
            };
        }
        // The same with the bit position not unrolled (a smaller loop body for many
        // symbols per byte), refilling before every `W::PER_REFILL`-th channel from channel 0:
        // at most that many symbols apart.
        macro_rules! symbol_at {
            ($r:ident, $ch:literal, $l:literal) => {
                if $ch < NCH && $l < K {
                    if $ch % W::PER_REFILL == 0 {
                        ar[$l].refill();
                    }
                    let idx = cur[$l][$ch] as usize & 0xFF;
                    let probe = &probes[$l][$ch];
                    let spred = base[$l][$ch].0[$r].wrapping_add(probe.partial[idx]);
                    let y = if const { byte_lut(NCH) } {
                        let (p, sign) = probability(spred, &probe.lut);
                        // One frame alone (K = 1) of 5 or 6 channels takes Q by shifts, the
                        // same to the bit: with no other frame to overlap with, the table's
                        // load lengthens its serial chain (#378). Measured on Zen 2: 4 to
                        // 5 % faster for 5 and 6 channels, 1 to 4 % slower for 1 and 2.
                        if K == 1 && NCH >= 5 {
                            sign ^ ar[$l].decode(p)
                        } else {
                            sign ^ ar[$l].decode_table(p, W::q(&probes[$l][0]))
                        }
                    } else {
                        let (p, sign) = probability_scaled(spred, W::scaled(probe));
                        sign ^ ar[$l].decode_scaled(p)
                    };
                    cur[$l][$ch] = (cur[$l][$ch] << 1) | y;
                }
            };
        }
        macro_rules! lanes_at {
            ($r:ident, $ch:literal) => {
                symbol_at!($r, $ch, 0);
                symbol_at!($r, $ch, 1);
                symbol_at!($r, $ch, 2);
                symbol_at!($r, $ch, 3);
            };
        }
        if K * NCH <= UNROLL_BYTE {
            bit!(0);
            bit!(1);
            bit!(2);
            bit!(3);
            bit!(4);
            bit!(5);
            bit!(6);
            bit!(7);
        } else {
            for r in 0..8 {
                lanes_at!(r, 0);
                lanes_at!(r, 1);
                lanes_at!(r, 2);
                lanes_at!(r, 3);
                lanes_at!(r, 4);
                lanes_at!(r, 5);
            }
        }
        for l in 0..K {
            // The byte's 8 bits are the output byte (5.5.9), and the newest history byte.
            let at = (HISTORY_BYTES + lanes[l].start + i) * NCH;
            if let Some(dst) = lanes[l].hist.get_mut(at..at + NCH) {
                for (d, &c) in dst.iter_mut().zip(cur[l].iter()) {
                    *d = c as u8;
                }
            }
            for ch in 0..NCH {
                let row = &tabs[l][ch][0][(cur[l][ch] & 0xFF) as usize];
                base[l][ch] = Aligned(core::array::from_fn(|r| rest[l][ch].0[r].wrapping_add(row[r])));
            }
        }
    }
    for l in 0..K {
        *lanes[l].arith = ar[l];
    }
}

/// Decodes bytes `start / 8 .. span.end / 8` of `nch` channels, with probability 128 for
/// bits `n < nh[c]` of channel c (5.5.5).
#[allow(clippy::needless_range_loop)]
fn run_general<W: Word>(
    start: usize,
    span: &Span<'_>,
    nch: usize,
    nh: &[usize; MAX_NCH],
    arith: &mut Arith<'_, W>,
    hist: &mut [u8],
) {
    for m in start / 8..span.end / 8 {
        let mut base = [[0i16; 8]; MAX_NCH];
        for ch in 0..nch {
            for d in 0..span.used[ch] {
                let byte = hist.get((HISTORY_BYTES + m - 1 - d) * nch + ch).copied().unwrap_or(0);
                let row = &span.tabs[ch][d][usize::from(byte)];
                for r in 0..8 {
                    // As in `rows`.
                    base[ch][r] = base[ch][r].wrapping_add(row[r]);
                }
            }
        }
        let mut cur = [0u32; MAX_NCH];
        for r in 0..8u32 {
            for ch in 0..nch {
                arith.refill();
                let half = 8 * m + (r as usize) < nh[ch];
                let idx = (1 << r) | cur[ch];
                let y = symbol(arith, base[ch][r as usize], span.partial[ch], idx, span.luts[ch], half);
                cur[ch] = (cur[ch] << 1) | y;
            }
        }
        let at = (HISTORY_BYTES + m) * nch;
        if let Some(dst) = hist.get_mut(at..at + nch) {
            for (d, &c) in dst.iter_mut().zip(cur.iter()) {
                *d = c as u8;
            }
        }
    }
}

/// Probability lookup tables have one entry per value of |Spred| / 8 (0 to 4096): a
/// ptable's entries (at most 64, 5.3.6), then its last one repeated. They are padded to
/// 8192 so that any `u16 >> 3` indexes them without a check.
const LUT_LEN: usize = 8192;

/// The entries of a [`Lut`] that can be read: |Spred| / 8 is at most 4096.
const LUT_USED: usize = 4097;

/// A probability lookup table: each entry is p, 1 to 128.
type Lut = [u8; LUT_LEN];

/// The first 64 entries of a [`Lut`] x 2^S, the scale of [`Arith`], indexed by
/// `min(|Spred| / 8, 63)` ([`probability_scaled`]).
pub(crate) type ScaledLut<W> = [W; MAX_PTABLE_LEN];

/// Q (5.5.7) x 2^S, the scale of [`Arith`], indexed by the top 5 bits of A x 2^52: with
/// t = floor(A / 128), Q is floor(t / 2) with bit 0 ORed with bit 0 of t.
///
/// One load instead of a shift and two logic operations before the multiply and a shift after
/// it. Measured on Zen 2 (#203), where the 2-channel loop is bound by its integer operations
/// rather than by the arithmetic decoder's chain, which this lengthens.
pub(crate) type QTable<W> = [W; 32];

const fn q_table() -> QTable<u64> {
    let mut q = [0; 32];
    let mut t = 0;
    while t < 32 {
        q[t] = (((t >> 1) | (t & 1)) as u64) << 52;
        t += 1;
    }
    q
}

/// [`q_table`] at the scale of `u32`, 2^20.
const fn q_table32() -> QTable<u32> {
    let wide = q_table();
    let mut q = [0; 32];
    let mut t = 0;
    while t < 32 {
        q[t] = (wide[t] >> 32) as u32;
        t += 1;
    }
    q
}

/// Whether [`run`] decodes `nch` channels with [`Lut`]s and [`Arith::decode`] (true) or with
/// [`ScaledLut`]s and [`Arith::decode_scaled`]. The output is the same; the speed is not, and
/// not monotonically in `nch`. The scaled form has the shorter multiply but adds the clamp
/// to the serial chain of every symbol.
///
/// Chosen by measurement on Zen 2 (Ryzen 9 3950X, generic build, decoding generated frames
/// of each channel count, #203); see the commit that changed it.
const fn byte_lut(nch: usize) -> bool {
    !matches!(nch, 3 | 4)
}

/// The partial shares (see [`Lane::partial`]) and probability table of one channel of a
/// chunk, copied together so that [`run`] reaches both from one address per frame, with
/// the channel's offset a constant, and holds fewer addresses in registers. Only the table
/// [`byte_lut`] chooses for the frame's channel count is filled, in both [`Word`]s. `q` never
/// changes; [`run`] reads channel 0's for every channel, so that only one is in the cache.
/// The `u32` tables come last, so that the layout of the `u64` ones is as before.
#[derive(Clone, Debug)]
#[repr(C, align(64))]
pub(crate) struct Probe {
    partial: [i16; 256],
    scaled: ScaledLut<u64>,
    q: QTable<u64>,
    lut: Lut,
    scaled32: ScaledLut<u32>,
    q32: QTable<u32>,
}

impl Probe {
    fn fill(&mut self, partial: &[i16; 256], lut: &Lut, byte: bool) {
        self.partial = *partial;
        if byte {
            // Only the entries that can be read (see [`Lane::build_luts`]).
            self.lut[..LUT_USED].copy_from_slice(&lut[..LUT_USED]);
        } else {
            for ((s, s32), &p) in self.scaled.iter_mut().zip(self.scaled32.iter_mut()).zip(lut) {
                *s = u64::from(p) << u64::SCALE;
                *s32 = u32::from(p) << u32::SCALE;
            }
        }
    }
}

const NO_PROBE: Probe = Probe {
    partial: [0; 256],
    scaled: [128 << u64::SCALE; MAX_PTABLE_LEN],
    q: q_table(),
    lut: [128; LUT_LEN],
    scaled32: [128 << u32::SCALE; MAX_PTABLE_LEN],
    q32: q_table32(),
};

/// The probes of the channels that are not decoded.
static NO_PROBES: [Probe; MAX_NCH] = [NO_PROBE; MAX_NCH];

/// The probability table of the channels that are not decoded.
static NO_LUT: Lut = [128; LUT_LEN];

/// The code bits cb[1], cb[2], ... of a frame, read MSB first; bits at or after the end
/// of the code read as 0 (5.3.7 item 3). Each read is one unaligned 8-byte load from a
/// realigned copy padded with zero bytes.
#[derive(Clone, Copy)]
struct CodeBits<'a> {
    bytes: &'a [u8],
    pos: usize,
}

/// Zero bytes after the realigned code, so that every 8-byte load inside the code exists.
const CODE_PADDING: usize = 8;

impl<'a> CodeBits<'a> {
    /// Copies the `len` code bits starting at bit `start` of `frame` into `buf`,
    /// realigned so that they start at bit 7 of byte 0, with every bit after them 0.
    fn new(buf: &'a mut Vec<u8>, frame: &[u8], start: usize, len: usize) -> Self {
        buf.clear();
        let shift = (start % 8) as u32;
        let first = start / 8;
        let nbytes = len.div_ceil(8);
        let src = frame.get(first..).unwrap_or(&[]);
        let realign = |hi: u8, lo: u8| (((u16::from(hi) << 8 | u16::from(lo)) << shift) >> 8) as u8;
        buf.extend(src.windows(2).take(nbytes).map(|w| realign(w[0], w[1])));
        // The last byte of the frame, if it is needed, has no byte after it.
        if buf.len() < nbytes {
            if let Some(&b) = src.get(buf.len()) {
                buf.push(realign(b, 0));
            }
        }
        buf.resize(nbytes, 0);
        if len % 8 != 0 {
            if let Some(last) = buf.last_mut() {
                *last &= 0xFF << (8 - len % 8);
            }
        }
        buf.extend_from_slice(&[0; CODE_PADDING]);
        CodeBits { bytes: buf, pos: 0 }
    }

    /// The next bits, from the most significant bit on, without taking them: all but the
    /// last 7 of a `W` or more.
    #[inline(always)]
    fn peek<W: Word>(&self) -> W {
        // Past the padded copy every bit is 0 (the code can be read beyond its end).
        W::load(self.bytes, self.pos / 8) << (self.pos % 8) as u32
    }

    /// Takes `k` bits.
    #[inline(always)]
    fn skip(&mut self, k: u32) {
        // At most 8 bits per symbol, a few million per frame: no wrap.
        self.pos = self.pos.wrapping_add(k as usize);
    }

    /// The next 12 bits as an integer.
    fn take12(&mut self) -> u32 {
        let v = (self.peek::<u64>() >> 52) as u32;
        self.skip(12);
        v
    }

    /// How many code bits (after cb[0]) have been taken.
    fn consumed(&self) -> usize {
        self.pos
    }
}

/// A plain frame (`DST_coded` = 0, specification 5, 5.2.1 item 2).
fn plain(frame: &[u8], out: &mut [u8]) -> Result<(), DstError> {
    if frame[0] & 0x3F != 0 {
        return Err(DstError::Stuffing);
    }
    let payload = &frame[1..];
    let n = payload.len().min(out.len());
    out[..n].copy_from_slice(&payload[..n]);
    out[n..].fill(0);
    Ok(())
}

fn read_filter(bits: &mut Bits<'_>) -> Result<Filter, DstError> {
    let order = bits.read(7)? as usize + 1;
    let mut values = [0i64; MAX_ORDER];
    if bits.bit()? == 0 {
        for v in values.iter_mut().take(order) {
            *v = i64::from(bits.read_tc9()?);
        }
    } else {
        let method = bits.read(2)? as usize;
        if method == 3 {
            return Err(DstError::CoefficientCoding);
        }
        let k = method + 1;
        if k >= order {
            return Err(DstError::CoefficientCoding);
        }
        for v in values.iter_mut().take(k) {
            *v = i64::from(bits.read_tc9()?);
        }
        let m = bits.read(3)?;
        for i in k..order {
            let r = bits.rice(m)?;
            let x: i64 = (0..k).map(|t| COEF_PRED[method][t] * values[i - 1 - t]).sum();
            let a = r - round8(x);
            if !(-256..=255).contains(&a) {
                return Err(DstError::CoefficientRange);
            }
            values[i] = a;
        }
    }
    let mut coefs = [0i32; MAX_ORDER];
    for (c, &v) in coefs.iter_mut().zip(values.iter()) {
        // Every value is within -256 to 255.
        *c = v as i32;
    }
    Ok(Filter { order, coefs })
}

fn read_ptable(bits: &mut Bits<'_>) -> Result<Vec<u32>, DstError> {
    let len = bits.read(6)? as usize + 1;
    if len == 1 {
        return Ok(vec![128]);
    }
    let mut values = [0i64; MAX_PTABLE_LEN];
    if bits.bit()? == 0 {
        for v in values.iter_mut().take(len) {
            *v = i64::from(bits.read(7)?) + 1;
        }
    } else {
        let method = bits.read(2)? as usize;
        if method == 3 {
            return Err(DstError::PtableCoding);
        }
        let k = method + 1;
        if k >= len {
            return Err(DstError::PtableCoding);
        }
        for v in values.iter_mut().take(k) {
            *v = i64::from(bits.read(7)?) + 1;
        }
        let m = bits.read(3)?;
        for i in k..len {
            let r = bits.rice(m)?;
            let x: i64 = (0..k).map(|t| PTABLE_PRED[method][t] * values[i - 1 - t]).sum();
            let p = r - round8(x);
            if !(1..=128).contains(&p) {
                return Err(DstError::PtableRange);
            }
            values[i] = p;
        }
    }
    // Every value is within 1 to 128.
    Ok(values[..len].iter().map(|&v| v as u32).collect())
}

/// Decodes one frame with a fresh decoder. See [`DstDecoder::decode`].
///
/// # Errors
///
/// As [`DstDecoder::decode`].
pub fn decode(frame: &[u8], channels: u8, out: &mut [u8]) -> Result<(), DstError> {
    DstDecoder::new().decode(frame, channels, out)
}

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

    /// A new decoder runs with the detected instruction set, not the generic one.
    #[test]
    fn new_decoder_uses_the_detected_isa() {
        assert_eq!(DstDecoder::new().isa, Isa::detect());
    }

    #[test]
    fn bitlen_examples() {
        assert_eq!([0, 1, 2, 3, 4, 7, 4576].map(bitlen), [0, 1, 2, 2, 3, 3, 13]);
    }

    /// `core-dispatch-avx2` really runs the wrapper. This test exists only in a Miri build
    /// with the features, and the slice requires it by name: if the slice loses its flags,
    /// the test is gone and the slice fails; if [`Isa::detect`] comes to need a feature the
    /// flags don't enable, this fails. (It is here because `dispatch.rs` may name
    /// `target_feature` only on its wrapper: `tests/common/unsafe_scan.rs`.)
    #[cfg(all(
        miri,
        target_feature = "avx2",
        target_feature = "bmi1",
        target_feature = "bmi2",
        target_feature = "lzcnt",
        target_feature = "movbe"
    ))]
    #[test]
    fn miri_slice_selects_the_wrapper() {
        assert_ne!(Isa::detect(), Isa::generic());
    }

    #[test]
    fn round8_floors() {
        assert_eq!(round8(-5), -1);
        assert_eq!(round8(-4), 0);
    }

    #[test]
    fn plain_frames() {
        crate::dispatch::testutil::with_big_stack(plain_frames_body);
    }

    fn plain_frames_body() {
        let mut out = vec![1u8; 2 * FRAME_BYTES_PER_CHANNEL];
        decode(&[0x40, 7, 8], 2, &mut out).unwrap();
        assert_eq!(&out[..3], &[7, 8, 0]);
        assert!(out[2..].iter().all(|&b| b == 0));
        assert_eq!(decode(&[0x01, 7], 2, &mut out), Err(DstError::Stuffing));
        assert_eq!(decode(&[0x00], 2, &mut out), Err(DstError::FrameTooShort));
        assert_eq!(decode(&[0x00, 1], 7, &mut out), Err(DstError::InvalidArguments));
    }

    // One test per frame count, so that Miri can run them in parallel jobs: this check is
    // most of Miri's time on the crate (#76).
    #[test]
    fn fast_loop_matches_general_1_frame() {
        fast_loop_matches_general::<u64>(1);
    }

    #[test]
    fn fast_loop_matches_general_1_frame_u32() {
        fast_loop_matches_general::<u32>(1);
    }

    #[test]
    fn fast_loop_matches_general_2_frames() {
        fast_loop_matches_general::<u64>(2);
    }

    #[test]
    fn fast_loop_matches_general_2_frames_u32() {
        fast_loop_matches_general::<u32>(2);
    }

    #[test]
    fn fast_loop_matches_general_3_frames() {
        fast_loop_matches_general::<u64>(3);
    }

    #[test]
    fn fast_loop_matches_general_3_frames_u32() {
        fast_loop_matches_general::<u32>(3);
    }

    #[test]
    fn fast_loop_matches_general_4_frames() {
        fast_loop_matches_general::<u64>(4);
    }

    #[test]
    fn fast_loop_matches_general_4_frames_u32() {
        fast_loop_matches_general::<u32>(4);
    }

    /// The lockstep loop of `k` frames and constant channel and table counts against the
    /// general loop run on each frame alone, with channels using different numbers of tables
    /// (zero beyond), frames at different positions with different histories and code, for
    /// every channel count and table count. With the arithmetic decoder in `W` (both [`Word`]s
    /// are tested on every target).
    fn fast_loop_matches_general<W: Word>(k: usize) {
        assert!((1..=MAX_LANES).contains(&k));
        let mut seed = 0x9E37_79B9_7F4A_7C15u64 ^ k as u64;
        let mut rnd = move || {
            seed ^= seed << 13;
            seed ^= seed >> 7;
            seed ^= seed << 17;
            seed
        };
        let code: Vec<u8> = (0..1024).map(|_| rnd() as u8).collect();
        let mut random: Vec<ByteTable> = Vec::new();
        for _ in 0..3 {
            random.push(core::array::from_fn(|_| core::array::from_fn(|_| (rnd() % 4097) as i16 - 2048)));
        }
        // For every number of tables used, 1 to 16: that many tables, then zero tables.
        let tables: Vec<[ByteTable; HISTORY_BYTES]> = (0..=HISTORY_BYTES)
            .map(|used| core::array::from_fn(|d| if d < used { random[d % 3] } else { [[0; 8]; 256] }))
            .collect();
        let partials: Vec<[i16; 256]> =
            (0..2).map(|_| core::array::from_fn(|_| (rnd() % 3585) as i16 - 1792)).collect();
        // As `build_luts` makes them: 64 entries, then the last one repeated.
        let luts: Vec<Lut> = (0..2)
            .map(|k| core::array::from_fn(|j| ((j.min(MAX_PTABLE_LEN - 1) * (k + 1) + k) % 128 + 1) as u8))
            .collect();
        let chunks: &[(usize, usize)] =
            if cfg!(miri) { &[(0, 0), (8, 24)] } else { &[(0, 0), (8, 16), (24, 96)] };
        for nch in 1..=MAX_NCH {
            for u in [4, 8, 16] {
                for &(start, end) in chunks {
                    // Frame l starts 64 l bits later; channel c of frame l uses u - (c + l)
                    // tables (at least 1).
                    let spans: Vec<Span<'_>> = (0..k)
                        .map(|l| {
                            let used = core::array::from_fn(|c| u - (c + l).min(u - 1));
                            Span {
                                end: end + 64 * l,
                                half: false,
                                used,
                                most: u,
                                tabs: core::array::from_fn(|c| &tables[used[c]]),
                                partial: core::array::from_fn(|c| &partials[(c + l) % 2]),
                                luts: core::array::from_fn(|c| &luts[(c + 2 * l) % 3 % 2]),
                                keys: [(0, 0); MAX_NCH],
                            }
                        })
                        .collect();
                    let starts: Vec<usize> = (0..k).map(|l| start + 64 * l).collect();
                    let len = (HISTORY_BYTES + FRAME_BYTES_PER_CHANNEL) * nch + WINDOW;
                    let hists: Vec<Vec<u8>> =
                        (0..k).map(|_| (0..len).map(|_| rnd() as u8).collect()).collect();
                    let mut results = Vec::new();
                    for general in [false, true] {
                        let mut bufs: Vec<Vec<u8>> = vec![Vec::new(); k];
                        let mut ars: Vec<Arith<'_, W>> = bufs
                            .iter_mut()
                            .enumerate()
                            .map(|(l, buf)| {
                                let from = &code[128 * l..];
                                Arith {
                                    a: W::from_u32(4095) << W::SCALE,
                                    x: W::from_u32(0),
                                    code: CodeBits::new(buf, from, 0, from.len() * 8),
                                }
                            })
                            .collect();
                        let mut hists = hists.clone();
                        if general {
                            for l in 0..k {
                                run_general(
                                    starts[l],
                                    &spans[l],
                                    nch,
                                    &[0; MAX_NCH],
                                    &mut ars[l],
                                    &mut hists[l],
                                );
                            }
                        } else {
                            let bytes = (end - start) / 8;
                            let probes: Vec<[Probe; MAX_NCH]> = spans
                                .iter()
                                .map(|s| {
                                    core::array::from_fn(|c| {
                                        let mut p = NO_PROBE;
                                        p.fill(s.partial[c], s.luts[c], byte_lut(nch));
                                        p
                                    })
                                })
                                .collect();
                            let mut runs: Vec<LaneRun<'_, '_, W>> = ars
                                .iter_mut()
                                .zip(hists.iter_mut())
                                .enumerate()
                                .map(|(l, (arith, hist))| LaneRun {
                                    start: starts[l] / 8,
                                    tabs: spans[l].tabs,
                                    probes: &probes[l],
                                    arith,
                                    hist,
                                })
                                .collect();
                            macro_rules! by_tables {
                                ($k:literal, $n:literal) => {
                                    match u {
                                        4 => run::<$k, $n, 4, W>(&mut runs, bytes),
                                        8 => run::<$k, $n, 8, W>(&mut runs, bytes),
                                        _ => run::<$k, $n, 16, W>(&mut runs, bytes),
                                    }
                                };
                            }
                            macro_rules! by_channels {
                                ($k:literal) => {
                                    match nch {
                                        1 => by_tables!($k, 1),
                                        2 => by_tables!($k, 2),
                                        3 => by_tables!($k, 3),
                                        4 => by_tables!($k, 4),
                                        5 => by_tables!($k, 5),
                                        _ => by_tables!($k, 6),
                                    }
                                };
                            }
                            match k {
                                1 => by_channels!(1),
                                2 => by_channels!(2),
                                3 => by_channels!(3),
                                _ => by_channels!(4),
                            }
                        }
                        // The loops refill at different times: compare the code bits after C
                        // as far as a refill makes them valid.
                        let state: Vec<_> = ars
                            .iter_mut()
                            .map(|ar| {
                                ar.refill();
                                (ar.a, ar.x, ar.code.pos)
                            })
                            .collect();
                        results.push((state, hists));
                    }
                    assert!(
                        results[0] == results[1],
                        "{k} frames, {nch} channels, {u} tables, chunk {start}..{end}"
                    );
                }
            }
        }
    }

    #[test]
    fn rice_codes() {
        // m = 2: q = 1 ("01"), lsb "10" = 2, u = 6, sign "1": -6.
        let data = [0b0110_1000];
        let mut b = Bits::new(&data);
        assert_eq!(b.rice(2), Ok(-6));
        // u = 0 reads no sign bit.
        let data = [0b1000_0000];
        let mut b = Bits::new(&data);
        assert_eq!(b.rice(0), Ok(0));
        assert_eq!(b.pos, 1);
        let mut b = Bits::new(&[0u8]);
        assert_eq!(b.rice(0), Err(DstError::HeaderTruncated));
    }

    /// `decode_table` steps as `decode` does, for C on both sides of the decision: every A and
    /// p, fewer under Miri.
    #[test]
    fn q_table_step_matches_decode() {
        let (a_step, p_step) = if cfg!(miri) { (97, 13) } else { (1, 1) };
        let q = q_table();
        for a in (2048u64..4096).step_by(a_step) {
            for p in (1u32..=128).step_by(p_step) {
                let w1 = a - ((a >> 8) | ((a >> 7) & 1)) * u64::from(p);
                for c in [0, w1 - 1, w1, a - 1] {
                    let arith = Arith { a: a << 52, x: c << 52, code: CodeBits { bytes: &[], pos: 0 } };
                    let (mut one, mut two) = (arith, arith);
                    assert_eq!(one.decode(p), two.decode_table(p, &q));
                    assert_eq!((one.a, one.x, one.code.pos), (two.a, two.x, two.code.pos));
                }
            }
        }
    }
    /// The arithmetic decoder in `u32` steps exactly as in `u64` (#369), in each of its three
    /// forms: the same symbol, A, C and code position, and after a refill the same look-ahead
    /// bits as far as `u32` holds them, for every A and p (fewer under Miri), C on both sides
    /// of the decision, and code bits that differ from step to step. Each case runs two
    /// symbols, so that the second starts from the first's renormalised state.
    #[test]
    fn u32_steps_as_u64() {
        let (a_step, p_step) = if cfg!(miri) { (89, 11) } else { (1, 1) };
        let mut seed = 0x2545_F491_4F6C_DD1Du64;
        let code: Vec<u8> = (0..64)
            .map(|_| {
                seed ^= seed << 13;
                seed ^= seed >> 7;
                seed ^= seed << 17;
                seed as u8
            })
            .chain([0; CODE_PADDING])
            .collect();
        let mut probe = NO_PROBE;
        let mut lut = [0u8; LUT_LEN];
        for (i, v) in lut.iter_mut().enumerate() {
            *v = (1 + i % 128) as u8;
        }
        probe.fill(&[0; 256], &lut, false);
        let (q64, q32) = (u64::q(&probe), u32::q(&probe));
        let (s64, s32) = (u64::scaled(&probe), u32::scaled(&probe));
        for a in (2048u32..4096).step_by(a_step) {
            for p in (1u32..=128).step_by(p_step) {
                let w1 = a - ((a >> 8) | ((a >> 7) & 1)) * p;
                for (n, c) in [0, w1 - 1, w1, a - 1].into_iter().enumerate() {
                    let pos = (a as usize * 7 + p as usize * 3 + n) % 256;
                    let at = |pos| CodeBits { bytes: &code, pos };
                    let one = Arith::<u64> { a: u64::from(a) << 52, x: u64::from(c) << 52, code: at(pos) };
                    let two = Arith::<u32> { a: a << 20, x: c << 20, code: at(pos) };
                    for form in 0..3 {
                        let (mut one, mut two) = (one, two);
                        for step in 0..2 {
                            one.refill();
                            two.refill();
                            assert_eq!(
                                (one.x >> 32) as u32,
                                two.x,
                                "a {a} p {p} c {c} form {form} step {step}"
                            );
                            let pp = (p + 37 * step) % 128 + 1;
                            let (y1, y2) = match form {
                                0 => (one.decode(pp), two.decode(pp)),
                                1 => (one.decode_table(pp, q64), two.decode_table(pp, q32)),
                                _ => {
                                    let j = (pp - 1) as usize % MAX_PTABLE_LEN;
                                    (one.decode_scaled(s64[j]), two.decode_scaled(s32[j]))
                                }
                            };
                            assert_eq!(y1, y2, "a {a} p {pp} c {c} form {form} step {step}");
                            assert_eq!((one.a >> 52) as u32, two.a >> 20);
                            assert_eq!((one.x >> 52) as u32, two.x >> 20);
                            assert_eq!(one.code.pos, two.code.pos);
                        }
                    }
                }
            }
        }
    }
}