scarletbook 0.7.0

Clean-room reader for Super Audio CD (Scarletbook) disc images
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
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
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Audio sector multiplexing (specification 4): frame reassembly, the timeline and tracks.

use std::collections::VecDeque;
use std::io::{Read, Seek};

use crate::control::Progress;
use crate::dst::{DstDecoder, DstError};
use crate::error::{Error, Slot, Warning, WarningCode};
use crate::image::{Image, ReadOutcome, SECTOR_SIZE};
use crate::log::{Level, Log, sb_log};
use crate::seek::{
    AreaIndex, Assembling, Claim, HintRecorder, Plan, Provisional, ProvisionalRecorder, Recorder,
    ResumedFrom, SeekIndexes, SeekPolicy, Speculate, Speculation, digest, first_record, locate,
};
use crate::toc::{Area, Track};

/// DSD bytes per channel in one frame (specification 0, 0.5).
pub const FRAME_BYTES_PER_CHANNEL: usize = 4704;

/// Largest frame under assembly in bytes (specification 4, 4.4.3 item 4).
pub const MAX_FRAME_BYTES: usize = 65_536;

/// Fill of a frame the disc does not supply (specification 0, 0.6).
pub const MISSING_FILL: u8 = 0x69;

/// Fill of a DST frame that cannot be decoded (specification 0, 0.6).
pub const INVALID_FILL: u8 = 0x55;

/// Largest channel count for which audio is produced (specification 4, 4.8).
pub const MAX_CHANNELS: u8 = 6;

/// Most `audio-sector-malformed` warnings kept per area cursor (specification 4, 4.4.5
/// item 3); the count of malformed sectors is kept in full.
pub const MAX_MALFORMED_WARNINGS: usize = 4096;

/// Most log lines of each kind of problem a cursor writes: malformed sectors and discarded
/// frames per area cursor, missing and invalid frames per track cursor. The first line
/// past the cap says that further ones are suppressed; the counts are kept in full.
pub const MAX_PROBLEM_LINES: usize = MAX_MALFORMED_WARNINGS;

/// The number of log lines written for one kind of problem, against
/// [`MAX_PROBLEM_LINES`].
#[derive(Clone, Copy, Debug, Default)]
struct LineCap(usize);

impl LineCap {
    /// Whether one more `level` line about `what` may be written to `log`. The first line
    /// refused writes a line saying that further ones are suppressed. Counts only when
    /// the level is enabled, so it costs one test without a log.
    #[inline]
    fn admit(&mut self, log: &Log, level: Level, slot: &str, what: &str) -> bool {
        if !log.enabled(level) {
            return false;
        }
        self.0 = self.0.saturating_add(1);
        if self.0 == MAX_PROBLEM_LINES + 1 {
            log.write(
                level,
                format_args!(
                    "area {slot}: further {what} lines suppressed (at most {MAX_PROBLEM_LINES} per cursor)"
                ),
            );
        }
        self.0 <= MAX_PROBLEM_LINES
    }
}

/// Why a sector is malformed (specification 4, 4.4.3), for the log.
#[derive(Clone, Copy, Debug)]
enum Malformed {
    /// Packet `p` of `k`, `len` bytes at `pos`, runs past the sector.
    Overrun { p: usize, k: usize, len: usize, pos: usize },
    /// A frame starts in packet `p` but the sector has only `f` frame records.
    NoRecord { p: usize, f: usize },
    /// Frame `number` grew past [`MAX_FRAME_BYTES`] and was discarded.
    Oversized { number: u32 },
}

impl std::fmt::Display for Malformed {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match *self {
            Malformed::Overrun { p, k, len, pos } => {
                write!(f, "packet {p} of {k} ({len} bytes at {pos}) overruns the sector")
            }
            Malformed::NoRecord { p, f: records } => {
                write!(f, "frame start in packet {p} without a frame record ({records} records)")
            }
            Malformed::Oversized { number } => {
                write!(f, "frame {number} exceeds {MAX_FRAME_BYTES} bytes and is discarded")
            }
        }
    }
}

/// Most timeline positions a cursor of the `parallel` feature holds ahead of its caller.
///
/// With `parallel`, a track's positions are demultiplexed on the calling thread up to
/// [`PARALLEL_FRAMES_PER_THREAD`] per thread of the cursor's pool (the current rayon pool
/// unless [`TrackAudioCursor::set_decode_on`] chose another) ahead of the frame
/// returned last, at most this many (on a pool of one thread, one group, as below). Each DST frame
/// becomes one job on the pool as soon as it is demultiplexed, so that the pool decodes
/// while the caller consumes the frames before it; every call tops the window up again.
/// Plain DSD and missing positions are filled in on the calling thread when they are
/// returned. Frames are returned in timeline order whatever order the jobs finish in.
///
/// A job decodes up to [`crate::dst::lanes`] consecutive DST frames together
/// ([`DstDecoder::decode_many`]), so the window is topped up in whole groups: a call
/// demultiplexes ahead only once at least a group fits below the bound, and never past it.
/// On the calling thread (without `parallel`, or on a pool of one thread) the window is
/// one such group, decoded on the calling thread when its first frame is asked for.
///
/// Each position held ahead is at most one DST frame's bytes (at most 65 536,
/// [`MAX_FRAME_BYTES`]) and, once decoded, its audio (at most 6 x 4704 bytes): a cursor
/// holds at most `512 x (65 536 + 6 x 4704)` bytes, about 48 MB, whatever the host (plus
/// the frame under assembly, and its read buffer: 64 KiB, or up to 1 MiB,
/// [`crate::seek::MAX_READ_SECTORS`] sectors, kept for the cursor's life once it has made a
/// read sized to its range, after a provisional start or a resume from a seek index); DST frames of 40 % of their decoded size need about 6.8 MB
/// at 2 channels and 20 MB at 6. The cap is a constant so that the memory held does not
/// grow with the host's thread count. It keeps 16 positions per thread up to 32 threads:
/// with groups of 2 or 3 frames per job, a cap of 256 left under 3 jobs per thread at 32
/// threads, and the pool ran short of work while the calling thread was busy (#61).
///
/// A cursor continued ([`crate::Disc::continue_track_audio`] and its range form) or dropped
/// while DST frames are in flight drops its handles on them: queued jobs then skip
/// decoding, and only jobs already decoding run to their end, at most one group of
/// [`crate::dst::lanes`] frames per pool thread. That memory is held briefly beside the
/// new cursor's window, and freed as those jobs finish.
///
/// Besides the window, each decoder holds its tables: per lane of
/// [`DstDecoder::decode_many`], at most 12 filters' byte tables (64 KiB each) and 12
/// ptables' probability tables (8 KiB each), and a 9 KiB copy of each channel's, about
/// 0.9 MB in use; the tables grow as frames need more of them and keep the capacity they
/// grew to, so a lane can hold more, and up to 1.33 MB per lane was measured (#246). A
/// cursor's own decoder, and each pool thread's, holds up to
/// [`crate::dst::lanes`] lanes of them.
///
/// [`TrackAudioCursor::with_dst_lanes`] replaces [`crate::dst::lanes`] throughout this
/// description, for that cursor; a chosen count of up to [`crate::dst::MAX_LANES`] keeps every
/// bound above.
///
/// Not part of the public API: a tuning value of the `parallel` decoder, not covered by semantic
/// versioning. It may change or go in any release.
#[doc(hidden)]
pub const MAX_PARALLEL_BATCH: usize = 512;

/// Positions held ahead per pool thread with the `parallel` feature (see
/// [`MAX_PARALLEL_BATCH`]).
///
/// Not part of the public API: a tuning value of the `parallel` decoder, not covered by semantic
/// versioning. It may change or go in any release.
#[doc(hidden)]
pub const PARALLEL_FRAMES_PER_THREAD: usize = 16;

/// Where a [`TrackAudioCursor`] decodes its DST frames, with the `parallel` feature
/// ([`TrackAudioCursor::set_decode_on`]). Whichever is chosen, the frames returned, their
/// order, counts and log lines are the same; only the threads that decode differ.
///
/// By a stated decision (#39), [`DecodeOn::Pool`] makes rayon 1 part of this crate's public
/// API rather than hiding it behind a wrapper: rayon 1 is stable, and a rayon 2 would need
/// a new major version of this crate.
#[cfg(feature = "parallel")]
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub enum DecodeOn {
    /// The rayon pool current at each call: the pool of the calling thread if it is one of
    /// a pool's threads (inside [`rayon::ThreadPool::install`]), rayon's global pool
    /// otherwise. The default.
    #[default]
    CurrentPool,
    /// This pool, whichever thread calls: the calling thread demultiplexes and the pool's
    /// threads decode. A pool of one thread decodes on the calling thread, as
    /// [`DecodeOn::CallingThread`]. The cursor holds the pool, so it stays alive while
    /// the cursor does.
    ///
    /// The calling thread works beside the pool's threads rather than among them, unlike
    /// inside [`rayon::ThreadPool::install`]: when it does substantial work with each frame
    /// (writing it out, converting it), a pool of one thread fewer than the logical CPUs
    /// leaves it a CPU. Measured on 16 vCPUs (#146), decoding a 50-minute 2-channel DST
    /// area through the C interface and writing each frame to files on the calling thread
    /// took 7.7 % longer than decoding inside `install` with 16 threads, and 4.6 % longer
    /// with 15; with a caller that does little, 16 were as fast or slightly faster.
    Pool(std::sync::Arc<rayon::ThreadPool>),
    /// The calling thread only, as without the `parallel` feature: no pool is used, not
    /// even rayon's global one.
    CallingThread,
}

/// Most frames that can start in one sector (specification 4, 4.8 item 3).
pub const FRAMES_PER_SECTOR: u64 = 7;

/// How a frame is coded, fixed by the DST flag of the sector it starts in.
///
/// Frozen: exhaustive on purpose, so a `match` needs no wildcard arm. The DST flag is one bit
/// of the sector header (specification 4, 4.3.1), so there are exactly two kinds.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FrameKind {
    /// DST-coded (specification 5).
    Dst,
    /// Plain DSD, exactly `C x 4704` bytes in interleaved layout.
    Dsd,
}

/// A frame accepted onto an area's timeline (specification 4, 4.5).
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct AreaFrame {
    /// Its frame number (timeline position).
    pub number: u32,
    /// Its kind.
    pub kind: FrameKind,
    /// Its bytes: `C x 4704` for plain DSD, 1 to 65 536 for DST.
    pub data: Vec<u8>,
}

#[derive(Debug)]
struct Assembly {
    number: u32,
    kind: FrameKind,
    data: Vec<u8>,
    remaining: i32,
    /// The LSN of the sector it starts in, for the log.
    start_lsn: u64,
}

/// Where the reassembler stands, for the log: the area and the LSN of the sector being
/// processed (0 when unknown).
#[derive(Clone, Copy)]
struct At<'a> {
    log: &'a Log,
    slot: Option<Slot>,
    lsn: u64,
}

impl At<'_> {
    fn slot(&self) -> &'static str {
        self.slot.map_or("?", Slot::name)
    }
}

/// The frame reassembler and timeline of one area (specification 4, 4.4 and 4.5).
///
/// Push the area's sectors in increasing LSN order with [`Demuxer::push_sector`], then
/// call [`Demuxer::finish`]. Accepted frames are queued and taken with
/// [`Demuxer::pop`]. At most 8 frames are queued after one push (7 started in the sector,
/// plus none extra: a frame is delivered only when the next one starts, or at the end).
#[derive(Debug)]
pub struct Demuxer {
    channels: u8,
    assembling: Option<Assembly>,
    next_acceptable: u32,
    ready: VecDeque<AreaFrame>,
    malformed: u64,
    /// The area, for the log.
    slot: Option<Slot>,
    /// Why the last sector pushed was malformed (its first reason), for the log.
    reason: Option<Malformed>,
    /// Lines written about discarded frames.
    discarded_lines: LineCap,
    /// One more than the largest number of a complete frame delivered, accepted or not; 0
    /// before any (for provisional checkpoints).
    seen: u32,
}

impl Demuxer {
    /// A reassembler for an area of `channels` channels (the area TOC's channel count).
    pub fn new(channels: u8) -> Self {
        Demuxer {
            channels,
            assembling: None,
            next_acceptable: 0,
            ready: VecDeque::new(),
            malformed: 0,
            slot: None,
            reason: None,
            discarded_lines: LineCap::default(),
            seen: 0,
        }
    }

    fn at<'a>(&self, log: &'a Log, lsn: u64) -> At<'a> {
        At { log, slot: self.slot, lsn }
    }

    /// Number of malformed sectors seen (specification 4, 4.4.5).
    pub fn malformed_sectors(&self) -> u64 {
        self.malformed
    }

    /// Takes the next accepted frame, if any.
    pub fn pop(&mut self) -> Option<AreaFrame> {
        self.ready.pop_front()
    }

    /// Processes one 2048-byte audio sector (specification 4, 4.4.3). Returns whether
    /// the sector was malformed.
    pub fn push_sector(&mut self, sector: &[u8; SECTOR_SIZE]) -> bool {
        self.push_sector_at(sector, self.at(&Log::none(), 0))
    }

    /// [`Demuxer::push_sector`], reporting to `at.log` with the sector's LSN.
    fn push_sector_at(&mut self, sector: &[u8; SECTOR_SIZE], at: At<'_>) -> bool {
        let header = sector[0];
        let dst = header & 1 != 0;
        let f = usize::from((header >> 2) & 7);
        let k = usize::from(header >> 5);
        let record = if dst { 4 } else { 3 };
        // H <= 1 + 14 + 28 = 43: every record lies inside the sector.
        let h = 1 + 2 * k + f * record;
        let byte = |i: usize| sector.get(i).copied().unwrap_or(0);
        self.reason = None;
        let mut malformed = false;
        let mut x = 0usize;
        let mut pos = h;
        for p in 0..k {
            let w = u16::from_be_bytes([byte(1 + 2 * p), byte(2 + 2 * p)]);
            let start = w & 0x8000 != 0;
            let packet_type = (w >> 11) & 7;
            let len = usize::from(w & 0x07FF);
            let Some(payload) = sector.get(pos..pos + len) else {
                self.reason.get_or_insert(Malformed::Overrun { p, k, len, pos });
                malformed = true;
                break;
            };
            if packet_type == 2 {
                if start {
                    self.deliver_if_complete(at);
                    if x < f {
                        let r = 1 + 2 * k + x * record;
                        let number =
                            (u32::from(byte(r)) * 60 + u32::from(byte(r + 1))) * 75 + u32::from(byte(r + 2));
                        let remaining = if dst { i32::from((byte(r + 3) >> 2) & 0x1F) } else { 0 };
                        let kind = if dst { FrameKind::Dst } else { FrameKind::Dsd };
                        // A plain frame is complete at C x 4704 bytes (4.4.2): reserved at
                        // once, it is never reallocated as its sectors arrive.
                        let data = match kind {
                            FrameKind::Dsd => Vec::with_capacity(
                                (usize::from(self.channels) * FRAME_BYTES_PER_CHANNEL).min(MAX_FRAME_BYTES),
                            ),
                            FrameKind::Dst => Vec::new(),
                        };
                        self.assembling = Some(Assembly { number, kind, data, remaining, start_lsn: at.lsn });
                        x += 1;
                    } else {
                        self.reason.get_or_insert(Malformed::NoRecord { p, f });
                        malformed = true;
                    }
                }
                if let Some(a) = &mut self.assembling {
                    if a.data.len() + len > MAX_FRAME_BYTES {
                        if self.discarded_lines.admit(at.log, Level::Warn, at.slot(), "discarded-frame") {
                            sb_log!(
                                at.log,
                                Warn,
                                "area {} frame {} (from LSN {}): discarded at LSN {}, more than {MAX_FRAME_BYTES} \
                                 bytes (4.4.3)",
                                at.slot(),
                                a.number,
                                a.start_lsn,
                                at.lsn
                            );
                        }
                        self.reason.get_or_insert(Malformed::Oversized { number: a.number });
                        self.assembling = None;
                        malformed = true;
                    } else {
                        a.data.extend_from_slice(payload);
                        // Bounded below by -(7 x sectors): no overflow in an i32 for any
                        // image of fewer than 300 million sectors per frame; saturate anyway.
                        a.remaining = a.remaining.saturating_sub(1);
                    }
                }
            }
            pos += len;
        }
        if malformed {
            // The demuxer does not know LSNs; AreaCursor turns this into warnings.
            self.malformed += 1;
        }
        malformed
    }

    /// Ends the area (specification 4, 4.4.4).
    pub fn finish(&mut self) {
        self.finish_at(self.at(&Log::none(), 0));
    }

    fn finish_at(&mut self, at: At<'_>) {
        self.deliver_if_complete(at);
    }

    fn deliver_if_complete(&mut self, at: At<'_>) {
        let Some(a) = self.assembling.take() else { return };
        let complete = !a.data.is_empty()
            && match a.kind {
                FrameKind::Dst => a.remaining == 0,
                FrameKind::Dsd => a.data.len() == usize::from(self.channels) * FRAME_BYTES_PER_CHANNEL,
            };
        if complete {
            self.seen = self.seen.max(a.number.saturating_add(1));
        }
        if complete && a.number >= self.next_acceptable {
            let (start_lsn, len) = (a.start_lsn, a.data.len());
            // Frame numbers are at most 1 166 880.
            self.next_acceptable = a.number + 1;
            self.ready.push_back(AreaFrame { number: a.number, kind: a.kind, data: a.data });
            // Logged once the frame is queued, so that a sink that panics loses nothing.
            sb_log!(
                at.log,
                Trace,
                "area {} frame {} (from LSN {start_lsn}): accepted, {:?}, {len} bytes",
                at.slot(),
                a.number,
                a.kind
            );
            return;
        }
        if !self.discarded_lines.admit(at.log, Level::Warn, at.slot(), "discarded-frame") {
            return;
        }
        if !complete {
            sb_log!(
                at.log,
                Warn,
                "area {} frame {} (from LSN {}): discarded, incomplete ({:?}, {} bytes{}; 4.4.2)",
                at.slot(),
                a.number,
                a.start_lsn,
                a.kind,
                a.data.len(),
                match a.kind {
                    FrameKind::Dst if a.remaining != 0 => ", sector count does not match",
                    _ => "",
                }
            );
        } else {
            sb_log!(
                at.log,
                Warn,
                "area {} frame {} (from LSN {}): discarded, not after the last accepted frame {} (4.5)",
                at.slot(),
                a.number,
                a.start_lsn,
                self.next_acceptable.saturating_sub(1)
            );
        }
    }
}

/// The reading state of an area's accepted frames, independent of the image it reads
/// from: pass the same image to every call of [`AreaCursor::next_frame`].
///
/// [`AreaFrames`] is the borrowing iterator over the same state.
#[derive(Debug)]
pub struct AreaCursor {
    demux: Demuxer,
    /// The image this cursor reads, bound on first use: its read cache and frames belong
    /// to that image.
    image_id: Option<u64>,
    slot: Slot,
    warnings: Vec<Warning>,
    next_lsn: u64,
    end_lsn: u64,
    buf: Vec<u8>,
    buf_lsn: u64,
    buf_sectors: u64,
    finished: bool,
    /// Lines written about malformed sectors.
    malformed_lines: LineCap,
    /// Records checkpoints for a seek index, when made from one.
    recorder: Option<Box<Recorder>>,
    /// Sectors processed before `replay.until` only rebuild the frame under assembly; the
    /// state is then set to the checkpoint's.
    replay: Option<Replay>,
    /// Where the scan started.
    resumed: ResumedFrom,
    /// [`AreaCursor::next_frame`] reads no sector at or past this LSN (returns `None`), for
    /// [`AreaIndex::extend`].
    stop_lsn: u64,
    /// The checkpoint's LSN and the digest its sector must have, until it is read.
    verify: Option<(u64, u64)>,
    /// The area, to scan it afresh when a seek index does not match the image.
    key: AreaKey,
    /// The malformed count and warnings reported before the first read: those of the
    /// scan a continuation moved this cursor ahead of (see [`AreaCursor::carry_counts`]).
    before_read: Option<Box<(u64, Vec<Warning>)>>,
    /// A provisional start to choose on the first read (specification 4, 4.2 item 8).
    speculate: Option<Speculate>,
    /// The provisional reading this cursor makes, if any (shared with the index that
    /// checks it), and whether that index has it.
    claim: Option<std::sync::Arc<Claim>>,
    claim_registered: bool,
    /// Records provisional checkpoints, for a provisional reading.
    provisional: Option<Box<ProvisionalRecorder>>,
    /// Reads below this LSN reach up to it, in calls of at most
    /// [`crate::seek::MAX_READ_SECTORS`] (reads sized to the range after a provisional start
    /// or a resume from a seek index); others read
    /// [`READ_CHUNK`] sectors at a time.
    read_to: u64,
    /// After that, reads below this LSN reach up to it in the same way: the rest of a
    /// provisional range, past what its first read could take.
    read_then: u64,
    /// Why this provisional reading is suspect, if it is (4.2 item 8).
    suspect: Option<crate::seek::Suspect>,
    /// Records seek hints, when made from an index that keeps them.
    hints: Option<Box<HintRecorder>>,
    /// A seek hint this cursor began at did not match the image: the index drops its hints.
    hints_stale: bool,
    /// Sectors read through the image by this cursor (its reading, see [`Progress`]).
    sectors_read: u64,
    /// Where the reading is expected to end: the sector after the range's estimated last.
    progress_end: u64,
    /// The counts published for other threads, once asked for.
    progress: Option<Progress>,
}

