flac-codec 1.3.1

A comprehensive library for handling FLAC files
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
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
// Copyright 2025 Brian Langenberger
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! For handling common FLAC stream items
//!
//! Many items are capitalized simply because they were capitalized
//! in the original FLAC format documentation.

use crate::Error;
use crate::crc::{Checksum, Crc16, CrcReader, CrcWriter};
use crate::metadata::Streaminfo;
use bitstream_io::{
    BitCount, BitRead, BitWrite, FromBitStream, FromBitStreamUsing, FromBitStreamWith,
    SignedBitCount, ToBitStream, ToBitStreamUsing, ToBitStreamWith,
};
use std::num::NonZero;

/// A common trait for signed integers
pub trait SignedInteger: private::SignedInteger {}

impl SignedInteger for i32 {}

impl private::SignedInteger for i32 {
    #[inline]
    fn from_u32(u: u32) -> Self {
        u as i32
    }

    #[inline]
    fn to_u32(self) -> u32 {
        self as u32
    }

    fn from_i64(i: i64) -> Self {
        i as i32
    }
}

impl SignedInteger for i64 {}

impl private::SignedInteger for i64 {
    #[inline]
    fn from_u32(u: u32) -> Self {
        u as i64
    }

    #[inline]
    fn to_u32(self) -> u32 {
        self as u32
    }

    #[inline]
    fn from_i64(i: i64) -> Self {
        i
    }
}

mod private {
    /// A common trait for signed integers
    pub trait SignedInteger:
        bitstream_io::SignedInteger
        + std::ops::Shl<Output = Self>
        + std::ops::Neg<Output = Self>
        + std::ops::AddAssign
        + Into<i64>
        + std::fmt::Display
    {
        /// Unconditionally converts a u32 to ourself
        fn from_u32(u: u32) -> Self;

        /// Unconditionally converts ourself to u32
        fn to_u32(self) -> u32;

        /// Unconditionally converts i64 to ourself
        fn from_i64(i: i64) -> Self;
    }
}

/// A FLAC frame header
///
/// | Bits      | Field |
/// |----------:|-------|
/// | 15        | sync code (`0b111111111111100`)
/// | 1         | `blocking_strategy`
/// | 4         | `block_size`
/// | 4         | `sample_rate`
/// | 4         | `channel_assignment`
/// | 3         | `bits_per_sample`
/// | 1         | padding (0)
/// | 8-56      | `frame_number`
/// | (8 or 16) | uncommon block size
/// | (8 or 16) | uncommon sample rate
/// | 8         | CRC-8 of header data
///
/// # Example
/// ```
/// use flac_codec::stream::{
///     FrameHeader, BlockSize, SampleRate, ChannelAssignment,
///     Independent, BitsPerSample, FrameNumber,
/// };
///
/// let mut data: &[u8] = &[
///     0b11111111, 0b1111100_0,  // sync code + blocking
///     0b0110_1001,              // block size + sample rate
///     0b0000_100_0,             // channels + bps + pad
///     0x00,                     // frame number
///     0x13,                     // uncommon block size (+1)
///     0x64,                     // CRC-8
/// ];
///
/// assert_eq!(
///     FrameHeader::read_subset(&mut data).unwrap(),
///     FrameHeader {
///         blocking_strategy: false,
///         block_size: BlockSize::Uncommon8(20),
///         sample_rate: SampleRate::Hz44100,
///         channel_assignment: ChannelAssignment::Independent(
///             Independent::Mono
///         ),
///         bits_per_sample: BitsPerSample::Bps16,
///         frame_number: FrameNumber(0),
///     },
/// );
/// ```
#[derive(Debug, Eq, PartialEq)]
pub struct FrameHeader {
    /// The blocking strategy bit
    pub blocking_strategy: bool,
    /// The block size, in samples
    pub block_size: BlockSize<u16>,
    /// The sample rate, in Hz
    pub sample_rate: SampleRate<u32>,
    /// How the channels are assigned
    pub channel_assignment: ChannelAssignment,
    /// The number if bits per output sample
    // pub bits_per_sample: SignedBitCount<32>,
    pub bits_per_sample: BitsPerSample,
    /// The frame's number in the stream
    pub frame_number: FrameNumber,
}

impl FrameHeader {
    const SYNC_CODE: u32 = 0b111111111111100;

    /// Reads new header from the given reader
    pub fn read<R: std::io::Read>(reader: &mut R, streaminfo: &Streaminfo) -> Result<Self, Error> {
        use crate::crc::{Checksum, Crc8, CrcReader};
        use bitstream_io::{BigEndian, BitReader};
        use std::io::Read;

        let mut crc8: CrcReader<_, Crc8> = CrcReader::new(reader);
        BitReader::endian(crc8.by_ref(), BigEndian)
            .parse_with(streaminfo)
            .and_then(|header| {
                crc8.into_checksum()
                    .valid()
                    .then_some(header)
                    .ok_or(Error::Crc8Mismatch)
            })
    }

    /// Reads new header from the given reader
    pub fn read_subset<R: std::io::Read>(reader: &mut R) -> Result<Self, Error> {
        use crate::crc::{Checksum, Crc8, CrcReader};
        use bitstream_io::{BigEndian, BitReader};
        use std::io::Read;

        let mut crc8: CrcReader<_, Crc8> = CrcReader::new(reader);
        BitReader::endian(crc8.by_ref(), BigEndian)
            .parse()
            .and_then(|header| {
                crc8.into_checksum()
                    .valid()
                    .then_some(header)
                    .ok_or(Error::Crc8Mismatch)
            })
    }

    /// Builds header to the given writer
    pub fn write<W: std::io::Write>(
        &self,
        writer: &mut W,
        streaminfo: &Streaminfo,
    ) -> Result<(), Error> {
        use crate::crc::{Crc8, CrcWriter};
        use bitstream_io::{BigEndian, BitWriter};
        use std::io::Write;

        let mut crc8: CrcWriter<_, Crc8> = CrcWriter::new(writer.by_ref());
        BitWriter::endian(crc8.by_ref(), BigEndian).build_with(self, streaminfo)?;
        let crc8 = crc8.into_checksum().into();
        writer.write_all(std::slice::from_ref(&crc8))?;
        Ok(())
    }

    /// Builds header to the given writer
    pub fn write_subset<W: std::io::Write>(&self, writer: &mut W) -> Result<(), Error> {
        use crate::crc::{Crc8, CrcWriter};
        use bitstream_io::{BigEndian, BitWriter};
        use std::io::Write;

        let mut crc8: CrcWriter<_, Crc8> = CrcWriter::new(writer.by_ref());
        BitWriter::endian(crc8.by_ref(), BigEndian).build(self)?;
        let crc8 = crc8.into_checksum().into();
        writer.write_all(std::slice::from_ref(&crc8))?;
        Ok(())
    }

    fn parse<R: BitRead + ?Sized>(
        r: &mut R,
        non_subset_rate: Option<u32>,
        non_subset_bps: Option<SignedBitCount<32>>,
    ) -> Result<Self, Error> {
        r.read_const::<15, { Self::SYNC_CODE }, _>(Error::InvalidSyncCode)?;
        let blocking_strategy = r.read_bit()?;
        let encoded_block_size = r.parse()?;
        let encoded_sample_rate = r.parse_using(non_subset_rate)?;
        let channel_assignment = r.parse()?;
        let bits_per_sample = r.parse_using(non_subset_bps)?;
        r.skip(1)?;
        let frame_number = r.parse()?;

        let frame_header = Self {
            blocking_strategy,
            frame_number,
            block_size: r.parse_using(encoded_block_size)?,
            sample_rate: r.parse_using(encoded_sample_rate)?,
            channel_assignment,
            bits_per_sample,
        };

        r.skip(8)?; // CRC-8

        Ok(frame_header)
    }

    fn build<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Error> {
        w.write_const::<15, { Self::SYNC_CODE }>()?;
        w.write_bit(self.blocking_strategy)?;
        w.build(&self.block_size)?;
        w.build(&self.sample_rate)?;
        w.build(&self.channel_assignment)?;
        w.build(&self.bits_per_sample)?;
        w.pad(1)?;
        w.build(&self.frame_number)?;

        // uncommon block size
        match self.block_size {
            BlockSize::Uncommon8(size) => {
                w.write::<8, _>(size.checked_sub(1).ok_or(Error::InvalidBlockSize)?)?
            }
            BlockSize::Uncommon16(size) => {
                w.write::<16, _>(size.checked_sub(1).ok_or(Error::InvalidBlockSize)?)?
            }
            _ => { /* do nothing */ }
        }

        // uncommon sample rate
        match self.sample_rate {
            SampleRate::KHz(rate) => w.write::<8, _>(rate / 1000)?,
            SampleRate::Hz(rate) => {
                w.write::<16, _>(rate)?;
            }
            SampleRate::DHz(rate) => {
                w.write::<16, _>(rate / 10)?;
            }
            _ => { /* do nothing */ }
        }

        Ok(())
    }
}

impl FromBitStreamWith<'_> for FrameHeader {
    type Error = Error;
    type Context = Streaminfo;

    fn from_reader<R: BitRead + ?Sized>(
        r: &mut R,
        streaminfo: &Streaminfo,
    ) -> Result<Self, Self::Error> {
        FrameHeader::parse(
            r,
            Some(streaminfo.sample_rate),
            Some(streaminfo.bits_per_sample),
        )
        .and_then(|h| {
            (u16::from(h.block_size) <= streaminfo.maximum_block_size)
                .then_some(h)
                .ok_or(Error::BlockSizeMismatch)
        })
        .and_then(|h| {
            (u32::from(h.sample_rate) == streaminfo.sample_rate)
                .then_some(h)
                .ok_or(Error::SampleRateMismatch)
        })
        .and_then(|h| {
            (h.channel_assignment.count() == streaminfo.channels.get())
                .then_some(h)
                .ok_or(Error::ChannelsMismatch)
        })
        .and_then(|h| {
            (h.bits_per_sample == streaminfo.bits_per_sample)
                .then_some(h)
                .ok_or(Error::BitsPerSampleMismatch)
        })
    }
}

impl FromBitStream for FrameHeader {
    type Error = Error;

    #[inline]
    fn from_reader<R: BitRead + ?Sized>(r: &mut R) -> Result<Self, Self::Error> {
        FrameHeader::parse(r, None, None)
    }
}

impl ToBitStreamWith<'_> for FrameHeader {
    type Error = Error;
    type Context = Streaminfo;

    #[inline]
    fn to_writer<W: BitWrite + ?Sized>(
        &self,
        w: &mut W,
        _streaminfo: &Streaminfo,
    ) -> Result<(), Self::Error> {
        self.build(w)
    }
}

impl ToBitStream for FrameHeader {
    type Error = Error;

    #[inline]
    fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Self::Error> {
        self.build(w)
    }
}

/// Possible block sizes in a FLAC frame, in samples
///
/// Common sizes are stored as a 4-bit value,
/// while uncommon sizes are stored as 8 or 16 bit values.
///
/// | Bits   | Block Size |
/// |-------:|------------|
/// | `0000` | invalid
/// | `0001` | 192
/// | `0010` | 576
/// | `0011` | 1152
/// | `0100` | 2304
/// | `0101` | 4606
/// | `0110` | 8 bit field (+1)
/// | `0111` | 16 bit field (+1)
/// | `1000` | 256
/// | `1001` | 512
/// | `1010` | 1024
/// | `1011` | 2048
/// | `1100` | 4096
/// | `1101` | 8192
/// | `1110` | 16384
/// | `1111` | 32768
///
/// Handing uncommon block sizes is why this type
/// is a generic with two different implementations
/// from reading from a bitstream.
/// The first reads common sizes, while the second
/// reads additional bits if necessary.
///
/// # Example
///
/// ```
/// use flac_codec::stream::BlockSize;
/// use bitstream_io::{BitReader, BitRead, BigEndian};
///
/// let data: &[u8] = &[
///     0b0110_1001,              // block size + sample rate
///     0b0000_100_0,             // channels + bps + pad
///     0x00,                     // frame number
///     0x13,                     // uncommon block size (+1)
/// ];
///
/// let mut r = BitReader::endian(data, BigEndian);
/// let block_size = r.parse::<BlockSize<()>>().unwrap();  // reads 0b0110
/// assert_eq!(
///     block_size,
///     BlockSize::Uncommon8(()),  // need to read actual block size from end of frame
/// );
/// r.skip(4 + 8 + 8).unwrap();    // skip unnecessary bits for this example
/// assert_eq!(
///     // read remainder of block size from end of frame
///     r.parse_using::<BlockSize<u16>>(block_size).unwrap(),
///     BlockSize::Uncommon8(0x13 + 1),
/// );
/// ```
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum BlockSize<B> {
    /// 192 samples
    Samples192,
    /// 576 samples
    Samples576,
    /// 1152 samples
    Samples1152,
    /// 2304 samples
    Samples2304,
    /// 4608 samples
    Samples4608,
    /// Uncommon 8 bit sample count + 1
    Uncommon8(B),
    /// Uncommon 16 bit sample count + 1
    Uncommon16(B),
    /// 256 samples
    Samples256,
    /// 512 samples
    Samples512,
    /// 1024 samples
    Samples1024,
    /// 2048 samples
    Samples2048,
    /// 4096 samples
    Samples4096,
    /// 8192 samples
    Samples8192,
    /// 16384 samples
    Samples16384,
    /// 32768 samples
    Samples32768,
}