/// The state a resumed scan takes once its replay reaches the checkpoint.
#[derive(Clone, Copy, Debug)]
struct Replay {
    until: u64,
    next_acceptable: u32,
    malformed: u64,
}

/// Sectors read per call to the reader.
const READ_CHUNK: u64 = 32;

/// The sector at offset `at` of a cursor's buffer, which holds it ([`AreaCursor::load`]).
fn held(buf: &[u8], at: usize) -> &[u8; SECTOR_SIZE] {
    static ZERO: [u8; SECTOR_SIZE] = [0; SECTOR_SIZE];
    buf.get(at..).and_then(<[u8]>::first_chunk).unwrap_or(&ZERO)
}

impl AreaCursor {
    /// A cursor at the start of `area`'s audio, in an image of `image_sectors` sectors.
    pub fn new(area: &Area, image_sectors: u64) -> Self {
        Self::with_key(AreaKey::new(area, image_sectors))
    }

    /// A cursor at the start of the area `key` names.
    fn with_key(key: AreaKey) -> Self {
        let (start, end) = key.audio_sector_range();
        let mut demux = Demuxer::new(key.channels);
        demux.slot = Some(key.slot);
        AreaCursor {
            demux,
            image_id: None,
            slot: key.slot,
            warnings: Vec::new(),
            next_lsn: start,
            end_lsn: end,
            buf: Vec::new(),
            buf_lsn: 0,
            buf_sectors: 0,
            finished: false,
            malformed_lines: LineCap::default(),
            recorder: None,
            replay: None,
            resumed: ResumedFrom::Start,
            stop_lsn: u64::MAX,
            verify: None,
            key,
            before_read: None,
            speculate: None,
            claim: None,
            claim_registered: false,
            provisional: None,
            read_to: 0,
            read_then: 0,
            suspect: None,
            hints: None,
            hints_stale: false,
            sectors_read: 0,
            progress_end: end,
            progress: None,
        }
    }

    /// The progress of this cursor's reading, readable from other threads (see
    /// [`Progress`]); the same object every time.
    pub fn progress(&mut self) -> Progress {
        let read = self.sectors_read;
        let expected = if self.finished { read } else { self.expected(self.next_lsn) };
        self.progress
            .get_or_insert_with(|| {
                let p = Progress::default();
                p.set(read, expected);
                p
            })
            .clone()
    }

    /// The sectors expected in all when the next sector to read is `next`.
    fn expected(&self, next: u64) -> u64 {
        self.sectors_read + self.progress_end.saturating_sub(next)
    }

    /// Counts `n` sectors read, the next to read being `next`.
    #[inline]
    fn count_read(&mut self, n: u64, next: u64) {
        self.sectors_read += n;
        if let Some(p) = &self.progress {
            p.set(self.sectors_read, self.expected(next));
        }
    }

    /// The reading is complete: nothing more is expected.
    pub(crate) fn progress_done(&self) {
        if let Some(p) = &self.progress {
            p.set(self.sectors_read, self.sectors_read);
        }
    }

    /// Sets where the reading is expected to end (the sector after the range's estimated
    /// last), also for the exact start a provisional one may fall back to.
    pub(crate) fn set_progress_end(&mut self, lsn: u64) {
        self.progress_end = lsn.min(self.end_lsn);
        if let Some(sp) = self.speculate.as_mut() {
            sp.exact.set_progress_end(lsn);
        }
    }

    /// Starts a new reading: counts from 0, and a [`Progress`] of its own once asked for.
    pub(crate) fn restart_progress(&mut self) {
        self.sectors_read = 0;
        self.progress = None;
    }

    /// Takes the counts of `from`, which this cursor replaces within one reading.
    fn keep_progress(&mut self, from: (u64, u64, Option<Progress>)) {
        (self.sectors_read, self.progress_end, self.progress) = from;
    }

    fn take_progress(&mut self) -> (u64, u64, Option<Progress>) {
        (self.sectors_read, self.progress_end, self.progress.take())
    }

    /// A cursor that chooses on its first read whether to begin provisionally (specification
    /// 4, 4.2 item 8) for positions `first` or more, or as `exact` does.
    pub(crate) fn speculative(
        exact: AreaCursor,
        (first, end): (u32, u32),
        (playtime, knots): (u32, Vec<(u64, u32)>),
        (interval, hint): (u32, Option<crate::seek::Hint>),
        options: crate::seek::SpeculativeOptions,
    ) -> Self {
        let from = match exact.resumed {
            ResumedFrom::Checkpoint { lsn, .. } => lsn,
            _ => exact.next_lsn,
        };
        let mut cursor = Self::with_key(exact.key);
        cursor.next_lsn = from;
        cursor.resumed = ResumedFrom::Speculative { lsn: 0, probes: 0 };
        cursor.claim = Some(Claim::new(cursor.slot, first));
        cursor.speculate = Some(Speculate {
            first,
            end,
            playtime,
            interval,
            options,
            knots,
            exact: Box::new(exact),
            from,
            hint,
        });
        cursor
    }

    /// Chooses the provisional start (see [`AreaCursor::speculative`]), reading through
    /// `image`; or takes the exact start, if the search finds nothing past it.
    /// A cancelled search keeps `sp` for the next read.
    fn begin<R: Read + Seek>(&mut self, image: &mut Image<R>, mut sp: Speculate) -> Result<(), Error> {
        let (start, _) = self.key.audio_sector_range();
        if let Some((l, t, to, confirmed)) = sp.hint {
            // A seek hint: one read from its sector to the range's end. Its first record
            // must be the hint's, or the hints are of another image (or a stale one).
            self.read_to = to;
            let sector = match self.sector(image, l) {
                Err(Error::Cancelled) => {
                    self.speculate = Some(sp);
                    return Err(Error::Cancelled);
                }
                r => r?,
            };
            if first_record(&sector) == Some(t) && t < sp.first {
                self.start_provisional(start, (l, 0), &sp);
                // Specification 4, 4.2 item 9 (sacd-spec `cb9530b`): (a) and (b) were
                // established at `l` for a `u_L` at most this range's first frame by a pass
                // over the image this index is bound to (its TOC fingerprint and key), and
                // sector `l` is as that pass read it: they hold for this reading too.
                if confirmed.is_some_and(|d| d == digest(&sector)) {
                    if let Some(claim) = &self.claim {
                        claim.confirm_saved();
                    }
                    sb_log!(
                        image.log(),
                        Debug,
                        "area {}: provisional reading from LSN {l} confirmed from saved state (4.2 item 9)",
                        self.slot
                    );
                }
                return Ok(());
            }
            sb_log!(
                image.log(),
                Warn,
                "area {}: seek hint at LSN {l} (frame {t}) does not match the image (first record {:?}): \
                 hints dropped, searching",
                self.slot,
                first_record(&sector)
            );
            self.hints_stale = true;
            self.read_to = 0;
            sp.hint = None;
        }
        let range = (sp.from, self.end_lsn);
        let located = locate(image, range, (sp.first, sp.playtime), &sp.knots, &sp.options, &mut |n| {
            self.count_read(n, sp.from)
        });
        let located = match located {
            Err(Error::Cancelled) => {
                self.speculate = Some(sp);
                return Err(Error::Cancelled);
            }
            r => r?,
        };
        let (l, probes) = (located.lsn, located.reads);
        // Frame numbers that decrease between the sectors read: suspect (4.2 item 8), and
        // read exactly if the caller asked for that.
        let exact_instead = located.decreasing && sp.options.exact_when_suspect;
        if l <= sp.from || exact_instead {
            let (image_id, counts, stale) = (self.image_id, self.take_progress(), self.hints_stale);
            *self = *sp.exact;
            self.image_id = image_id;
            self.hints_stale = stale;
            self.keep_progress(counts);
            sb_log!(
                image.log(),
                Debug,
                "area {}: no provisional start past LSN {} for frame {} ({probes} reads): exact",
                self.slot,
                sp.from,
                sp.first
            );
            return Ok(());
        }
        // Begins at the sector found (4.2 item 8): on an image whose frames start in
        // non-decreasing number order, every frame that starts before it is numbered at most
        // its first record's, which is below `first`, so (a) and (b) hold there.
        self.start_provisional(start, (l, probes), &sp);
        if located.decreasing && self.suspect.is_none() {
            self.suspect = Some(crate::seek::Suspect::FrameNumbersDecrease);
        }
        // Reads on from the probe that found `l`, without reading it again.
        if let Some((at, bytes)) = located.chunk {
            self.buf_sectors = (bytes.len() / SECTOR_SIZE) as u64;
            self.buf_lsn = at;
            self.buf = bytes;
        }
        // The next read reaches the range's estimated end: its frames from `l` at the
        // density found, plus a quarter and a few sectors.
        let (sectors, frames) = located.density;
        let span =
            u128::from(sp.end.saturating_sub(located.frame)) * u128::from(sectors) / u128::from(frames);
        let span = u64::try_from(span + span / 4 + 4).unwrap_or(u64::MAX);
        let through_first =
            u128::from(sp.first + 1 - located.frame) * u128::from(sectors) / u128::from(frames);
        let through_first = u64::try_from(through_first + through_first / 4 + 4).unwrap_or(u64::MAX);
        // From the first sector not yet read: past the probe kept, or `l`.
        let from = if self.buf_sectors > 0 { (self.buf_lsn + self.buf_sectors).max(l) } else { l };
        // Through the range's first frame and on to its estimated end, as far as the budget
        // left after the search allows; that much and no more (it can be less than a chunk).
        // Nothing is left when the search's last read took it all: the reads toward the
        // range's end follow at once.
        let left = crate::seek::FIRST_FRAME_BUDGET.saturating_sub(located.used);
        let need = (l + through_first).saturating_sub(from);
        let range = l.saturating_add(span).saturating_sub(from);
        self.read_to = from + need.max(range).min(left);
        self.read_then = l.saturating_add(span);
        Ok(())
    }

    /// Begins a provisional reading at sector `l`, chosen after `probes` reads (4.2 item 8):
    /// no frame under assembly, `sp.first` as the next acceptable frame number.
    fn start_provisional(&mut self, start: u64, (l, probes): (u64, u32), sp: &Speculate) {
        self.next_lsn = l;
        self.demux.next_acceptable = sp.first;
        self.resumed = ResumedFrom::Speculative { lsn: l, probes };
        if let Some(claim) = &self.claim {
            claim.set_lsn(l);
        }
        self.provisional = Some(ProvisionalRecorder::new(start, l, sp.interval));
        if sp.options.layout_suspect {
            self.suspect = Some(crate::seek::Suspect::AreaLayout);
        }
    }

    /// Why this cursor's provisional reading is suspect, if it is ([`crate::Suspect`];
    /// specification 4, 4.2 item 8): `None` for exact positions and for a provisional
    /// reading with no reason to doubt it. Informative: the reading is settled as any other.
    pub fn suspect(&self) -> Option<crate::seek::Suspect> {
        self.suspect.filter(|_| self.claim.as_ref().is_some_and(|c| c.lsn() > 0))
    }

    /// The seek hints recorded since the last call.
    pub(crate) fn take_hints(&mut self) -> Vec<(u32, u32)> {
        self.hints.as_mut().map(|h| h.take()).unwrap_or_default()
    }

    /// The reading has ended: its last seek hint is recorded, and the hints are news.
    pub(crate) fn flush_hints(&mut self) {
        if let Some(h) = self.hints.as_deref_mut() {
            h.flush();
        }
    }

    /// Whether a seek hint this cursor began at did not match the image (once).
    pub(crate) fn hints_stale(&mut self) -> bool {
        std::mem::take(&mut self.hints_stale)
    }

    /// Records seek hints from now on, with `recorder`.
    pub(crate) fn record_hints(&mut self, recorder: Option<Box<HintRecorder>>) {
        if let Some(sp) = self.speculate.as_mut() {
            sp.exact.hints = recorder.as_ref().map(|r| Box::new(HintRecorder::clone(r)));
        }
        self.hints = recorder;
    }

    /// Reads up to `lsn` (exclusive) in one call when the next read starts below it.
    pub(crate) fn size_first_read(&mut self, lsn: u64) {
        self.read_to = lsn;
    }

    /// A provisional reading for positions `first` or more that starts at the provisional
    /// checkpoint `p` at sector `lsn` (an earlier provisional reading's), instead of
    /// searching; `exact` gives the area.
    pub(crate) fn provisional_at(
        exact: &AreaCursor,
        (lsn, p): (u64, Provisional),
        first: u32,
        interval: u32,
    ) -> Self {
        let mut cursor = Self::with_key(exact.key);
        let (start, _) = cursor.key.audio_sector_range();
        let from = lsn - u64::from(p.back);
        cursor.next_lsn = from;
        cursor.demux.next_acceptable = first;
        if from < lsn {
            // Lemma B of #68, as for an exact resume: rebuilds the frame under assembly.
            cursor.replay = Some(Replay { until: lsn, next_acceptable: first, malformed: 0 });
        }
        cursor.verify = Some((lsn, p.digest));
        cursor.resumed = ResumedFrom::Speculative { lsn, probes: 0 };
        let claim = Claim::new(cursor.slot, first);
        claim.set_lsn(lsn);
        cursor.claim = Some(claim);
        cursor.provisional = Some(ProvisionalRecorder::new(start, lsn, interval));
        cursor
    }

    /// The state at `lsn` (at or before the frontier of `index`) of a reader processing
    /// from the area's first sector: its next acceptable frame number, the number of its
    /// frame under assembly, and its malformed count; rebuilt from the checkpoint at or
    /// before `lsn`, reading through `image` (for a checkpoint boundary `lsn`, at most
    /// [`crate::seek::REPLAY_SECTORS`] sectors to replay and the checkpoint's own sector;
    /// otherwise up to the interval more). `None` if the index does not match the image
    /// there: the checkpoint's sector does not have its digest. The digest is always
    /// compared, also when no sector before `lsn` needs reading.
    pub(crate) fn state_at<R: Read + Seek>(
        index: &AreaIndex,
        lsn: u64,
        image: &mut Image<R>,
    ) -> Result<Option<(u32, Option<u32>, u64)>, Error> {
        let mut cursor = Self::with_key(index.key());
        if let Some(j) = index.checkpoint_before(lsn) {
            cursor.resume_at(index, index.plan_at(j));
        }
        cursor.recorder = None;
        cursor.scan_to(image, lsn)?;
        if let ResumedFrom::Discarded { .. } = cursor.resumed {
            return Ok(None);
        }
        // The scan stops before sector `lsn`: when that is the checkpoint's own sector,
        // its digest is still to compare (a stale index, or one of another image of the
        // same size, must not confirm anything).
        if let Some((at, want)) = cursor.verify {
            if at < cursor.end_lsn && digest(&cursor.sector(image, at)?) != want {
                return Ok(None);
            }
        }
        let d = &cursor.demux;
        Ok(Some((d.next_acceptable, d.assembling.as_ref().map(|a| a.number), d.malformed)))
    }

    /// Whether this cursor's positions are provisional (see [`SeekPolicy`]).
    pub fn speculation(&self) -> Speculation {
        self.claim.as_ref().map_or(Speculation::Exact, |c| c.speculation())
    }

    /// The number of this cursor's provisional reading, as events name it
    /// ([`crate::seek::SeekEvent::claim`]); `None` for an exact cursor.
    pub fn claim(&self) -> Option<u64> {
        self.claim.as_ref().map(|c| c.id)
    }

    /// The sector the malformed count and warnings begin at: `None` for the area's first
    /// sector, `Some(L)` for a provisional reading (specification 4, 4.4.5 item 5).
    pub fn claim_lsn(&self) -> Option<u64> {
        self.claim.as_ref().map(|c| c.lsn()).filter(|&l| l > 0)
    }

    /// The provisional reading, the first time it is asked for once `L` is chosen.
    pub(crate) fn unregistered_claim(&mut self) -> Option<std::sync::Arc<Claim>> {
        let claim = self.claim.as_ref().filter(|c| !self.claim_registered && c.lsn() > 0)?;
        let claim = std::sync::Arc::clone(claim);
        self.claim_registered = true;
        Some(claim)
    }

    /// The provisional checkpoints recorded since the last call.
    pub(crate) fn take_provisional_checkpoints(&mut self) -> Vec<(u64, Provisional)> {
        self.provisional.as_mut().map(|p| std::mem::take(&mut p.list)).unwrap_or_default()
    }

    /// Whether this cursor has anything for an index: checkpoints, a provisional reading
    /// or provisional checkpoints.
    #[inline]
    pub(crate) fn has_news(&self) -> bool {
        self.recorder.as_deref().is_some_and(Recorder::has_news)
            || (!self.claim_registered && self.claim.as_ref().is_some_and(|c| c.lsn() > 0))
            || self.provisional.as_ref().is_some_and(|p| !p.list.is_empty())
            || self.hints_stale
            || self.hints.as_deref().is_some_and(HintRecorder::has_news)
    }

    /// A cursor of the area of `index` that starts from it for positions `first` or more
    /// (specification 4, 4.2 item 7): at the last checkpoint whose next acceptable frame
    /// number is at most `first`, with its malformed count and warnings those of the scan
    /// from the first sector, recording checkpoints past the index's frontier.
    pub(crate) fn resume(index: &AreaIndex, first: u32) -> Self {
        let mut cursor = Self::with_key(index.key());
        let slot = cursor.slot;
        let warn = |lsn: u32| Warning {
            code: WarningCode::AudioSectorMalformed,
            slot: Some(slot),
            track: None,
            lsn: Some(lsn),
        };
        match index.plan(first) {
            Plan::Start => cursor.recorder = index.recorder(cursor.next_lsn),
            Plan::End(end) => {
                // No frame numbered `first` or more is accepted: nothing to read. The counts
                // are those of a scan to the end, which a scan from the first sector makes.
                cursor.next_lsn = cursor.end_lsn;
                cursor.finished = true;
                cursor.demux.next_acceptable = end.next_acceptable;
                cursor.demux.malformed = end.malformed;
                cursor.warnings = index.malformed_below(cursor.end_lsn).map(warn).collect();
                cursor.resumed = ResumedFrom::End;
            }
            plan @ Plan::At { .. } => cursor.resume_at(index, plan),
        }
        cursor
    }

    /// Resumes at the checkpoint `plan` names (a [`Plan::At`] of `index`).
    fn resume_at(&mut self, index: &AreaIndex, plan: Plan<'_>) {
        let slot = self.slot;
        let warn = |lsn: u32| Warning {
            code: WarningCode::AudioSectorMalformed,
            slot: Some(slot),
            track: None,
            lsn: Some(lsn),
        };
        let Plan::At { lsn, checkpoint, held } = plan else { return };
        // Specification 4, 4.4.5 item 4: a late reader MAY report the malformed
        // sectors an earlier pass found; this one reports them all, as a scan from
        // the first sector would.
        self.warnings = index.malformed_below(lsn).map(warn).collect();
        let replay_from = match held {
            Some((h, bytes)) => {
                self.demux.assembling = Some(Assembly {
                    number: h.number,
                    kind: h.kind,
                    data: bytes.to_vec(),
                    remaining: h.remaining,
                    start_lsn: lsn - u64::from(checkpoint.back),
                });
                lsn
            }
            None => lsn - u64::from(checkpoint.back),
        };
        self.demux.next_acceptable = checkpoint.next_acceptable;
        self.demux.malformed = checkpoint.malformed_before;
        if replay_from < lsn {
            // Lemma B1 of #68: from the first start packet the replay processes, its
            // frame under assembly is the scan's; the frames it delivers are all
            // numbered below the checkpoint's `a`, and are dropped.
            self.replay = Some(Replay {
                until: lsn,
                next_acceptable: checkpoint.next_acceptable,
                malformed: checkpoint.malformed_before,
            });
        }
        self.next_lsn = replay_from;
        self.verify = Some((lsn, checkpoint.digest));
        self.recorder = index.recorder(lsn);
        self.resumed = ResumedFrom::Checkpoint { lsn, replay_from };
    }

    /// Starts afresh at the area's first audio sector: the seek index this cursor started
    /// from does not hold sector `lsn` as it is in the image (a stale index, or one of
    /// another image of the same size). Nothing was returned from it yet: the sectors
    /// processed so far only rebuilt the frame under assembly.
    fn discard_index(&mut self, log: &Log, lsn: u64) {
        let (image_id, stop, counts) = (self.image_id, self.stop_lsn, self.take_progress());
        *self = Self::with_key(self.key);
        self.image_id = image_id;
        self.keep_progress(counts);
        self.resumed = ResumedFrom::Discarded { lsn };
        if stop != u64::MAX {
            // Extending the index (`scan_to`): stop here; reading from the first sector
            // would only record nothing.
            self.stop_lsn = self.next_lsn;
        }
        sb_log!(
            log,
            Warn,
            "area {}: seek index does not match the image at LSN {lsn}, discarded; scanning from LSN {}",
            self.slot,
            self.next_lsn
        );
    }

    /// Where this cursor's scan started (see [`ResumedFrom`]).
    pub fn resumed_from(&self) -> ResumedFrom {
        self.resumed
    }