impl FromBitStream for BlockSize<()> {
    type Error = Error;

    fn from_reader<R: BitRead + ?Sized>(r: &mut R) -> Result<Self, Self::Error> {
        match r.read::<4, u8>()? {
            0b0000 => Err(Error::InvalidBlockSize),
            0b0001 => Ok(Self::Samples192),
            0b0010 => Ok(Self::Samples576),
            0b0011 => Ok(Self::Samples1152),
            0b0100 => Ok(Self::Samples2304),
            0b0101 => Ok(Self::Samples4608),
            0b0110 => Ok(Self::Uncommon8(())),
            0b0111 => Ok(Self::Uncommon16(())),
            0b1000 => Ok(Self::Samples256),
            0b1001 => Ok(Self::Samples512),
            0b1010 => Ok(Self::Samples1024),
            0b1011 => Ok(Self::Samples2048),
            0b1100 => Ok(Self::Samples4096),
            0b1101 => Ok(Self::Samples8192),
            0b1110 => Ok(Self::Samples16384),
            0b1111 => Ok(Self::Samples32768),
            0b10000.. => unreachable!(), // 4-bit field
        }
    }
}

impl FromBitStreamUsing for BlockSize<u16> {
    type Context = BlockSize<()>;
    type Error = Error;

    fn from_reader<R: BitRead + ?Sized>(r: &mut R, size: BlockSize<()>) -> Result<Self, Error> {
        match size {
            BlockSize::Samples192 => Ok(Self::Samples192),
            BlockSize::Samples576 => Ok(Self::Samples576),
            BlockSize::Samples1152 => Ok(Self::Samples1152),
            BlockSize::Samples2304 => Ok(Self::Samples2304),
            BlockSize::Samples4608 => Ok(Self::Samples4608),
            BlockSize::Samples256 => Ok(Self::Samples256),
            BlockSize::Samples512 => Ok(Self::Samples512),
            BlockSize::Samples1024 => Ok(Self::Samples1024),
            BlockSize::Samples2048 => Ok(Self::Samples2048),
            BlockSize::Samples4096 => Ok(Self::Samples4096),
            BlockSize::Samples8192 => Ok(Self::Samples8192),
            BlockSize::Samples16384 => Ok(Self::Samples16384),
            BlockSize::Samples32768 => Ok(Self::Samples32768),
            BlockSize::Uncommon8(()) => Ok(Self::Uncommon8(r.read::<8, u16>()? + 1)),
            BlockSize::Uncommon16(()) => Ok(Self::Uncommon16(
                r.read::<16, u16>()?
                    .checked_add(1)
                    .ok_or(Error::InvalidBlockSize)?,
            )),
        }
    }
}

impl<B> ToBitStream for BlockSize<B> {
    type Error = std::io::Error;

    fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Self::Error> {
        w.write::<4, u8>(match self {
            Self::Samples192 => 0b0001,
            Self::Samples576 => 0b0010,
            Self::Samples1152 => 0b0011,
            Self::Samples2304 => 0b0100,
            Self::Samples4608 => 0b0101,
            Self::Uncommon8(_) => 0b0110,
            Self::Uncommon16(_) => 0b0111,
            Self::Samples256 => 0b1000,
            Self::Samples512 => 0b1001,
            Self::Samples1024 => 0b1010,
            Self::Samples2048 => 0b1011,
            Self::Samples4096 => 0b1100,
            Self::Samples8192 => 0b1101,
            Self::Samples16384 => 0b1110,
            Self::Samples32768 => 0b1111,
        })
    }
}

impl From<BlockSize<u16>> for u16 {
    fn from(size: BlockSize<u16>) -> Self {
        match size {
            BlockSize::Samples192 => 192,
            BlockSize::Samples576 => 576,
            BlockSize::Samples1152 => 1152,
            BlockSize::Samples2304 => 2304,
            BlockSize::Samples4608 => 4608,
            BlockSize::Samples256 => 256,
            BlockSize::Samples512 => 512,
            BlockSize::Samples1024 => 1024,
            BlockSize::Samples2048 => 2048,
            BlockSize::Samples4096 => 4096,
            BlockSize::Samples8192 => 8192,
            BlockSize::Samples16384 => 16384,
            BlockSize::Samples32768 => 32768,
            BlockSize::Uncommon8(s) | BlockSize::Uncommon16(s) => s,
        }
    }
}

impl TryFrom<u16> for BlockSize<u16> {
    type Error = Error;

    fn try_from(size: u16) -> Result<Self, Error> {
        match size {
            0 => Err(Error::InvalidBlockSize),
            192 => Ok(Self::Samples192),
            576 => Ok(Self::Samples576),
            1152 => Ok(Self::Samples1152),
            2304 => Ok(Self::Samples2304),
            4608 => Ok(Self::Samples4608),
            256 => Ok(Self::Samples256),
            512 => Ok(Self::Samples512),
            1024 => Ok(Self::Samples1024),
            2048 => Ok(Self::Samples2048),
            4096 => Ok(Self::Samples4096),
            8192 => Ok(Self::Samples8192),
            16384 => Ok(Self::Samples16384),
            32768 => Ok(Self::Samples32768),
            size if size <= 256 => Ok(Self::Uncommon8(size)),
            size => Ok(Self::Uncommon16(size)),
        }
    }
}

impl std::fmt::Display for BlockSize<u16> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        u16::from(*self).fmt(f)
    }
}

/// Possible sample rates in a FLAC frame
///
/// Common rates are stored as a 4-bit value,
/// while uncommon rates are stored as 8 or 16 bit values.
/// Sample rates defined in the STREAMINFO metadata block
/// are only possible on a "non-subset" stream, which is
/// not streamable.
///
/// | Bits   | Sample Rate |
/// |-------:|-------------|
/// | `0000` | get from STREAMINFO
/// | `0001` | 88200 Hz
/// | `0010` | 176400 Hz
/// | `0011` | 192000 Hz
/// | `0100` | 8000 Hz
/// | `0101` | 16000 Hz
/// | `0110` | 22050 Hz
/// | `0111` | 24000 Hz
/// | `1000` | 32000 Hz
/// | `1001` | 44100 Hz
/// | `1010` | 48000 Hz
/// | `1011` | 96000 Hz
/// | `1100` | read 8 bits, in kHz
/// | `1101` | read 16 bits, in Hz
/// | `1110` | read 16 bits, in 10s of Hz
/// | `1111` | invalid sample rate
///
/// Handing uncommon frame rates is why this type is a generic
/// with multiple implementations from reading from a bitstream.
/// The first reads common rates, while the second reads additional bits if necessary.
///
/// # Example
///
/// ```
/// use flac_codec::stream::SampleRate;
/// use bitstream_io::{BitReader, BitRead, BigEndian};
///
/// let data: &[u8] = &[
///     0b0110_1001,              // block size + sample rate
///     0b0000_100_0,             // channels + bps + pad
///     0x00,                     // frame number
///     0x13,                     // uncommon block size (+1)
/// ];
///
/// let mut r = BitReader::endian(data, BigEndian);
/// r.skip(4).unwrap();          // skip block size
/// let sample_rate = r.parse::<SampleRate<()>>().unwrap();  // reads 0b1001
/// assert_eq!(
///     sample_rate,
///     SampleRate::Hz44100,     // got defined sample rate
/// );
/// r.skip(8 + 8 + 8).unwrap();  // skip unnecessary bits for this example
/// assert_eq!(
///     // since our rate is defined, no need to read additional bits
///     r.parse_using::<SampleRate<u32>>(sample_rate).unwrap(),
///     SampleRate::Hz44100,
/// );
/// ```
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum SampleRate<R> {
    /// Get rate from STREAMINFO metadata block
    Streaminfo(u32),
    /// 88200 Hz
    Hz88200,
    /// 176,400 Hz
    Hz176400,
    /// 192,000 Hz
    Hz192000,
    /// 8,000 Hz
    Hz8000,
    /// 16,000 Hz
    Hz16000,
    /// 22,050 Hz
    Hz22050,
    /// 24,000 Hz
    Hz24000,
    /// 32,000 Hz
    Hz32000,
    /// 44,100 Hz
    Hz44100,
    /// 48,000 Hz
    Hz48000,
    /// 96,000 Hz
    Hz96000,
    /// 8-bit value in kHz
    KHz(R),
    /// 16-bit value in Hz
    Hz(R),
    /// 16-bit value * 10 in Hz
    DHz(R),
}

/// Reads the raw sample rate bits, which need to be finalized
impl FromBitStreamUsing for SampleRate<()> {
    type Context = Option<u32>;

    type Error = Error;

    fn from_reader<R: BitRead + ?Sized>(
        r: &mut R,
        streaminfo_rate: Option<u32>,
    ) -> Result<Self, Self::Error> {
        match r.read::<4, u8>()? {
            0b0000 => Ok(Self::Streaminfo(
                streaminfo_rate.ok_or(Error::NonSubsetSampleRate)?,
            )),
            0b0001 => Ok(Self::Hz88200),
            0b0010 => Ok(Self::Hz176400),
            0b0011 => Ok(Self::Hz192000),
            0b0100 => Ok(Self::Hz8000),
            0b0101 => Ok(Self::Hz16000),
            0b0110 => Ok(Self::Hz22050),
            0b0111 => Ok(Self::Hz24000),
            0b1000 => Ok(Self::Hz32000),
            0b1001 => Ok(Self::Hz44100),
            0b1010 => Ok(Self::Hz48000),
            0b1011 => Ok(Self::Hz96000),
            0b1100 => Ok(Self::KHz(())),
            0b1101 => Ok(Self::Hz(())),
            0b1110 => Ok(Self::DHz(())),
            0b1111 => Err(Error::InvalidSampleRate),
            _ => unreachable!(), // 4-bit field
        }
    }
}

impl FromBitStream for SampleRate<()> {
    type Error = Error;

    #[inline]
    fn from_reader<R: BitRead + ?Sized>(r: &mut R) -> Result<Self, Self::Error> {
        r.parse_using(None)
    }
}

impl FromBitStreamUsing for SampleRate<u32> {
    type Context = SampleRate<()>;

    type Error = Error;

    fn from_reader<R: BitRead + ?Sized>(
        r: &mut R,
        rate: SampleRate<()>,
    ) -> Result<Self, Self::Error> {
        match rate {
            SampleRate::Streaminfo(s) => Ok(Self::Streaminfo(s)),
            SampleRate::Hz88200 => Ok(Self::Hz88200),
            SampleRate::Hz176400 => Ok(Self::Hz176400),
            SampleRate::Hz192000 => Ok(Self::Hz192000),
            SampleRate::Hz8000 => Ok(Self::Hz8000),
            SampleRate::Hz16000 => Ok(Self::Hz16000),
            SampleRate::Hz22050 => Ok(Self::Hz22050),
            SampleRate::Hz24000 => Ok(Self::Hz24000),
            SampleRate::Hz32000 => Ok(Self::Hz32000),
            SampleRate::Hz44100 => Ok(Self::Hz44100),
            SampleRate::Hz48000 => Ok(Self::Hz48000),
            SampleRate::Hz96000 => Ok(Self::Hz96000),
            SampleRate::KHz(()) => Ok(Self::KHz(r.read::<8, u32>()? * 1000)),
            SampleRate::Hz(()) => Ok(Self::Hz(r.read::<16, _>()?)),
            SampleRate::DHz(()) => Ok(Self::DHz(r.read::<16, u32>()? * 10)),
        }
    }
}

/// Writes the raw sample rate bits
impl<R> ToBitStream for SampleRate<R> {
    type Error = std::io::Error;

    fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Self::Error> {
        w.write::<4, u8>(match self {
            Self::Streaminfo(_) => 0b0000,
            Self::Hz88200 => 0b0001,
            Self::Hz176400 => 0b0010,
            Self::Hz192000 => 0b0011,
            Self::Hz8000 => 0b0100,
            Self::Hz16000 => 0b0101,
            Self::Hz22050 => 0b0110,
            Self::Hz24000 => 0b0111,
            Self::Hz32000 => 0b1000,
            Self::Hz44100 => 0b1001,
            Self::Hz48000 => 0b1010,
            Self::Hz96000 => 0b1011,
            Self::KHz(_) => 0b1100,
            Self::Hz(_) => 0b1101,
            Self::DHz(_) => 0b1110,
        })
    }
}