    /// Scans up to (not including) sector `stop`, or to the end, dropping the frames:
    /// whether the end was reached.
    pub(crate) fn scan_to<R: Read + Seek>(&mut self, image: &mut Image<R>, stop: u64) -> Result<bool, Error> {
        self.stop_lsn = stop;
        let result = loop {
            match self.next_frame(image) {
                Some(Ok(_)) => {}
                Some(Err(e)) => break Err(e),
                None => break Ok(self.finished),
            }
        };
        self.stop_lsn = u64::MAX;
        result
    }

    /// The checkpoints recorded for a seek index.
    pub(crate) fn recorder(&self) -> Option<&Recorder> {
        self.recorder.as_deref()
    }

    pub(crate) fn recorder_mut(&mut self) -> Option<&mut Recorder> {
        self.recorder.as_deref_mut()
    }

    /// Marks the checkpoints this cursor records as those of the disc's own index.
    pub(crate) fn keep_for_disc(&mut self) {
        if let Some(r) = self.recorder.as_deref_mut() {
            r.kept = true;
        }
        if let Some(sp) = self.speculate.as_mut() {
            sp.exact.keep_for_disc();
        }
    }

    /// Records no more checkpoints.
    pub(crate) fn stop_recording(&mut self) {
        self.recorder = None;
    }

    /// Reports, until this cursor first reads, the malformed count and warnings of `from`,
    /// whose scan a continuation moved ahead through a seek index: a scan from the area's
    /// first sector, as `from` was, reports them at that point (and this cursor, once it
    /// reads, those of the same scan further on).
    pub(crate) fn carry_counts(&mut self, from: &AreaCursor) {
        self.before_read = Some(Box::new((from.malformed_sectors(), from.warnings().to_vec())));
    }

    /// The image this cursor read, once it has read.
    pub(crate) fn image_id(&self) -> Option<u64> {
        self.image_id
    }

    /// The area's slot.
    pub(crate) fn slot(&self) -> Slot {
        self.slot
    }

    /// The next sector the scan reads.
    pub(crate) fn scan_lsn(&self) -> u64 {
        self.next_lsn
    }

    /// Number of malformed sectors processed so far by this cursor's scan of its area. The
    /// scan starts at the area's first audio sector, not at the track, and a continued
    /// cursor keeps counting from where the earlier tracks left off.
    /// Track cursors read ahead of the frames they return (a group of a few frames,
    /// or with `parallel` a window of bounded size), so this may count sectors of frames
    /// not yet returned.
    pub fn malformed_sectors(&self) -> u64 {
        // A cursor started from a seek index holds the counts of the sectors before its
        // checkpoint, which a scan from the first sector reports only once it has read.
        match (&self.image_id, &self.before_read) {
            (Some(_), _) => self.demux.malformed_sectors(),
            (None, Some(b)) => b.0,
            (None, None) => 0,
        }
    }

    /// The `audio-sector-malformed` warnings of the sectors processed so far, with slot
    /// and LSN, in processing order (specification 4, 4.4.5). At most
    /// [`MAX_MALFORMED_WARNINGS`] are kept; [`AreaCursor::malformed_sectors`] counts them
    /// all. Like that count, they may include sectors of frames not yet returned.
    pub fn warnings(&self) -> &[Warning] {
        match (&self.image_id, &self.before_read) {
            (Some(_), _) => &self.warnings,
            (None, Some(b)) => &b.1,
            (None, None) => &[],
        }
    }

    fn sector<R: Read + Seek>(&mut self, image: &mut Image<R>, lsn: u64) -> Result<[u8; SECTOR_SIZE], Error> {
        let at = self.load(image, lsn)?;
        Ok(*held(&self.buf, at))
    }

    /// Reads sector `lsn` into the buffer, with the sectors after it that the read takes,
    /// unless it is there already, and gives its offset in the buffer: the scan reads the
    /// sector there ([`held`]), without a copy.
    fn load<R: Read + Seek>(&mut self, image: &mut Image<R>, lsn: u64) -> Result<usize, Error> {
        if !(self.buf_lsn..self.buf_lsn + self.buf_sectors).contains(&lsn) {
            // A read sized to the range reads what it was sized to, less than a chunk too.
            let sized = self.read_to.saturating_sub(lsn);
            let then = self.read_then.saturating_sub(lsn);
            let n = if sized > 0 { sized } else { READ_CHUNK.max(then) }
                .min(crate::seek::MAX_READ_SECTORS)
                .min(self.end_lsn - lsn);
            image.check_cancel()?;
            self.buf.resize(n as usize * SECTOR_SIZE, 0);
            // For the image the cursor was made for, the range lies below its sector
            // count; another image may be shorter, which is reported, not assumed.
            if image.read_into(lsn, &mut self.buf)? == ReadOutcome::OutOfRange {
                sb_log!(
                    image.log(),
                    Error,
                    "area {}: audio sectors from LSN {lsn} outside the image",
                    self.slot
                );
                return Err(Error::InvalidArgument("audio sectors outside the image"));
            }
            self.count_read(n, lsn + n);
            self.buf_lsn = lsn;
            self.buf_sectors = n;
        }
        Ok((lsn - self.buf_lsn) as usize * SECTOR_SIZE)
    }

    /// The next accepted frame, `None` at the end of the area.
    ///
    /// The cursor binds to the first image it reads; with an image of another identifier
    /// ([`Image::id`]) it returns [`Error::InvalidArgument`] (and stays usable with its
    /// own). The images of a disc's [`crate::Disc::share`] and `clone` have the same
    /// identifier: they read the same bytes, so the cursor reads through any of them.
    pub fn next_frame<R: Read + Seek>(&mut self, image: &mut Image<R>) -> Option<Result<AreaFrame, Error>> {
        match self.image_id {
            None => {
                self.image_id = Some(image.id());
                if let Some(claim) = &self.claim {
                    claim.set_image(image.id());
                }
                if let Some(sp) = self.speculate.take() {
                    if let Err(e) = self.begin(image, sp) {
                        if let Error::Cancelled = e {
                            // Searched again, from the start, on the next read.
                            self.image_id = None;
                        } else {
                            self.finished = true;
                        }
                        return Some(Err(e));
                    }
                }
                match self.resumed {
                    ResumedFrom::Start => sb_log!(
                        image.log(),
                        Debug,
                        "area {}: scanning audio sectors LSN {}..{}",
                        self.slot,
                        self.next_lsn,
                        self.end_lsn
                    ),
                    ResumedFrom::Checkpoint { lsn, replay_from } => sb_log!(
                        image.log(),
                        Debug,
                        "area {}: resuming at LSN {lsn} from seek index (next acceptable {}, replay from LSN \
                         {replay_from}), scanning to LSN {}",
                        self.slot,
                        self.replay.map_or(self.demux.next_acceptable, |r| r.next_acceptable),
                        self.end_lsn
                    ),
                    ResumedFrom::End => sb_log!(
                        image.log(),
                        Debug,
                        "area {}: seek index: no frame accepted at or after the range, nothing to read",
                        self.slot
                    ),
                    ResumedFrom::Speculative { lsn, probes } => sb_log!(
                        image.log(),
                        Info,
                        "area {}: provisional reading from LSN {lsn} for frames {}.. ({probes} reads to choose it; \
                         4.2 item 8): positions provisional, counts from LSN {lsn}",
                        self.slot,
                        self.demux.next_acceptable
                    ),
                    // Set only once the cursor reads.
                    ResumedFrom::Discarded { .. } => {}
                }
            }
            Some(id) if id != image.id() => {
                return Some(Err(Error::InvalidArgument("audio cursor used with another image")));
            }
            Some(_) => {}
        }
        loop {
            if let Some(f) = self.demux.pop() {
                return Some(Ok(f));
            }
            if self.finished {
                return None;
            }
            if let Some(r) = self.replay.filter(|r| self.next_lsn >= r.until) {
                // The replay has rebuilt the frame under assembly: the checkpoint's state
                // from here (before reading sector `until`, so that a scan stopping there
                // sees the state at it).
                self.demux.ready.clear();
                self.demux.next_acceptable = r.next_acceptable;
                self.demux.malformed = r.malformed;
                self.replay = None;
            }
            if self.next_lsn >= self.stop_lsn && self.replay.is_none() && self.next_lsn < self.end_lsn {
                return None;
            }
            if self.next_lsn < self.end_lsn {
                let lsn = self.next_lsn;
                self.next_lsn += 1;
                match self.load(image, lsn) {
                    Ok(at) => {
                        let s = held(&self.buf, at);
                        if let Some(r) = self.replay {
                            if lsn < r.until {
                                // Rebuilds the frame under assembly only: no log lines, no
                                // warnings, nothing delivered, and the malformed count stays
                                // the checkpoint's, which counts these sectors already, also
                                // if a read fails before the replay ends (4.4.5 item 2).
                                let malformed = self.demux.malformed;
                                self.demux.push_sector_at(s, self.demux.at(&Log::none(), lsn));
                                self.demux.malformed = malformed;
                                self.demux.ready.clear();
                                continue;
                            }
                        }
                        if let Some((at, want)) = self.verify.filter(|&(at, _)| at == lsn) {
                            self.verify = None;
                            if digest(s) != want {
                                self.discard_index(image.log(), at);
                                continue;
                            }
                        }
                        if let Some(h) = self.hints.as_deref_mut() {
                            h.see(lsn, s);
                        }
                        if let Some(pr) = self.provisional.as_deref_mut().filter(|p| p.due(lsn)) {
                            let under = self.demux.assembling.as_ref().map(|a| (lsn - a.start_lsn, a.number));
                            pr.record(lsn, under, self.demux.seen, s);
                        }
                        if let Some(rec) = self.recorder.as_deref_mut().filter(|r| r.due(lsn)) {
                            let d = &self.demux;
                            let assembling = d.assembling.as_ref().map(|a| Assembling {
                                start_lsn: a.start_lsn,
                                number: a.number,
                                kind: a.kind,
                                remaining: a.remaining,
                                data: &a.data,
                            });
                            rec.record(lsn, d.next_acceptable, d.malformed, assembling, s);
                        }
                        let at = self.demux.at(image.log(), lsn);
                        let malformed = self.demux.push_sector_at(s, at);
                        if let Some(reason) = self.demux.reason.filter(|_| malformed) {
                            let code = WarningCode::AudioSectorMalformed.code();
                            let log = image.log();
                            if self.malformed_lines.admit(log, Level::Warn, self.slot.name(), code) {
                                sb_log!(
                                    log,
                                    Warn,
                                    "area {} audio sector LSN {lsn}: {code}: {reason}",
                                    self.slot
                                );
                            }
                        }
                        if malformed && self.warnings.len() < MAX_MALFORMED_WARNINGS {
                            // LSNs of audio sectors come from u32 fields.
                            let lsn = u32::try_from(lsn).ok();
                            self.warnings.push(Warning {
                                code: WarningCode::AudioSectorMalformed,
                                slot: Some(self.slot),
                                track: None,
                                lsn,
                            });
                        }
                    }
                    Err(Error::Cancelled) => {
                        // Nothing was read: the same sector next time.
                        self.next_lsn = lsn;
                        return Some(Err(Error::Cancelled));
                    }
                    Err(e) => {
                        self.finished = true;
                        return Some(Err(e));
                    }
                }
            } else {
                self.demux.finish_at(self.demux.at(image.log(), self.end_lsn));
                self.finished = true;
                self.progress_done();
                if let Some(rec) = self.recorder.as_deref_mut() {
                    rec.finish(self.demux.next_acceptable, self.demux.malformed);
                }
                sb_log!(
                    image.log(),
                    Debug,
                    "area {}: scan ended at LSN {}, {} malformed sectors",
                    self.slot,
                    self.end_lsn,
                    self.demux.malformed_sectors()
                );
            }
        }
    }
}

/// Sector `lsn` of `image`, read alone.
pub(crate) fn read_sector<R: Read + Seek>(
    image: &mut Image<R>,
    lsn: u64,
) -> Result<[u8; SECTOR_SIZE], Error> {
    let mut out = [0u8; SECTOR_SIZE];
    image.check_cancel()?;
    if image.read_into(lsn, &mut out)? == ReadOutcome::OutOfRange {
        return Err(Error::InvalidArgument("audio sectors outside the image"));
    }
    Ok(out)
}

/// The accepted frames of an area, read from an image in increasing LSN order.
#[derive(Debug)]
pub struct AreaFrames<'a, R> {
    image: &'a mut Image<R>,
    cursor: AreaCursor,
}

impl<'a, R: Read + Seek> AreaFrames<'a, R> {
    pub(crate) fn new(image: &'a mut Image<R>, area: &Area) -> Self {
        let cursor = AreaCursor::new(area, image.sector_count());
        AreaFrames { image, cursor }
    }

    pub(crate) fn with_cursor(image: &'a mut Image<R>, cursor: AreaCursor) -> Self {
        AreaFrames { image, cursor }
    }

    /// Number of malformed sectors processed so far by this cursor's scan of its area. The
    /// scan starts at the area's first audio sector, not at the track, and a continued
    /// cursor keeps counting from where the earlier tracks left off.
    /// Track cursors read ahead of the frames they return (a group of a few frames,
    /// or with `parallel` a window of bounded size), so this may count sectors of frames
    /// not yet returned.
    pub fn malformed_sectors(&self) -> u64 {
        self.cursor.malformed_sectors()
    }

    /// The `audio-sector-malformed` warnings of this cursor's scan of its area so far
    /// (see [`AreaCursor::warnings`]): per area, not per track, and each sector once.
    pub fn warnings(&self) -> &[Warning] {
        self.cursor.warnings()
    }

    /// The progress of the reading, readable from other threads (see [`Progress`]).
    pub fn progress(&mut self) -> Progress {
        self.cursor.progress()
    }
}

impl<R: Read + Seek> Iterator for AreaFrames<'_, R> {
    type Item = Result<AreaFrame, Error>;

    fn next(&mut self) -> Option<Self::Item> {
        self.cursor.next_frame(self.image)
    }
}

/// The sectors `[start, end)` of an area that exist in an image of `n` sectors
/// (specification 4, 4.2).
pub fn audio_sector_range(area: &Area, n: u64) -> (u64, u64) {
    let start = u64::from(area.audio_start_lsn);
    let end = (u64::from(area.audio_end_lsn) + 1).min(n);
    (start, end.max(start))
}

/// Checks whether a track produces audio (specification 4, 4.8).
///
/// # Errors
///
/// [`Error::ChannelCountUnsupported`], [`Error::TrackEmpty`] or
/// [`Error::TrackExceedsCapacity`], in that order of precedence.
pub fn check_track(area: &Area, track: &Track, image_sectors: u64) -> Result<(), Error> {
    check_channels(area)?;
    if track.duration_frames == 0 {
        return Err(Error::TrackEmpty);
    }
    check_capacity(area, track.end_frame(), image_sectors)
}

/// Checks whether the frame range `[first, end)` of an area produces audio
/// (specification 4, 4.7.1 items 3 and 4).
///
/// A range must lie in the area's play range `[0, P)`, `first <= end <= P` with `P` the
/// area's play time ([`Area::playtime_frames`]); anything else is a caller error. The
/// checks of 4.8 then apply as to a track, with `end - first` as the duration and `end`
/// as the end frame.
///
/// # Errors
///
/// [`Error::ChannelCountUnsupported`], [`Error::FrameRangeInvalid`] (the caller error),
/// [`Error::TrackEmpty`] (`first == end`) or [`Error::TrackExceedsCapacity`], in that
/// order of precedence. The 4.8 outcomes keep their track codes (specification 7, 7.7.4
/// reports them per track or per frame range).
pub fn check_range(area: &Area, first: u32, end: u32, image_sectors: u64) -> Result<(), Error> {
    check_channels(area)?;
    let playtime = area.playtime_frames();
    if first > end || end > playtime {
        return Err(Error::FrameRangeInvalid { first, end, playtime });
    }
    if first == end {
        return Err(Error::TrackEmpty);
    }
    check_capacity(area, end, image_sectors)
}

/// Specification 4, 4.8 item 1.
pub(crate) fn check_channels(area: &Area) -> Result<(), Error> {
    if !(1..=MAX_CHANNELS).contains(&area.channel_count) {
        return Err(Error::ChannelCountUnsupported { channels: area.channel_count });
    }
    Ok(())
}

/// Specification 4, 4.8 item 3, for a track or range ending at `end_frame`.
fn check_capacity(area: &Area, end_frame: u32, image_sectors: u64) -> Result<(), Error> {
    let (start, end) = audio_sector_range(area, image_sectors);
    let capacity = (end - start).saturating_mul(FRAMES_PER_SECTOR);
    if u64::from(end_frame) > capacity {
        return Err(Error::TrackExceedsCapacity { end_frame, capacity });
    }
    Ok(())
}

/// Most bytes of packet data an audio sector can carry: 2048 less the smallest header of
/// a sector with a packet, the 1-byte sector header and one 2-byte packet record
/// (specification 4, 4.3.1, 4.3.2 and 4.3.4 item 1).
const PACKET_BYTES_PER_SECTOR: u64 = SECTOR_SIZE as u64 - 3;

/// What an area's TOC claims against the audio sectors the image holds (specification 4,
/// 4.2 and 4.8), for a consumer's own plausibility check of the area's length:
/// [`area_capacity`] or [`crate::Disc::area_capacity`].
///
/// These are figures, not a verdict, and the consumer chooses the threshold. Only
/// [`AreaCapacity::capacity`] is a bound of the specification on what a track may claim
/// (4.8 item 3), and the library already refuses a track past it
/// ([`Error::TrackExceedsCapacity`]). [`AreaCapacity::plain_frame_bound`] holds for every
/// image but bounds plain DSD frames only. For DST the specification gives no bound below
/// 7 frames per sector: a DST frame's size depends on its content (4.4.2). The figure of
/// specification 7, 7.9 (informative) is that 110 commercial discs carry at most 0.6
/// frames per audio sector.
///
/// Every figure is computed without overflow, division by zero or NaN, whatever the TOC
/// holds; see each field.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct AreaCapacity {
    /// `n = max(0, S1' - S0 + 1)`, the area's audio sectors that exist in the image
    /// (specification 4, 4.2 item 1 and 4.8 item 3): 0 when they all lie past its end.
    pub audio_sectors: u64,
    /// `P`, the area's play time in frames ([`Area::playtime_frames`]).
    pub playtime_frames: u32,
    /// The largest track end frame `s_i + d_i` of the area's tracks ([`Track::end_frame`]),
    /// 0 when it has none.
    pub max_track_end: u32,
    /// The capacity `Q = 7 x n` (specification 4, 4.8 item 3; 7.5): a sector's header can
    /// start at most 7 frames (4.3.1). A track ending past it is refused.
    pub capacity: u64,
    /// `floor(n x 2045 / (C x 4704))`, the most plain DSD frames the area's sectors can
    /// carry, `C` its channel count; `None` when `C` is not 1 to 6, for which no audio is
    /// produced (4.8 item 1).
    ///
    /// Own derivation from the specification: a sector carrying audio has at least one
    /// packet record, so at least 3 bytes of header (4.3.1, 4.3.2, 4.3.4 item 1), which
    /// leaves at most 2045 bytes of packet data; a plain frame is complete with exactly
    /// `C x 4704` bytes of them (4.1 item 1, 4.4.2), and no byte belongs to two frames.
    /// It bounds the plain frames of every image, conforming or not, but not DST frames,
    /// and only the sectors' DST flag says which kind an area carries (the TOC's frame
    /// format is informative, 3.4.2 item 2), so it applies only to an area known to be
    /// plain DSD. Dense "3 in 14" packing (4.10 item 2) gives 3/14 frames per sector at 2
    /// channels, against this bound's 2045/9408.
    pub plain_frame_bound: Option<u64>,
}

impl AreaCapacity {
    /// The frames the TOC claims, `max(P, max_track_end)`, per audio sector present (`n`).
    ///
    /// `f64::INFINITY` when `n` is 0, whatever the TOC claims, so that a `> limit` test
    /// treats an area with no audio sectors in the image as implausible; never NaN.
    pub fn frames_per_sector(&self) -> f64 {
        if self.audio_sectors == 0 {
            return f64::INFINITY;
        }
        let claimed = self.playtime_frames.max(self.max_track_end);
        // n <= 2^32 and claimed < 2^32 are exact in an f64.
        f64::from(claimed) / self.audio_sectors as f64
    }
}

/// The figures of [`AreaCapacity`] for `area` in an image of `image_sectors` sectors
/// (specification 4, 4.2 and 4.8). Arithmetic on the TOC's fields only: it reads nothing.
pub fn area_capacity(area: &Area, image_sectors: u64) -> AreaCapacity {
    let (start, end) = audio_sector_range(area, image_sectors);
    let n = end - start;
    let plain_frame_bound = (1..=MAX_CHANNELS).contains(&area.channel_count).then(|| {
        let frame = u64::from(area.channel_count) * FRAME_BYTES_PER_CHANNEL as u64;
        // n <= 2^32, so n x 2045 fits; saturating all the same.
        n.saturating_mul(PACKET_BYTES_PER_SECTOR) / frame
    });
    AreaCapacity {
        audio_sectors: n,
        playtime_frames: area.playtime_frames(),
        max_track_end: area.tracks.iter().map(Track::end_frame).max().unwrap_or(0),
        capacity: n.saturating_mul(FRAMES_PER_SECTOR),
        plain_frame_bound,
    }
}

/// Track `number`'s **track with pause** (specification 4, 4.7.1 item 5): `[a, b)` with
/// `a = 0` for track 1 and its own start `s_i` for every other track, and
/// `b = max(s_i + d_i, s_j)` when the track numbered `j = i + 1` exists, `max(s_i + d_i, P)`
/// for the last track. With tracks out of order or overlapping these ranges may overlap,
/// and are used as they are. `None` if the area has no such track.
///
/// Check the range with [`check_range`] as for any range: it may be empty (a track of
/// duration 0 whose successor starts where it does), which is `track-empty`.
pub fn track_range_with_pause(area: &Area, number: u32) -> Option<(u32, u32)> {
    let track = area.track(number)?;
    let first = if number == 1 { 0 } else { track.start_frame };
    let next =
        number.checked_add(1).and_then(|n| area.track(n)).map_or(area.playtime_frames(), |t| t.start_frame);
    Some((first, next.max(track.end_frame())))
}

/// What a cursor reads: a track, or any frame range of an area
/// ([`crate::Disc::audio_cursor`], [`crate::Disc::frames_cursor`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FrameSpan {
    /// Track `n` (1-based) of the area, checked by [`check_track`].
    Track(u32),
    /// The frames `[first, end)` of the area, checked by [`check_range`]; the whole area
    /// is `[0, P)`, with `P` its play time.
    Range(u32, u32),
}

/// How a cursor starts: the seek index it starts from and its seek policy.
///
/// [`crate::Disc::audio_cursor`] and [`crate::Disc::frames_cursor`] default to the disc's
/// index and policy for the area; [`TrackCursor::open_range`] and
/// [`TrackAudioCursor::open_range`] to no index and [`SeekPolicy::Exact`].
#[derive(Clone, Copy, Debug, Default)]
pub struct CursorOptions<'a> {
    index: Option<&'a AreaIndex>,
    policy: Option<SeekPolicy>,
}

impl<'a> CursorOptions<'a> {
    /// The defaults.
    pub fn new() -> Self {
        Self::default()
    }

    /// Starts from `index`, of the caller's, rather than the default: at its last
    /// checkpoint whose next acceptable frame number is at most the first frame read, or
    /// reading nothing when the index is complete and no such frame is accepted. The
    /// positions, their contents, the counts and warnings are those of a scan from the
    /// area's first audio sector; only the sectors read and the log lines differ, sectors
    /// replayed to rebuild the frame under assembly not being logged.
    ///
    /// The cursor records the checkpoints it crosses past the index's frontier; take them
    /// with [`AreaIndex::absorb`]. An empty index ([`AreaIndex::new`]) gives a scan from the
    /// first sector that builds one. An index of another area or image size is
    /// [`Error::InvalidArgument`] when the cursor is opened.
    pub fn with_index(mut self, index: &'a AreaIndex) -> Self {
        self.index = Some(index);
        self
    }

    /// Reads with `policy` rather than the default. With [`SeekPolicy::Speculative`], the
    /// start may be provisional (specification 4, 4.2 item 8, sacd-spec `82eac6c`) when the
    /// exact start would read more than the options' gap before the range's estimated
    /// position: the cursor chooses on its first read; [`TrackCursor::speculation`] and
    /// [`TrackCursor::resumed_from`] then say which start it took. A provisional cursor
    /// records no checkpoints.
    pub fn with_policy(mut self, policy: SeekPolicy) -> Self {
        self.policy = Some(policy);
        self
    }

    /// The index asked for, if any.
    pub(crate) fn index(&self) -> Option<&'a AreaIndex> {
        self.index
    }

    /// The policy asked for, if any.
    pub(crate) fn policy(&self) -> Option<SeekPolicy> {
        self.policy
    }
}

/// How a continuation opens its range ([`Continuation::log_audio`]).
///
/// Not part of the public API: plumbing of the C interface, not covered by semantic
/// versioning. It may change or go in any release.
#[doc(hidden)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Opening {
    /// The earlier cursor's scan goes on.
    Continues,
    /// A start from the seek index.
    FromIndex,
    /// A new scan from the area's first sector.
    Fresh,
}

/// A track or frame range of an area, checked ([`check_track`] or [`check_range`]), that
/// a cursor can continue into without failing: see [`crate::Disc::track_continuation`]
/// and [`crate::Disc::range_continuation`].
#[derive(Clone, Copy, Debug)]
pub struct Continuation<'a> {
    area: &'a Area,
    first: u32,
    end: u32,
    image_sectors: u64,
    image_id: Option<u64>,
    /// The disc's log, and the track number when this is a track, for the log.
    log: &'a Log,
    track: Option<u32>,
    /// The disc's seek indexes.
    seek: &'a SeekIndexes,
    /// The disc's seek policy for the area.
    policy: SeekPolicy,
}

impl<'a> Continuation<'a> {
    pub(crate) fn new(
        area: &'a Area,
        (first, end): (u32, u32),
        (image_sectors, image_id): (u64, Option<u64>),
        log: &'a Log,
        track: Option<u32>,
        (seek, policy): (&'a SeekIndexes, SeekPolicy),
    ) -> Self {
        Continuation { area, first, end, image_sectors, image_id, log, track, seek, policy }
    }

    /// The disc's index for this range's area, if it keeps one, under a read lock.
    fn with_index<T>(&self, f: impl FnOnce(Option<&AreaIndex>) -> T) -> T {
        self.seek.read(self.area.slot, |index| f(index.filter(|i| self.check_index(i).is_ok())))
    }

    /// Logs (at [`Level::Info`]) the opening of `what` as `opening`.
    fn log_how(&self, what: &str, opening: Opening) {
        if self.log.enabled(Level::Info) {
            let how = match opening {
                Opening::Continues => "continuing the earlier scan",
                Opening::FromIndex => "from the seek index",
                Opening::Fresh => "new scan of the area",
            };
            log_open(self.log, self.area, self.track, (self.first, self.end), what, how);
        }
    }

    /// Takes what `cursor` recorded into the disc's index, if the cursor read this image.
    fn absorb(&self, cursor: &mut AreaCursor) {
        if let Some(id) = self.image_id {
            self.seek.absorb(cursor, id);
        }
    }

    /// Takes what `cursor` recorded into the caller's `index`, if the cursor read this
    /// image and its checkpoints join the index; otherwise leaves them (they may be the
    /// disc's).
    fn absorb_into(&self, cursor: &mut AreaCursor, index: &mut AreaIndex) {
        let other_image = matches!((cursor.image_id(), self.image_id), (Some(a), Some(b)) if a != b);
        if !other_image && index.take_from(cursor).is_ok() {
            AreaIndex::drain(cursor);
        }
    }

    /// The frame range, `[first, end)`.
    pub fn range(&self) -> (u32, u32) {
        (self.first, self.end)
    }

    /// `prev` continued into this range (see [`crate::Disc::continue_range_audio`]),
    /// or a fresh cursor when its state cannot be reused, or a start from the disc's seek
    /// index. Logs the opening first.
    pub fn audio(self, prev: TrackAudioCursor) -> TrackAudioCursor {
        let opening = self.log_audio(&prev);
        self.audio_as(prev, opening)
    }

    /// How this range's audio opens from `prev`, decided once: logged (at
    /// [`Level::Info`]) and returned, for [`Continuation::audio_as`] to open it so.
    /// [`Continuation::audio`] does both.
    ///
    /// Not part of the public API: plumbing of the C interface, not covered by semantic
    /// versioning. It may change or go in any release.
    #[doc(hidden)]
    pub fn log_audio(&self, prev: &TrackAudioCursor) -> Opening {
        let opening = self.with_index(|index| {
            prev.opening(self.area, self.first, (self.image_sectors, self.image_id), index)
        });
        self.log_how("decoded audio", opening);
        opening
    }

    /// [`Continuation::audio`] without logging: no log sink runs during the call. For a
    /// caller that must not run one while it hands `prev` over (the C interface, whose
    /// callbacks could otherwise reach a handle being consumed); it calls
    /// [`Continuation::log_audio`] first, while `prev` is still guarded, then
    /// [`Continuation::audio_as`] with its answer.
    ///
    /// Not part of the public API: plumbing of the C interface, not covered by semantic
    /// versioning. It may change or go in any release.
    #[doc(hidden)]
    pub fn audio_unlogged(self, prev: TrackAudioCursor) -> TrackAudioCursor {
        let opening = self.with_index(|index| {
            prev.opening(self.area, self.first, (self.image_sectors, self.image_id), index)
        });
        self.audio_as(prev, opening)
    }

    /// Opens this range's audio from `prev` as `opening` says (from
    /// [`Continuation::log_audio`]), so that the log and the cursor agree; first takes
    /// what `prev` recorded into the disc's index. No log sink runs.
    ///
    /// Not part of the public API: plumbing of the C interface, not covered by semantic
    /// versioning. It may change or go in any release.
    #[doc(hidden)]
    pub fn audio_as(self, mut prev: TrackAudioCursor, opening: Opening) -> TrackAudioCursor {
        self.absorb(&mut prev.frames.area);
        self.with_index(|index| {
            let mut next = prev.open_as(
                self.area,
                (self.first, self.end),
                (self.image_sectors, self.image_id),
                index,
                (opening, self.policy),
            );
            if opening != Opening::Continues && index.is_some() {
                next.frames.area.keep_for_disc();
            }
            next
        })
    }

    /// `prev` continued into this range (see [`crate::Disc::continue_range_frames`]), as
    /// [`Continuation::audio`] does for decoded audio.
    pub fn frames(self, prev: TrackCursor) -> TrackCursor {
        let opening = self.log_frames(&prev);
        self.frames_as(prev, opening)
    }

    /// How this range's frames open from `prev` (see [`Continuation::log_audio`]).
    ///
    /// Not part of the public API: plumbing of the C interface, not covered by semantic
    /// versioning. It may change or go in any release.
    #[doc(hidden)]
    pub fn log_frames(&self, prev: &TrackCursor) -> Opening {
        let opening = self.with_index(|index| {
            prev.opening(self.area, self.first, self.image_sectors, self.image_id, index)
        });
        self.log_how("frames", opening);
        opening
    }

    /// [`Continuation::frames`] without logging (see [`Continuation::audio_unlogged`]).
    ///
    /// Not part of the public API: plumbing of the C interface, not covered by semantic
    /// versioning. It may change or go in any release.
    #[doc(hidden)]
    pub fn frames_unlogged(self, prev: TrackCursor) -> TrackCursor {
        let opening = self.with_index(|index| {
            prev.opening(self.area, self.first, self.image_sectors, self.image_id, index)
        });
        self.frames_as(prev, opening)
    }

    /// Opens this range's frames from `prev` as `opening` says (see
    /// [`Continuation::audio_as`]).
    ///
    /// Not part of the public API: plumbing of the C interface, not covered by semantic
    /// versioning. It may change or go in any release.
    #[doc(hidden)]
    pub fn frames_as(self, mut prev: TrackCursor, opening: Opening) -> TrackCursor {
        self.absorb(&mut prev.area);
        self.with_index(|index| {
            let mut next = prev.open_as(
                self.area,
                (self.first, self.end),
                (self.image_sectors, self.image_id),
                index,
                (opening, self.policy),
            );
            if opening != Opening::Continues && index.is_some() {
                next.area.keep_for_disc();
            }
            next
        })
    }

    /// Whether `index` is of this range's area and image size, as the `_indexed` methods
    /// need.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidArgument`] if it is not.
    ///
    /// Not part of the public API: plumbing of the C interface, not covered by semantic
    /// versioning. It may change or go in any release.
    #[doc(hidden)]
    pub fn check_index(&self, index: &AreaIndex) -> Result<(), Error> {
        index.check_key(self.area, self.image_sectors)
    }

    /// How this range's audio opens from `prev` with the caller's seek `index` in place of
    /// the disc's: logged and returned, for [`Continuation::audio_indexed_as`].
    ///
    /// Not part of the public API: plumbing of the C interface, not covered by semantic
    /// versioning. It may change or go in any release.
    #[doc(hidden)]
    pub fn log_audio_indexed(&self, prev: &TrackAudioCursor, index: &AreaIndex) -> Opening {
        let index = Some(index).filter(|i| self.check_index(i).is_ok());
        let opening = prev.opening(self.area, self.first, (self.image_sectors, self.image_id), index);
        self.log_how("decoded audio", opening);
        opening
    }

    /// [`Continuation::audio_unlogged`] with the caller's seek `index` (of this range's
    /// area, [`Continuation::check_index`]) in place of the disc's: first takes what
    /// `prev` recorded into it, then continues `prev` or starts from it. An index of
    /// another area is not used.
    ///
    /// Not part of the public API: plumbing of the C interface, not covered by semantic
    /// versioning. It may change or go in any release.
    #[doc(hidden)]
    pub fn audio_indexed_unlogged(self, prev: TrackAudioCursor, index: &mut AreaIndex) -> TrackAudioCursor {
        let opening = {
            let index = Some(&*index).filter(|i| self.check_index(i).is_ok());
            prev.opening(self.area, self.first, (self.image_sectors, self.image_id), index)
        };
        self.audio_indexed_as(prev, index, opening)
    }

    /// [`Continuation::audio_as`] with the caller's seek `index`.
    ///
    /// Not part of the public API: plumbing of the C interface, not covered by semantic
    /// versioning. It may change or go in any release.
    #[doc(hidden)]
    pub fn audio_indexed_as(
        self,
        mut prev: TrackAudioCursor,
        index: &mut AreaIndex,
        opening: Opening,
    ) -> TrackAudioCursor {
        self.absorb_into(&mut prev.frames.area, index);
        let index = Some(&*index).filter(|i| self.check_index(i).is_ok());
        prev.open_as(
            self.area,
            (self.first, self.end),
            (self.image_sectors, self.image_id),
            index,
            (opening, self.policy),
        )
    }

    /// How this range's frames open from `prev` with the caller's `index` (see
    /// [`Continuation::log_audio_indexed`]).
    ///
    /// Not part of the public API: plumbing of the C interface, not covered by semantic
    /// versioning. It may change or go in any release.
    #[doc(hidden)]
    pub fn log_frames_indexed(&self, prev: &TrackCursor, index: &AreaIndex) -> Opening {
        let index = Some(index).filter(|i| self.check_index(i).is_ok());
        let opening = prev.opening(self.area, self.first, self.image_sectors, self.image_id, index);
        self.log_how("frames", opening);
        opening
    }

    /// [`Continuation::frames_unlogged`] with the caller's seek `index` (see
    /// [`Continuation::audio_indexed_unlogged`]).
    ///
    /// Not part of the public API: plumbing of the C interface, not covered by semantic
    /// versioning. It may change or go in any release.
    #[doc(hidden)]
    pub fn frames_indexed_unlogged(self, prev: TrackCursor, index: &mut AreaIndex) -> TrackCursor {
        let opening = {
            let index = Some(&*index).filter(|i| self.check_index(i).is_ok());
            prev.opening(self.area, self.first, self.image_sectors, self.image_id, index)
        };
        self.frames_indexed_as(prev, index, opening)
    }

    /// [`Continuation::frames_as`] with the caller's seek `index`.
    ///
    /// Not part of the public API: plumbing of the C interface, not covered by semantic
    /// versioning. It may change or go in any release.
    #[doc(hidden)]
    pub fn frames_indexed_as(
        self,
        mut prev: TrackCursor,
        index: &mut AreaIndex,
        opening: Opening,
    ) -> TrackCursor {
        self.absorb_into(&mut prev.area, index);
        let index = Some(&*index).filter(|i| self.check_index(i).is_ok());
        prev.open_as(
            self.area,
            (self.first, self.end),
            (self.image_sectors, self.image_id),
            index,
            (opening, self.policy),
        )
    }

    /// Logs (at [`Level::Info`]) the opening of this range's frames on a new scan, as
    /// [`Continuation::fresh_frames`] does not.
    ///
    /// Not part of the public API: plumbing of the C interface, not covered by semantic
    /// versioning. It may change or go in any release.
    #[doc(hidden)]
    pub fn log_fresh_frames(&self) {
        self.log_how("frames", Opening::Fresh);
    }

    /// A fresh cursor of this range's positions (see [`TrackCursor::open_range`]), without
    /// logging (see [`Continuation::log_fresh_frames`]).
    ///
    /// Not part of the public API: plumbing of the C interface, not covered by semantic
    /// versioning. It may change or go in any release.
    #[doc(hidden)]
    pub fn fresh_frames(self) -> TrackCursor {
        self.seek.read(self.area.slot, |index| {
            let index = index.filter(|i| i.check_key(self.area, self.image_sectors).is_ok());
            let range = (self.first, self.end);
            let mut c = TrackCursor::start_with(self.area, range, self.image_sectors, index, self.policy);
            if index.is_some() {
                c.area.keep_for_disc();
            }
            c
        })
    }
}

/// Logs the opening of a track (`track` is its number) or frame range `[first, end)` of
/// `area`.
pub(crate) fn log_open(
    log: &Log,
    area: &Area,
    track: Option<u32>,
    (first, end): (u32, u32),
    what: &str,
    how: &str,
) {
    let slot = area.slot;
    let c = area.channel_count;
    match track {
        Some(n) => {
            sb_log!(log, Info, "area {slot} track {n}: frames {first}..{end} ({c} channels), {what}, {how}")
        }
        None => sb_log!(log, Info, "area {slot} range: frames {first}..{end} ({c} channels), {what}, {how}"),
    }
}

/// What a timeline position holds (specification 4, 4.6), before DST decoding.
///
/// Frozen: exhaustive on purpose, so a `match` needs no wildcard arm. A position's stored
/// content is a DST frame, a plain frame or none (specification 4, 4.6.1 item 1), and a frame
/// is one [`FrameKind`] or the other.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FrameContent {
    /// A plain DSD frame: `C x 4704` bytes in interleaved layout, used unchanged.
    Dsd(Vec<u8>),
    /// A DST frame's bytes, to be decoded.
    Dst(Vec<u8>),
    /// No accepted frame fills the position.
    Missing,
}

impl FrameContent {
    /// The position's **DST equivalent** (specification 4, 4.6.1 item 3): a DST frame that
    /// decodes, with `channels` channels, to exactly the position's content of 4.6. For a
    /// DST frame its stored bytes; for a plain frame the byte 0x00 (a plain DST frame
    /// header, 5.2.1) followed by its bytes; for a missing position 0x00 followed by
    /// `channels x 4704` bytes of 0x69. At most `1 + 6 x 4704` bytes for a plain or missing
    /// position, [`MAX_FRAME_BYTES`] for a DST frame.
    ///
    /// `channels` is the area's channel count (the cursors' `channels()`); it sizes only
    /// the missing fill. [`TrackFrames::dst_equivalent`] and
    /// [`TrackCursor::dst_equivalent`] pass it for you.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidArgument`] if `channels` is not 1 to 6.
    pub fn dst_equivalent(&self, channels: u8) -> Result<std::borrow::Cow<'_, [u8]>, Error> {
        if !(1..=MAX_CHANNELS).contains(&channels) {
            return Err(Error::InvalidArgument("channel count must be 1 to 6"));
        }
        Ok(self.equivalent_checked(channels))
    }

    /// [`FrameContent::dst_equivalent`] for a channel count already checked (1 to 6).
    fn equivalent_checked(&self, channels: u8) -> std::borrow::Cow<'_, [u8]> {
        let plain = |bytes: &[u8]| {
            let mut v = Vec::with_capacity(1 + bytes.len());
            v.push(0x00);
            v.extend_from_slice(bytes);
            v
        };
        match self {
            FrameContent::Dst(bytes) => std::borrow::Cow::Borrowed(bytes),
            FrameContent::Dsd(bytes) => std::borrow::Cow::Owned(plain(bytes)),
            FrameContent::Missing => {
                let fill = fill_frame(channels, MISSING_FILL);
                std::borrow::Cow::Owned(plain(&fill))
            }
        }
    }
}

/// One timeline position of a track or frame range.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct TrackFrame {
    /// The frame number.
    pub number: u32,
    /// Its content.
    pub content: FrameContent,
}

impl TrackFrame {
    /// A timeline position holding `content`, for a caller that decodes frames it saved
    /// ([`decode_frame`]).
    ///
    /// ```
    /// use scarletbook::{DstDecoder, FrameContent, FrameStatus, TrackFrame, audio::decode_frame};
    ///
    /// let frame = TrackFrame::new(7, FrameContent::Missing);
    /// let audio = decode_frame(&mut DstDecoder::new(), frame, 2).unwrap();
    /// assert_eq!((audio.number, audio.status), (7, FrameStatus::Missing));
    /// assert_eq!(audio.data, vec![0x69; 2 * 4704]);
    /// ```
    pub fn new(number: u32, content: FrameContent) -> Self {
        TrackFrame { number, content }
    }
}