impl From<SampleRate<u32>> for u32 {
    fn from(rate: SampleRate<u32>) -> Self {
        match rate {
            SampleRate::Streaminfo(u)
            | SampleRate::KHz(u)
            | SampleRate::Hz(u)
            | SampleRate::DHz(u) => u,
            SampleRate::Hz88200 => 88200,
            SampleRate::Hz176400 => 176400,
            SampleRate::Hz192000 => 192000,
            SampleRate::Hz8000 => 8000,
            SampleRate::Hz16000 => 16000,
            SampleRate::Hz22050 => 22050,
            SampleRate::Hz24000 => 24000,
            SampleRate::Hz32000 => 32000,
            SampleRate::Hz44100 => 44100,
            SampleRate::Hz48000 => 48000,
            SampleRate::Hz96000 => 96000,
        }
    }
}

impl TryFrom<u32> for SampleRate<u32> {
    type Error = Error;

    fn try_from(sample_rate: u32) -> Result<Self, Error> {
        match sample_rate {
            88200 => Ok(Self::Hz88200),
            176400 => Ok(Self::Hz176400),
            192000 => Ok(Self::Hz192000),
            8000 => Ok(Self::Hz8000),
            16000 => Ok(Self::Hz16000),
            22050 => Ok(Self::Hz22050),
            24000 => Ok(Self::Hz24000),
            32000 => Ok(Self::Hz32000),
            44100 => Ok(Self::Hz44100),
            48000 => Ok(Self::Hz48000),
            96000 => Ok(Self::Hz96000),
            rate if (rate % 1000) == 0 && (rate / 1000) < u8::MAX as u32 => Ok(Self::KHz(rate)),
            rate if (rate % 10) == 0 && (rate / 10) < u16::MAX as u32 => Ok(Self::DHz(rate)),
            rate if rate < u16::MAX as u32 => Ok(Self::Hz(rate)),
            rate if rate < 1 << 20 => Ok(Self::Streaminfo(rate)),
            _ => Err(Error::InvalidSampleRate),
        }
    }
}

impl std::fmt::Display for SampleRate<u32> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        u32::from(*self).fmt(f)
    }
}

/// How independent channels are stored
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Independent {
    /// 1 monoaural channel
    Mono = 1,
    /// left, right channels
    Stereo = 2,
    /// left, right, center channels
    Channels3 = 3,
    /// front left, front right, back left, back right channels
    Channels4 = 4,
    /// front left, front right, front center,
    /// back/surround left, back/surround right channels
    Channels5 = 5,
    /// front left, front right, front center,
    /// LFE, back/surround left, back/surround right channels
    Channels6 = 6,
    /// front left, front right, front center,
    /// LFE, back center, side left, side right channels
    Channels7 = 7,
    /// front left, front right, front center,
    /// LFE, back left, back right, side left, side right channels
    Channels8 = 8,
}

impl From<Independent> for u8 {
    fn from(ch: Independent) -> Self {
        ch as u8
    }
}

impl From<Independent> for usize {
    fn from(ch: Independent) -> Self {
        ch as usize
    }
}

impl TryFrom<usize> for Independent {
    type Error = ();

    fn try_from(ch: usize) -> Result<Self, Self::Error> {
        match ch {
            1 => Ok(Self::Mono),
            2 => Ok(Self::Stereo),
            3 => Ok(Self::Channels3),
            4 => Ok(Self::Channels4),
            5 => Ok(Self::Channels5),
            6 => Ok(Self::Channels6),
            7 => Ok(Self::Channels7),
            8 => Ok(Self::Channels8),
            _ => Err(()),
        }
    }
}

/// How the channels are assigned in a FLAC frame
///
/// | Bits   | Channel Assingment |
/// |-------:|--------------------|
/// | `0000` | 1 mono channel
/// | `0001` | 2 independent channels
/// | `0010` | 3 independent channels
/// | `0011` | 4 independent channels
/// | `0100` | 5 independent channels
/// | `0101` | 6 independent channels
/// | `0110` | 7 independent channels
/// | `0111` | 8 independent channels
/// | `1000` | left channel, side channel
/// | `1001` | side channel, right channel
/// | `1010` | mid channel, side channel
/// | `1011` | invalid channel assignment
/// | `1100` | invalid channel assignment
/// | `1101` | invalid channel assignment
/// | `1110` | invalid channel assignment
/// | `1111` | invalid channel assignment
///
/// # Example
///
/// ```
/// use flac_codec::stream::{ChannelAssignment, Independent};
/// use bitstream_io::{BitReader, BitRead, BigEndian};
///
/// let data: &[u8] = &[
///     0b0000_100_0,             // channels + bps + pad
/// ];
///
/// let mut r = BitReader::endian(data, BigEndian);
/// assert_eq!(
///     r.parse::<ChannelAssignment>().unwrap(),
///     ChannelAssignment::Independent(Independent::Mono),
/// );
/// ```
///
/// The samples in the side channel can be calculated like:
///
/// > sideᵢ = leftᵢ - rightᵢ
///
/// This requires that the side channel have one additional
/// bit-per-sample during decoding, since the difference
/// between the left and right channels could overflow
/// if the two are at opposite extremes.
///
/// And with a bit of math, we can see that:
///
/// > rightᵢ = leftᵢ - sideᵢ
///
/// or:
///
/// > leftᵢ = sideᵢ + rightᵢ
///
/// For transforming left-side and side-right assignments back
/// to left-right for output.
///
/// The samples in the mid channel can be calculated like:
///
/// > midᵢ = (leftᵢ + rightᵢ) ÷ 2
///
/// Mid-side assignment can be restored to left-right like:
///
/// > sumᵢ = midᵢ × 2 + |sideᵢ| % 2
/// >
/// > leftᵢ = (sumᵢ + sideᵢ) ÷ 2
/// >
/// > rightᵢ = (sumᵢ - sideᵢ) ÷ 2
///
/// The mid channel does *not* require any additional bits
/// to decode, since the average cannot exceed either channel.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ChannelAssignment {
    /// Channels are stored independently
    Independent(Independent),
    /// Channel 0 is stored verbatim, channel 1 derived from both
    LeftSide,
    /// Channel 0 is derived from both, channel 1 is stored verbatim
    SideRight,
    /// Channel 0 is averaged from both, channel 1 is derived from both
    MidSide,
}

impl ChannelAssignment {
    /// Returns total number of channels defined by assignment
    pub fn count(&self) -> u8 {
        match self {
            Self::Independent(c) => (*c).into(),
            _ => 2,
        }
    }
}

impl std::fmt::Display for ChannelAssignment {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::Independent(_) => "INDEPENDENT".fmt(f),
            Self::LeftSide => "LEFT_SIDE".fmt(f),
            Self::SideRight => "SIDE_RIGHT".fmt(f),
            Self::MidSide => "MID_SIDE".fmt(f),
        }
    }
}

impl FromBitStream for ChannelAssignment {
    type Error = Error;

    fn from_reader<R: BitRead + ?Sized>(r: &mut R) -> Result<Self, Error> {
        match r.read::<4, u8>()? {
            0b0000 => Ok(Self::Independent(Independent::Mono)),
            0b0001 => Ok(Self::Independent(Independent::Stereo)),
            0b0010 => Ok(Self::Independent(Independent::Channels3)),
            0b0011 => Ok(Self::Independent(Independent::Channels4)),
            0b0100 => Ok(Self::Independent(Independent::Channels5)),
            0b0101 => Ok(Self::Independent(Independent::Channels6)),
            0b0110 => Ok(Self::Independent(Independent::Channels7)),
            0b0111 => Ok(Self::Independent(Independent::Channels8)),
            0b1000 => Ok(Self::LeftSide),
            0b1001 => Ok(Self::SideRight),
            0b1010 => Ok(Self::MidSide),
            0b1011..=0b1111 => Err(Error::InvalidChannels),
            0b10000.. => unreachable!(), // 4-bit field
        }
    }
}

impl ToBitStream for ChannelAssignment {
    type Error = Error;

    fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Error> {
        Ok(w.write::<4, u8>(match self {
            Self::Independent(Independent::Mono) => 0b0000,
            Self::Independent(Independent::Stereo) => 0b0001,
            Self::Independent(Independent::Channels3) => 0b0010,
            Self::Independent(Independent::Channels4) => 0b0011,
            Self::Independent(Independent::Channels5) => 0b0100,
            Self::Independent(Independent::Channels6) => 0b0101,
            Self::Independent(Independent::Channels7) => 0b0110,
            Self::Independent(Independent::Channels8) => 0b0111,
            Self::LeftSide => 0b1000,
            Self::SideRight => 0b1001,
            Self::MidSide => 0b1010,
        })?)
    }
}

/// The the possible bits-per-sample of a FLAC frame
///
/// Common bits-per-sample are stored as a 3-bit value,
/// while uncommon bits-per-sample are stored in the
/// STREAMINFO metadata block.
/// Bits-per-sample defined in the STREAMINFO metadata block
/// are only possible on a "non-subset" stream, which is
/// not streamable.
///
/// | Bits  | Bits-per-Sample |
/// |------:|-------------|
/// | `000` | get from STREAMINFO
/// | `001` | 8
/// | `010` | 12
/// | `011` | invalid
/// | `100` | 16
/// | `101` | 20
/// | `110` | 24
/// | `111` | 32
///
/// # Example
/// ```
/// use flac_codec::stream::BitsPerSample;
/// use bitstream_io::{BitReader, BitRead, BigEndian};
///
/// let data: &[u8] = &[
///     0b0000_100_0,             // channels + bps + pad
/// ];
///
/// let mut r = BitReader::endian(data, BigEndian);
/// r.skip(4).unwrap();  // skip channel assignment
/// assert_eq!(
///     r.parse::<BitsPerSample>().unwrap(),
///     BitsPerSample::Bps16,
/// );
/// ```
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum BitsPerSample {
    /// Gets bps from STREAMINFO metadata block
    Streaminfo(SignedBitCount<32>),
    /// 8 bits-per-sample
    Bps8,
    /// 12 bits-per-sample
    Bps12,
    /// 16 bits-per-sample
    Bps16,
    /// 20 bits-per-sample
    Bps20,
    /// 24 bits-per-sample
    Bps24,
    /// 32 bits-per-sample
    Bps32,
}

impl BitsPerSample {
    const BPS8: SignedBitCount<32> = SignedBitCount::new::<8>();
    const BPS12: SignedBitCount<32> = SignedBitCount::new::<12>();
    const BPS16: SignedBitCount<32> = SignedBitCount::new::<16>();
    const BPS20: SignedBitCount<32> = SignedBitCount::new::<20>();
    const BPS24: SignedBitCount<32> = SignedBitCount::new::<24>();
    const BPS32: SignedBitCount<32> = SignedBitCount::new::<32>();

    /// Adds the given number of bits to this bit count, if possible.
    ///
    /// If the number of bits would overflow the maximum count,
    /// returns `None`.
    #[inline]
    pub fn checked_add(self, rhs: u32) -> Option<SignedBitCount<32>> {
        match self {
            Self::Streaminfo(c) => c.checked_add(rhs),
            Self::Bps8 => Self::BPS8.checked_add(rhs),
            Self::Bps12 => Self::BPS12.checked_add(rhs),
            Self::Bps16 => Self::BPS16.checked_add(rhs),
            Self::Bps20 => Self::BPS20.checked_add(rhs),
            Self::Bps24 => Self::BPS24.checked_add(rhs),
            Self::Bps32 => Self::BPS32.checked_add(rhs),
        }
    }
}

impl PartialEq<SignedBitCount<32>> for BitsPerSample {
    fn eq(&self, rhs: &SignedBitCount<32>) -> bool {
        match self {
            Self::Streaminfo(c) => c.eq(rhs),
            Self::Bps8 => Self::BPS8.eq(rhs),
            Self::Bps12 => Self::BPS12.eq(rhs),
            Self::Bps16 => Self::BPS16.eq(rhs),
            Self::Bps20 => Self::BPS20.eq(rhs),
            Self::Bps24 => Self::BPS24.eq(rhs),
            Self::Bps32 => Self::BPS32.eq(rhs),
        }
    }
}

impl From<BitsPerSample> for SignedBitCount<32> {
    #[inline]
    fn from(bps: BitsPerSample) -> Self {
        match bps {
            BitsPerSample::Streaminfo(c) => c,
            BitsPerSample::Bps8 => BitsPerSample::BPS8,
            BitsPerSample::Bps12 => BitsPerSample::BPS12,
            BitsPerSample::Bps16 => BitsPerSample::BPS16,
            BitsPerSample::Bps20 => BitsPerSample::BPS20,
            BitsPerSample::Bps24 => BitsPerSample::BPS24,
            BitsPerSample::Bps32 => BitsPerSample::BPS32,
        }
    }
}