/// The reading state of one track's timeline positions (specification 4, 4.7),
/// independent of the image it reads from. [`TrackFrames`] is the borrowing iterator.
///
/// A track is one frame range of its area; [`TrackCursor::open_range`] reads any other
/// (the whole area, or tracks with the pauses between them) with the same frame
/// numbering, timeline and contents.
#[derive(Debug)]
pub struct TrackCursor {
    area: AreaCursor,
    /// Which area, and in which image, the area cursor reads: continuing into a track of
    /// another area (or the same area of another image) needs a fresh scan.
    area_key: AreaKey,
    next: u32,
    end: u32,
    channels: u8,
    peeked: Option<AreaFrame>,
    exhausted: bool,
    failed: bool,
    /// Missing positions returned since the cursor was made or continued.
    missing: u64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct AreaKey {
    pub(crate) slot: Slot,
    pub(crate) start: u32,
    pub(crate) end: u32,
    pub(crate) channels: u8,
    pub(crate) image_sectors: u64,
}

impl AreaKey {
    /// The existing audio sectors, as [`audio_sector_range`].
    pub(crate) fn audio_sector_range(&self) -> (u64, u64) {
        let start = u64::from(self.start);
        let end = (u64::from(self.end) + 1).min(self.image_sectors);
        (start, end.max(start))
    }

    pub(crate) fn new(area: &Area, image_sectors: u64) -> Self {
        AreaKey {
            slot: area.slot,
            start: area.audio_start_lsn,
            end: area.audio_end_lsn,
            channels: area.channel_count,
            image_sectors,
        }
    }
}

impl TrackCursor {
    /// A cursor at the start of `track` of `area`, after the checks of 4.8.
    ///
    /// # Errors
    ///
    /// As [`check_track`].
    pub fn new(area: &Area, track: &Track, image_sectors: u64) -> Result<Self, Error> {
        check_track(area, track, image_sectors)?;
        Ok(Self::start(area, track.start_frame, track.end_frame(), image_sectors))
    }

    /// A cursor at frame `first` of `area`, ending before frame `end`, after
    /// [`check_range`]: the positions `first` to `end - 1` in order, exactly as a track
    /// covering them would give. See [`CursorOptions`] for the seek index and policy.
    ///
    /// # Errors
    ///
    /// As [`check_range`], then [`Error::InvalidArgument`] if the options' index is of
    /// another area or image size.
    pub fn open_range(
        area: &Area,
        first: u32,
        end: u32,
        image_sectors: u64,
        options: CursorOptions<'_>,
    ) -> Result<Self, Error> {
        check_range(area, first, end, image_sectors)?;
        let index = options.index();
        if let Some(index) = index {
            index.check_key(area, image_sectors)?;
        }
        Ok(match (index, options.policy().unwrap_or_default()) {
            (None, SeekPolicy::Exact) => Self::start(area, first, end, image_sectors),
            (Some(index), SeekPolicy::Exact) => Self::start_indexed(area, first, end, image_sectors, index),
            (index, policy) => Self::start_with(area, (first, end), image_sectors, index, policy),
        })
    }

    /// A scan of `area` for the range `[first, end)`, already checked, from `index` (of
    /// that area, checked).
    pub(crate) fn start_indexed(
        area: &Area,
        first: u32,
        end: u32,
        image_sectors: u64,
        index: &AreaIndex,
    ) -> Self {
        let mut cursor = TrackCursor {
            area: AreaCursor::resume(index, first),
            ..Self::start(area, first, end, image_sectors)
        }
        .estimated(area);
        if let ResumedFrom::Checkpoint { lsn, replay_from } = cursor.area.resumed {
            // One read from the replay to the range's end: through the seek hint after it,
            // or the range's frames at the area's average density from the checkpoint (whose
            // successor is past `first`, so frame `first` starts within an interval of it),
            // plus a quarter and a few sectors.
            let (s0, s1) = audio_sector_range(area, image_sectors);
            let hinted = index.hint(first, end, area.playtime_frames()).filter(|h| h.3).map(|h| h.2);
            let to = hinted.filter(|&to| to > lsn).unwrap_or_else(|| {
                let frames = u128::from(end - first);
                let span = frames * u128::from(s1 - s0) / u128::from(area.playtime_frames().max(1));
                let span = u64::try_from(span + span / 4 + 4).unwrap_or(u64::MAX);
                lsn.saturating_add(u64::from(index.interval())).saturating_add(span)
            });
            // At most the replay, an interval and 64 sectors of the range (128 KiB): a range
            // to the area's end is not read ahead further than that.
            let most = lsn + u64::from(index.interval()) + 64;
            cursor.area.size_first_read(to.min(most).min(replay_from + crate::seek::MAX_READ_SECTORS));
        }
        cursor.area.record_hints(index.hint_recorder());
        cursor
    }

    /// This cursor, expecting its reading to end where the range's end lies in proportion
    /// to the area's play time (see [`Progress`]).
    fn estimated(mut self, area: &Area) -> Self {
        let (start, stop) = audio_sector_range(area, self.area_key.image_sectors);
        let playtime = area.playtime_frames();
        let lsn = if playtime == 0 || self.end >= playtime {
            stop
        } else {
            start + (u128::from(stop - start) * u128::from(self.end) / u128::from(playtime)) as u64
        };
        self.area.set_progress_end(lsn);
        self
    }

    /// The progress of this cursor's reading, readable from other threads (see
    /// [`Progress`]): the sectors read since it was made or continued.
    pub fn progress(&mut self) -> Progress {
        self.area.progress()
    }

    /// A cursor of the range, already checked, from `index` (of the area, checked) or the
    /// first sector, provisional where `policy` allows it.
    pub(crate) fn start_with(
        area: &Area,
        (first, end): (u32, u32),
        image_sectors: u64,
        index: Option<&AreaIndex>,
        policy: SeekPolicy,
    ) -> Self {
        let exact = match index {
            Some(index) => Self::start_indexed(area, first, end, image_sectors, index),
            None => Self::start(area, first, end, image_sectors),
        };
        let interval = index.map_or(crate::seek::DEFAULT_INTERVAL, AreaIndex::interval);
        let mut cursor = exact.speculate(area, (first, end), (interval, index), policy).estimated(area);
        cursor.area.record_hints(index.and_then(AreaIndex::hint_recorder));
        cursor
    }

    /// This cursor, or a provisional one in its place when `policy` allows it and the
    /// exact start lies more than the options' gap before the range's estimated position.
    fn speculate(
        self,
        area: &Area,
        (first, end): (u32, u32),
        (interval, provisional): (u32, Option<&AreaIndex>),
        policy: SeekPolicy,
    ) -> Self {
        let SeekPolicy::Speculative(mut options) = policy else { return self };
        // Audio sectors past the image's end make the area's layout suspect (4.2 item 8); a
        // disc also checks them against the other area's (`SpeculativeOptions::layout_suspect`).
        options.layout_suspect |= u64::from(area.audio_end_lsn) >= self.area_key.image_sectors;
        if options.layout_suspect && options.exact_when_suspect {
            return self;
        }
        let from = match self.area.resumed {
            ResumedFrom::Checkpoint { lsn, .. } => lsn,
            ResumedFrom::Start => self.area.next_lsn,
            // Reads nothing, or a cursor already chosen: keep it.
            _ => return self,
        };
        let (start, stop) = audio_sector_range(area, self.area_key.image_sectors);
        let playtime = area.playtime_frames();
        if playtime == 0 {
            return self;
        }
        // The range's position in proportion to the play time.
        let estimate = start + (u128::from(stop - start) * u128::from(first) / u128::from(playtime)) as u64;
        if estimate <= from.saturating_add(options.min_gap_sectors) {
            return self;
        }
        // A seek hint near `first` (seek hints, 4.2 item 8 locator samples): one read from it,
        // no search; the read ends through the next hint past the range, or is estimated.
        let hint = provisional
            .and_then(|i| i.hint(first, end, playtime))
            .filter(|h| h.0 > from)
            .map(|(lsn, t, to, _)| (lsn, t, to, provisional.and_then(|i| i.confirmation(lsn, first))));
        // An earlier provisional reading's checkpoint around `first`: no search needed.
        if let Some(p) = provisional
            .and_then(|i| i.plan_provisional(first))
            .filter(|&(lsn, _)| lsn > from && hint.is_none())
        {
            let mut area_cursor = AreaCursor::provisional_at(&self.area, p, first, interval);
            if options.layout_suspect {
                area_cursor.suspect = Some(crate::seek::Suspect::AreaLayout);
            }
            return TrackCursor { area: area_cursor, ..self };
        }
        // Track starts inside the audio sectors, as points to interpolate between (4.2 item
        // 8 lets them choose `L`; they never change what is read from it).
        let knots = area
            .tracks
            .iter()
            .map(|t| (u64::from(t.start_lsn), t.start_frame))
            .filter(|&(l, _)| (start..stop).contains(&l))
            .collect();
        let area_cursor = AreaCursor::speculative(
            self.area,
            (first, self.end),
            (playtime, knots),
            (interval, hint),
            options,
        );
        TrackCursor { area: area_cursor, ..self }
    }

    /// The slot of this cursor's area.
    pub fn slot(&self) -> Slot {
        self.area_key.slot
    }

    /// Whether this cursor's positions are provisional (see [`SeekPolicy`]).
    pub fn speculation(&self) -> Speculation {
        self.area.speculation()
    }

    /// Why the provisional reading is suspect, if it is (see [`crate::Suspect`]).
    pub fn suspect(&self) -> Option<crate::Suspect> {
        self.area.suspect()
    }

    /// Where its malformed count and warnings begin (see [`AreaCursor::claim_lsn`]).
    pub fn claim_lsn(&self) -> Option<u64> {
        self.area.claim_lsn()
    }

    /// The number of the provisional reading, as events name it ([`crate::SeekEvent`]);
    /// `None` for exact positions.
    pub fn claim(&self) -> Option<u64> {
        self.area.claim()
    }

    /// Where this cursor's scan started (see [`ResumedFrom`]); continued cursors keep it.
    pub fn resumed_from(&self) -> ResumedFrom {
        self.area.resumed_from()
    }

    pub(crate) fn area_mut(&mut self) -> &mut AreaCursor {
        &mut self.area
    }

    /// A fresh scan of `area` for the range `[first, end)`, already checked.
    pub(crate) fn start(area: &Area, first: u32, end: u32, image_sectors: u64) -> Self {
        let cursor = TrackCursor {
            area: AreaCursor::new(area, image_sectors),
            area_key: AreaKey::new(area, image_sectors),
            next: first,
            end,
            channels: area.channel_count,
            peeked: None,
            exhausted: false,
            failed: false,
            missing: 0,
        };
        cursor.estimated(area)
    }

    /// A cursor at the start of `track`, reusing this cursor's reading state when that
    /// gives the same result as a fresh scan, so that reading an area's tracks in order
    /// reads each audio sector once.
    ///
    /// A cursor only ever discards accepted frames numbered below its current position.
    /// The state is therefore reused when `track` is in the same area (same slot, audio
    /// range, channel count and image size) and starts at or after that position, and no
    /// read has failed. Otherwise this is [`TrackCursor::new`]. Either way the frames are
    /// exactly those of a fresh scan (specification 4, 4.2 item 5).
    ///
    /// This method cannot tell two images of the same size apart; a cursor continued
    /// onto another image refuses to read it (see [`AreaCursor::next_frame`]). Use
    /// [`crate::Disc::continue_track_audio`], which compares the images and scans afresh.
    ///
    /// A cursor made from a seek index ([`CursorOptions::with_index`]) does not keep
    /// the index: continued backwards with this method, it scans from the area's first
    /// sector. To start from the index instead, open a new cursor from it.
    ///
    /// # Errors
    ///
    /// As [`check_track`].
    pub fn continue_to(self, area: &Area, track: &Track, image_sectors: u64) -> Result<Self, Error> {
        check_track(area, track, image_sectors)?;
        Ok(self.continue_in(area, track.start_frame, track.end_frame(), (image_sectors, None), None))
    }

    /// A cursor for the frame range `[first, end)` of `area`, continuing this one's
    /// reading state where that gives the same result, as [`TrackCursor::continue_to`]
    /// does for a track: the state is reused when `first` is at or after this cursor's
    /// position in the same area.
    ///
    /// # Errors
    ///
    /// As [`check_range`].
    pub fn continue_to_range(
        self,
        area: &Area,
        first: u32,
        end: u32,
        image_sectors: u64,
    ) -> Result<Self, Error> {
        check_range(area, first, end, image_sectors)?;
        Ok(self.continue_in(area, first, end, (image_sectors, None), None))
    }

    /// As [`TrackCursor::continue_to_range`] for a range already checked, also starting
    /// afresh when this cursor has read an image other than `image_id`, and from `index`
    /// (of `area`) when that is given and the state is not reused.
    pub(crate) fn continue_in(
        self,
        area: &Area,
        first: u32,
        end: u32,
        (image_sectors, image_id): (u64, Option<u64>),
        index: Option<&AreaIndex>,
    ) -> Self {
        let opening = self.opening(area, first, image_sectors, image_id, index);
        self.open_as(area, (first, end), (image_sectors, image_id), index, (opening, SeekPolicy::Exact))
    }

    /// How [`TrackCursor::continue_in`] opens the range starting at `first`.
    pub(crate) fn opening(
        &self,
        area: &Area,
        first: u32,
        image_sectors: u64,
        image_id: Option<u64>,
        index: Option<&AreaIndex>,
    ) -> Opening {
        if self.reuses(area, first, image_sectors, image_id, index) {
            Opening::Continues
        } else if index.is_some() {
            Opening::FromIndex
        } else {
            Opening::Fresh
        }
    }

    /// The range `[first, end)` opened as `opening` says (from [`TrackCursor::opening`]):
    /// this cursor's state reused, a start from `index`, or a new scan.
    pub(crate) fn open_as(
        self,
        area: &Area,
        (first, end): (u32, u32),
        (image_sectors, image_id): (u64, Option<u64>),
        index: Option<&AreaIndex>,
        (opening, policy): (Opening, SeekPolicy),
    ) -> Self {
        let reusable = self.reusable(area, first, image_sectors, image_id);
        match (opening, index) {
            (Opening::Continues, _) if reusable => {
                let mut next = TrackCursor { next: first, end, missing: 0, ..self };
                next.area.restart_progress();
                next.estimated(area)
            }
            // A range (or track) before this cursor's position, or in another area, scans
            // the area again: specification 4, 4.2 item 6 allows a pass per track or range,
            // and item 7 a start from the seek index (item 8 a provisional one, if allowed).
            (Opening::Continues | Opening::FromIndex, Some(index)) => {
                let mut next = Self::start_with(area, (first, end), image_sectors, Some(index), policy);
                if reusable
                    && next.area.speculation() == Speculation::Exact
                    && self.area.speculation() == Speculation::Exact
                {
                    // Moved ahead of a scan that could have gone on: until it reads, it
                    // reports what that scan reports (a pass from the first sector). Not
                    // from a provisional scan, whose counts begin at its `L` (4.4.5 items 4
                    // and 5).
                    next.area.carry_counts(&self.area);
                }
                next
            }
            _ => Self::start_with(area, (first, end), image_sectors, None, policy),
        }
    }

    /// Whether [`TrackCursor::continue_in`] keeps this cursor's reading state: when it
    /// can ([`TrackCursor::reusable`]), unless `index` starts the range more than two
    /// checkpoints past the sector this cursor reads next.
    fn reuses(
        &self,
        area: &Area,
        first: u32,
        image_sectors: u64,
        image_id: Option<u64>,
        index: Option<&AreaIndex>,
    ) -> bool {
        self.reusable(area, first, image_sectors, image_id)
            && index.is_none_or(|index| {
                let ahead = 2 * u64::from(index.interval());
                index.plan_lsn(first).is_some_and(|lsn| lsn <= self.area.scan_lsn().saturating_add(ahead))
            })
    }

    /// Whether [`TrackCursor::continue_in`] keeps this cursor's reading state.
    fn reusable(&self, area: &Area, first: u32, image_sectors: u64, image_id: Option<u64>) -> bool {
        let other_image = matches!((self.area.image_id, image_id), (Some(a), Some(b)) if a != b);
        !(self.failed
            || other_image
            || self.area_key != AreaKey::new(area, image_sectors)
            || first < self.next)
    }

    /// The area's channel count `C` (1 to 6).
    pub fn channels(&self) -> u8 {
        self.channels
    }

    /// The DST equivalent of a position of this cursor's area (specification 4, 4.6.1 item
    /// 3; see [`FrameContent::dst_equivalent`]), with the area's channel count.
    pub fn dst_equivalent<'c>(&self, content: &'c FrameContent) -> std::borrow::Cow<'c, [u8]> {
        // The channel count passed the checks of 4.8 item 1 when the cursor was made.
        content.equivalent_checked(self.channels)
    }

    /// Positions returned so far that no accepted frame fills ([`FrameContent::Missing`]);
    /// 0 again after [`crate::Disc::continue_track_frames`] or [`crate::Disc::continue_range_frames`].
    pub fn missing_frames(&self) -> u64 {
        self.missing
    }

    /// The frame range still to come, `[next, end)`.
    pub fn range(&self) -> (u32, u32) {
        (self.next, self.end)
    }

    /// Number of malformed sectors processed so far by this cursor's scan of its area. The
    /// scan starts at the area's first audio sector, not at the track, and a continued
    /// cursor keeps counting from where the earlier tracks left off.
    /// Track cursors read ahead of the frames they return (a group of a few frames,
    /// or with `parallel` a window of bounded size), so this may count sectors of frames
    /// not yet returned.
    pub fn malformed_sectors(&self) -> u64 {
        self.area.malformed_sectors()
    }

    /// The `audio-sector-malformed` warnings of this cursor's scan of its area so far
    /// (see [`AreaCursor::warnings`]): per area, not per track, and each sector once.
    pub fn warnings(&self) -> &[Warning] {
        self.area.warnings()
    }

    /// The next timeline position, `None` after the track's (or range's) last frame.
    pub fn next_frame<R: Read + Seek>(&mut self, image: &mut Image<R>) -> Option<Result<TrackFrame, Error>> {
        if self.next >= self.end {
            return None;
        }
        if let Err(e) = image.check_cancel() {
            return Some(Err(e));
        }
        let t = self.next;
        // Accepted frames arrive in increasing order: skip those before t. Stops reading
        // as soon as a frame at or after t is seen (specification 4, 4.5 item 4).
        while !self.exhausted && self.peeked.as_ref().is_none_or(|f| f.number < t) {
            match self.area.next_frame(image) {
                Some(Ok(f)) => self.peeked = Some(f),
                // Nothing consumed: position t again next time.
                Some(Err(Error::Cancelled)) => return Some(Err(Error::Cancelled)),
                Some(Err(e)) => {
                    self.next = self.end;
                    self.failed = true;
                    return Some(Err(e));
                }
                None => {
                    self.peeked = None;
                    self.exhausted = true;
                }
            }
        }
        self.next += 1;
        if self.next >= self.end {
            self.area.progress_done();
            self.area.flush_hints();
        }
        if let Some(claim) = &self.area.claim {
            claim.returned(t);
        }
        let content = match self.peeked.take_if(|f| f.number == t) {
            Some(f) => match f.kind {
                FrameKind::Dsd => FrameContent::Dsd(f.data),
                FrameKind::Dst => FrameContent::Dst(f.data),
            },
            None => {
                self.missing += 1;
                FrameContent::Missing
            }
        };
        Some(Ok(TrackFrame { number: t, content }))
    }
}

/// The timeline positions of one track or frame range, in order (specification 4, 4.7),
/// without decoding: each position's frame as stored, a DST frame's bytes (its length is
/// the frame length `FB` of specification 5) or a plain frame's `C x 4704` bytes, or
/// [`FrameContent::Missing`]. Decoding a DST frame's bytes with [`DstDecoder`] gives the
/// position's decoded audio; frame numbers, the timeline, missing positions and malformed
/// sectors are exactly those of the decoded reads ([`TrackAudio`]).
///
/// A frame is at most [`MAX_FRAME_BYTES`] bytes: nothing larger is ever assembled.
// Specification 4, 4.6.1 items 1 and 2 (the stored content of a track or frame range):
// positions are DST, plain or missing as stored, missing positions are counted and
// invalid DST frames are not reported, since validity is known only by decoding.
#[derive(Debug)]
pub struct TrackFrames<'a, R> {
    image: &'a mut Image<R>,
    cursor: TrackCursor,
    /// The disc's seek indexes, which take the checkpoints the cursor records.
    seek: Option<&'a SeekIndexes>,
}

impl<'a, R: Read + Seek> TrackFrames<'a, R> {
    pub(crate) fn with_cursor(
        image: &'a mut Image<R>,
        cursor: TrackCursor,
        seek: Option<&'a SeekIndexes>,
    ) -> Self {
        TrackFrames { image, cursor, seek }
    }

    /// The reading state, to continue into a later track or range with
    /// [`crate::Disc::continue_track_frames`] or [`crate::Disc::continue_range_frames`].
    pub fn into_cursor(self) -> TrackCursor {
        self.cursor
    }

    /// The area's channel count `C` (1 to 6).
    pub fn channels(&self) -> u8 {
        self.cursor.channels()
    }

    /// Positions returned so far that no accepted frame fills (see
    /// [`TrackCursor::missing_frames`]).
    pub fn missing_frames(&self) -> u64 {
        self.cursor.missing_frames()
    }

    /// The DST equivalent of a position of this track or range (specification 4, 4.6.1
    /// item 3; see [`FrameContent::dst_equivalent`]), with the area's channel count.
    pub fn dst_equivalent<'c>(&self, content: &'c FrameContent) -> std::borrow::Cow<'c, [u8]> {
        self.cursor.dst_equivalent(content)
    }

    /// The frame range still to come, `[next, end)`.
    pub fn range(&self) -> (u32, u32) {
        self.cursor.range()
    }

    /// Number of malformed sectors processed so far by this cursor's scan of its area. The
    /// scan starts at the area's first audio sector, not at the track, and a continued
    /// cursor keeps counting from where the earlier tracks left off.
    /// Track cursors read ahead of the frames they return (a group of a few frames,
    /// or with `parallel` a window of bounded size), so this may count sectors of frames
    /// not yet returned.
    pub fn malformed_sectors(&self) -> u64 {
        self.cursor.malformed_sectors()
    }

    /// The `audio-sector-malformed` warnings of this cursor's scan of its area so far
    /// (see [`AreaCursor::warnings`]): per area, not per track, and each sector once.
    pub fn warnings(&self) -> &[Warning] {
        self.cursor.warnings()
    }

    /// Whether the positions are provisional (see [`SeekPolicy`]).
    pub fn speculation(&self) -> Speculation {
        self.cursor.speculation()
    }

    /// Why the provisional reading is suspect, if it is (see [`crate::Suspect`]).
    pub fn suspect(&self) -> Option<crate::Suspect> {
        self.cursor.suspect()
    }

    /// Where the malformed count and warnings begin (see [`AreaCursor::claim_lsn`]).
    pub fn claim_lsn(&self) -> Option<u64> {
        self.cursor.claim_lsn()
    }

    /// The number of the provisional reading, as events name it ([`crate::SeekEvent`]);
    /// `None` for exact positions.
    pub fn claim(&self) -> Option<u64> {
        self.cursor.claim()
    }

    /// The progress of the reading, readable from other threads (see [`Progress`]).
    pub fn progress(&mut self) -> Progress {
        self.cursor.progress()
    }
}

impl<R: Read + Seek> Iterator for TrackFrames<'_, R> {
    type Item = Result<TrackFrame, Error>;

    fn next(&mut self) -> Option<Self::Item> {
        let frame = self.cursor.next_frame(self.image);
        if let Some(seek) = self.seek {
            seek.absorb(&mut self.cursor.area, self.image.id());
        }
        frame
    }
}

/// How a decoded timeline position was produced (specification 4, 4.6).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FrameStatus {
    /// A plain DSD frame, passed through unchanged.
    Dsd,
    /// A DST frame, decoded.
    Decoded,
    /// No frame: filled with 0x69.
    Missing,
    /// An invalid DST frame: filled with 0x55.
    Invalid(DstError),
}

/// One decoded timeline position: `C x 4704` bytes in interleaved layout.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct AudioFrame {
    /// The frame number.
    pub number: u32,
    /// How it was produced.
    pub status: FrameStatus,
    /// The DSD bytes, interleaved (specification 0, 0.6).
    pub data: Vec<u8>,
}

/// Decodes one timeline position of an area of `channels` channels (specification 4,
/// 4.6).
///
/// # Errors
///
/// [`Error::InvalidArgument`] if `channels` is not 1 to 6, or a plain DSD frame is not
/// `channels x 4704` bytes.
pub fn decode_frame(decoder: &mut DstDecoder, frame: TrackFrame, channels: u8) -> Result<AudioFrame, Error> {
    if !(1..=MAX_CHANNELS).contains(&channels) {
        return Err(Error::InvalidArgument("channel count must be 1 to 6"));
    }
    if let FrameContent::Dsd(data) = &frame.content {
        if data.len() != usize::from(channels) * FRAME_BYTES_PER_CHANNEL {
            return Err(Error::InvalidArgument("a plain DSD frame must be channels x 4704 bytes"));
        }
    }
    Ok(decode_checked(decoder, frame, channels))
}

/// [`decode_frame`] for arguments already validated: `channels` is 1 to 6 (checked by
/// [`check_track`]) and plain frames are complete (4.4.2).
fn decode_checked(decoder: &mut DstDecoder, frame: TrackFrame, channels: u8) -> AudioFrame {
    let (status, data) = match frame.content {
        FrameContent::Dsd(data) => (FrameStatus::Dsd, data),
        FrameContent::Missing => (FrameStatus::Missing, fill_frame(channels, MISSING_FILL)),
        FrameContent::Dst(bytes) => {
            let mut out = vec![0u8; usize::from(channels) * FRAME_BYTES_PER_CHANNEL];
            match decoder.decode(&bytes, channels, &mut out) {
                Ok(()) => (FrameStatus::Decoded, out),
                Err(e) => {
                    // The channel count was checked (4.8) and the buffer sized from it, so
                    // only frame rules can fail here.
                    debug_assert_ne!(
                        e,
                        DstError::InvalidArguments,
                        "decoder arguments checked by check_track"
                    );
                    out.fill(INVALID_FILL);
                    (FrameStatus::Invalid(e), out)
                }
            }
        }
    };
    AudioFrame { number: frame.number, status, data }
}

/// [`decode_checked`] for DST frames (`frames` all have `FrameContent::Dst`), together
/// with [`DstDecoder::decode_many`]: the same frames as decoding them one by one.
fn decode_dst_run(
    decoder: &mut DstDecoder,
    frames: Vec<TrackFrame>,
    channels: u8,
    log: &Log,
) -> Vec<AudioFrame> {
    if let (Some(first), Some(last)) = (frames.first(), frames.last()) {
        sb_log!(
            log,
            Trace,
            "decoding DST frames {}..={} on thread {:?}",
            first.number,
            last.number,
            std::thread::current().id()
        );
    }
    let size = usize::from(channels) * FRAME_BYTES_PER_CHANNEL;
    let mut outs = vec![vec![0u8; size]; frames.len()];
    let results = {
        let bytes: Vec<&[u8]> = frames
            .iter()
            .map(|f| match &f.content {
                FrameContent::Dst(b) => b.as_slice(),
                _ => &[],
            })
            .collect();
        let mut slices: Vec<&mut [u8]> = outs.iter_mut().map(Vec::as_mut_slice).collect();
        decoder.decode_many(&bytes, channels, &mut slices)
    };
    frames
        .into_iter()
        .zip(outs)
        .zip(results)
        .map(|((frame, mut out), result)| {
            let status = match result {
                Ok(()) => FrameStatus::Decoded,
                Err(e) => {
                    // The channel count was checked (4.8) and the buffers sized from it, so
                    // only frame rules can fail here.
                    debug_assert_ne!(
                        e,
                        DstError::InvalidArguments,
                        "decoder arguments checked by check_track"
                    );
                    out.fill(INVALID_FILL);
                    FrameStatus::Invalid(e)
                }
            };
            AudioFrame { number: frame.number, status, data: out }
        })
        .collect()
}

/// A position's stored content (specification 4, 4.6.1 item 2) next to its decoded audio
/// ([`TrackAudioCursor::next_frame_with_stored`]): what [`TrackCursor::next_frame`] gives
/// for it, without a second copy of a plain frame.
///
/// Frozen: exhaustive on purpose, so a `match` needs no wildcard arm, for the reason given at
/// [`FrameContent`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Stored {
    /// A DST frame's bytes as stored (its decoding is the [`AudioFrame`]'s data).
    Dst(Vec<u8>),
    /// A plain DSD frame: its stored bytes are the [`AudioFrame`]'s data, unchanged
    /// (status [`FrameStatus::Dsd`]).
    Dsd,
    /// No accepted frame fills the position.
    Missing,
}

impl Stored {
    /// The position's [`FrameContent`], given its decoded `frame` (which a plain one's
    /// bytes are copied from).
    pub fn content(&self, frame: &AudioFrame) -> FrameContent {
        match self {
            Stored::Dst(bytes) => FrameContent::Dst(bytes.clone()),
            Stored::Dsd => FrameContent::Dsd(frame.data.clone()),
            Stored::Missing => FrameContent::Missing,
        }
    }

    /// The stored bytes, given the decoded `frame`: a DST frame's, a plain frame's (the
    /// frame's data), none for a missing position.
    pub fn bytes<'a>(&'a self, frame: &'a AudioFrame) -> &'a [u8] {
        match self {
            Stored::Dst(bytes) => bytes,
            Stored::Dsd => &frame.data,
            Stored::Missing => &[],
        }
    }
}

/// The decoding state of one track's audio (specification 4, 4.6 and 4.7), or of any
/// frame range of an area ([`TrackAudioCursor::open_range`]), independent of the image it
/// reads from. [`TrackAudio`] is the borrowing iterator.
///
/// With the `parallel` feature, DST frames are decoded on a rayon thread pool ahead of
/// the caller, while the calling thread demultiplexes and consumes; memory stays bounded
/// (a cursor holds at most about 48 MB of frames ahead, whatever the host, plus its decoder
/// tables and read buffer). The pool is the current one unless
/// `TrackAudioCursor::set_decode_on` (also from the `parallel` feature) says otherwise.
#[derive(Debug)]
pub struct TrackAudioCursor {
    frames: TrackCursor,
    /// Where DST frames are decoded; kept by continuations.
    #[cfg(feature = "parallel")]
    decode_on: DecodeOn,
    /// How many DST frames to decode together, if chosen
    /// ([`TrackAudioCursor::with_dst_lanes`]); kept by continuations.
    dst_lanes: Option<usize>,
    /// Decodes on the calling thread: always without `parallel`; with it, the positions
    /// that are not DST frames, and everything on a pool of one thread.
    decoder: DstDecoder,
    /// Positions demultiplexed but not yet returned, in timeline order: they come before
    /// `pending_error`.
    ahead: VecDeque<Pending>,
    /// Frames decoded on the calling thread together with the one returned before them,
    /// not yet returned: they come before `ahead`.
    ready: VecDeque<AudioFrame>,
    /// An error met while demultiplexing, reported after every frame before it.
    pending_error: Option<Error>,
    /// With [`TrackAudioCursor::keep_stored`], the stored content of each position
    /// demultiplexed and not yet returned, in timeline order: one per position of
    /// `ready` and `ahead`, in step with them.
    stored: Option<VecDeque<Stored>>,
    missing: u64,
    invalid: u64,
    /// Lines written about missing frames.
    missing_lines: LineCap,
    /// Lines written about invalid DST frames.
    invalid_lines: LineCap,
}

/// A position demultiplexed ahead of the caller.
#[derive(Debug)]
enum Pending {
    /// Decoded on the calling thread when it is returned.
    Here(TrackFrame),
    /// The `usize`th frame of a group of DST frames being decoded on the pool.
    #[cfg(feature = "parallel")]
    Pool(std::sync::Arc<pool::Job>, usize),
}

impl TrackAudioCursor {
    /// A cursor at the start of `track` of `area`, after the checks of 4.8.
    ///
    /// # Errors
    ///
    /// As [`check_track`].
    pub fn new(area: &Area, track: &Track, image_sectors: u64) -> Result<Self, Error> {
        Ok(Self::from_frames(TrackCursor::new(area, track, image_sectors)?))
    }

    /// A cursor at frame `first` of `area`, ending before frame `end` (see
    /// [`TrackCursor::open_range`]): the whole area is `[0, P)`, with `P` the play time.
    /// Frame numbering, fills, statuses and counts are exactly as for a track, and with any
    /// seek index or policy of `options` as without one.
    ///
    /// # Errors
    ///
    /// As [`TrackCursor::open_range`].
    pub fn open_range(
        area: &Area,
        first: u32,
        end: u32,
        image_sectors: u64,
        options: CursorOptions<'_>,
    ) -> Result<Self, Error> {
        // Missing and invalid frames are counted per range (4.7.1 item 6).
        Ok(Self::from_frames(TrackCursor::open_range(area, first, end, image_sectors, options)?))
    }

    /// Where this cursor's scan started (see [`ResumedFrom`]).
    pub fn resumed_from(&self) -> ResumedFrom {
        self.frames.resumed_from()
    }

    /// The slot of this cursor's area.
    pub fn slot(&self) -> Slot {
        self.frames.slot()
    }

    /// Whether this cursor's positions are provisional (see [`SeekPolicy`]). Its missing
    /// and invalid counts are provisional as well (specification 4, 4.7.1 item 6).
    pub fn speculation(&self) -> Speculation {
        self.frames.speculation()
    }

    /// Why the provisional reading is suspect, if it is (see [`crate::Suspect`]).
    pub fn suspect(&self) -> Option<crate::Suspect> {
        self.frames.suspect()
    }

    /// Where its malformed count and warnings begin (see [`AreaCursor::claim_lsn`]).
    pub fn claim_lsn(&self) -> Option<u64> {
        self.frames.claim_lsn()
    }

    /// The number of the provisional reading, as events name it ([`crate::SeekEvent`]);
    /// `None` for exact positions.
    pub fn claim(&self) -> Option<u64> {
        self.frames.claim()
    }

    /// A cursor at the start of `track`, continuing this one's reading state where that
    /// gives the same result (see [`TrackCursor::continue_to`]). Frames of this cursor
    /// not yet returned are dropped; the counts start again at 0. With `parallel`, DST
    /// frames of this cursor still queued on the pool are then not decoded (frames being
    /// decoded at that moment run to their end, and are then freed).
    ///
    /// # Errors
    ///
    /// As [`check_track`].
    pub fn continue_to(self, area: &Area, track: &Track, image_sectors: u64) -> Result<Self, Error> {
        check_track(area, track, image_sectors)?;
        Ok(self.continue_in(area, track.start_frame, track.end_frame(), (image_sectors, None), None))
    }

    /// A cursor for the frame range `[first, end)`, continuing this one's reading state
    /// where that gives the same result (see [`TrackCursor::continue_to_range`]). Tracks
    /// and ranges may follow each other in any mix. Frames of this cursor not yet
    /// returned are dropped; the counts start again at 0.
    ///
    /// # Errors
    ///
    /// As [`check_range`].
    pub fn continue_to_range(
        self,
        area: &Area,
        first: u32,
        end: u32,
        image_sectors: u64,
    ) -> Result<Self, Error> {
        check_range(area, first, end, image_sectors)?;
        Ok(self.continue_in(area, first, end, (image_sectors, None), None))
    }

    /// As [`TrackAudioCursor::continue_to_range`] for a range already checked (see
    /// [`TrackCursor::continue_in`]).
    pub(crate) fn continue_in(
        self,
        area: &Area,
        first: u32,
        end: u32,
        image: (u64, Option<u64>),
        index: Option<&AreaIndex>,
    ) -> Self {
        let opening = self.opening(area, first, image, index);
        self.open_as(area, (first, end), image, index, (opening, SeekPolicy::Exact))
    }

    /// How [`TrackAudioCursor::continue_in`] opens the range starting at `first`.
    pub(crate) fn opening(
        &self,
        area: &Area,
        first: u32,
        (image_sectors, image_id): (u64, Option<u64>),
        index: Option<&AreaIndex>,
    ) -> Opening {
        match self.pending_error {
            Some(_) if index.is_some() => Opening::FromIndex,
            Some(_) => Opening::Fresh,
            None => self.frames.opening(area, first, image_sectors, image_id, index),
        }
    }

    /// The range opened as `opening` says (see [`TrackCursor::open_as`]).
    pub(crate) fn open_as(
        self,
        area: &Area,
        range: (u32, u32),
        image: (u64, Option<u64>),
        index: Option<&AreaIndex>,
        opening: (Opening, SeekPolicy),
    ) -> Self {
        // Frames decoded or demultiplexed ahead of the caller came from the track cursor
        // already, so it stands after them and they lie inside this range: dropping them
        // loses nothing a later range can use (jobs still on the pool finish unread). An
        // error ends the reuse.
        let mut frames = self.frames;
        if self.pending_error.is_some() {
            frames.failed = true;
        }
        let mut next = Self::from_frames(frames.open_as(area, range, image, index, opening));
        #[cfg(feature = "parallel")]
        {
            next.decode_on = self.decode_on;
        }
        next.dst_lanes = self.dst_lanes;
        next.stored = self.stored.map(|_| VecDeque::new());
        next
    }

    pub(crate) fn from_frames(frames: TrackCursor) -> Self {
        TrackAudioCursor {
            frames,
            #[cfg(feature = "parallel")]
            decode_on: DecodeOn::default(),
            dst_lanes: None,
            decoder: DstDecoder::new(),
            ahead: VecDeque::new(),
            ready: VecDeque::new(),
            pending_error: None,
            stored: None,
            missing: 0,
            invalid: 0,
            missing_lines: LineCap::default(),
            invalid_lines: LineCap::default(),
        }
    }

    /// The area's channel count `C` (1 to 6).
    pub fn channels(&self) -> u8 {
        self.frames.channels()
    }

    /// Frames returned so far that were missing (filled with 0x69).
    pub fn missing_frames(&self) -> u64 {
        self.missing
    }

    /// Frames returned so far that were invalid DST frames (filled with 0x55).
    pub fn invalid_dst_frames(&self) -> u64 {
        self.invalid
    }

    /// Number of malformed sectors processed so far by this cursor's scan of its area. The
    /// scan starts at the area's first audio sector, not at the track, and a continued
    /// cursor keeps counting from where the earlier tracks left off.
    /// Track cursors read ahead of the frames they return (a group of a few frames,
    /// or with `parallel` a window of bounded size), so this may count sectors of frames
    /// not yet returned.
    pub fn malformed_sectors(&self) -> u64 {
        self.frames.malformed_sectors()
    }

    /// The `audio-sector-malformed` warnings of this cursor's scan of its area so far
    /// (see [`AreaCursor::warnings`]): per area, not per track, and each sector once.
    pub fn warnings(&self) -> &[Warning] {
        self.frames.warnings()
    }

    /// The progress of this cursor's reading, readable from other threads (see
    /// [`Progress`]): the sectors read since it was made or continued.
    pub fn progress(&mut self) -> Progress {
        self.frames.progress()
    }

    /// Where DST frames are decoded (see [`DecodeOn`]); continuations keep it.
    #[cfg(feature = "parallel")]
    pub fn decode_on(&self) -> &DecodeOn {
        &self.decode_on
    }

    /// Chooses where the DST frames demultiplexed from now on are decoded (see
    /// [`DecodeOn`]); continuations ([`crate::Disc::continue_track_audio`] and the like) keep
    /// the choice. Frames already sent to a pool finish there and are returned in order,
    /// so the frames returned are the same whenever this is called.
    #[cfg(feature = "parallel")]
    pub fn set_decode_on(&mut self, on: DecodeOn) {
        self.decode_on = on;
    }

    /// This cursor, decoding `lanes` DST frames together on each thread
    /// ([`crate::dst::DstDecoder::decode_many`]) instead of the [`crate::dst::lanes`] for
    /// its channel count, on the calling thread and on a pool alike; continuations
    /// ([`TrackAudioCursor::continue_to`] and the like) keep the choice.
    ///
    /// It changes speed and memory only: the frames returned, their order, counts and
    /// `Warn` log lines are the same for every value, whenever this is called. Positions
    /// are read ahead in groups of this size too (see [`MAX_PARALLEL_BATCH`]), and the
    /// `Trace` lines naming each group follow it. This is for measuring: which count is
    /// fastest depends on the processor and the pool. Without this call the cursor uses
    /// [`crate::dst::lanes`], whose values are tuning: the default can change in any release,
    /// per build and per CPU, while a count chosen here stays as chosen.
    ///
    /// # Errors
    ///
    /// [`Error::DstLanesInvalid`] unless `lanes` is from 1 to [`crate::dst::MAX_LANES`]; the
    /// cursor is dropped with the call.
    pub fn with_dst_lanes(mut self, lanes: usize) -> Result<Self, Error> {
        if !(1..=crate::dst::MAX_LANES).contains(&lanes) {
            return Err(Error::DstLanesInvalid { lanes });
        }
        self.dst_lanes = Some(lanes);
        Ok(self)
    }

    /// The count chosen with [`TrackAudioCursor::with_dst_lanes`], if any.
    pub fn dst_lanes(&self) -> Option<usize> {
        self.dst_lanes
    }

    /// How many frames of `channels` channels to decode together.
    fn group(&self, channels: u8) -> usize {
        self.dst_lanes.unwrap_or_else(|| crate::dst::lanes(channels))
    }

    /// Most positions held ahead of the caller, the one being returned included: one group
    /// of frames decoded together on the calling thread (see [`MAX_PARALLEL_BATCH`]) or,
    /// with `parallel` on a pool of more than one thread, many.
    fn window(&self, channels: u8) -> usize {
        let group = self.group(channels);
        #[cfg(feature = "parallel")]
        {
            let threads = match &self.decode_on {
                DecodeOn::CurrentPool => rayon::current_num_threads(),
                DecodeOn::Pool(pool) => pool.current_num_threads(),
                DecodeOn::CallingThread => 1,
            };
            match threads {
                0 | 1 => group,
                n => (PARALLEL_FRAMES_PER_THREAD * n).min(MAX_PARALLEL_BATCH),
            }
        }
        #[cfg(not(feature = "parallel"))]
        {
            group
        }
    }