impl From<BitsPerSample> for u32 {
    #[inline]
    fn from(bps: BitsPerSample) -> Self {
        match bps {
            BitsPerSample::Streaminfo(c) => c.into(),
            BitsPerSample::Bps8 => 8,
            BitsPerSample::Bps12 => 12,
            BitsPerSample::Bps16 => 16,
            BitsPerSample::Bps20 => 20,
            BitsPerSample::Bps24 => 24,
            BitsPerSample::Bps32 => 32,
        }
    }
}

impl From<SignedBitCount<32>> for BitsPerSample {
    #[inline]
    fn from(bps: SignedBitCount<32>) -> Self {
        match bps {
            Self::BPS8 => Self::Bps8,
            Self::BPS12 => Self::Bps12,
            Self::BPS16 => Self::Bps16,
            Self::BPS20 => Self::Bps20,
            Self::BPS24 => Self::Bps24,
            Self::BPS32 => Self::Bps32,
            bps => Self::Streaminfo(bps),
        }
    }
}

impl FromBitStreamUsing for BitsPerSample {
    type Context = Option<SignedBitCount<32>>;
    type Error = Error;

    fn from_reader<R: BitRead + ?Sized>(
        r: &mut R,
        streaminfo_bps: Option<SignedBitCount<32>>,
    ) -> Result<Self, Error> {
        match r.read::<3, u8>()? {
            0b000 => Ok(Self::Streaminfo(
                streaminfo_bps.ok_or(Error::NonSubsetBitsPerSample)?,
            )),
            0b001 => Ok(Self::Bps8),
            0b010 => Ok(Self::Bps12),
            0b011 => Err(Error::InvalidBitsPerSample),
            0b100 => Ok(Self::Bps16),
            0b101 => Ok(Self::Bps20),
            0b110 => Ok(Self::Bps24),
            0b111 => Ok(Self::Bps32),
            0b1000.. => unreachable!(), // 3-bit field
        }
    }
}

impl FromBitStream for BitsPerSample {
    type Error = Error;

    #[inline]
    fn from_reader<R: BitRead + ?Sized>(r: &mut R) -> Result<Self, Error> {
        r.parse_using(None)
    }
}

impl ToBitStream for BitsPerSample {
    type Error = std::io::Error;

    fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Self::Error> {
        w.write::<3, u8>(match self {
            Self::Streaminfo(_) => 0b000,
            Self::Bps8 => 0b001,
            Self::Bps12 => 0b010,
            Self::Bps16 => 0b100,
            Self::Bps20 => 0b101,
            Self::Bps24 => 0b110,
            Self::Bps32 => 0b111,
        })
    }
}

/// A frame number in the stream, as FLAC frames or samples
///
/// The frame number is stored as a UTF-8-like value
/// where the total number of bytes is encoded
/// in the initial byte.
///
/// | byte 0     | byte 1     | byte 2     | byte 3     | byte 4     | byte 5     | byte 6
/// |------------|------------|------------|------------|------------|------------|---------
/// | `0xxxxxxx` |            |            |            |            |            |
/// | `110xxxxx` | `10xxxxxx` |            |            |            |            |
/// | `1110xxxx` | `10xxxxxx` | `10xxxxxx` |            |            |            |
/// | `11110xxx` | `10xxxxxx` | `10xxxxxx` | `10xxxxxx` |            |            |
/// | `111110xx` | `10xxxxxx` | `10xxxxxx` | `10xxxxxx` | `10xxxxxx` |            |
/// | `1111110x` | `10xxxxxx` | `10xxxxxx` | `10xxxxxx` | `10xxxxxx` | `10xxxxxx` |
/// | `11111110` | `10xxxxxx` | `10xxxxxx` | `10xxxxxx` | `10xxxxxx` | `10xxxxxx` | `10xxxxxx`
///
/// The `x` bits are the frame number, encoded from most-significant
/// to least significant.
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub struct FrameNumber(pub u64);

impl FrameNumber {
    /// Our maximum frame number
    const MAX_FRAME_NUMBER: u64 = (1 << 36) - 1;

    /// Attempt to increment frame number
    ///
    /// # Error
    ///
    /// Returns an error if the frame number is too large
    pub fn try_increment(&mut self) -> Result<(), Error> {
        if self.0 < Self::MAX_FRAME_NUMBER {
            self.0 += 1;
            Ok(())
        } else {
            Err(Error::ExcessiveFrameNumber)
        }
    }
}

impl std::fmt::Display for FrameNumber {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl FromBitStream for FrameNumber {
    type Error = Error;

    fn from_reader<R: BitRead + ?Sized>(r: &mut R) -> Result<Self, Error> {
        match r.read_unary::<0>()? {
            0 => Ok(Self(r.read::<7, _>()?)),
            1 => Err(Error::InvalidFrameNumber),
            bytes @ 2..=7 => {
                let mut frame = r.read_var(7 - bytes)?;
                for _ in 1..bytes {
                    r.read_const::<2, 0b10, _>(Error::InvalidFrameNumber)?;
                    frame = (frame << 6) | r.read::<6, u64>()?;
                }
                Ok(Self(frame))
            }
            _ => Err(Error::InvalidFrameNumber),
        }
    }
}

impl ToBitStream for FrameNumber {
    type Error = Error;

    fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Error> {
        #[inline]
        fn byte(num: u64, byte: u32) -> u8 {
            0b10_000000 | ((num >> (6 * byte)) & 0b111111) as u8
        }

        match self.0 {
            v @ 0..=0x7F => {
                w.write_unary::<0>(0)?;
                w.write::<7, _>(v)?;
                Ok(())
            }
            v @ 0x80..=0x7FF => {
                w.write_unary::<0>(2)?;
                w.write::<5, _>(v >> 6)?;
                w.write::<8, _>(byte(v, 0))?;
                Ok(())
            }
            v @ 0x800..=0xFFFF => {
                w.write_unary::<0>(3)?;
                w.write::<4, _>(v >> (6 * 2))?;
                w.write::<8, _>([byte(v, 1), byte(v, 0)])?;
                Ok(())
            }
            v @ 0x1_0000..=0x1F_FFFF => {
                w.write_unary::<0>(4)?;
                w.write::<3, _>(v >> (6 * 3))?;
                w.write::<8, _>([byte(v, 2), byte(v, 1), byte(v, 0)])?;
                Ok(())
            }
            v @ 0x20_0000..=0x3FF_FFFF => {
                w.write_unary::<0>(5)?;
                w.write::<2, _>(v >> (6 * 4))?;
                w.write::<8, _>([byte(v, 3), byte(v, 2), byte(v, 1), byte(v, 0)])?;
                Ok(())
            }
            v @ 0x400_0000..=0x7FFF_FFFF => {
                w.write_unary::<0>(6)?;
                w.write::<1, _>(v >> (6 * 5))?;
                w.write::<8, _>([byte(v, 4), byte(v, 3), byte(v, 2), byte(v, 1), byte(v, 0)])?;
                Ok(())
            }
            v @ 0x8000_0000..=0xF_FFFF_FFFF => {
                w.write_unary::<0>(7)?;
                w.write::<8, _>([
                    byte(v, 5),
                    byte(v, 4),
                    byte(v, 3),
                    byte(v, 2),
                    byte(v, 1),
                    byte(v, 0),
                ])?;
                Ok(())
            }
            _ => Err(Error::InvalidFrameNumber),
        }
    }
}

#[test]
fn test_frame_number() {
    use bitstream_io::{BigEndian, BitRead, BitReader, BitWrite, BitWriter};

    let mut buf: [u8; 7] = [0; 7];

    for i in (0..=0xFFFF)
        .chain((0x1_0000..=0x1F_FFFF).step_by(32))
        .chain((0x20_0000..=0x3FF_FFFF).step_by(1024))
        .chain((0x400_0000..=0x7FFF_FFFF).step_by(33760))
        .chain((0x8000_0000..=0xF_FFFF_FFFF).step_by(1048592))
    {
        let num = FrameNumber(i);

        assert!(
            BitWriter::endian(buf.as_mut_slice(), BigEndian)
                .build(&num)
                .is_ok()
        );

        let num2 = BitReader::endian(buf.as_slice(), BigEndian)
            .parse::<FrameNumber>()
            .unwrap();

        assert_eq!(num.0, num2.0);

        buf.fill(0);
    }
}

/// A Subframe Header
///
/// | Bits | Field   | Meaning
/// |-----:|---------|--------
/// | 1    | pad (0) |
/// | 6    | `type_` | subframe type and (if any) order
/// | 1    | has wasted bits | whether the subframe has wasted bits-per-sample
/// | (0+) | `wasted_bps`| the number of wasted bits-per-sample, as unary
///
/// "Wasted" bits is when all of the samples in a given subframe
/// have one or more `0` bits in the least-significant bits position.
/// In this case, the samples can all be safely right shifted
/// by that amount of wasted bits during encoding, and left
/// shifted by that amount of bits during decoding, without loss.
///
/// This is an uncommon case.
#[derive(Debug)]
pub struct SubframeHeader {
    /// The subframe header's type
    pub type_: SubframeHeaderType,
    /// The number of wasted bits-per-sample
    pub wasted_bps: u32,
}

impl FromBitStream for SubframeHeader {
    type Error = Error;

    fn from_reader<R: BitRead + ?Sized>(r: &mut R) -> Result<Self, Error> {
        r.read_const::<1, 0, _>(Error::InvalidSubframeHeader)?;
        Ok(Self {
            type_: r.parse()?,
            wasted_bps: match r.read_bit()? {
                false => 0,
                true => r.read_unary::<1>()? + 1,
            },
        })
    }
}

impl ToBitStream for SubframeHeader {
    type Error = Error;

    fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Error> {
        w.write_const::<1, 0>()?;
        w.build(&self.type_)?;
        match self.wasted_bps.checked_sub(1) {
            None => w.write_bit(false)?,
            Some(wasted) => {
                w.write_bit(true)?;
                w.write_unary::<1>(wasted)?;
            }
        }

        Ok(())
    }
}

/// A subframe's type
#[derive(Debug, Eq, PartialEq, Copy, Clone, Hash, Ord, PartialOrd)]
pub enum SubframeType {
    /// A constant subframe
    Constant,
    /// A verbatim subframe
    Verbatim,
    /// A fixed subframe
    Fixed,
    /// An LPC subframe
    Lpc,
}

impl std::fmt::Display for SubframeType {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::Constant => "CONSTANT".fmt(f),
            Self::Verbatim => "VERBATIM".fmt(f),
            Self::Fixed => "FIXED".fmt(f),
            Self::Lpc => "LPC".fmt(f),
        }
    }
}

/// A subframe header's type and order
///
/// This is always a 6-bit field.
///
/// | Bits     | Type | Order
/// |----------|------|--------
/// | `000000` | CONSTANT | N/A
/// | `000001` | VERBATIM | N/A
/// | `000010` to `000111` | reserved | N/A
/// | `001000` to `001100` | FIXED    | `v - 8`
/// | `001101` to `011111` | reserved | N/A
/// | `100000` to `111111` | LPC      | `v - 31`
#[derive(Debug, Eq, PartialEq)]
pub enum SubframeHeaderType {
    /// All samples are the same
    ///
    /// # Example
    /// ```
    /// use flac_codec::stream::SubframeHeaderType;
    /// use bitstream_io::{BitReader, BitRead, BigEndian};
    ///
    /// let data: &[u8] = &[0b0_000000_0];
    /// let mut r = BitReader::endian(data, BigEndian);
    /// r.skip(1).unwrap();  // pad bit
    /// assert_eq!(
    ///     r.parse::<SubframeHeaderType>().unwrap(),
    ///     SubframeHeaderType::Constant,
    /// );
    /// ```
    Constant,
    /// All samples as stored verbatim, without compression
    ///
    /// # Example
    /// ```
    /// use flac_codec::stream::SubframeHeaderType;
    /// use bitstream_io::{BitReader, BitRead, BigEndian};
    ///
    /// let data: &[u8] = &[0b0_000001_0];
    /// let mut r = BitReader::endian(data, BigEndian);
    /// r.skip(1).unwrap();  // pad bit
    /// assert_eq!(
    ///     r.parse::<SubframeHeaderType>().unwrap(),
    ///     SubframeHeaderType::Verbatim,
    /// );
    /// ```
    Verbatim,
    /// Samples are stored with one of a set of fixed LPC parameters
    ///
    /// # Example
    /// ```
    /// use flac_codec::stream::SubframeHeaderType;
    /// use bitstream_io::{BitReader, BitRead, BigEndian};
    ///
    /// let data: &[u8] = &[0b0_001100_0];
    /// let mut r = BitReader::endian(data, BigEndian);
    /// r.skip(1).unwrap();  // pad bit
    /// assert_eq!(
    ///     r.parse::<SubframeHeaderType>().unwrap(),
    ///     SubframeHeaderType::Fixed { order: 0b001100 - 8 },  // order = 4
    /// );
    /// ```
    Fixed {
        /// The predictor order, from 0..5
        order: u8,
    },
    /// Samples are stored with dynamic LPC parameters
    ///
    /// # Example
    /// ```
    /// use flac_codec::stream::SubframeHeaderType;
    /// use bitstream_io::{BitReader, BitRead, BigEndian};
    /// use std::num::NonZero;
    ///
    /// let data: &[u8] = &[0b0_100000_0];
    /// let mut r = BitReader::endian(data, BigEndian);
    /// r.skip(1).unwrap();  // pad bit
    /// assert_eq!(
    ///     r.parse::<SubframeHeaderType>().unwrap(),
    ///     SubframeHeaderType::Lpc {
    ///         order: NonZero::new(0b100000 - 31).unwrap(),  // order = 1
    ///     },
    /// );
    /// ```
    Lpc {
        /// The predictor order, from 1..33
        order: NonZero<u8>,
    },
}