    /// Demultiplexes positions, a whole number of groups of `lanes` of them, when a group
    /// fits in the window, until the track ends or an error is met (kept for after the
    /// positions before it). With `parallel` on a pool of more than one thread, each group
    /// of consecutive DST frames goes to the pool at once.
    ///
    /// The image reader stays on the calling thread: only decoding jobs, which own their
    /// frames, go to the pool. Returns whether it stopped at a cancellation request, which
    /// leaves the positions demultiplexed so far in the window and no error pending.
    fn fill<R: Read + Seek>(&mut self, image: &mut Image<R>) -> bool {
        let channels = self.channels();
        let window = self.window(channels);
        let group = self.group(channels);
        let held = self.ahead.len() + self.ready.len();
        if self.pending_error.is_some() || (held > 0 && held + group > window) {
            return false;
        }
        let mut room = (window - held) / group * group;
        #[cfg(feature = "parallel")]
        let mut batch: Vec<TrackFrame> = Vec::with_capacity(group);
        let mut cancelled = false;
        while self.pending_error.is_none() && room > 0 {
            let next = self.frames.next_frame(image);
            if let (Some(stored), Some(Ok(f))) = (self.stored.as_mut(), &next) {
                stored.push_back(match &f.content {
                    // A copy: the frame itself goes on to its decoding, wherever that runs.
                    FrameContent::Dst(bytes) => Stored::Dst(bytes.clone()),
                    // Returned unchanged as the decoded data: nothing to copy.
                    FrameContent::Dsd(_) => Stored::Dsd,
                    FrameContent::Missing => Stored::Missing,
                });
            }
            match next {
                #[cfg(feature = "parallel")]
                Some(Ok(f @ TrackFrame { content: FrameContent::Dst(_), .. })) if window > group => {
                    batch.push(f);
                    if batch.len() == group {
                        self.spawn_batch(&mut batch, channels, image.log());
                    }
                }
                Some(Ok(f)) => {
                    #[cfg(feature = "parallel")]
                    self.spawn_batch(&mut batch, channels, image.log());
                    self.ahead.push_back(Pending::Here(f));
                }
                Some(Err(Error::Cancelled)) => {
                    cancelled = true;
                    break;
                }
                Some(Err(e)) => {
                    #[cfg(feature = "parallel")]
                    self.spawn_batch(&mut batch, channels, image.log());
                    self.pending_error = Some(e);
                }
                None => break,
            }
            room -= 1;
        }
        #[cfg(feature = "parallel")]
        self.spawn_batch(&mut batch, channels, image.log());
        debug_assert!(self.stored_in_step(), "stored content out of step after fill");
        cancelled
    }

    /// Sends the DST frames of `batch` (consecutive positions) to the cursor's pool as one
    /// job, which reports to `log`.
    #[cfg(feature = "parallel")]
    fn spawn_batch(&mut self, batch: &mut Vec<TrackFrame>, channels: u8, log: &Log) {
        if batch.is_empty() {
            return;
        }
        let n = batch.len();
        let pool = match &self.decode_on {
            DecodeOn::Pool(pool) => Some(&**pool),
            DecodeOn::CurrentPool | DecodeOn::CallingThread => None,
        };
        let job = pool::Job::spawn(std::mem::take(batch), channels, log.clone(), pool);
        self.ahead.extend((0..n).map(|i| Pending::Pool(std::sync::Arc::clone(&job), i)));
    }

    /// The next decoded frame, `None` after the track's (or range's) last frame.
    ///
    /// With `parallel`, while the next frame is still being decoded on a pool, a calling
    /// thread that belongs to a pool runs that pool's pending jobs meanwhile; otherwise,
    /// or when there are none, it blocks until the frame is decoded. A panic while decoding
    /// on the pool is resumed on the calling thread.
    ///
    /// While cancellation is requested ([`crate::CancelToken`]) it returns
    /// [`Error::Cancelled`] and keeps every frame for later.
    ///
    /// With [`TrackAudioCursor::keep_stored`], the position's stored content is dropped;
    /// [`TrackAudioCursor::next_frame_with_stored`] returns it too.
    pub fn next_frame<R: Read + Seek>(&mut self, image: &mut Image<R>) -> Option<Result<AudioFrame, Error>> {
        let frame = self.next_decoded(image);
        if let (Some(Ok(_)), Some(stored)) = (&frame, self.stored.as_mut()) {
            let popped = stored.pop_front();
            debug_assert!(popped.is_some() && self.stored_in_step(), "stored content out of step");
        }
        frame
    }

    /// Whether the stored content kept (if any) is one per position held ahead: each
    /// position `fill` takes pushes one, and each position returned pops one.
    fn stored_in_step(&self) -> bool {
        self.stored.as_ref().is_none_or(|s| s.len() == self.ready.len() + self.ahead.len())
    }

    /// Keeps, from now on, each position's stored content next to its decoding, for
    /// [`TrackAudioCursor::next_frame_with_stored`]: from one read of the area's sectors,
    /// both what [`TrackCursor::next_frame`] gives (as stored, DST frames undecoded) and
    /// what [`TrackAudioCursor::next_frame`] gives, decoded where the cursor decodes
    /// (`TrackAudioCursor::set_decode_on`, with the `parallel` feature) with the same positions held ahead. A DST
    /// frame's bytes are copied (at most [`MAX_FRAME_BYTES`]) before it goes to its
    /// decoding. Continuations keep the choice.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidArgument`] once positions are held ahead of the caller (after the
    /// first read, until the cursor is continued): their content was not kept.
    pub fn keep_stored(&mut self) -> Result<(), Error> {
        if self.stored.is_some() {
            return Ok(());
        }
        if !(self.ready.is_empty() && self.ahead.is_empty()) {
            return Err(Error::InvalidArgument("stored content is kept only from before the first read"));
        }
        self.stored = Some(VecDeque::new());
        Ok(())
    }

    /// Whether the cursor keeps stored content ([`TrackAudioCursor::keep_stored`]).
    pub fn keeps_stored(&self) -> bool {
        self.stored.is_some()
    }

    /// The next position, decoded as [`TrackAudioCursor::next_frame`] gives it, with its
    /// stored content as [`TrackCursor::next_frame`] gives it (for the same frame number;
    /// see [`Stored`]: a plain frame's bytes are the decoded data, not copied again).
    /// [`Stored::content`] gives the [`FrameContent`], [`TrackAudioCursor::dst_equivalent`]
    /// its DST equivalent. The two calls may be mixed.
    ///
    /// # Errors
    ///
    /// As [`TrackAudioCursor::next_frame`], and [`Error::InvalidArgument`] if the cursor
    /// does not keep stored content ([`TrackAudioCursor::keep_stored`]).
    pub fn next_frame_with_stored<R: Read + Seek>(
        &mut self,
        image: &mut Image<R>,
    ) -> Option<Result<(AudioFrame, Stored), Error>> {
        if self.stored.is_none() {
            return Some(Err(Error::InvalidArgument("the cursor does not keep stored content")));
        }
        let frame = match self.next_decoded(image)? {
            Ok(f) => f,
            Err(e) => return Some(Err(e)),
        };
        // One content per position returned, in the same order (see `fill`).
        let popped = self.stored.as_mut().and_then(VecDeque::pop_front);
        debug_assert!(popped.is_some() && self.stored_in_step(), "stored content out of step");
        Some(match popped {
            Some(stored) => Ok((frame, stored)),
            // Never reached: a bug, reported rather than filled in.
            None => Err(Error::Io(std::io::Error::other("internal error: stored content out of step"))),
        })
    }

    /// The DST equivalent of a position of this cursor's area (specification 4, 4.6.1
    /// item 3; see [`FrameContent::dst_equivalent`]), with the area's channel count.
    pub fn dst_equivalent<'c>(&self, content: &'c FrameContent) -> std::borrow::Cow<'c, [u8]> {
        self.frames.dst_equivalent(content)
    }

    /// [`TrackAudioCursor::next_frame`], leaving the stored content of the position (if
    /// kept) to the caller.
    fn next_decoded<R: Read + Seek>(&mut self, image: &mut Image<R>) -> Option<Result<AudioFrame, Error>> {
        if let Err(e) = image.check_cancel() {
            return Some(Err(e));
        }
        let mut frame = if let Some(f) = self.ready.pop_front() {
            f
        } else {
            if self.fill(image) {
                return Some(Err(Error::Cancelled));
            }
            match self.ahead.pop_front() {
                Some(Pending::Here(f)) => {
                    let channels = self.channels();
                    if matches!(f.content, FrameContent::Dst(_)) {
                        // This frame and the DST frames waiting behind it, together.
                        let mut run = vec![f];
                        let group = self.group(channels);
                        while run.len() < group {
                            match self.ahead.front() {
                                Some(Pending::Here(TrackFrame { content: FrameContent::Dst(_), .. })) => {
                                    if let Some(Pending::Here(g)) = self.ahead.pop_front() {
                                        run.push(g);
                                    }
                                }
                                _ => break,
                            }
                        }
                        let mut decoded =
                            decode_dst_run(&mut self.decoder, run, channels, image.log()).into_iter();
                        let first = decoded.next()?;
                        self.ready.extend(decoded);
                        first
                    } else {
                        decode_checked(&mut self.decoder, f, channels)
                    }
                }
                #[cfg(feature = "parallel")]
                Some(Pending::Pool(job, i)) => job.wait(i),
                None => return self.pending_error.take().map(Err),
            }
        };
        // Logged and counted as frames are returned, so the counts never run ahead of the
        // caller, whatever the window, and frame problems are logged in timeline order.
        let log = image.log();
        let level = match frame.status {
            FrameStatus::Missing | FrameStatus::Invalid(_) => Level::Warn,
            FrameStatus::Dsd | FrameStatus::Decoded => Level::Trace,
        };
        if log.enabled(level) {
            // The frame stays in the cursor while the sink runs: if the sink panics, the
            // next call returns (and logs) it again, and nothing is counted twice.
            let (number, status, slot) = (frame.number, frame.status, self.frames.area.slot);
            self.ready.push_front(frame);
            match status {
                FrameStatus::Missing => {
                    if self.missing_lines.admit(log, level, slot.name(), "missing-frame") {
                        sb_log!(log, Warn, "area {slot} frame {number}: missing, filled with 0x69 (4.6)");
                    }
                }
                FrameStatus::Invalid(e) => {
                    if self.invalid_lines.admit(log, level, slot.name(), "invalid-DST-frame") {
                        sb_log!(
                            log,
                            Warn,
                            "area {slot} frame {number}: invalid DST frame ({e}, rule {} of 5.6), filled with 0x55 \
                             (4.6)",
                            e.rule()
                        );
                    }
                }
                FrameStatus::Dsd | FrameStatus::Decoded => {
                    sb_log!(log, Trace, "area {slot} frame {number}: {status:?}");
                }
            }
            frame = self.ready.pop_front()?;
        }
        match frame.status {
            FrameStatus::Missing => self.missing += 1,
            FrameStatus::Invalid(_) => self.invalid += 1,
            FrameStatus::Dsd | FrameStatus::Decoded => {}
        }
        Some(Ok(frame))
    }
}

/// A cursor whose recorded checkpoints [`AreaIndex::absorb`] takes: [`AreaCursor`],
/// [`TrackCursor`] or [`TrackAudioCursor`]. Sealed: implemented only by this crate.
pub trait SeekCursor: sealed::Sealed {}

pub(crate) mod sealed {
    /// The area cursor inside a [`super::SeekCursor`].
    pub trait Sealed {
        /// The area cursor, to take its checkpoints.
        fn area_cursor_mut(&mut self) -> &mut super::AreaCursor;
    }
}

impl SeekCursor for AreaCursor {}
impl SeekCursor for TrackCursor {}
impl SeekCursor for TrackAudioCursor {}

impl sealed::Sealed for AreaCursor {
    fn area_cursor_mut(&mut self) -> &mut AreaCursor {
        self
    }
}

impl sealed::Sealed for TrackCursor {
    fn area_cursor_mut(&mut self) -> &mut AreaCursor {
        &mut self.area
    }
}

impl sealed::Sealed for TrackAudioCursor {
    fn area_cursor_mut(&mut self) -> &mut AreaCursor {
        &mut self.frames.area
    }
}

/// Decoding jobs on rayon's pool, for the `parallel` feature.
#[cfg(feature = "parallel")]
mod pool {
    use std::any::Any;
    use std::cell::RefCell;
    use std::panic::AssertUnwindSafe;
    use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};

    use super::{AudioFrame, TrackFrame, decode_dst_run};
    use crate::dst::DstDecoder;
    use crate::log::{Log, sb_log};

    thread_local! {
        /// Each pool thread's decoder, reused from frame to frame.
        static DECODER: RefCell<DstDecoder> = RefCell::new(DstDecoder::new());
    }

    /// A group of consecutive DST frames decoded on the pool; each frame is taken once.
    #[derive(Debug, Default)]
    pub(super) struct Job {
        state: Mutex<State>,
        done: Condvar,
    }

    /// The payload of a panic, until it is resumed.
    type Panic = Option<Box<dyn Any + Send>>;

    #[derive(Debug, Default)]
    struct State {
        /// The decoded frames, or the panic that stopped their decoding (`None` once
        /// resumed on a thread).
        result: Option<Result<Vec<Option<AudioFrame>>, Panic>>,
        /// Whether the owner sleeps on `done`: only then does the job wake it.
        waiting: bool,
    }

    impl Job {
        fn lock(&self) -> MutexGuard<'_, State> {
            // A panic never happens while the lock is held: the state stays consistent.
            self.state.lock().unwrap_or_else(PoisonError::into_inner)
        }

        /// Starts decoding `frames` (DST frames) on `pool`, or the current pool if `None`,
        /// reporting to `log` from the pool's thread.
        pub(super) fn spawn(
            frames: Vec<TrackFrame>,
            channels: u8,
            log: Log,
            pool: Option<&rayon::ThreadPool>,
        ) -> Arc<Job> {
            let job = Arc::new(Job::default());
            let out = Arc::clone(&job);
            let work = move || {
                // Besides `out` here, the only handles are the owner's, one per frame of the
                // group in its window. A count of 1 means it dropped them all (a cursor
                // continued or dropped with frames in flight): nobody will take these
                // frames, so skip decoding them. The count cannot rise again; any new
                // handle to a job breaks this test. Jobs already decoding finish; see
                // MAX_PARALLEL_BATCH.
                if Arc::strong_count(&out) == 1 {
                    return;
                }
                let range = (frames.first().map(|f| f.number), frames.last().map(|f| f.number));
                let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
                    DECODER.with(|d| match d.try_borrow_mut() {
                        Ok(mut d) => decode_dst_run(&mut d, frames, channels, &log),
                        // Reached only if this thread's decoder is in use further up the stack:
                        // a log sink called while it is borrowed ran other pool jobs (for
                        // example by decoding on this pool itself, which waits in
                        // rayon::yield_now). Stay correct with a fresh decoder.
                        Err(_) => decode_dst_run(&mut DstDecoder::new(), frames, channels, &log),
                    })
                }));
                if result.is_err() {
                    // A sink that panics again here is caught as well, and the job's panic
                    // stays the one resumed.
                    let _ = std::panic::catch_unwind(AssertUnwindSafe(|| {
                        sb_log!(
                            &log,
                            Error,
                            "panic while decoding DST frames {:?}..={:?} on a pool thread; resumed on the caller",
                            range.0,
                            range.1
                        );
                    }));
                    // Start afresh rather than reuse a decoder a panic left behind.
                    DECODER.with(|d| {
                        if let Ok(mut d) = d.try_borrow_mut() {
                            *d = DstDecoder::new();
                        }
                    });
                }
                let result = result.map(|v| v.into_iter().map(Some).collect()).map_err(Some);
                let mut state = out.lock();
                state.result = Some(result);
                if state.waiting {
                    out.done.notify_one();
                }
            };
            match pool {
                Some(pool) => pool.spawn(work),
                None => rayon::spawn(work),
            }
            job
        }

        /// Frame `i` of the group, decoded: runs other pool jobs while it is not ready, or
        /// blocks when there are none (every job then runs on some thread, and finishes) or
        /// this thread is not one of the pool's.
        pub(super) fn wait(&self, i: usize) -> AudioFrame {
            loop {
                if let Some(f) = Self::take(&mut self.lock(), i) {
                    return f;
                }
                if rayon::yield_now() != Some(rayon::Yield::Executed) {
                    let mut state = self.lock();
                    state.waiting = true;
                    loop {
                        if let Some(f) = Self::take(&mut state, i) {
                            return f;
                        }
                        state = self.done.wait(state).unwrap_or_else(PoisonError::into_inner);
                    }
                }
            }
        }

        /// Frame `i`, if the group is decoded; resumes the panic of a group that failed
        /// (for later frames of it, a new one).
        fn take(state: &mut State, i: usize) -> Option<AudioFrame> {
            match state.result.as_mut()? {
                Ok(frames) => frames.get_mut(i).and_then(Option::take),
                Err(panic) => std::panic::resume_unwind(
                    panic.take().unwrap_or_else(|| Box::new("a group of DST frames panicked while decoding")),
                ),
            }
        }
    }
}

/// The decoded audio of one track or frame range, frame by frame (specification 4, 4.6
/// and 4.7).
#[derive(Debug)]
pub struct TrackAudio<'a, R> {
    image: &'a mut Image<R>,
    cursor: TrackAudioCursor,
    /// The disc's seek indexes, which take the checkpoints the cursor records.
    seek: Option<&'a SeekIndexes>,
}

impl<'a, R: Read + Seek> TrackAudio<'a, R> {
    pub(crate) fn with_cursor(
        image: &'a mut Image<R>,
        cursor: TrackAudioCursor,
        seek: Option<&'a SeekIndexes>,
    ) -> Self {
        TrackAudio { image, cursor, seek }
    }

    /// The decoding state, to continue into a later track or range with
    /// [`crate::Disc::continue_track_audio`] or [`crate::Disc::continue_range_audio`].
    pub fn into_cursor(self) -> TrackAudioCursor {
        self.cursor
    }

    /// The area's channel count `C` (1 to 6).
    pub fn channels(&self) -> u8 {
        self.cursor.channels()
    }

    /// Frames returned so far that were missing (filled with 0x69).
    pub fn missing_frames(&self) -> u64 {
        self.cursor.missing_frames()
    }

    /// Frames returned so far that were invalid DST frames (filled with 0x55).
    pub fn invalid_dst_frames(&self) -> u64 {
        self.cursor.invalid_dst_frames()
    }

    /// Number of malformed sectors processed so far by this cursor's scan of its area. The
    /// scan starts at the area's first audio sector, not at the track, and a continued
    /// cursor keeps counting from where the earlier tracks left off.
    /// Track cursors read ahead of the frames they return (a group of a few frames,
    /// or with `parallel` a window of bounded size), so this may count sectors of frames
    /// not yet returned.
    pub fn malformed_sectors(&self) -> u64 {
        self.cursor.malformed_sectors()
    }

    /// The `audio-sector-malformed` warnings of this cursor's scan of its area so far
    /// (see [`AreaCursor::warnings`]): per area, not per track, and each sector once.
    pub fn warnings(&self) -> &[Warning] {
        self.cursor.warnings()
    }

    /// Whether the positions are provisional (see [`SeekPolicy`]).
    pub fn speculation(&self) -> Speculation {
        self.cursor.speculation()
    }

    /// Why the provisional reading is suspect, if it is (see [`crate::Suspect`]).
    pub fn suspect(&self) -> Option<crate::Suspect> {
        self.cursor.suspect()
    }

    /// Where the malformed count and warnings begin (see [`AreaCursor::claim_lsn`]).
    pub fn claim_lsn(&self) -> Option<u64> {
        self.cursor.claim_lsn()
    }

    /// The number of the provisional reading, as events name it ([`crate::SeekEvent`]);
    /// `None` for exact positions.
    pub fn claim(&self) -> Option<u64> {
        self.cursor.claim()
    }

    /// The progress of the reading, readable from other threads (see [`Progress`]).
    pub fn progress(&mut self) -> Progress {
        self.cursor.progress()
    }
}

impl<R: Read + Seek> TrackAudio<'_, R> {
    /// Keeps each position's stored content from now on (see
    /// [`TrackAudioCursor::keep_stored`]), for [`TrackAudio::next_with_stored`].
    ///
    /// # Errors
    ///
    /// As [`TrackAudioCursor::keep_stored`].
    pub fn keep_stored(&mut self) -> Result<(), Error> {
        self.cursor.keep_stored()
    }

    /// The next position decoded, with its stored content (see
    /// [`TrackAudioCursor::next_frame_with_stored`]).
    pub fn next_with_stored(&mut self) -> Option<Result<(AudioFrame, Stored), Error>> {
        let frame = self.cursor.next_frame_with_stored(self.image);
        if let Some(seek) = self.seek {
            seek.absorb(&mut self.cursor.frames.area, self.image.id());
        }
        frame
    }
}

impl<R: Read + Seek> Iterator for TrackAudio<'_, R> {
    type Item = Result<AudioFrame, Error>;

    fn next(&mut self) -> Option<Self::Item> {
        let frame = self.cursor.next_frame(self.image);
        if let Some(seek) = self.seek {
            seek.absorb(&mut self.cursor.frames.area, self.image.id());
        }
        frame
    }
}

/// A frame of `channels` channels filled with one byte value.
pub fn fill_frame(channels: u8, value: u8) -> Vec<u8> {
    vec![value; usize::from(channels) * FRAME_BYTES_PER_CHANNEL]
}