impl SubframeHeaderType {
    /// A set of FIXED subframe coefficients
    ///
    /// Note that these are in the reverse order from how
    /// they're usually presented, simply because we'll
    /// be predicting samples in reverse order.
    pub const FIXED_COEFFS: [&[i64]; 5] = [&[], &[1], &[2, -1], &[3, -3, 1], &[4, -6, 4, -1]];
}

impl FromBitStream for SubframeHeaderType {
    type Error = Error;

    fn from_reader<R: BitRead + ?Sized>(r: &mut R) -> Result<Self, Error> {
        match r.read::<6, u8>()? {
            0b000000 => Ok(Self::Constant),
            0b000001 => Ok(Self::Verbatim),
            v @ 0b001000..=0b001100 => Ok(Self::Fixed {
                order: v - 0b001000,
            }),
            v @ 0b100000..=0b111111 => Ok(Self::Lpc {
                order: NonZero::new(v - 31).unwrap(),
            }),
            _ => Err(Error::InvalidSubframeHeaderType),
        }
    }
}

impl ToBitStream for SubframeHeaderType {
    type Error = Error;

    fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Error> {
        w.write::<6, u8>(match self {
            Self::Constant => 0b000000,
            Self::Verbatim => 0b000001,
            Self::Fixed { order } => 0b001000 + order,
            Self::Lpc { order } => order.get() + 31,
        })?;
        Ok(())
    }
}

/// A FLAC residual partition header
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ResidualPartitionHeader<const RICE_MAX: u32> {
    /// Standard, un-escaped partition
    Standard {
        /// The partition's Rice parameter
        rice: BitCount<RICE_MAX>,
    },
    /// Escaped partition
    Escaped {
        /// The size of each residual in bits
        escape_size: SignedBitCount<0b11111>,
    },
    /// All residuals in partition are 0
    Constant,
}

impl<const RICE_MAX: u32> FromBitStream for ResidualPartitionHeader<RICE_MAX> {
    type Error = std::io::Error;

    fn from_reader<R: BitRead + ?Sized>(r: &mut R) -> Result<Self, Self::Error> {
        let rice = r.read_count()?;

        if rice == BitCount::new::<{ RICE_MAX }>() {
            match r.read_count()?.signed_count() {
                Some(escape_size) => Ok(Self::Escaped { escape_size }),
                None => Ok(Self::Constant),
            }
        } else {
            Ok(Self::Standard { rice })
        }
    }
}

impl<const RICE_MAX: u32> ToBitStream for ResidualPartitionHeader<RICE_MAX> {
    type Error = std::io::Error;

    fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Self::Error> {
        match self {
            Self::Standard { rice } => w.write_count(*rice),
            Self::Escaped { escape_size } => {
                w.write_count(BitCount::<RICE_MAX>::new::<{ RICE_MAX }>())?;
                w.write_count(escape_size.count())
            }
            Self::Constant => {
                w.write_count(BitCount::<RICE_MAX>::new::<{ RICE_MAX }>())?;
                w.write_count(BitCount::<0b11111>::new::<0>())
            }
        }
    }
}

/// A whole FLAC frame
///
/// A FLAC frame consists of a header, one or more subframes
/// (each corresponding to a different channel), and concludes with
/// a CRC-16 checksum over all the data in the frame.
///
/// ```text
/// ┌──────────┬────────┬┄┄┄┄┄┄┄┄┬┄┄┄┬────────┬┄┄┄┄┄┄┄┄┬┄┄┄╮
/// │ FLAC Tag │ Block₀ │ Block₁ ┆ … ┆ Frame₀ │ Frame₁ ┆ … ┆ FLAC File
/// └──────────┴────────┴┄┄┄┄┄┄┄┄┴┄┄┄┼────────┼┄┄┄┄┄┄┄┄┴┄┄┄╯
/// ╭────────────────────────────────╯        ╰─────────╮
/// ├──────────────┬───────────┬┄┄┄┄┄┄┄┄┄┄┄┬┄┄┄┬────────┤
/// │ Frame Header │ Subframe₀ │ Subframe₁ ┆ … ┆ CRC-16 │    FLAC Frame
/// └──────────────┴───────────┴┄┄┄┄┄┄┄┄┄┄┄┴┄┄┄┴────────┘
/// ```
///
/// # Example
///
/// ```
/// use flac_codec::stream::{
///     Frame, FrameHeader, BlockSize, SampleRate, ChannelAssignment,
///     Independent, BitsPerSample, FrameNumber, SubframeWidth, Subframe,
/// };
///
/// let mut data: &[u8] = &[
///     // frame header
///     0xff, 0xf8, 0x69, 0x08, 0x00, 0x13, 0x64,
///     // subframe
///     0x00, 0x00, 0x00,
///     // CRC-16
///     0xd3, 0x3b,
/// ];
///
/// assert_eq!(
///     Frame::read_subset(&mut data).unwrap(),
///     Frame {
///         header: FrameHeader {
///             blocking_strategy: false,
///             block_size: BlockSize::Uncommon8(20),
///             sample_rate: SampleRate::Hz44100,
///             channel_assignment: ChannelAssignment::Independent(
///                 Independent::Mono
///             ),
///             bits_per_sample: BitsPerSample::Bps16,
///             frame_number: FrameNumber(0),
///         },
///         subframes: vec![
///             SubframeWidth::Common(
///                 Subframe::Constant {
///                     block_size: 20,
///                     sample: 0x00_00,
///                     wasted_bps: 0,
///                 },
///             )
///         ],
///     },
/// );
/// ```
#[derive(Debug, Eq, PartialEq)]
pub struct Frame {
    /// The FLAC frame's header
    pub header: FrameHeader,
    /// A FLAC frame's sub-frames
    pub subframes: Vec<SubframeWidth>,
}

impl Frame {
    fn read_inner<R, F>(reader: &mut R, read_header: F) -> Result<Self, Error>
    where
        R: std::io::Read,
        F: FnOnce(&mut CrcReader<&mut R, Crc16>) -> Result<FrameHeader, Error>,
    {
        use bitstream_io::{BigEndian, BitReader};
        use std::io::Read;

        let mut crc16_reader: CrcReader<_, Crc16> = CrcReader::new(reader.by_ref());

        let header = read_header(crc16_reader.by_ref())?;

        let mut reader = BitReader::endian(crc16_reader.by_ref(), BigEndian);

        let subframes = match header.channel_assignment {
            ChannelAssignment::Independent(total_channels) => (0..total_channels as u8)
                .map(|_| {
                    reader
                        .parse_using::<Subframe<i32>>((
                            header.block_size.into(),
                            header.bits_per_sample.into(),
                        ))
                        .map(SubframeWidth::Common)
                })
                .collect::<Result<Vec<_>, _>>()?,
            ChannelAssignment::LeftSide => vec![
                reader
                    .parse_using((header.block_size.into(), header.bits_per_sample.into()))
                    .map(SubframeWidth::Common)?,
                match header.bits_per_sample.checked_add(1) {
                    Some(side_bps) => reader
                        .parse_using((header.block_size.into(), side_bps))
                        .map(SubframeWidth::Common)?,
                    None => reader
                        .parse_using((
                            header.block_size.into(),
                            SignedBitCount::from(header.bits_per_sample)
                                .checked_add(1)
                                .unwrap(),
                        ))
                        .map(SubframeWidth::Wide)?,
                },
            ],
            ChannelAssignment::SideRight => vec![
                match header.bits_per_sample.checked_add(1) {
                    Some(side_bps) => reader
                        .parse_using((header.block_size.into(), side_bps))
                        .map(SubframeWidth::Common)?,
                    None => reader
                        .parse_using((
                            header.block_size.into(),
                            SignedBitCount::from(header.bits_per_sample)
                                .checked_add(1)
                                .unwrap(),
                        ))
                        .map(SubframeWidth::Wide)?,
                },
                reader
                    .parse_using((header.block_size.into(), header.bits_per_sample.into()))
                    .map(SubframeWidth::Common)?,
            ],
            ChannelAssignment::MidSide => vec![
                reader
                    .parse_using((header.block_size.into(), header.bits_per_sample.into()))
                    .map(SubframeWidth::Common)?,
                match header.bits_per_sample.checked_add(1) {
                    Some(side_bps) => reader
                        .parse_using((header.block_size.into(), side_bps))
                        .map(SubframeWidth::Common)?,
                    None => reader
                        .parse_using((
                            header.block_size.into(),
                            SignedBitCount::from(header.bits_per_sample)
                                .checked_add(1)
                                .unwrap(),
                        ))
                        .map(SubframeWidth::Wide)?,
                },
            ],
        };

        reader.byte_align();
        reader.skip(16)?; // CRC-16 checksum

        if crc16_reader.into_checksum().valid() {
            Ok(Self { header, subframes })
        } else {
            Err(Error::Crc16Mismatch)
        }
    }

    /// Reads new frame from the given reader
    #[inline]
    pub fn read<R: std::io::Read>(reader: &mut R, streaminfo: &Streaminfo) -> Result<Self, Error> {
        Self::read_inner(reader, |r| FrameHeader::read(r, streaminfo))
    }

    /// Reads new frame from the given reader
    ///
    /// Subset files are streamable FLAC files whose decoding
    /// parameters are fully contained within each frame header.
    #[inline]
    pub fn read_subset<R: std::io::Read>(reader: &mut R) -> Result<Self, Error> {
        Self::read_inner(reader, |r| FrameHeader::read_subset(r))
    }

    fn write_inner<W, F>(&self, write_header: F, writer: &mut W) -> Result<(), Error>
    where
        W: std::io::Write,
        F: FnOnce(&mut CrcWriter<&mut W, Crc16>, &FrameHeader) -> Result<(), Error>,
    {
        use bitstream_io::{BigEndian, BitWriter};
        use std::io::Write;

        let mut crc16_writer: CrcWriter<_, Crc16> = CrcWriter::new(writer.by_ref());

        write_header(crc16_writer.by_ref(), &self.header)?;

        let mut writer = BitWriter::endian(crc16_writer.by_ref(), BigEndian);

        match self.header.channel_assignment {
            ChannelAssignment::Independent(total_channels) => {
                assert_eq!(total_channels as usize, self.subframes.len());

                for subframe in &self.subframes {
                    // independent subframes should always be standard width
                    if let SubframeWidth::Common(subframe) = subframe {
                        writer.build_using(subframe, self.header.bits_per_sample.into())?;
                    }
                }
            }
            ChannelAssignment::LeftSide => match self.subframes.as_slice() {
                [left, side] => {
                    if let SubframeWidth::Common(left) = left {
                        writer.build_using(left, self.header.bits_per_sample.into())?;
                    }

                    match side {
                        SubframeWidth::Common(side) => {
                            writer.build_using(
                                side,
                                self.header
                                    .bits_per_sample
                                    .checked_add(1)
                                    .ok_or(Error::ExcessiveBps)?,
                            )?;
                        }
                        SubframeWidth::Wide(side) => {
                            writer.build_using(
                                side,
                                SignedBitCount::from(self.header.bits_per_sample)
                                    .checked_add(1)
                                    .ok_or(Error::ExcessiveBps)?,
                            )?;
                        }
                    }
                }
                _ => panic!("incorrect subframe count for left-side"),
            },
            ChannelAssignment::SideRight => match self.subframes.as_slice() {
                [side, right] => {
                    match side {
                        SubframeWidth::Common(side) => {
                            writer.build_using(
                                side,
                                self.header
                                    .bits_per_sample
                                    .checked_add(1)
                                    .ok_or(Error::ExcessiveBps)?,
                            )?;
                        }
                        SubframeWidth::Wide(side) => {
                            writer.build_using(
                                side,
                                SignedBitCount::from(self.header.bits_per_sample)
                                    .checked_add(1)
                                    .ok_or(Error::ExcessiveBps)?,
                            )?;
                        }
                    }

                    if let SubframeWidth::Common(right) = right {
                        writer.build_using(right, self.header.bits_per_sample.into())?;
                    }
                }
                _ => panic!("incorrect subframe count for left-side"),
            },
            ChannelAssignment::MidSide => match self.subframes.as_slice() {
                [mid, side] => {
                    if let SubframeWidth::Common(mid) = mid {
                        writer.build_using(mid, self.header.bits_per_sample.into())?;
                    }

                    match side {
                        SubframeWidth::Common(side) => {
                            writer.build_using(
                                side,
                                self.header
                                    .bits_per_sample
                                    .checked_add(1)
                                    .ok_or(Error::ExcessiveBps)?,
                            )?;
                        }
                        SubframeWidth::Wide(side) => {
                            writer.build_using(
                                side,
                                SignedBitCount::from(self.header.bits_per_sample)
                                    .checked_add(1)
                                    .ok_or(Error::ExcessiveBps)?,
                            )?;
                        }
                    }
                }
                _ => panic!("incorrect subframe count for left-side"),
            },
        }

        let crc16: u16 = writer.aligned_writer()?.checksum().into();
        writer.write_from(crc16)?;

        Ok(())
    }