/// Copies channel `channel` of an interleaved frame into `out` (4704 bytes).
///
/// # Errors
///
/// [`Error::InvalidArgument`] if the sizes do not match.
pub fn deinterleave(frame: &[u8], channels: u8, channel: u8, out: &mut [u8]) -> Result<(), Error> {
    let c = usize::from(channels);
    if c == 0
        || channel >= channels
        || frame.len() != c * FRAME_BYTES_PER_CHANNEL
        || out.len() != FRAME_BYTES_PER_CHANNEL
    {
        return Err(Error::InvalidArgument("frame, channel or output size mismatch"));
    }
    for (o, chunk) in out.iter_mut().zip(frame.chunks_exact(c)) {
        *o = chunk.get(usize::from(channel)).copied().unwrap_or(0);
    }
    Ok(())
}

/// The track a slot and number name, with its area.
pub(crate) fn find_track(areas: &[Area], slot: Slot, number: u32) -> Result<(&Area, &Track), Error> {
    let area = areas.iter().find(|a| a.slot == slot).ok_or(Error::NoSuchArea(slot))?;
    let track = area.track(number).ok_or(Error::NoSuchTrack { slot, track: number })?;
    Ok((area, track))
}

/// Areas for the unit tests of other modules.
#[cfg(test)]
pub(crate) mod tests_support {
    /// An area of `sectors` malformed audio sectors at LSN 0, one track over all its frames.
    pub(crate) fn area(sectors: u32) -> (crate::Image<std::io::Cursor<Vec<u8>>>, crate::Area, crate::Track) {
        super::tests::malformed_area(sectors, sectors)
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use crate::toc::Timecode;

    fn sector(header: u8, packets: &[(bool, u8, u16)], records: &[[u8; 4]], dst: bool) -> [u8; 2048] {
        let mut s = [0u8; 2048];
        s[0] = header;
        let mut at = 1;
        for &(start, ty, len) in packets {
            let w = (u16::from(start) << 15) | (u16::from(ty) << 11) | len;
            s[at..at + 2].copy_from_slice(&w.to_be_bytes());
            at += 2;
        }
        for r in records {
            let n = if dst { 4 } else { 3 };
            s[at..at + n].copy_from_slice(&r[..n]);
            at += n;
        }
        s
    }

    #[test]
    fn dst_frame_across_two_sectors() {
        let mut d = Demuxer::new(2);
        // Sector 1: DST flag, 1 frame record, 1 audio packet (start) of 100 bytes.
        let s1 = sector(1 | (1 << 2) | (1 << 5), &[(true, 2, 100)], &[[0, 0, 5, 2 << 2]], true);
        // Sector 2: 1 audio packet continuing the frame.
        let s2 = sector(1 | (1 << 5), &[(false, 2, 50)], &[], true);
        assert!(!d.push_sector(&s1));
        assert!(!d.push_sector(&s2));
        assert!(d.pop().is_none());
        d.finish();
        let f = d.pop().unwrap();
        assert_eq!((f.number, f.kind, f.data.len()), (5, FrameKind::Dst, 150));
    }

    #[test]
    fn overrun_and_backwards_timecodes() {
        let mut d = Demuxer::new(2);
        let over =
            sector(1 | (1 << 2) | (2 << 5), &[(true, 2, 2000), (false, 2, 100)], &[[0, 0, 1, 1 << 2]], true);
        assert!(d.push_sector(&over));
        // The first packet was appended before the overrun stopped the sector; its
        // remaining count reached 0, so the frame is complete and is delivered at the end.
        d.finish();
        assert_eq!(d.pop().map(|f| f.number), Some(1));
        let mut d = Demuxer::new(2);
        let a = sector(1 | (1 << 2) | (1 << 5), &[(true, 2, 10)], &[[0, 0, 9, 1 << 2]], true);
        let b = sector(1 | (1 << 2) | (1 << 5), &[(true, 2, 10)], &[[0, 0, 3, 1 << 2]], true);
        d.push_sector(&a);
        d.push_sector(&b);
        d.finish();
        assert_eq!(d.pop().map(|f| f.number), Some(9));
        assert!(d.pop().is_none());
    }

    #[test]
    fn start_without_record_is_malformed() {
        let mut d = Demuxer::new(2);
        let s = sector(1 << 5, &[(true, 2, 10)], &[], false);
        assert!(d.push_sector(&s));
        d.finish();
        assert!(d.pop().is_none());
    }

    #[cfg(feature = "parallel")]
    #[test]
    #[cfg_attr(miri, ignore = "starts 67 threads")]
    fn parallel_window_is_capped() {
        let (_, area, track) = malformed_area(1, 1);
        let mut cursor = TrackAudioCursor::new(&area, &track, 1).unwrap();
        let pool = |n| std::sync::Arc::new(rayon::ThreadPoolBuilder::new().num_threads(n).build().unwrap());
        let (wide, narrow, single) = (pool(64), pool(2), pool(1));
        wide.install(|| assert_eq!(cursor.window(2), MAX_PARALLEL_BATCH));
        narrow.install(|| assert_eq!(cursor.window(2), 2 * PARALLEL_FRAMES_PER_THREAD));
        single.install(|| assert_eq!(cursor.window(2), crate::dst::lanes(2)));
        // A pool chosen for the cursor counts whatever pool the caller runs on.
        cursor.set_decode_on(DecodeOn::Pool(std::sync::Arc::clone(&narrow)));
        wide.install(|| assert_eq!(cursor.window(2), 2 * PARALLEL_FRAMES_PER_THREAD));
        assert_eq!(cursor.window(2), 2 * PARALLEL_FRAMES_PER_THREAD);
        cursor.set_decode_on(DecodeOn::Pool(single));
        wide.install(|| assert_eq!(cursor.window(2), crate::dst::lanes(2)));
        cursor.set_decode_on(DecodeOn::CallingThread);
        wide.install(|| assert_eq!(cursor.window(2), crate::dst::lanes(2)));
        // Continuations keep the choice.
        let next = cursor.continue_to(&area, &track, 1).unwrap();
        assert!(matches!(next.decode_on(), DecodeOn::CallingThread));
        // The bound documented on MAX_PARALLEL_BATCH: each position held ahead is at most
        // one frame of DST bytes and one of decoded audio, about 48 MB in all.
        let bound = MAX_PARALLEL_BATCH * (MAX_FRAME_BYTES + 6 * FRAME_BYTES_PER_CHANNEL);
        assert!(bound <= 48_100_000, "{bound}");
    }

    /// An area of `sectors` malformed audio sectors (a packet that overruns each one) at
    /// LSN 0, with one track of `frames` frames, all missing.
    pub(crate) fn malformed_area(
        sectors: u32,
        frames: u32,
    ) -> (Image<std::io::Cursor<Vec<u8>>>, Area, Track) {
        // One packet (k = 1), audio, 2047 bytes: past the end of the sector.
        area_of(sectors, frames, |_, s| s[..3].copy_from_slice(&[1 << 5, 0x17, 0xFF]))
    }

    /// An area of `sectors` well-formed audio sectors at LSN 0, each starting plain frame
    /// `i` with 10 bytes only, so that every frame is discarded as incomplete; one track
    /// of `frames` frames, all missing.
    fn incomplete_frames_area(sectors: u32, frames: u32) -> (Image<std::io::Cursor<Vec<u8>>>, Area, Track) {
        area_of(sectors, frames, |i, s| {
            // k = 1 packet, f = 1 frame record, plain DSD; a start audio packet of 10 bytes;
            // the record's timecode is frame i.
            let (m, sec, f) = ((i / 4500) as u8, (i / 75 % 60) as u8, (i % 75) as u8);
            s[..6].copy_from_slice(&[(1 << 5) | (1 << 2), 0x90, 10, m, sec, f]);
        })
    }

    /// An area of `sectors` sectors at LSN 0, sector `i` written by `fill`, with one track
    /// of `frames` frames.
    fn area_of(
        sectors: u32,
        frames: u32,
        fill: impl Fn(usize, &mut [u8]),
    ) -> (Image<std::io::Cursor<Vec<u8>>>, Area, Track) {
        use crate::toc::{AreaKind, AreaText, Timecode, TrackText, Version};
        let mut bytes = vec![0u8; sectors as usize * SECTOR_SIZE];
        for (i, s) in bytes.chunks_exact_mut(SECTOR_SIZE).enumerate() {
            fill(i, s);
        }
        let image = Image::options()
            .with_format(crate::SectorFormat::Plain)
            .open(std::io::Cursor::new(bytes))
            .unwrap();
        let playtime = Timecode {
            minutes: (frames / 4500) as u8,
            seconds: (frames / 75 % 60) as u8,
            frames: (frames % 75) as u8,
        };
        let track = Track {
            number: 1,
            start_lsn: 0,
            length_sectors: sectors,
            start_frame: 0,
            duration_frames: frames,
            start_flags: 0,
            duration_flags: 0,
            isrc: None,
            genre: None,
            text: TrackText::default(),
        };
        let area = Area {
            slot: Slot::TwoChannel,
            kind: AreaKind::TwoChannel,
            version: Version { major: 1, minor: 20 },
            toc_lsn: 0,
            toc_sectors: 0,
            max_byte_rate: 0,
            sample_frequency_code: 4,
            frame_format: 0,
            channel_count: 2,
            area_config: 0,
            max_available_channels: 2,
            area_mute_flags: 0,
            track_attribute: 0,
            playtime,
            track_offset: 0,
            audio_start_lsn: 0,
            audio_end_lsn: sectors - 1,
            text_channel_count: 0,
            locales: Vec::new(),
            text_charset: 0,
            text: AreaText::default(),
            tracks: vec![track.clone()],
        };
        (image, area, track)
    }

    type Lines = std::sync::Arc<std::sync::Mutex<Vec<String>>>;

    fn recorder(level: Level) -> (Log, Lines) {
        let lines = Lines::default();
        let sink = std::sync::Arc::clone(&lines);
        (Log::new(level, move |_, m| sink.lock().unwrap().push(m.to_string())), lines)
    }

    #[test]
    #[cfg_attr(miri, ignore = "decodes thousands of frames")]
    fn problem_lines_are_capped() {
        let n = MAX_PROBLEM_LINES + 100;
        let (mut image, area, track) = malformed_area(n as u32, n as u32);
        let (log, lines) = recorder(Level::Warn);
        image.set_log(log);
        let mut cursor = TrackAudioCursor::new(&area, &track, image.sector_count()).unwrap();
        let mut frames = 0;
        while let Some(f) = cursor.next_frame(&mut image) {
            assert_eq!(f.unwrap().status, FrameStatus::Missing);
            frames += 1;
        }
        assert_eq!((frames, cursor.missing_frames()), (n, n as u64));
        assert_eq!(cursor.malformed_sectors(), n as u64);
        let lines = lines.lock().unwrap();
        let malformed: Vec<_> = lines.iter().filter(|m| m.contains(": audio-sector-malformed: ")).collect();
        let missing = lines.iter().filter(|m| m.contains(": missing, filled")).count();
        assert_eq!((malformed.len(), missing), (MAX_PROBLEM_LINES, MAX_PROBLEM_LINES));
        // The lines are those of the warnings kept, which are capped alike.
        let listed: Vec<_> = cursor
            .warnings()
            .iter()
            .map(|w| {
                format!(
                    "area 2ch audio sector LSN {}: audio-sector-malformed: packet 0 of 1 (2047 bytes at 3) overruns the sector",
                    w.lsn.unwrap()
                )
            })
            .collect();
        assert_eq!(malformed.into_iter().cloned().collect::<Vec<_>>(), listed);
        for what in ["audio-sector-malformed", "missing-frame"] {
            let suppressed =
                format!("area 2ch: further {what} lines suppressed (at most {MAX_PROBLEM_LINES} per cursor)");
            assert_eq!(lines.iter().filter(|m| **m == suppressed).count(), 1, "{what}");
        }

        // Frames the reassembler discards: capped alike, per area cursor.
        let (mut image, area, track) = incomplete_frames_area(n as u32, n as u32);
        let (log, lines) = recorder(Level::Warn);
        image.set_log(log);
        let mut cursor = TrackAudioCursor::new(&area, &track, image.sector_count()).unwrap();
        while let Some(f) = cursor.next_frame(&mut image) {
            assert_eq!(f.unwrap().status, FrameStatus::Missing);
        }
        assert_eq!(cursor.malformed_sectors(), 0);
        let lines = lines.lock().unwrap();
        let discarded: Vec<_> =
            lines.iter().filter(|m| m.contains(": discarded, incomplete (Dsd, 10 bytes")).collect();
        assert_eq!(discarded.len(), MAX_PROBLEM_LINES);
        assert_eq!(
            discarded[0],
            "area 2ch frame 0 (from LSN 0): discarded, incomplete (Dsd, 10 bytes; 4.4.2)"
        );
        let suppressed = format!(
            "area 2ch: further discarded-frame lines suppressed (at most {MAX_PROBLEM_LINES} per cursor)"
        );
        assert_eq!(lines.iter().filter(|m| **m == suppressed).count(), 1);
        // Its first line comes right after the last discarded frame admitted.
        let at = lines.iter().position(|m| *m == suppressed).unwrap();
        assert!(lines[..at].iter().filter(|m| m.contains(": discarded,")).count() == MAX_PROBLEM_LINES);
    }

    #[test]
    fn a_frame_survives_a_sink_that_panics() {
        let (mut image, area, track) = malformed_area(1, 3);
        let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let counter = std::sync::Arc::clone(&calls);
        image.set_log(Log::new(Level::Warn, move |_, m| {
            if m.to_string().contains("frame 1: missing")
                && counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed) == 0
            {
                panic!("sink");
            }
        }));
        let mut cursor = TrackAudioCursor::new(&area, &track, image.sector_count()).unwrap();
        assert_eq!(cursor.next_frame(&mut image).unwrap().unwrap().number, 0);
        let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| cursor.next_frame(&mut image)));
        assert!(caught.is_err());
        assert_eq!(cursor.missing_frames(), 1, "the frame whose line panicked is not counted");
        let numbers: Vec<_> =
            std::iter::from_fn(|| cursor.next_frame(&mut image)).map(|f| f.unwrap().number).collect();
        assert_eq!(numbers, [1, 2]);
        assert_eq!(cursor.missing_frames(), 3);
    }

    #[test]
    fn decode_frame_rejects_bad_arguments() {
        let mut d = DstDecoder::new();
        let missing = || TrackFrame { number: 0, content: FrameContent::Missing };
        for channels in [0, 7, 255] {
            assert!(matches!(decode_frame(&mut d, missing(), channels), Err(Error::InvalidArgument(_))));
        }
        let short = TrackFrame { number: 0, content: FrameContent::Dsd(vec![0; 10]) };
        assert!(matches!(decode_frame(&mut d, short, 2), Err(Error::InvalidArgument(_))));
        let ok = decode_frame(&mut d, missing(), 2).unwrap();
        assert_eq!((ok.status, ok.data.len()), (FrameStatus::Missing, 2 * 4704));
    }

    #[test]
    fn dst_equivalents() {
        let missing = FrameContent::Missing.dst_equivalent(3).unwrap();
        assert_eq!(missing.len(), 1 + 3 * FRAME_BYTES_PER_CHANNEL);
        assert_eq!(missing[0], 0);
        assert!(missing[1..].iter().all(|&b| b == MISSING_FILL));
        let plain = FrameContent::Dsd(vec![7; FRAME_BYTES_PER_CHANNEL]);
        let plain = plain.dst_equivalent(1).unwrap();
        assert_eq!((plain.len(), plain[0], plain[1]), (1 + FRAME_BYTES_PER_CHANNEL, 0, 7));
        let dst = FrameContent::Dst(vec![1, 2, 3]);
        assert_eq!(&*dst.dst_equivalent(6).unwrap(), &[1, 2, 3]);
        for channels in [0, 7, 255] {
            assert!(matches!(FrameContent::Missing.dst_equivalent(channels), Err(Error::InvalidArgument(_))));
        }
    }

    #[test]
    fn deinterleave_channel() {
        let frame: Vec<u8> = (0..2 * 4704).map(|i| (i % 2) as u8).collect();
        let mut out = vec![9u8; 4704];
        deinterleave(&frame, 2, 1, &mut out).unwrap();
        assert!(out.iter().all(|&b| b == 1));
        assert!(deinterleave(&frame, 2, 2, &mut out).is_err());
    }

    /// An area of `channels` channels whose audio sectors are `[start, end]` as stored,
    /// with play time `playtime` and one track per `(start, duration)` given, read
    /// nothing from (#340).
    fn capacity_area(
        channels: u8,
        (start, end): (u32, u32),
        playtime: Timecode,
        tracks: &[(u32, u32)],
    ) -> Area {
        let (_, mut area, track) = area_of(1, 1, |_, _| {});
        area.channel_count = channels;
        area.audio_start_lsn = start;
        area.audio_end_lsn = end;
        area.playtime = playtime;
        area.tracks = tracks
            .iter()
            .map(|&(s, d)| Track { start_frame: s, duration_frames: d, ..track.clone() })
            .collect();
        area
    }

    fn tc(frames: u32) -> Timecode {
        Timecode {
            minutes: (frames / 4500) as u8,
            seconds: (frames / 75 % 60) as u8,
            frames: (frames % 75) as u8,
        }
    }

    /// The figures of a synthetic area against their derivation (specification 4, 4.2 and
    /// 4.8; #340), with the plain bound per channel count.
    #[test]
    fn area_capacity_of_synthetic_areas() {
        let area = capacity_area(2, (100, 199), tc(50), &[(0, 20), (20, 40)]);
        let c = area_capacity(&area, 1000);
        assert_eq!((c.audio_sectors, c.playtime_frames, c.max_track_end, c.capacity), (100, 50, 60, 700));
        // floor(100 x 2045 / 9408) = floor(21.7...)
        assert_eq!(c.plain_frame_bound, Some(21));
        assert_eq!(c.frames_per_sector(), 0.6);
        // The image ends inside the area: only the sectors that exist count (4.2 item 1).
        let c = area_capacity(&area, 150);
        assert_eq!((c.audio_sectors, c.capacity, c.plain_frame_bound), (50, 350, Some(10)));
        assert_eq!(c.frames_per_sector(), 1.2);
        // n = 9408 sectors hold at most 2045 x 9408 bytes of packet data: 2045 plain frames
        // of 2 channels, 818 of 5 (rounded down), 681 of 6.
        for (channels, bound) in [(1, 4090), (2, 2045), (3, 1363), (4, 1022), (5, 818), (6, 681)] {
            let area = capacity_area(channels, (0, 9407), tc(0), &[]);
            let c = area_capacity(&area, 9408);
            assert_eq!(c.plain_frame_bound, Some(bound), "{channels} channels");
            assert_eq!((c.max_track_end, c.frames_per_sector()), (0, 0.0));
        }
        // The bound per sector to 4 places (2045/9408, 2045/23520 and 2045/28224; #340 gave
        // 0.0870 for 5 channels, a rounding of 0.086947), and above it the play time per
        // sector measured on #340's densely packed synthetic plain areas.
        for (channels, per_sector, measured) in
            [(2, 0.2174, 0.2172), (5, 0.0869, 0.0869), (6, 0.0725, 0.0724)]
        {
            let area = capacity_area(channels, (0, 999_999), tc(0), &[]);
            let bound = area_capacity(&area, 1_000_000).plain_frame_bound.unwrap();
            let bound = bound as f64 / 1e6;
            assert!((bound - per_sector).abs() < 5e-5, "{channels} channels: {bound}");
            assert!(measured <= bound, "{channels} channels: {bound}");
        }
    }

    /// Hostile TOCs: no audio sector in the image, sectors reversed, channel counts outside
    /// 1 to 6, and every field at its largest (#340).
    #[test]
    fn area_capacity_of_hostile_areas() {
        // Every audio sector past the end of the image, or the range reversed: n = 0, and
        // the figure per sector is infinite, never NaN, even when the TOC claims nothing.
        for (range, playtime, tracks) in
            [((500, 600), 75, &[(0, 75)][..]), ((500, 600), 0, &[]), ((300, 200), 10, &[(0, 10)])]
        {
            let c = area_capacity(&capacity_area(2, range, tc(playtime), tracks), 400);
            assert_eq!((c.audio_sectors, c.capacity, c.plain_frame_bound), (0, 0, Some(0)));
            assert_eq!(c.frames_per_sector(), f64::INFINITY);
            assert!(c.frames_per_sector() > 1e300);
        }
        // No audio is produced for these channel counts (4.8 item 1): no plain bound.
        for channels in [0, 7, 8, 255] {
            let c = area_capacity(&capacity_area(channels, (0, 9), tc(5), &[(0, 5)]), 10);
            assert_eq!((c.audio_sectors, c.capacity, c.plain_frame_bound), (10, 70, None));
            assert_eq!(c.frames_per_sector(), 0.5);
        }
        // The largest values: n = 2^32, a play time of 255:255:255 and a track ending at
        // u32::MAX (its end saturates).
        let largest = Timecode { minutes: 255, seconds: 255, frames: 255 };
        let area = capacity_area(1, (0, u32::MAX), largest, &[(u32::MAX - 1, u32::MAX), (5, 1)]);
        let c = area_capacity(&area, u64::MAX);
        let n = 1u64 << 32;
        assert_eq!((c.audio_sectors, c.capacity, c.max_track_end), (n, 7 * n, u32::MAX));
        assert_eq!(c.playtime_frames, largest.frame_number());
        assert_eq!(c.plain_frame_bound, Some(n * 2045 / 4704));
        assert_eq!(c.frames_per_sector(), f64::from(u32::MAX) / n as f64);
        assert!(c.frames_per_sector() < 1.0);
    }
}