    /// Writes frame to the given writer
    pub fn write<W: std::io::Write>(
        &self,
        streaminfo: &Streaminfo,
        writer: &mut W,
    ) -> Result<(), Error> {
        self.write_inner(|w, header| header.write(w, streaminfo), writer)
    }

    /// Writes frame to the given writer
    ///
    /// Subset files are streamable FLAC files whose encoding
    /// parameters are fully contained within each frame header.
    #[inline]
    pub fn write_subset<W: std::io::Write>(&self, writer: &mut W) -> Result<(), Error> {
        self.write_inner(|w, header| header.write_subset(w), writer)
    }
}

/// An iterator of Frames
pub struct FrameIterator<R> {
    reader: crate::Counter<R>,
    blocks: crate::metadata::BlockList,
    metadata_len: u64,
    remaining_samples: Option<u64>,
}

impl<R: std::io::Read> FrameIterator<R> {
    /// Opens new FrameIterator from the given reader
    ///
    /// The reader must be positioned at the start of the
    /// FLAC stream.  If the file has non-FLAC data
    /// at the beginning (such as ID3v2 tags), one
    /// should skip such data before initializing a `FrameIterator`.
    pub fn new(reader: R) -> Result<Self, Error> {
        let mut reader = crate::Counter::new(reader);
        let blocks = crate::metadata::BlockList::read(&mut reader)?;

        Ok(Self {
            metadata_len: reader.count,
            remaining_samples: blocks.streaminfo().total_samples.map(|s| s.get()),
            blocks,
            reader,
        })
    }

    /// Returns shared reference to FLAC's metadata blocks
    pub fn metadata(&self) -> &crate::metadata::BlockList {
        &self.blocks
    }

    /// Returns total length of all metadata blocks and FLAC tag
    pub fn metadata_len(&self) -> u64 {
        self.metadata_len
    }
}

impl FrameIterator<std::io::BufReader<std::fs::File>> {
    /// Opens new FrameIterator from file on disk
    pub fn open<P: AsRef<std::path::Path>>(path: P) -> Result<Self, Error> {
        std::fs::File::open(path.as_ref())
            .map_err(Error::Io)
            .and_then(|f| Self::new(std::io::BufReader::new(f)))
    }
}

impl<R: std::io::Read> Iterator for FrameIterator<R> {
    /// Returns both frame and frame's absolute position in stream, in bytes
    type Item = Result<(Frame, u64), Error>;

    fn next(&mut self) -> Option<Self::Item> {
        match self.remaining_samples.as_mut() {
            Some(0) => None,
            Some(remaining) => {
                let offset = self.reader.count;
                match Frame::read(&mut self.reader, self.blocks.streaminfo()) {
                    Ok(frame) => {
                        *remaining = remaining
                            .checked_sub(u64::from(u16::from(frame.header.block_size)))
                            .unwrap_or_default();
                        Some(Ok((frame, offset)))
                    }
                    Err(err) => Some(Err(err)),
                }
            }
            None => {
                // if total number of remaining samples isn't known,
                // treat an EOF error as the end of stream
                // (this is an uncommon case)
                let offset = self.reader.count;
                match Frame::read(&mut self.reader, self.blocks.streaminfo()) {
                    Ok(frame) => Some(Ok((frame, offset))),
                    Err(Error::Io(err)) if err.kind() == std::io::ErrorKind::UnexpectedEof => None,
                    Err(err) => Some(Err(err)),
                }
            }
        }
    }
}

impl<R> crate::metadata::Metadata for FrameIterator<R> {
    fn channel_count(&self) -> u8 {
        self.blocks.streaminfo().channels.get()
    }

    fn channel_mask(&self) -> crate::metadata::ChannelMask {
        self.blocks.channel_mask()
    }

    fn sample_rate(&self) -> u32 {
        self.blocks.streaminfo().sample_rate
    }

    fn bits_per_sample(&self) -> u32 {
        self.blocks.streaminfo().bits_per_sample.into()
    }

    fn total_samples(&self) -> Option<u64> {
        self.blocks.streaminfo().total_samples.map(|s| s.get())
    }

    fn md5(&self) -> Option<&[u8; 16]> {
        self.blocks.streaminfo().md5.as_ref()
    }
}

/// A 32 or 64-bit FLAC file subframe
///
/// The FLAC format itself is limited to 32-bit samples
/// for input and output, as shown in the STREAMINFO metadata
/// block.  However, channel correlation means that the
/// side (difference) channel needs 1 additional bit.
/// Therefore, the side channel of a 32-bit stereo stream
/// needs *33* bits to store its samples.
///
/// Such subframes are considered "wide" and need to
/// handle 64-bit samples internally.
///
/// This is an extremely rare case in practice.
#[derive(Debug, Eq, PartialEq)]
pub enum SubframeWidth {
    /// A common 32-bit subframe
    Common(Subframe<i32>),
    /// A rare 64-bit subframe
    Wide(Subframe<i64>),
}

/// A FLAC's frame's subframe, one per channel
///
/// A subframe consists of a subframe header followed by subframe data.
#[derive(Debug, Eq, PartialEq)]
pub enum Subframe<I> {
    /// A CONSTANT subframe, in which all samples are identical
    ///
    /// | Bits                       | Field    |
    /// |----------------------------|----------|
    /// | subframe's bits-per-sample | `sample` |
    ///
    /// This single sample is repeated for all the samples in the subframe.
    ///
    /// This is typically for long stretches of silence,
    /// or for the difference channel when both channels are
    /// identical in a stereo stream (false stereo).
    ///
    /// # Example
    ///
    /// ```
    /// use flac_codec::stream::Subframe;
    /// use bitstream_io::{BitReader, BitRead, BigEndian, SignedBitCount};
    ///
    /// let data: &[u8] = &[
    ///     0b0_000000_0,  // subframe header
    ///     0x00, 0x00,    // subframe data
    /// ];
    ///
    /// let mut r = BitReader::endian(data, BigEndian);
    ///
    /// assert_eq!(
    ///     r.parse_using::<Subframe<i32>>((20, SignedBitCount::new::<16>())).unwrap(),
    ///     Subframe::Constant {
    ///         // taken from context
    ///         block_size: 20,
    ///         // constant subframes always have exactly one sample
    ///         // this sample's size is a signed 16-bit value
    ///         // taken from the subframe signed bit count
    ///         sample: 0x00_00,
    ///         // wasted bits-per-sample is taken from the subframe header
    ///         wasted_bps: 0,
    ///     },
    /// );
    /// ```
    Constant {
        /// the subframe's block size in samples
        block_size: u16,
        /// The subframe's sample
        sample: I,
        /// Any wasted bits-per-sample
        wasted_bps: u32,
    },
    /// A VERBATIM subframe, in which all samples are stored uncompressed
    ///
    /// | Bits           | Field      |
    /// |----------------|------------|
    /// | subframe's bps | `samples₀` |
    /// | subframe's bps | `samples₁` |
    /// | subframe's bps | `samples₂` |
    /// |                | ⋮          |
    ///
    /// The number of samples equals the frame's block size.
    ///
    /// This is for random noise which does not compress well
    /// by any other method.
    ///
    /// # Example
    ///
    /// ```
    /// use flac_codec::stream::Subframe;
    /// use bitstream_io::{BitReader, BitRead, BigEndian, SignedBitCount};
    ///
    /// let data: &[u8] = &[
    ///     0b0_000001_0,  // subframe header
    ///     // subframe data
    ///     0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x04,
    ///     0x00, 0x05, 0x00, 0x06, 0x00, 0x07, 0x00, 0x08, 0x00, 0x09,
    ///     0x00, 0x0a, 0x00, 0x0b, 0x00, 0x0c, 0x00, 0x0d, 0x00, 0x0e,
    ///     0x00, 0x0f, 0x00, 0x10, 0x00, 0x11, 0x00, 0x12, 0x00, 0x13,
    /// ];
    ///
    /// let mut r = BitReader::endian(data, BigEndian);
    ///
    /// assert_eq!(
    ///     r.parse_using::<Subframe<i32>>((20, SignedBitCount::new::<16>())).unwrap(),
    ///     Subframe::Verbatim {
    ///         // the total number of samples equals the block size
    ///         // (20 in this case)
    ///         // each sample is a signed 16-bit value,
    ///         // taken from the subframe signed bit count
    ///         samples: vec![
    ///             0x00, 0x01, 0x02, 0x03, 0x04,
    ///             0x05, 0x06, 0x07, 0x08, 0x09,
    ///             0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
    ///             0x0f, 0x10, 0x11, 0x12, 0x13,
    ///         ],
    ///         // wasted bits-per-sample is taken from the subframe header
    ///         wasted_bps: 0,
    ///     },
    /// );
    /// ```
    Verbatim {
        /// The subframe's samples
        samples: Vec<I>,
        /// Any wasted bits-per-sample
        wasted_bps: u32,
    },
    /// A FIXED subframe, encoded with a fixed set of parameters
    ///
    /// | Bits           | Field         |
    /// |----------------|---------------|
    /// | subframe's bps | `warm_up₀`    |
    /// | subframe's bps | `warm_up₁`    |
    /// | subframe's bps | `warm_up₂`    |
    /// |                | ⋮             |
    /// |                | [`Residuals`] |
    ///
    /// The number of warm-up simples equals the subframe's
    /// predictor order (from the subframe header).
    ///
    /// FIXED subframes have predictor coefficients that are
    /// defined by their predictor order.  Because those coefficients
    /// require no floating-point math to calculate, these subframes
    /// can be encoded by limited hardware with no floating-point
    /// capabilities.
    ///
    /// # Example
    ///
    /// ```
    /// use flac_codec::stream::{Subframe, Residuals, ResidualPartition};
    /// use bitstream_io::{BitReader, BitRead, BigEndian, BitCount, SignedBitCount};
    ///
    /// let data: &[u8] = &[
    ///     0b0_001100_0,  // subframe header
    ///     // warm-up samples
    ///     0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03,
    ///     // residuals
    ///     0x00, 0x3f, 0xff, 0xc0,
    /// ];
    ///
    /// let mut r = BitReader::endian(data, BigEndian);
    ///
    /// assert_eq!(
    ///     r.parse_using::<Subframe<i32>>((20, SignedBitCount::new::<16>())).unwrap(),
    ///     Subframe::Fixed {
    ///         // predictor order is determined from subframe header
    ///         order: 4,
    ///         // the total number of warm-up samples equals the predictor order (4)
    ///         // each warm-up sample is a signed 16-bit value,
    ///         // taken from the subframe signed bit count
    ///         warm_up: vec![0x00, 0x01, 0x02, 0x03],
    ///         // the total number of residuals equals the block size
    ///         // minus the predictor order,
    ///         // which is 20 - 4 = 16 in this case
    ///         residuals: Residuals::Method0 {
    ///             partitions: vec![
    ///                 ResidualPartition::Standard {
    ///                     rice: BitCount::new::<0>(),
    ///                     residuals: vec![0; 16],
    ///                 }
    ///             ],
    ///         },
    ///         // wasted bits-per-sample is taken from the subframe header
    ///         wasted_bps: 0,
    ///     },
    /// );
    /// ```
    Fixed {
        /// The subframe's predictor order from 0 to 4 (inclusive)
        order: u8,
        /// The subframe's warm-up samples (one per order)
        warm_up: Vec<I>,
        /// The subframe's residuals
        residuals: Residuals<I>,
        /// Any wasted bits-per-sample
        wasted_bps: u32,
    },
    /// An LPC subframe, encoded with a variable set of parameters
    ///
    /// | Bits           | Field            |
    /// |----------------|------------------|
    /// | subframe's bps | `warm_up₀`       |
    /// | subframe's bps | `warm_up₁`       |
    /// | subframe's bps | `warm_up₂`       |
    /// |                | ⋮                |
    /// | 4              | `precision` (+1) |
    /// | 5              | `shift`          |
    /// | `precision`    | `coefficients₀`  |
    /// | `precision`    | `coefficients₁`  |
    /// | `precision`    | `coefficients₂`  |
    /// |                | ⋮                |
    /// |                | [`Residuals`]    |
    ///
    /// The number of warm-up samples *and* number of predictor
    /// coefficients is equal to the subframe's predictor order
    /// (from the subframe header).  The `precision` value
    /// is used to determine the size of the predictor coefficients.
    /// The `shift` value is stored as a signed integer,
    /// but negative shifts are *not* supported by the format
    /// and should be considered an error.
    ///
    /// # Example
    ///
    /// ```
    /// use flac_codec::stream::{Subframe, Residuals, ResidualPartition};
    /// use bitstream_io::{BitReader, BitRead, BigEndian, BitCount, SignedBitCount};
    /// use std::num::NonZero;
    ///
    /// let data: &[u8] = &[
    ///     0b0_100000_0,  // subframe header
    ///     // warm-up sample
    ///     0x00, 0x00,
    ///     // precision + shift + coefficient
    ///     0b1011_0101, 0b1_0111110, 0b00101_000,
    ///     // residuals
    ///     0x02, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x80,
    /// ];
    ///
    /// let mut r = BitReader::endian(data, BigEndian);
    ///
    /// assert_eq!(
    ///     r.parse_using::<Subframe<i32>>((20, SignedBitCount::new::<16>())).unwrap(),
    ///     Subframe::Lpc {
    ///         // predictor order is determined from the subframe header
    ///         order: NonZero::new(1).unwrap(),
    ///         // the total number of warm-up samples equals the predictor order (1)
    ///         // each warm-up sample is a signed 16-bit value,
    ///         // taken from the subframe signed bit count
    ///         warm_up: vec![0x00],
    ///         // precision is a 4 bit value, plus one
    ///         precision: SignedBitCount::new::<{0b1011 + 1}>(),  // 12 bits
    ///         // shift is a 5 bit value
    ///         shift: 0b0101_1,  // 11
    ///         // the total number of coefficients equals the predictor order (1)
    ///         // size of each coefficient is a signed 12-bit value (from precision)
    ///         coefficients: vec![0b0111110_00101],  // 1989
    ///         // the total number of residuals equals the block size
    ///         // minus the predictor order,
    ///         // which is 20 - 1 = 19 in this case
    ///         residuals: Residuals::Method0 {
    ///             partitions: vec![
    ///                 ResidualPartition::Standard {
    ///                     rice: BitCount::new::<1>(),
    ///                     residuals: vec![
    ///                          1, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    ///                          2, 2, 2, 2, 2, 2, 2, 2, 2
    ///                     ],
    ///                 }
    ///             ],
    ///         },
    ///         // wasted bits-per-sample is taken from the subframe header
    ///         wasted_bps: 0,
    ///     },
    /// );
    /// ```
    Lpc {
        /// The subframe's predictor order
        order: NonZero<u8>,
        /// The subframe's warm-up samples (one per order)
        warm_up: Vec<I>,
        /// The subframe's QLP precision
        precision: SignedBitCount<15>,
        /// The subframe's QLP shift
        shift: u32,
        /// The subframe's QLP coefficients (one per order)
        coefficients: Vec<i32>,
        /// The subframe's residuals
        residuals: Residuals<I>,
        /// Any wasted bits-per-sample
        wasted_bps: u32,
    },
}

impl<I> Subframe<I> {
    /// Our subframe type
    pub fn subframe_type(&self) -> SubframeType {
        match self {
            Self::Constant { .. } => SubframeType::Constant,
            Self::Verbatim { .. } => SubframeType::Verbatim,
            Self::Fixed { .. } => SubframeType::Fixed,
            Self::Lpc { .. } => SubframeType::Lpc,
        }
    }
}

impl<I: SignedInteger> Subframe<I> {
    /// Decodes subframe to samples
    ///
    /// Note that decoding subframes to samples using this method
    /// is intended for analysis purposes.  The [`crate::decode`]
    /// module's decoders are preferred for general-purpose
    /// decoding as they perform fewer temporary allocations.
    pub fn decode(&self) -> Box<dyn Iterator<Item = I> + '_> {
        fn predict<I: SignedInteger>(coefficients: &[i64], qlp_shift: u32, channel: &mut [I]) {
            for split in coefficients.len()..channel.len() {
                let (predicted, residuals) = channel.split_at_mut(split);

                residuals[0] += I::from_i64(
                    predicted
                        .iter()
                        .rev()
                        .zip(coefficients)
                        .map(|(x, y)| (*x).into() * y)
                        .sum::<i64>()
                        >> qlp_shift,
                );
            }
        }

        match self {
            Self::Constant {
                sample,
                block_size,
                wasted_bps,
            } => Box::new((0..*block_size).map(move |_| *sample << *wasted_bps)),
            Self::Verbatim {
                samples,
                wasted_bps,
            } => Box::new(samples.iter().map(move |sample| *sample << *wasted_bps)),
            Self::Fixed {
                order,
                warm_up,
                residuals,
                wasted_bps,
            } => {
                let mut samples = warm_up.clone();
                samples.extend(residuals.residuals());
                predict(
                    SubframeHeaderType::FIXED_COEFFS[*order as usize],
                    0,
                    &mut samples,
                );
                Box::new(samples.into_iter().map(move |sample| sample << *wasted_bps))
            }
            Self::Lpc {
                warm_up,
                coefficients,
                residuals,
                wasted_bps,
                shift,
                ..
            } => {
                let mut samples = warm_up.clone();
                samples.extend(residuals.residuals());
                predict(
                    &coefficients
                        .iter()
                        .copied()
                        .map(i64::from)
                        .collect::<Vec<_>>(),
                    *shift,
                    &mut samples,
                );
                Box::new(samples.into_iter().map(move |sample| sample << *wasted_bps))
            }
        }
    }
}

fn read_subframe<const MAX: u32, R, I>(
    r: &mut R,
    block_size: u16,
    bits_per_sample: SignedBitCount<MAX>,
) -> Result<Subframe<I>, Error>
where
    R: BitRead + ?Sized,
    I: SignedInteger,
{
    match r.parse()? {
        SubframeHeader {
            type_: SubframeHeaderType::Constant,
            wasted_bps,
        } => Ok(Subframe::Constant {
            block_size,
            sample: r.read_signed_counted(
                bits_per_sample
                    .checked_sub::<MAX>(wasted_bps)
                    .ok_or(Error::ExcessiveWastedBits)?,
            )?,
            wasted_bps,
        }),
        SubframeHeader {
            type_: SubframeHeaderType::Verbatim,
            wasted_bps,
        } => {
            let effective_bps = bits_per_sample
                .checked_sub::<MAX>(wasted_bps)
                .ok_or(Error::ExcessiveWastedBits)?;

            Ok(Subframe::Verbatim {
                samples: (0..block_size)
                    .map(|_| r.read_signed_counted::<MAX, I>(effective_bps))
                    .collect::<Result<Vec<_>, _>>()?,
                wasted_bps,
            })
        }
        SubframeHeader {
            type_: SubframeHeaderType::Fixed { order },
            wasted_bps,
        } => {
            let effective_bps = bits_per_sample
                .checked_sub::<MAX>(wasted_bps)
                .ok_or(Error::ExcessiveWastedBits)?;

            Ok(Subframe::Fixed {
                order,
                warm_up: (0..order)
                    .map(|_| r.read_signed_counted::<MAX, I>(effective_bps))
                    .collect::<Result<Vec<_>, _>>()?,
                residuals: r.parse_using((block_size.into(), order.into()))?,
                wasted_bps,
            })
        }
        SubframeHeader {
            type_: SubframeHeaderType::Lpc { order },
            wasted_bps,
        } => {
            let effective_bps = bits_per_sample
                .checked_sub::<MAX>(wasted_bps)
                .ok_or(Error::ExcessiveWastedBits)?;

            let warm_up = (0..order.get())
                .map(|_| r.read_signed_counted::<MAX, I>(effective_bps))
                .collect::<Result<Vec<_>, _>>()?;

            let precision: SignedBitCount<15> = r
                .read_count::<0b1111>()?
                .checked_add(1)
                .and_then(|c| c.signed_count())
                .ok_or(Error::InvalidQlpPrecision)?;

            let shift: u32 = r
                .read::<5, i32>()?
                .try_into()
                .map_err(|_| Error::NegativeLpcShift)?;

            let coefficients = (0..order.get())
                .map(|_| r.read_signed_counted(precision))
                .collect::<Result<Vec<_>, _>>()?;

            Ok(Subframe::Lpc {
                order,
                warm_up,
                precision,
                shift,
                coefficients,
                residuals: r.parse_using((block_size.into(), order.get().into()))?,
                wasted_bps,
            })
        }
    }
}

impl FromBitStreamUsing for Subframe<i32> {
    type Context = (u16, SignedBitCount<32>);
    type Error = Error;

    fn from_reader<R: BitRead + ?Sized>(
        r: &mut R,
        (block_size, bits_per_sample): (u16, SignedBitCount<32>),
    ) -> Result<Self, Error> {
        read_subframe(r, block_size, bits_per_sample)
    }
}

impl FromBitStreamUsing for Subframe<i64> {
    type Context = (u16, SignedBitCount<33>);
    type Error = Error;

    fn from_reader<R: BitRead + ?Sized>(
        r: &mut R,
        (block_size, bits_per_sample): (u16, SignedBitCount<33>),
    ) -> Result<Self, Error> {
        read_subframe(r, block_size, bits_per_sample)
    }
}

fn write_subframe<const MAX: u32, W, I>(
    w: &mut W,
    bits_per_sample: SignedBitCount<MAX>,
    subframe: &Subframe<I>,
) -> Result<(), Error>
where
    W: BitWrite + ?Sized,
    I: SignedInteger,
{
    match subframe {
        Subframe::Constant {
            sample, wasted_bps, ..
        } => {
            w.build(&SubframeHeader {
                type_: SubframeHeaderType::Constant,
                wasted_bps: *wasted_bps,
            })?;

            w.write_signed_counted(
                bits_per_sample
                    .checked_sub::<MAX>(*wasted_bps)
                    .ok_or(Error::ExcessiveWastedBits)?,
                *sample,
            )?;

            Ok(())
        }
        Subframe::Verbatim {
            samples,
            wasted_bps,
        } => {
            let effective_bps = bits_per_sample
                .checked_sub::<MAX>(*wasted_bps)
                .ok_or(Error::ExcessiveWastedBits)?;

            w.build(&SubframeHeader {
                type_: SubframeHeaderType::Verbatim,
                wasted_bps: *wasted_bps,
            })?;

            for sample in samples {
                w.write_signed_counted(effective_bps, *sample)?;
            }

            Ok(())
        }
        Subframe::Fixed {
            order,
            warm_up,
            residuals,
            wasted_bps,
        } => {
            assert_eq!(*order as usize, warm_up.len());

            let effective_bps = bits_per_sample
                .checked_sub::<MAX>(*wasted_bps)
                .ok_or(Error::ExcessiveWastedBits)?;

            w.build(&SubframeHeader {
                type_: SubframeHeaderType::Fixed { order: *order },
                wasted_bps: *wasted_bps,
            })?;

            for sample in warm_up {
                w.write_signed_counted(effective_bps, *sample)?;
            }

            w.build(residuals)?;

            Ok(())
        }
        Subframe::Lpc {
            order,
            warm_up,
            precision,
            shift,
            coefficients,
            residuals,
            wasted_bps,
        } => {
            assert_eq!(order.get() as usize, warm_up.len());
            assert_eq!(order.get() as usize, coefficients.len());

            let effective_bps = bits_per_sample
                .checked_sub::<MAX>(*wasted_bps)
                .ok_or(Error::ExcessiveWastedBits)?;

            w.build(&SubframeHeader {
                type_: SubframeHeaderType::Lpc { order: *order },
                wasted_bps: *wasted_bps,
            })?;

            for sample in warm_up {
                w.write_signed_counted(effective_bps, *sample)?;
            }

            w.write_count(
                precision
                    .checked_sub::<0b1111>(1)
                    .ok_or(Error::InvalidQlpPrecision)?
                    .count(),
            )?;

            w.write::<5, i32>(i32::try_from(*shift).unwrap())?;

            for coeff in coefficients {
                w.write_signed_counted(*precision, *coeff)?;
            }

            w.build(residuals)?;

            Ok(())
        }
    }
}

impl ToBitStreamUsing for Subframe<i32> {
    type Context = SignedBitCount<32>;
    type Error = Error;

    fn to_writer<W: BitWrite + ?Sized>(
        &self,
        w: &mut W,
        bits_per_sample: SignedBitCount<32>,
    ) -> Result<(), Error> {
        write_subframe(w, bits_per_sample, self)
    }
}

impl ToBitStreamUsing for Subframe<i64> {
    type Context = SignedBitCount<33>;
    type Error = Error;

    fn to_writer<W: BitWrite + ?Sized>(
        &self,
        w: &mut W,
        bits_per_sample: SignedBitCount<33>,
    ) -> Result<(), Error> {
        write_subframe(w, bits_per_sample, self)
    }
}

/// A residual block's type
#[derive(Debug, Eq, PartialEq, Copy, Clone, Hash, Ord, PartialOrd)]
pub enum CodingMethod {
    /// Partitioned Rice code with 4-bit parameters
    Rice,
    /// Partitioned Rice code with 5-bit parameters
    Rice2,
}

impl std::fmt::Display for CodingMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::Rice => "RICE".fmt(f),
            Self::Rice2 => "RICE2".fmt(f),
        }
    }
}

/// Residual values for FIXED or LPC subframes
///
/// | Bits | Meaning |
/// |-----:|---------|
/// | 2    | residual coding method
/// | 4    | partition order
/// |      | residual partition₀
/// |      | (residual partition₁)
/// |      | ⋮
///
/// The residual coding method can be 0 or 1.
/// A coding method of 0 means 4-bit Rice parameters
/// in residual partitions.  A coding method of 5
/// means 5-bit Rice parameters in residual partitions
/// (method 0 is the common case).
///
/// The number of residual partitions equals
/// 2ⁿ where n is the partition order.
///
/// # Example
/// ```
/// use flac_codec::stream::{Residuals, ResidualPartition};
/// use bitstream_io::{BitReader, BitRead, BigEndian, BitCount};
///
/// let data: &[u8] = &[
///     0b00_0000_00,  // coding method + partition order + partition
///     // residual partition
///     0b01010001,
///     0b00010001,
///     0b00010001,
///     0b00010001,
///     0b00010001,
///     0b00010001,
///     0b00010001,
///     0b00010001,
///     0b00010001,
///     0b00010000,
///     0b00000000,
/// ];
///
/// let mut r = BitReader::endian(data, BigEndian);
///
/// assert_eq!(
///     r.parse_using::<Residuals<i32>>((20, 1)).unwrap(),
///     // coding method = 0b00
///     // partition order = 0b0000, or 1 partition
///     Residuals::Method0 {
///         partitions: vec![
///             ResidualPartition::Standard {
///                 rice: BitCount::new::<1>(),
///                 residuals: vec![
///                      1, 2, 2, 2, 2, 2, 2, 2, 2, 2,
///                      2, 2, 2, 2, 2, 2, 2, 2, 2
///                 ],
///             }
///         ],
///     },
/// );
/// ```
#[derive(Debug, Eq, PartialEq)]
pub enum Residuals<I> {
    /// Coding method 0
    Method0 {
        /// The residual partitions
        partitions: Vec<ResidualPartition<0b1111, I>>,
    },
    /// Coding method 1
    Method1 {
        /// The residual partitions
        partitions: Vec<ResidualPartition<0b11111, I>>,
    },
}

impl<I> Residuals<I> {
    /// The type of coding method in use, either Rice or Rice2
    pub fn coding_method(&self) -> CodingMethod {
        match self {
            Self::Method0 { .. } => CodingMethod::Rice,
            Self::Method1 { .. } => CodingMethod::Rice2,
        }
    }

    /// The residual block's partition order
    pub fn partition_order(&self) -> u32 {
        match self {
            Self::Method0 { partitions } => partitions.len().ilog2(),
            Self::Method1 { partitions } => partitions.len().ilog2(),
        }
    }
}

impl<I: SignedInteger> Residuals<I> {
    /// Iterates over all individual residual values
    fn residuals(&self) -> Box<dyn Iterator<Item = I> + '_> {
        match self {
            Self::Method0 { partitions } => Box::new(partitions.iter().flat_map(|p| p.residuals())),
            Self::Method1 { partitions } => Box::new(partitions.iter().flat_map(|p| p.residuals())),
        }
    }
}

impl<I: SignedInteger> FromBitStreamUsing for Residuals<I> {
    type Context = (usize, usize);
    type Error = Error;

    fn from_reader<R: BitRead + ?Sized>(
        r: &mut R,
        (block_size, predictor_order): (usize, usize),
    ) -> Result<Self, Error> {
        fn read_partitions<const RICE_MAX: u32, R: BitRead + ?Sized, I: SignedInteger>(
            reader: &mut R,
            (block_size, predictor_order): (usize, usize),
        ) -> Result<Vec<ResidualPartition<RICE_MAX, I>>, Error> {
            let partition_order = reader.read::<4, u32>()?;
            let partition_count = 1 << partition_order;

            (0..partition_count)
                .map(|p| {
                    reader.parse_using(
                        (block_size / partition_count)
                            .checked_sub(if p == 0 { predictor_order } else { 0 })
                            .ok_or(Error::InvalidPartitionOrder)?,
                    )
                })
                .collect()
        }

        match r.read::<2, u8>()? {
            0 => Ok(Self::Method0 {
                partitions: read_partitions::<0b1111, R, I>(r, (block_size, predictor_order))?,
            }),
            1 => Ok(Self::Method1 {
                partitions: read_partitions::<0b11111, R, I>(r, (block_size, predictor_order))?,
            }),
            _ => Err(Error::InvalidCodingMethod),
        }
    }
}

impl<I: SignedInteger> ToBitStream for Residuals<I> {
    type Error = Error;

    fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Error> {
        fn write_partitions<const RICE_MAX: u32, W: BitWrite + ?Sized, I: SignedInteger>(
            writer: &mut W,
            partitions: &[ResidualPartition<RICE_MAX, I>],
        ) -> Result<(), Error> {
            assert!(!partitions.is_empty());
            assert!(partitions.len().is_power_of_two());

            writer.write::<4, _>(partitions.len().ilog2())?;

            for partition in partitions.iter() {
                writer.build(partition)?;
            }

            Ok(())
        }

        match self {
            Self::Method0 { partitions } => {
                w.write::<2, u8>(0)?; // coding method
                write_partitions(w, partitions)
            }
            Self::Method1 { partitions } => {
                w.write::<2, u8>(1)?; // coding method
                write_partitions(w, partitions)
            }
        }
    }
}

/// An individual residual block partition
///
/// Each partition consists of a Rice parameter
/// followed by an optional escape code and signed residual values.
/// The number of bits to read for the Rice parameters
/// depends on if we're using coding method 0 or 1.
/// If the Rice parameter equals the maximum,
/// it means the partition is escaped in some way
/// (this is an uncommon case).
///
/// | Bits    | Meaning |
/// |--------:|---------|
/// | 4 or 5  | Rice parameter
/// | (5)     | escape code if parameter is `1111` or `11111`
///
/// The total number of residuals in the partition is:
///
/// > block size ÷ partition count - predictor order
///
/// for the first partition, and:
///
/// > block size ÷ partition count
///
/// for subsequent partitions.
///
/// If the partition is escaped, we read an additional 5 bit value
/// to determine the size of each signed residual in the partition.
/// If the *escape code* is 0, all the residuals in the partition are 0
/// (this is an even more uncommon case).
///
/// # Example
/// ```
/// use flac_codec::stream::ResidualPartition;
/// use bitstream_io::{BitReader, BitRead, BigEndian, BitCount};
///
/// let data: &[u8] = &[
///     0b0001_01_0_0,  // Rice code + residuals
///     0b01_0_001_0_0,
///     0b01_0_001_0_0,
///     0b01_0_001_0_0,
///     0b01_0_001_0_0,
///     0b01_0_001_0_0,
///     0b01_0_001_0_0,
///     0b01_0_001_0_0,
///     0b01_0_001_0_0,
///     0b01_0_001_0_0,
/// ];
///
/// let mut r = BitReader::endian(data, BigEndian);
/// assert_eq!(
///     r.parse_using::<ResidualPartition<0b1111, i32>>(19).unwrap(),
///     ResidualPartition::Standard {
///         rice: BitCount::new::<0b0001>(),
///         residuals: vec![
///              1, 2, 2, 2, 2, 2, 2, 2, 2, 2,
///              2, 2, 2, 2, 2, 2, 2, 2, 2
///         ],
///     },
/// );
/// ```
///
/// Each individual residual is a unary value with a stop bit of 1
/// for the most-significant bits, followed by "Rice" number of
/// bits as the least significant bits, combined into a single
/// unsigned value.
///
/// Unary-encoding is simply counting the number of 0 bits
/// before the next 1 bit:
///
/// | Bits    | Value |
/// |--------:|-------|
/// | `1`     | 0
/// | `01`    | 1
/// | `001`   | 2
/// | `0001`  | 3
/// | `00001` | 4
/// | ⋮       |
///
/// Unlike regular twos-complement signed values, individual residuals
/// are stored with the sign in the *least* significant bit position.
/// They can be transformed from unsigned to signed like:
/// ```
/// fn unsigned_to_signed(unsigned: u32) -> i32 {
///     if (unsigned & 1) == 1 {
///         // negative residual
///         -((unsigned >> 1) as i32) - 1
///     } else {
///         // positive residual
///         (unsigned >> 1) as i32
///     }
/// }
/// ```
///
/// In our example, above, the Rice parameter happens to be 1
/// and all the sign bits happen to be 0, so the value of each
/// signed residual is simply its preceding unary value
/// (which are all `01` or `001`, meaning 1 and 2).
///
/// As one can see, the smaller the value each residual has,
/// the smaller it can be when written to disk.
/// And the key to making residual values small is to choose
/// predictor coefficients which best match the input signal.
/// The more accurate the prediction, the less difference
/// there is between the predicted values and the actual
/// values - which means smaller residuals - which means
/// better compression.
#[derive(Debug, Eq, PartialEq)]
pub enum ResidualPartition<const RICE_MAX: u32, I> {
    /// A standard residual partition
    Standard {
        /// The partition's Rice parameter
        rice: BitCount<RICE_MAX>,
        /// The partition's residuals
        residuals: Vec<I>,
    },
    /// An escaped residual partition
    Escaped {
        /// The size of each residual in bits
        escape_size: SignedBitCount<0b11111>,
        /// The partition's residuals
        residuals: Vec<I>,
    },
    /// A partition in which all residuals are 0
    Constant {
        /// The length of the partition in samples
        partition_len: usize,
    },
}

impl<const RICE_MAX: u32, I: SignedInteger> ResidualPartition<RICE_MAX, I> {
    fn residuals(&self) -> Box<dyn Iterator<Item = I> + '_> {
        match self {
            Self::Standard { residuals, .. } | Self::Escaped { residuals, .. } => {
                Box::new(residuals.iter().copied())
            }
            Self::Constant { partition_len } => {
                Box::new(std::iter::repeat_n(I::default(), *partition_len))
            }
        }
    }
}

impl<const RICE_MAX: u32, I: SignedInteger> FromBitStreamUsing for ResidualPartition<RICE_MAX, I> {
    type Context = usize;
    type Error = Error;

    fn from_reader<R: BitRead + ?Sized>(r: &mut R, partition_len: usize) -> Result<Self, Error> {
        match r.parse::<ResidualPartitionHeader<RICE_MAX>>()? {
            ResidualPartitionHeader::Standard { rice } => Ok(Self::Standard {
                residuals: (0..partition_len)
                    .map(|_| {
                        let msb = r.read_unary::<1>()?;
                        let lsb = r.read_counted::<RICE_MAX, u32>(rice)?;
                        let unsigned = (msb << u32::from(rice)) | lsb;
                        Ok::<_, Error>(if (unsigned & 1) == 1 {
                            -(I::from_u32(unsigned >> 1)) - I::ONE
                        } else {
                            I::from_u32(unsigned >> 1)
                        })
                    })
                    .collect::<Result<Vec<_>, _>>()?,
                rice,
            }),
            ResidualPartitionHeader::Escaped { escape_size } => Ok(Self::Escaped {
                residuals: (0..partition_len)
                    .map(|_| r.read_signed_counted(escape_size))
                    .collect::<Result<Vec<_>, _>>()?,
                escape_size,
            }),
            ResidualPartitionHeader::Constant => Ok(Self::Constant { partition_len }),
        }
    }
}

impl<const RICE_MAX: u32, I: SignedInteger> ToBitStream for ResidualPartition<RICE_MAX, I> {
    type Error = Error;

    fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Error> {
        match self {
            Self::Standard { residuals, rice } => {
                w.build(&ResidualPartitionHeader::Standard { rice: *rice })?;

                let mask = rice.mask_lsb();

                for residual in residuals {
                    let (msb, lsb) = mask(if residual.is_negative() {
                        (((-*residual).to_u32() - 1) << 1) + 1
                    } else {
                        (*residual).to_u32() << 1
                    });
                    w.write_unary::<1>(msb)?;
                    w.write_checked(lsb)?;
                }
                Ok(())
            }
            Self::Escaped {
                escape_size,
                residuals,
            } => {
                w.build(&ResidualPartitionHeader::<RICE_MAX>::Escaped {
                    escape_size: *escape_size,
                })?;

                for residual in residuals {
                    w.write_signed_counted(*escape_size, *residual)?;
                }

                Ok(())
            }
            Self::Constant { .. } => Ok(w.build(&ResidualPartitionHeader::<RICE_MAX>::Constant)?),
        }
    }
}