scarletbook 0.5.9

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
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Seeking within an area: saved reading state, so that a frame range far into an area
//! does not need a scan of the area from its first audio sector (issue #68).
//!
//! # Why an index
//!
//! The frames a range holds depend on every audio sector before it: the next acceptable
//! frame number `a` (specification 4, 4.5) is one more than the largest number of any
//! complete frame delivered so far, and a single sector anywhere before the range can
//! raise it past every frame of the range (4.5 item 2). A reader that has not read that
//! sector cannot tell the two images apart, so no exact reader can seek a first time
//! without reading the area up to the range. What it can do is keep the state of that
//! read: an [`AreaIndex`] holds the reading state of an area every `K` sectors
//! ([`IndexOptions::interval`]) from its first audio sector up to the index's
//! **frontier**. A cursor that starts from it resumes at the last checkpoint whose `a` is
//! at most the range's first frame, rebuilds the frame under assembly there, and reads
//! on as a scan from the first sector would: the frames, statuses, counts and warnings it
//! returns are exactly those of such a scan; only its reads and log lines differ.
//!
//! # Building one
//!
//! An index is built by reading: a cursor made from an index
//! ([`crate::TrackCursor::for_range_indexed`], [`crate::TrackAudioCursor::for_range_indexed`])
//! records a checkpoint each time its scan crosses a boundary past the index's frontier,
//! and [`AreaIndex::absorb`] takes those checkpoints into the index. Each audio sector is
//! then read at most once per index for building it, and once the frontier lies past a
//! range, opening that range reads at most `W + K` sectors before the sectors of its own
//! frames (`W` = [`REPLAY_SECTORS`], unless the frame under assembly there is longer and
//! does not fit the inline budget).
//!
//! # Trust
//!
//! An index is the reading state of one area of one image. It is keyed by the area (slot,
//! audio sector range, channel count) and the image's sector count, and a cursor refuses
//! an index of another key. Each checkpoint also holds a digest (64-bit FNV-1a) of the
//! sector at its LSN, which a cursor resuming there compares with that sector when it
//! reads it (it reads it anyway), before it returns anything: on a mismatch it discards
//! the index, logs a warning and scans from the first sector ([`ResumedFrom::Discarded`]).
//!
//! What that digest catches: an index of another image of the same size and layout, or of
//! an image changed since, whenever the checkpoint's own sector differs (with a 2^-64
//! chance of missing it). What it does not: a change only in the other sectors before the
//! checkpoint, which can change the reading state there without changing that sector (the
//! replayed sectors and the stored frame under assembly are not checked either); and a
//! cursor that reads nothing at all (a range wholly past the last accepted frame of a
//! complete index), which has no sector to compare. An index is thus **trusted for correctness and validated for safety**, like
//! the image itself: [`AreaIndex::from_bytes`] checks every bound and invariant before it
//! allocates, so that hostile bytes give an error, never a panic or an unbounded
//! allocation, but an index forged to pass those checks can make a cursor return other
//! frames than the image holds (still within the bounds of any read).
//!
//! # Specification
//!
//! Beginning at a checkpoint is specification 4, 4.2 item 7 (sacd-spec `da6b900`): the
//! frame under assembly there is the one processing from the first sector leaves (stored,
//! or rebuilt by replaying from the sector it started in), and the cursor begins with the
//! checkpoint's next acceptable frame number, the scan's own, which is at most the range's
//! first frame `u`; 4.5 item 6 gives why that is exact. Malformed counts and warnings
//! include those the earlier pass found (4.4.5 item 4), and replayed sectors are not
//! reported again (4.4.5 item 2). Specification 7, 7.1 items 2 and 3 bound the memory and
//! the passes.

mod persist;

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

use crate::audio::{
    AreaCursor, AreaKey, FrameKind, MAX_FRAME_BYTES, MAX_MALFORMED_WARNINGS, audio_sector_range,
};
use crate::error::Error;
use crate::image::{Image, SECTOR_SIZE};
use crate::log::sb_log;
use crate::toc::Area;

/// Default checkpoint interval `K` in sectors.
pub const DEFAULT_INTERVAL: u32 = 64;

/// Largest checkpoint interval `K` in sectors.
pub const MAX_INTERVAL: u32 = 65_536;

/// Default bound on the bytes of frames under assembly an index stores (1 MiB).
pub const DEFAULT_INLINE_BUDGET: usize = 1 << 20;

/// Most sectors a resume replays to rebuild the frame under assembly, `W`, unless that
/// frame does not fit the inline budget.
///
/// On well-formed images a frame spans at most 31 sectors (a DST frame's sector count,
/// specification 4, 4.3.3; a plain frame at most `ceil(6 x 4704 / 2045) + 1 = 15`), so a
/// checkpoint never stores a frame's bytes. A hostile frame may be spread over any number
/// of sectors; a checkpoint whose frame under assembly started more than `W` sectors
/// before it stores the frame's bytes (at most [`MAX_FRAME_BYTES`]) while the index's
/// inline budget lasts, and is replayed from the frame's first sector otherwise.
pub const REPLAY_SECTORS: u64 = 32;

/// Options of an [`AreaIndex`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct IndexOptions {
    /// The checkpoint interval `K` in sectors, 1 to [`MAX_INTERVAL`]: the index holds
    /// about `24` bytes per `K` audio sectors, and a resume reads at most `K` sectors
    /// past its checkpoint before the range's first frame is known.
    pub interval: u32,
    /// The most bytes of frames under assembly the index stores, over all its checkpoints
    /// (see [`REPLAY_SECTORS`]); 0 stores none. A cursor made from the index may hold as
    /// much again while it records. Saved indexes keep at most 4 GiB of it.
    pub inline_budget: usize,
    /// Seek hints ([`AreaIndex#seek-hints`]): a sample is recorded at least this many
    /// frames after the one before. Default [`DEFAULT_HINT_SPACING`]; 0 records none.
    pub hint_spacing: u32,
    /// The most seek hints kept, at most [`MAX_HINTS`]; past it, those closest (in frames)
    /// to the hint before them are dropped. Default [`DEFAULT_MAX_HINTS`] (8 bytes each, saved and in memory).
    /// An index loaded with [`AreaIndex::from_bytes`] keeps at most its `max_inline_budget / 8`.
    pub max_hints: usize,
}

impl Default for IndexOptions {
    fn default() -> Self {
        IndexOptions {
            interval: DEFAULT_INTERVAL,
            inline_budget: DEFAULT_INLINE_BUDGET,
            hint_spacing: DEFAULT_HINT_SPACING,
            max_hints: DEFAULT_MAX_HINTS,
        }
    }
}

impl IndexOptions {
    /// The defaults: `K` = [`DEFAULT_INTERVAL`], [`DEFAULT_INLINE_BUDGET`].
    pub fn new() -> Self {
        Self::default()
    }

    /// These options with checkpoint interval `interval`.
    pub fn with_interval(self, interval: u32) -> Self {
        IndexOptions { interval, ..self }
    }

    /// These options with inline budget `bytes`.
    pub fn with_inline_budget(self, bytes: usize) -> Self {
        IndexOptions { inline_budget: bytes, ..self }
    }

    /// These options with seek hints `spacing` frames apart (0 for none), at most `max`.
    pub fn with_hints(self, spacing: u32, max: usize) -> Self {
        IndexOptions { hint_spacing: spacing, max_hints: max, ..self }
    }
}

/// Default [`IndexOptions::hint_spacing`], in frames (about 0.1 s, 16 sectors of DST).
pub const DEFAULT_HINT_SPACING: u32 = 8;

/// Default [`IndexOptions::max_hints`]: 16 KiB.
pub const DEFAULT_MAX_HINTS: usize = 2048;

/// Most seek hints an index keeps or loads.
pub const MAX_HINTS: usize = 65_536;

/// A seek hint is used for a range whose first frame lies at most this many frames after
/// the hint's.
pub const HINT_REACH: u32 = 64;

/// Where a cursor made from an index started its scan.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ResumedFrom {
    /// At the area's first audio sector, as a cursor made without an index.
    Start,
    /// At the checkpoint at sector `lsn`, after replaying the sectors from `replay_from`
    /// (equal to `lsn` when nothing was replayed) to rebuild the frame under assembly.
    Checkpoint {
        /// The checkpoint's LSN.
        lsn: u64,
        /// The first sector read.
        replay_from: u64,
    },
    /// Nowhere: the index is complete and no frame at or after the range's first is
    /// accepted, so every position is missing and nothing is read.
    End,
    /// At the area's first audio sector, after finding that the index does not hold
    /// sector `lsn` as the image has it (its digest differs): a stale index, or one of
    /// another image of the same size. The index was not used; the cursor records nothing.
    Discarded {
        /// The checkpoint whose sector differs.
        lsn: u64,
    },
    /// At sector `lsn`, provisionally (specification 4, 4.2 item 8, sacd-spec `82eac6c`):
    /// with no frame under assembly and the range's first frame as the next acceptable
    /// frame number, after `probes` reads that chose `lsn` (see [`SeekPolicy`]). The
    /// positions are provisional ([`Speculation`]). Both are 0 until the cursor first
    /// reads, which is when it chooses.
    Speculative {
        /// The sector the provisional reading began at, `L`.
        lsn: u64,
        /// The reads made to choose it.
        probes: u32,
    },
}

/// How cursors start a range that the seek index (if any) cannot reach cheaply.
///
/// [`SeekPolicy::Exact`], the default, starts every range from the area's first sector or
/// from a checkpoint of the seek index (specification 4, 4.2 items 6 and 7), so that its
/// positions are always this specification's. [`SeekPolicy::Speculative`] lets a cursor
/// begin far into an area without reading the sectors before it: **provisional reading**,
/// specification 4, 4.2 item 8 (sacd-spec `82eac6c`). Opting in is the caller's request
/// that item requires.
///
/// # Provisional reading
///
/// A cursor that would have to read more than [`SpeculativeOptions::min_gap_sectors`]
/// sectors before the range's estimated position chooses a sector `L` instead: it searches
/// the frame records' timecodes for a sector whose first frame record is numbered below the
/// range's first frame `u`, close before frame `u` (interpolation between the area's
/// track starts; then from the last probe at its density, the first time corrected toward
/// the average back to the other track start; then, once probes lie on both sides, regula
/// falsi with the Illinois weighting; with a bisection safeguard: a few reads of
/// [`SpeculativeOptions::probe_sectors`], and one larger read when an interval just
/// past or around frame `u` fits what is left of about 144 KiB; a fifth read, if the search
/// gets that far, reads what is left of 160 KiB around its guess, so that it can hold frame
/// `u` too, and the search goes on only if it finds no sector before frame `u`; at most a constant times
/// `log2(n + 1)` sectors for an area of `n` audio sectors, as 7.1 item 3 allows), and
/// begins at that sector, with no frame under assembly and `u` as the next acceptable frame
/// number. It reads on from its last probe, through frame `u` and on toward the range's
/// estimated end as far as those 144 KiB allow, in one call sized to that (less than 32
/// sectors too), and then on to the range's estimated end in calls of at
/// most [`MAX_READ_SECTORS`]: the range the caller asks for sizes the reads.
///
/// Its positions are exactly the specification's when both (4.2 item 8):
/// - (a) `a_L <= u`: no frame numbered `u` or more was accepted before `L` by a reader
///   processing from the first sector; and
/// - (b) the frame under assembly at `L` is none or has a frame number below `u`.
///
/// They hold on every image whose frames start in increasing frame number order (any
/// well-formed disc, repeated frame numbers included: the frames that start before `L` are
/// numbered at most `L`'s first record, which is below `u`; 4.3.3 and 4.4.3 item 3.3), but no read of `L` or later sectors can establish
/// them: one earlier sector can break (a). So the positions are **provisional** ([`Speculation::Pending`])
/// until a pass from the first sector establishes or refutes them. When (a) or (b) fails,
/// positions numbered `a*` or more are still exact, where `a*` is the next acceptable frame
/// number of a reader processing from the first sector just after it delivered or
/// discarded the frame under assembly at `L`; below `a*`, a provisional position can differ
/// whether or not the specification's is missing (a frame accepted before `L` is never
/// seen, and frames the specification discards can be accepted). Every frame a provisional
/// reading returns is a complete frame of the image, in increasing frame number order.
///
/// The malformed sectors and warnings of a provisional reading cover the sectors it
/// processes from `L` only (4.4.5 item 5); [`crate::TrackCursor::counts_from`] says so.
/// Its missing and invalid counts are provisional too (4.7.1 item 6).
///
/// # Not serving positions that will be refuted
///
/// No test of the sectors a provisional reading reads can tell that it will be refuted (4.2
/// item 8). A caller that must not serve positions that may differ can:
/// - wait for [`Speculation::Confirmed`] before serving: with a seek index kept,
///   [`crate::Disc::verify_speculation`] (on a clone, in another thread) settles a reading
///   once its pass reaches `L`, which costs that pass;
/// - serve at once, and on [`Speculation::Refuted`] (an event of
///   [`crate::Disc::take_seek_events`]) invalidate and re-read positions `first` to
///   `exact_from - 1`: the library cannot take back what it returned;
/// - read exactly ([`SeekPolicy::Exact`]) in an area whose TOC is implausible, for example
///   one whose audio sectors run past the image's end or over the other area's TOC or audio
///   sectors: a provisional reading there can land in sectors that are not this area's
///   audio, as on the corpus image `area-audio-past-end`, and is then refuted;
/// - use the **suspect** mark (4.2 item 8, sacd-spec `eafaaba`): a cursor's
///   [`crate::TrackCursor::suspect`] gives a reason of the library's own to doubt its reading
///   ([`Suspect`]: such a layout, or frame numbers that decreased between the sectors its
///   search read), and [`SpeculativeOptions::exact_when_suspect`] reads those exactly
///   instead. The mark is informative: it does not change how the reading is settled, and
///   a reading without it can still be refuted.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum SeekPolicy {
    /// Exact reads only: the default.
    #[default]
    Exact,
    /// Provisional reading where an exact start would read far.
    Speculative(SpeculativeOptions),
}

/// Options of [`SeekPolicy::Speculative`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct SpeculativeOptions {
    /// Read exactly when the exact start lies at most this many sectors before the range's
    /// estimated position (in proportion to the play time). Default 2 048 (4 MiB).
    pub min_gap_sectors: u64,
    /// Sectors per probe read while searching, 1 to 32. Default 8 (16 KiB).
    pub probe_sectors: u32,
    /// Most probes per search. Default 48; at most `2 x ceil(log2(n + 1)) + 4` are made in
    /// any case, for an area of `n` audio sectors.
    pub max_probes: u32,
    /// Read exactly, instead of provisionally, where a reading would be [`Suspect`]: in an
    /// area whose layout is suspect, and after a search that saw frame numbers decrease
    /// (4.2 item 8 allows either). Default `false`.
    pub exact_when_suspect: bool,
    /// The area's layout is suspect ([`Suspect::AreaLayout`]): set by a disc from its TOC for
    /// the cursors it makes, not by callers.
    pub(crate) layout_suspect: bool,
}

impl Default for SpeculativeOptions {
    fn default() -> Self {
        SpeculativeOptions {
            min_gap_sectors: 2048,
            probe_sectors: 8,
            max_probes: 48,
            exact_when_suspect: false,
            layout_suspect: false,
        }
    }
}

impl SpeculativeOptions {
    /// The defaults.
    pub fn new() -> Self {
        Self::default()
    }

    /// These options with `min_gap_sectors`.
    pub fn with_min_gap_sectors(self, sectors: u64) -> Self {
        SpeculativeOptions { min_gap_sectors: sectors, ..self }
    }

    /// These options with `probe_sectors` (clamped to 1 to 32 when used).
    pub fn with_probe_sectors(self, sectors: u32) -> Self {
        SpeculativeOptions { probe_sectors: sectors, ..self }
    }

    /// These options with `max_probes`.
    pub fn with_max_probes(self, probes: u32) -> Self {
        SpeculativeOptions { max_probes: probes, ..self }
    }

    /// These options with `exact_when_suspect`.
    pub fn with_exact_when_suspect(self, exact: bool) -> Self {
        SpeculativeOptions { exact_when_suspect: exact, ..self }
    }
}

/// Whether a cursor's positions are this specification's, or provisional (specification
/// 4, 4.2 item 8; see [`SeekPolicy`]).
///
/// A cursor chooses its start on its first read: check this after the first frame.
/// Before it, a cursor allowed to read provisionally shows `Pending { lsn: 0, .. }`, even
/// one that then finds an exact start better and reports [`Speculation::Exact`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Speculation {
    /// Not a provisional reading: the positions are exact.
    Exact,
    /// A provisional reading from sector `lsn` for positions `first` or more, not yet
    /// established or refuted (`lsn` is 0 until the cursor first reads).
    Pending {
        /// `L`.
        lsn: u64,
        /// `u`, the range's first frame when the reading began.
        first: u32,
    },
    /// A provisional reading whose conditions (a) and (b) a pass from the first sector has
    /// established: its positions are this specification's (4.2 item 8).
    Confirmed {
        /// `L`.
        lsn: u64,
        /// `u`.
        first: u32,
    },
    /// A provisional reading whose condition (a) or (b) fails: its positions numbered
    /// `first` to `exact_from - 1` are **possibly different** from this specification's
    /// (4.2 item 8), whether or not they are missing; from `exact_from` on they are exact.
    /// `exact_from` is at least the specification's `a*` (the next acceptable frame number
    /// of a reader from the first sector just after it delivered or discarded the frame
    /// under assembly at `L`): the larger of `a_L` and one more than that frame's number.
    Refuted {
        /// `L`.
        lsn: u64,
        /// `u`.
        first: u32,
        /// The last position the cursor had returned, if any.
        last_returned: Option<u32>,
        /// Positions from here on are exact.
        exact_from: u32,
    },
    /// A provisional reading that will not be checked: dropped past the limit of
    /// [`MAX_CLAIMS`] pending readings per index, or found to be of an index that does not
    /// match the image. Its positions stay provisional.
    Unverified {
        /// `L`.
        lsn: u64,
        /// `u`.
        first: u32,
    },
}

/// Why a provisional reading is **suspect**: a reason of the reader's own to expect its
/// conditions (a) or (b) to fail (specification 4, 4.2 item 8, sacd-spec `eafaaba`). The
/// mark is informative: a suspect reading is provisional like any other and is settled
/// exactly as any other ([`Speculation`]); a caller may choose not to serve its positions
/// before it is confirmed, or to read such areas exactly
/// ([`SpeculativeOptions::exact_when_suspect`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Suspect {
    /// The area's TOC places its audio sectors past the end of the image, or over the other
    /// area's TOC or audio sectors (checked by a disc from its TOC; a cursor made without a
    /// disc checks only the end of the image).
    AreaLayout,
    /// The first frame records of the sectors read while choosing `L` decrease from one
    /// sector to a later one.
    FrameNumbersDecrease,
}

/// Most provisional readings an index keeps waiting to be checked; past it, the oldest is
/// dropped as [`Speculation::Unverified`].
pub const MAX_CLAIMS: usize = 256;

/// Most verdicts kept waiting to be taken, per index ([`AreaIndex::take_events`]) and per
/// disc and area ([`crate::Disc::take_seek_events`]); past it, the oldest are dropped (the
/// cursors still hold their verdicts).
pub const MAX_EVENTS: usize = 4 * MAX_CLAIMS;

/// Appends `events` to `queue`, keeping the last [`MAX_EVENTS`].
pub(crate) fn queue_events(queue: &mut Vec<SeekEvent>, events: impl IntoIterator<Item = SeekEvent>) {
    queue.extend(events);
    if queue.len() > MAX_EVENTS {
        queue.drain(..queue.len() - MAX_EVENTS);
    }
}

/// What became of a provisional reading: an event of [`AreaIndex::take_events`] and
/// [`crate::Disc::take_seek_events`].
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct SeekEvent {
    /// The area.
    pub slot: crate::Slot,
    /// The provisional reading, as the cursors that made it number it
    /// ([`crate::TrackCursor::speculation_id`]).
    pub claim: u64,
    /// Its verdict: [`Speculation::Confirmed`], [`Speculation::Refuted`] or
    /// [`Speculation::Unverified`].
    pub speculation: Speculation,
}

static NEXT_CLAIM: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);

/// The verdict on a provisional reading.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Verdict {
    Confirmed,
    Refuted { exact_from: u32 },
    Unverified,
}

/// A provisional reading (`L`, `u`), shared by the cursor that made it (and its
/// continuations) and the index that checks it.
#[derive(Debug)]
pub(crate) struct Claim {
    pub(crate) id: u64,
    slot: crate::Slot,
    first: u32,
    lsn: std::sync::atomic::AtomicU64,
    /// One more than the last position returned, 0 for none.
    returned: std::sync::atomic::AtomicU32,
    verdict: std::sync::Mutex<Option<Verdict>>,
    /// The image the reading read ([`Image::id`]), 0 until it reads: it is checked
    /// against that image only.
    image: std::sync::atomic::AtomicU64,
}

impl Claim {
    pub(crate) fn new(slot: crate::Slot, first: u32) -> std::sync::Arc<Self> {
        std::sync::Arc::new(Claim {
            id: NEXT_CLAIM.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
            slot,
            first,
            lsn: std::sync::atomic::AtomicU64::new(0),
            returned: std::sync::atomic::AtomicU32::new(0),
            verdict: std::sync::Mutex::new(None),
            image: std::sync::atomic::AtomicU64::new(0),
        })
    }

    /// Notes the image the reading reads.
    pub(crate) fn set_image(&self, id: u64) {
        self.image.store(id, std::sync::atomic::Ordering::Relaxed);
    }

    /// The image the reading read, if it has read.
    fn image(&self) -> Option<u64> {
        Some(self.image.load(std::sync::atomic::Ordering::Relaxed)).filter(|&id| id != 0)
    }

    pub(crate) fn set_lsn(&self, lsn: u64) {
        self.lsn.store(lsn, std::sync::atomic::Ordering::Relaxed);
    }

    pub(crate) fn lsn(&self) -> u64 {
        self.lsn.load(std::sync::atomic::Ordering::Relaxed)
    }

    /// Notes that position `t` was returned.
    #[inline]
    pub(crate) fn returned(&self, t: u32) {
        self.returned.fetch_max(t.saturating_add(1), std::sync::atomic::Ordering::Relaxed);
    }

    fn verdict(&self) -> Option<Verdict> {
        // Nothing panics while the lock is held.
        *self.verdict.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Settles the claim as confirmed from saved established state (4.2 item 9).
    pub(crate) fn confirm_saved(&self) {
        self.settle(Verdict::Confirmed);
    }

    /// Settles the claim, once: whether this call did.
    fn settle(&self, verdict: Verdict) -> bool {
        let mut v = self.verdict.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
        if v.is_some() {
            return false;
        }
        *v = Some(verdict);
        true
    }

    pub(crate) fn speculation(&self) -> Speculation {
        let (lsn, first) = (self.lsn(), self.first);
        match self.verdict() {
            None => Speculation::Pending { lsn, first },
            Some(Verdict::Confirmed) => Speculation::Confirmed { lsn, first },
            Some(Verdict::Refuted { exact_from }) => {
                let r = self.returned.load(std::sync::atomic::Ordering::Relaxed);
                Speculation::Refuted { lsn, first, last_returned: r.checked_sub(1), exact_from }
            }
            Some(Verdict::Unverified) => Speculation::Unverified { lsn, first },
        }
    }

    fn event(&self) -> SeekEvent {
        SeekEvent { slot: self.slot, claim: self.id, speculation: self.speculation() }
    }
}

/// The state of a provisional reading at a checkpoint boundary it crossed, after it had
/// resynchronised (delivered a frame): where its frame under assembly started (`back`, as
/// in [`Checkpoint`], at most [`REPLAY_SECTORS`]), the digest of the sector, and one more
/// than the largest frame number it had delivered complete (`seen`). Used only by later
/// provisional starts (never by exact ones), and not saved.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Provisional {
    pub(crate) back: u32,
    pub(crate) digest: u64,
    pub(crate) seen: u32,
    /// The number of the frame under assembly there, if any.
    pub(crate) under: Option<u32>,
}

/// The provisional checkpoints a provisional reading records.
#[derive(Debug)]
pub(crate) struct ProvisionalRecorder {
    interval: u64,
    next: u64,
    pub(crate) list: Vec<(u64, Provisional)>,
}

impl ProvisionalRecorder {
    /// A recorder of the boundaries `start + j x interval` after `from`.
    pub(crate) fn new(start: u64, from: u64, interval: u32) -> Box<Self> {
        let k = u64::from(interval.max(1));
        let next = start + (from - start) / k * k + k;
        Box::new(ProvisionalRecorder { interval: k, next, list: Vec::new() })
    }

    #[inline]
    pub(crate) fn due(&self, lsn: u64) -> bool {
        lsn == self.next
    }

    /// Records the boundary before sector `lsn`, if the reading has resynchronised.
    pub(crate) fn record(
        &mut self,
        lsn: u64,
        under: Option<(u64, u32)>,
        seen: u32,
        sector: &[u8; SECTOR_SIZE],
    ) {
        self.next += self.interval;
        let back = under.map_or(0, |(b, _)| b);
        if seen > 0 && back <= REPLAY_SECTORS {
            // At most REPLAY_SECTORS.
            let back = back as u32;
            let under = under.map(|(_, n)| n);
            self.list.push((lsn, Provisional { back, digest: digest(sector), seen, under }));
        }
    }
}

/// The seek hints a cursor records as it reads: sectors whose first frame record is at
/// least the spacing after the last one recorded (or below it).
#[derive(Clone, Debug)]
pub(crate) struct HintRecorder {
    spacing: u32,
    last: Option<u32>,
    pub(crate) list: Vec<(u32, u32)>,
    /// The last sector with a frame record seen and not recorded: recorded when the reading
    /// ends, so that the hints reach the end of what was read.
    tail: Option<(u32, u32)>,
    /// The reading has ended: whatever is recorded is news.
    flushed: bool,
}

/// Seek hints a cursor holds before an index takes them.
const HINTS_PER_TAKE: usize = 64;

impl HintRecorder {
    /// Notes sector `lsn`, whose bytes are `sector`.
    #[inline]
    pub(crate) fn see(&mut self, lsn: u64, sector: &[u8; SECTOR_SIZE]) {
        let Some(t) = first_record(sector) else { return };
        // Audio LSNs come from u32 fields.
        let Ok(lsn) = u32::try_from(lsn) else { return };
        if self.last.is_none_or(|l| t >= l.saturating_add(self.spacing) || t < l)
            && self.list.len() < MAX_HINTS
        {
            self.list.push((lsn, t));
            self.last = Some(t);
            self.tail = None;
        } else {
            self.tail = Some((lsn, t));
        }
    }

    /// The reading has ended: records the last sector seen, and makes the hints news.
    pub(crate) fn flush(&mut self) {
        if let Some(tail) = self.tail.take() {
            if self.list.len() < MAX_HINTS {
                self.list.push(tail);
            }
        }
        self.flushed = true;
    }

    /// The hints recorded, taken.
    pub(crate) fn take(&mut self) -> Vec<(u32, u32)> {
        self.flushed = false;
        std::mem::take(&mut self.list)
    }

    /// Whether enough hints wait for an index to take them, or the reading has ended.
    #[inline]
    pub(crate) fn has_news(&self) -> bool {
        self.list.len() >= HINTS_PER_TAKE || (self.flushed && !self.list.is_empty())
    }
}

/// A seek hint to begin at: (sector, its first record's frame number, the end of the read
/// to make there, and the digest the sector must have when a saved confirmation covers the
/// range).
pub(crate) type Hint = (u64, u32, u64, Option<u64>);

/// A provisional start still to be chosen: on the cursor's first read, from the area's
/// play time and the exact plan the cursor holds meanwhile.
#[derive(Debug)]
pub(crate) struct Speculate {
    pub(crate) first: u32,
    /// The range's end, to size the first read.
    pub(crate) end: u32,
    pub(crate) playtime: u32,
    pub(crate) interval: u32,
    pub(crate) options: SpeculativeOptions,
    /// The area's track starts (LSN, frame number), to steer the search.
    pub(crate) knots: Vec<(u64, u32)>,
    /// The exact start, used when the search finds nothing better.
    pub(crate) exact: Box<AreaCursor>,
    /// Where the exact start begins: the search looks past it.
    pub(crate) from: u64,
    /// A seek hint to begin at instead of searching: (sector, its first record's frame
    /// number, the end of the read to make there, and the digest the sector must have when
    /// a saved confirmation covers the range).
    pub(crate) hint: Option<Hint>,
}

/// The first frame record of a sector, as a frame number (specification 4, 4.3.2).
pub(crate) fn first_record(sector: &[u8]) -> Option<u32> {
    let header = *sector.first()?;
    let (f, k) = ((header >> 2) & 7, usize::from(header >> 5));
    if f == 0 {
        return None;
    }
    let r = 1 + 2 * k;
    let tc = sector.get(r..r + 3)?;
    Some((u32::from(tc[0]) * 60 + u32::from(tc[1])) * 75 + u32::from(tc[2]))
}

/// Most sectors one probe reads before giving up on finding a frame record (a DST frame
/// spans at most 31 sectors on well-formed discs, 4.3.3).
const PROBE_SPAN: u64 = 32;

/// The search stops once the sector found is estimated to lie at most this many sectors
/// before the frame wanted: reading them costs less than another probe.
///
/// Regula falsi aims this many sectors (and half a probe) early, so that a guess that is a
/// little off tends to land just before the frame wanted, which a read from there covers.
const ILLINOIS_MARGIN: u64 = 4;
const CLOSE_SECTORS: u64 = 16;

/// The most sectors the search and the read through the range's first frame are meant to
/// take together (144 KiB): the search reads all of a narrow enough interval at once within
/// it, and the read after a provisional start goes through the range's first frame and on
/// toward the range's estimated end only as far as it allows (if the first frame is further
/// than the budget reaches, the reads after it, toward the range's end, get it).
pub(crate) const FIRST_FRAME_BUDGET: u64 = 72;

/// The read calls a cold seek is meant to take through the range's first frame (issue #123):
/// the read that would be the last of them reads all of [`LAST_READ_BUDGET`] that is left, so
/// that it can end the search and hold the first frame at once.
const SEARCH_CALLS: u32 = 5;

/// The most sectors the search may take when its last read under [`SEARCH_CALLS`] reads all
/// that is left (160 KiB): a little more than [`FIRST_FRAME_BUDGET`], which the other reads
/// keep to.
const LAST_READ_BUDGET: u64 = 80;

/// Most sectors a cursor reads in one call (1 MiB): after a provisional start, a cursor reads
/// up to the range's estimated end in calls of up to this many sectors, and after a resume
/// from a seek index its first read is sized to the range (at most the replay, the interval
/// and 64 sectors); every other read is at most 32 sectors. A sized read trades bytes for
/// round trips: a range of a frame or two after a resume reads up to `W + K + 64` sectors in
/// one call where 32-sector reads would have stopped earlier in two or three, and a failing
/// device fails that one read before frames the smaller reads would have returned. A cancellation request ([`crate::CancelToken`]) that arrives during
/// such a read takes effect once it completes.
pub const MAX_READ_SECTORS: u64 = 512;

/// What [`locate`] found.
#[derive(Debug)]
pub(crate) struct Located {
    /// The sector found (the search interval's start if none): its first frame record is
    /// numbered below the frame wanted.
    pub(crate) lsn: u64,
    /// The reads made.
    pub(crate) reads: u32,
    /// The last read that holds `lsn`, as (first sector, bytes), to read on from.
    pub(crate) chunk: Option<(u64, Vec<u8>)>,
    /// The frame number of `lsn`'s first record (0 if none was found).
    pub(crate) frame: u32,
    /// Sectors per frame around `lsn`, as (sectors, frames), frames at least 1.
    pub(crate) density: (u64, u32),
    /// Whether the first frame records the probes read decrease from one sector to a later
    /// one (a reason to mark the reading suspect, 4.2 item 8).
    pub(crate) decreasing: bool,
    /// The sectors the probes read.
    pub(crate) used: u64,
}

/// The point to interpolate the frame `first` between, within `[lo, hi)`: the tightest of the
/// bounds and the knots (track starts) inside it, which steer the guess but never narrow the
/// interval (a hostile TOC costs probes, not correctness).
fn bracket(lo: (u64, u32), hi: (u64, u32), knots: &[(u64, u32)], first: u32) -> ((u64, u32), (u64, u32)) {
    let inside = |&&(l, t): &&(u64, u32)| l > lo.0 && l < hi.0 && t >= lo.1 && t <= hi.1;
    // The nearest frame numbers on each side, then the nearest sectors.
    let a = knots
        .iter()
        .filter(inside)
        .filter(|k| k.1 <= first)
        .max_by_key(|k| (k.1, k.0))
        .copied()
        .unwrap_or(lo);
    let b = knots
        .iter()
        .filter(inside)
        .filter(|k| k.1 > first && k.0 > a.0)
        .min_by_key(|k| (k.1, k.0))
        .copied()
        .unwrap_or(hi);
    if b.1 > a.1 { (a, b) } else { (lo, hi) }
}

/// Searches `[lo, hi)` for a sector whose first frame record's timecode is below
/// `first`, as close before the frame numbered `first` as the probes allow (see
/// [`Located`]). `knots` are (LSN, frame number) points to interpolate between, such as
/// the track starts. `on_read` is told the sectors of each read; a cancellation request
/// ([`crate::CancelToken`]) is honoured before each.
pub(crate) fn locate<R: Read + Seek>(
    image: &mut Image<R>,
    (mut lo, mut hi): (u64, u64),
    (first, playtime): (u32, u32),
    knots: &[(u64, u32)],
    options: &SpeculativeOptions,
    on_read: &mut dyn FnMut(u64),
) -> Result<Located, Error> {
    let per = u64::from(options.probe_sectors.clamp(1, 32));
    // Specification 7, 7.1 item 3: at most a constant times log2(n + 1) sectors.
    let n = hi.saturating_sub(lo);
    let log = u64::BITS - n.leading_zeros();
    let max = options.max_probes.min(2 * log + 4);
    // A read that ends the search may read past `hi`, up to the interval's end.
    let end = hi;
    let mut buf = vec![0u8; per.max(LAST_READ_BUDGET) as usize * SECTOR_SIZE];
    let (mut lo_t, mut hi_t) = (0u32, playtime.max(first.saturating_add(1)));
    // Whether `hi` comes from a probe (not from the interval's end), and the Illinois halvings
    // of each bound's weight in regula falsi, with the bound the last step moved.
    let mut hi_probed = false;
    let (mut halved_lo, mut halved_hi, mut moved) = (0u32, 0u32, None::<bool>);
    let (mut reads, mut halve, mut found_lo, mut slow) = (0u32, false, false, 0u32);
    let mut chunk: Option<(u64, Vec<u8>)> = None;
    // The records the last two probes found nearest `first` (sector, frame number), and the
    // last probe's own sectors per frame (sectors, frames): on a disc of uneven bit rate
    // they predict the frame's sector better than an average over a long interval.
    let (mut anchor, mut previous) = (None::<(u64, u32)>, None::<(u64, u32)>);
    let mut local: Option<(u64, u32)> = None;
    // The area's average sectors per frame.
    let average = (n, playtime.max(1));
    // Sectors per frame near the anchor: between the last two anchors when they are at
    // least 3 frames apart, else the last probe's when it saw 2 records or more, else the
    // area's average.
    let density = |anchor: Option<(u64, u32)>, previous: Option<(u64, u32)>, local: Option<(u64, u32)>| {
        let secant = anchor.zip(previous).and_then(|((m, t), (pm, pt))| {
            let (s, f) = (m.abs_diff(pm), t.abs_diff(pt));
            (f >= 3 && (m > pm) == (t > pt)).then_some((s, f))
        });
        secant.or(local).unwrap_or(average)
    };
    let sectors = |(s, f): (u64, u32), frames: u32| {
        u64::try_from(u128::from(frames) * u128::from(s) / u128::from(f.max(1))).unwrap_or(u64::MAX)
    };
    // Every (sector, first record) the probes read, to see whether they decrease.
    let mut records: Vec<(u64, u32)> = Vec::new();
    let mut used = 0u64;
    // The probes aim at the start of the frame before `first`, whose record must be found
    // below `first`.
    let want = first.saturating_sub(1);
    while hi - lo > PROBE_SPAN && reads < max {
        let mut d = density(anchor, previous, local);
        if found_lo && sectors(d, first - lo_t) <= CLOSE_SECTORS {
            break;
        }
        let ((a, a_t), (b, b_t)) = bracket((lo, lo_t), (hi, hi_t), knots, first);
        // The first correction after the first probe: the geometric mean of that probe's own
        // density and the average back to the knot on the other side of `first`. Where the
        // density changes along the way (a loud passage after a quiet one), the first is too
        // high and the second too low.
        if previous.is_none() {
            if let (Some((m, t)), Some((ls, lf))) = (anchor, local) {
                let (om, ot) = if t > first { (a, a_t) } else { (b, b_t) };
                if ot != t && om != m {
                    let avg = m.abs_diff(om) as f64 / f64::from(t.abs_diff(ot));
                    let mean = (avg * ls as f64 / f64::from(lf)).sqrt();
                    d = ((mean * 1024.0) as u64, 1024);
                }
            }
        }
        let guess = if found_lo && hi_probed {
            // Regula falsi between the two probed bounds, the Illinois way: a bound kept by
            // two steps in a row has its weight halved, so that the guesses do not creep up
            // on `first` from one side. Half a probe and a few sectors early.
            let fl = u128::from(want - lo_t) << (32 - halved_lo.min(32));
            let fh = u128::from(hi_t.saturating_sub(want)) << (32 - halved_hi.min(32));
            let x = lo + (u128::from(hi - lo) * fl / (fl + fh).max(1)) as u64;
            x.saturating_sub(per / 2 + ILLINOIS_MARGIN)
        } else if halve {
            a + (b - a) / 2
        } else if let Some((m, t)) = anchor {
            // From the last probe's record at the local density, half a probe early.
            let dist = sectors(d, want.abs_diff(t));
            if want >= t { m.saturating_add(dist) } else { m.saturating_sub(dist) }.saturating_sub(per / 2)
        } else {
            let num = u128::from(first.saturating_sub(a_t));
            let den = u128::from(b_t.saturating_sub(a_t).max(1));
            // Half a probe before the estimate, so that the probe tends to straddle it.
            (a + (u128::from(b - a) * num / den) as u64).saturating_sub(per / 2)
        }
        .clamp(lo + 1, hi - 1);
        // The frames between `first` and the nearest bound, which each step must halve.
        let gap = |a_t: u32, b_t: u32| first.saturating_sub(a_t).min(b_t.saturating_sub(first));
        let before = gap(a_t, b_t);
        // One probe: from `guess`, `per` sectors at a time, until a record, starting reads
        // only below `guess + PROBE_SPAN` (the last may end up to `per - 1` past it) and
        // below `hi`, so a record found lies in `[guess, hi)`. Every record of the read
        // counts: the last sector whose first record is below `first`, and the first after
        // it whose first record is not.
        let (mut below, mut above, mut any) = (None, None, None);
        let mut last: Option<(u64, u32)> = None;
        let (mut guess, mut size, mut final_read) = (guess, per, false);
        let left = FIRST_FRAME_BUDGET.saturating_sub(used);
        if hi_probed {
            // Frame `first` starts a few frames before `hi`: read back from there, through
            // `hi`, at the highest density seen, if that fits what is left of the budget.
            let dense = [d, average, local.unwrap_or(average)]
                .into_iter()
                .max_by(|x, y| (u128::from(x.0) * u128::from(y.1)).cmp(&(u128::from(y.0) * u128::from(x.1))))
                .unwrap_or(average);
            let back = sectors(dense, hi_t.saturating_sub(first) + 1);
            let start = hi.saturating_sub(back + back / 8 + 4).max(if found_lo { lo } else { 0 });
            if hi + 1 - start <= left {
                (guess, size, final_read) = (start, hi + 1 - start, true);
            } else if found_lo && hi - lo <= left && left > per {
                // The whole interval at once: frame `first` starts in it.
                (guess, size, final_read) = (lo, hi - lo, true);
            }
        }
        // The last read under `SEARCH_CALLS` reads what is left of `LAST_READ_BUDGET`, so that
        // it holds frame `first` too: on from where a final read starts; otherwise around the
        // guess, more of it before than after (the guesses of regula falsi fall on the same
        // side where the bit rate changes, and frame `first` takes some sectors after its
        // start). If it finds no sector below `first`, the search goes on.
        let rest = LAST_READ_BUDGET.saturating_sub(used);
        let mut chance = false;
        if reads + 1 == SEARCH_CALLS && rest > size {
            if final_read {
                size = rest.min(hi.saturating_add(PROBE_SPAN) - guess).max(size);
            } else {
                guess = (guess + per / 2).saturating_sub(rest * 5 / 8).max(lo + 1);
                (size, final_read, chance) = (rest, true, true);
            }
        }
        let mut at = guess;
        while any.is_none() && at < hi.min(guess + PROBE_SPAN.max(size)) && reads < max {
            // A final read is not cut at `hi`: the sectors after it hold the rest of frame
            // `first`, and the search ends with it.
            let count = size.min(if final_read { end } else { hi } - at);
            let read = &mut buf[..count as usize * SECTOR_SIZE];
            image.check_cancel()?;
            if image.read_into(at, read)? == crate::image::ReadOutcome::OutOfRange {
                return Err(Error::InvalidArgument("audio sectors outside the image"));
            }
            on_read(count);
            reads += 1;
            used += count;
            for i in 0..count {
                let Some(t) = first_record(&read[i as usize * SECTOR_SIZE..]) else { continue };
                records.push((at + i, t));
                any = any.or(Some((at + i, t)));
                last = Some((at + i, t));
                if t < first {
                    (below, above) = (Some((at + i, t)), None);
                } else if below.is_some() && above.is_none() {
                    above = Some((at + i, t));
                }
            }
            if below.is_some() {
                chunk = Some((at, read.to_vec()));
            }
            at += count;
        }
        if let (Some((m1, t1)), Some((m2, t2))) = (any, last) {
            previous = anchor;
            anchor = Some(below.unwrap_or((m1, t1)));
            local = (m2 > m1 && t2 > t1).then(|| (m2 - m1, t2 - t1));
        }
        let found_now = below.is_some();
        match (below, any.map(|(_, t)| t)) {
            (Some((m, t)), _) => {
                (lo, lo_t, found_lo) = (m, t, true);
                (halved_lo, halved_hi) = (0, if moved == Some(false) { halved_hi + 1 } else { 0 });
                moved = Some(false);
                if above.is_some() {
                    // Frame `first` starts within this read: done.
                    break;
                }
            }
            (None, Some(t)) => {
                (hi, hi_t, hi_probed) = (guess, t.max(lo_t.saturating_add(1)), true);
                (halved_hi, halved_lo) = (0, if moved == Some(true) { halved_lo + 1 } else { 0 });
                moved = Some(true);
            }
            (None, None) => hi = guess,
        }
        if final_read && (found_now || !chance) {
            break;
        }
        // Two steps in a row that did not at least halve the frames between `first` and the
        // nearest bound are followed by a bisection (of the interval between the tightest
        // knots): the first such step gives the secant its second point.
        let ((_, a_t), (_, b_t)) = bracket((lo, lo_t), (hi, hi_t), knots, first);
        slow = if halve || gap(a_t, b_t).saturating_mul(2) <= before { 0 } else { slow + 1 };
        halve = slow >= 2;
    }
    let chunk =
        chunk.filter(|(at, bytes)| found_lo && (*at..*at + (bytes.len() / SECTOR_SIZE) as u64).contains(&lo));
    // For sizing the read that follows, the larger of the two: reading a few sectors too
    // many costs less than another call.
    let density = [density(anchor, previous, local), average]
        .into_iter()
        .max_by(|a, b| (u128::from(a.0) * u128::from(b.1)).cmp(&(u128::from(b.0) * u128::from(a.1))))
        .unwrap_or(average);
    records.sort_unstable_by_key(|r| r.0);
    let decreasing = records.windows(2).any(|w| w[1].1 < w[0].1);
    Ok(Located { lsn: lo, reads, chunk, frame: lo_t, density, decreasing, used })
}

/// The reading state of the scan at a boundary `c = S0 + jK`, before sector `c`
/// (specification 4, 4.4.1 and 4.5): `a`, the malformed sectors before `c`, and where the
/// frame under assembly started.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Checkpoint {
    /// `a` at `c`.
    pub(crate) next_acceptable: u32,
    /// `c - r` for a frame under assembly that started in sector `r`, 0 for none.
    pub(crate) back: u32,
    /// Malformed sectors in `[S0, c)`.
    pub(crate) malformed_before: u64,
    /// FNV-1a of sector `c`, the first sector a resume reads after its replay.
    pub(crate) digest: u64,
}

/// The bytes of a frame under assembly that started in sector `start`: the longest prefix
/// any checkpoint holds. A frame under assembly only grows, so the checkpoints within one
/// frame share one buffer, and a frame spread over many checkpoints costs its bytes once.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Frame {
    pub(crate) start: u64,
    pub(crate) bytes: Vec<u8>,
}

/// The frame under assembly of the checkpoint numbered `at`: the first `len` bytes of
/// frame `frame`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Held {
    pub(crate) at: u32,
    pub(crate) frame: u32,
    pub(crate) len: u32,
    pub(crate) number: u32,
    pub(crate) kind: FrameKind,
    pub(crate) remaining: i32,
}

/// Stored frames under assembly, by increasing checkpoint number and start sector.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Stored {
    pub(crate) frames: Vec<Frame>,
    pub(crate) held: Vec<Held>,
    /// Bytes of `frames`.
    pub(crate) used: usize,
}

impl Stored {
    /// Stores the frame under assembly of checkpoint `at` (after every one stored), which
    /// started in sector `start` and holds `data`, if its new bytes fit in `budget` bytes
    /// in all: whether it was stored. Bytes the last frame already holds cost nothing.
    pub(crate) fn add(
        &mut self,
        at: u32,
        start: u64,
        (number, kind, remaining): (u32, FrameKind, i32),
        data: &[u8],
        budget: usize,
    ) -> bool {
        if data.len() > MAX_FRAME_BYTES {
            return false;
        }
        let frame = match self.frames.last_mut() {
            Some(f) if f.start == start => {
                let common = f.bytes.len().min(data.len());
                // Always a prefix of the same frame; anything else is not stored.
                if f.bytes[..common] != data[..common] {
                    return false;
                }
                let grow = data.len() - common;
                if self.used + grow > budget {
                    return false;
                }
                f.bytes.extend_from_slice(&data[common..]);
                self.used += grow;
                self.frames.len() - 1
            }
            _ => {
                if self.used + data.len() > budget {
                    return false;
                }
                self.frames.push(Frame { start, bytes: data.to_vec() });
                self.used += data.len();
                self.frames.len() - 1
            }
        };
        // At most MAX_FRAME_BYTES bytes, and fewer frames than checkpoints.
        let (frame, len) = (frame as u32, data.len() as u32);
        self.held.push(Held { at, frame, len, number, kind, remaining });
        true
    }

    /// The frame under assembly of checkpoint `at`, if stored.
    pub(crate) fn get(&self, at: u32) -> Option<(&Held, &[u8])> {
        let h = &self.held[self.held.binary_search_by_key(&at, |h| h.at).ok()?];
        Some((h, self.bytes(h)))
    }

    pub(crate) fn bytes(&self, h: &Held) -> &[u8] {
        self.frames.get(h.frame as usize).and_then(|f| f.bytes.get(..h.len as usize)).unwrap_or(&[])
    }

    fn memory(&self) -> usize {
        self.held.capacity() * std::mem::size_of::<Held>()
            + self.frames.capacity() * std::mem::size_of::<Frame>()
            + self.frames.iter().map(|f| f.bytes.capacity()).sum::<usize>()
    }

    /// Copies the frame under assembly of `other`'s checkpoint `at` (which started in
    /// sector `start`) as this one's, within `budget`.
    fn take(&mut self, other: &Stored, at: u32, start: u64, budget: usize) {
        if let Some((h, bytes)) = other.get(at) {
            self.add(at, start, (h.number, h.kind, h.remaining), bytes, budget);
        }
    }
}

/// The state once the scan has ended (specification 4, 4.4.4).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct EndState {
    /// `a` after the last delivery.
    pub(crate) next_acceptable: u32,
    /// Malformed sectors of the area.
    pub(crate) malformed: u64,
}

/// How a cursor made from an index starts.
#[derive(Debug)]
pub(crate) enum Plan<'a> {
    /// At the area's first audio sector.
    Start,
    /// At a checkpoint.
    At {
        lsn: u64,
        checkpoint: Checkpoint,
        /// Its frame under assembly when stored, else replayed from `lsn - back`.
        held: Option<(&'a Held, &'a [u8])>,
    },
    /// After the end.
    End(EndState),
}

/// The frame under assembly at a boundary, as the cursor holds it.
pub(crate) struct Assembling<'a> {
    pub(crate) start_lsn: u64,
    pub(crate) number: u32,
    pub(crate) kind: FrameKind,
    pub(crate) remaining: i32,
    pub(crate) data: &'a [u8],
}

/// FNV-1a (64-bit) of a sector.
pub(crate) fn digest(sector: &[u8; SECTOR_SIZE]) -> u64 {
    sector.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3))
}

// Indexes are built on one thread and used on others.
const _: () = {
    const fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<AreaIndex>();
};

/// Saved reading state of one area: the scan's state every [`IndexOptions::interval`]
/// sectors from the area's first audio sector up to the index's frontier, so that a cursor
/// can start a frame range there instead of at the first sector (see the [module
/// documentation](self)).
///
/// # One index per image
///
/// An index holds the reading state of one area of **one image**. Its key (the area's
/// slot, audio sector range and channel count, and the image's sector count) cannot tell
/// apart two images of the same size and layout, such as two rips of one disc, and an index
/// fed from both would mix their state: a later read of one could report the other's
/// malformed sectors and warnings, or frames under assembly, with no error. So within a
/// process, an index is of the image of the first cursor it takes checkpoints from
/// ([`AreaIndex::absorb`], [`AreaIndex::extend`]; [`crate::Image::id`], which the discs
/// made by [`crate::Disc::share`] and `clone` share), and refuses cursors and reads of any
/// other. A provisional reading it takes ([`SeekPolicy`]) binds it the same way, and the
/// reading is checked only against the image it read. That identity is not saved: an index loaded with [`AreaIndex::from_bytes`] (or
/// given to [`crate::Disc::set_seek_index`]) takes the image of its first absorb or
/// extend, and is trusted to be of it (loading is safe, not exact; see the [module
/// documentation](self#trust)).
///
/// # Memory
///
/// At most 24 bytes per `K` existing audio sectors (one checkpoint each), plus the
/// frames under assembly stored within [`IndexOptions::inline_budget`] (each at most
/// [`MAX_FRAME_BYTES`]), plus the LSNs of the first [`MAX_MALFORMED_WARNINGS`] malformed
/// sectors (16 KiB): [`AreaIndex::memory`] reports it. A 50-minute 2-channel DST area
/// (475 000 sectors) at `K = 64` takes about 180 KB.
///
/// # Seek hints
///
/// An index also keeps **seek hints** (the locator samples of specification 4, 4.2 item 8,
/// sacd-spec `cb9530b`): sectors whose first frame record its cursors read, with that
/// record's frame number, at least [`IndexOptions::hint_spacing`] frames apart, at most
/// [`IndexOptions::max_hints`] of them (8 bytes each). They are saved with the index, so
/// that after a remount a provisional reading ([`SeekPolicy::Speculative`]) of a range near
/// one read before needs no search: it begins at the hint with the largest frame number
/// below the range's first frame (at most [`HINT_REACH`] frames below), and reads from
/// there through the next hint past the range in **one read call** (at most
/// [`MAX_READ_SECTORS`]). A hint only chooses `L`: the positions are provisional
/// ([`Speculation::Pending`]) as from any provisional start, whatever the hint says, unless
/// a saved confirmation covers them (below). The hint's sector is read anyway; if its first record is not the hint's, the
/// hints are of another image or a stale one: the cursor logs a warning, searches as
/// without hints, and the index drops them.
///
/// A disc that keeps the index ([`crate::Disc::enable_seek_index`],
/// [`crate::Disc::set_seek_index`]) also gives it a fingerprint of its TOC (the image's
/// sector count and format, the master TOC's version, album and disc catalogue numbers,
/// genres, area pointers, flags and date, and the area TOC's fields and track list; not
/// text), saved with it: a disc with another TOC refuses it, at no cost in reads.
///
/// # Saved confirmations
///
/// Saved confirmations are used and kept only by an index whose TOC fingerprint a disc of
/// this process has checked against its own TOC ([`crate::Disc::enable_seek_index`],
/// [`crate::Disc::set_seek_index`]; not saved): an index loaded with
/// [`AreaIndex::from_bytes`] and used directly (`for_range_speculative`,
/// `for_range_indexed`, [`AreaIndex::extend`]) keeps its readings provisional and records
/// no confirmation, whatever image it reads.
///
/// When verification ([`AreaIndex::verify`]) confirms a provisional reading from `L` for
/// positions `u_L` or more, such an index keeps (`L`, `u_L`) and the
/// digest of sector `L`, and saves them (16 bytes each, at most
/// [`IndexOptions::max_hints`]). What that pass established, (a) and (b) of 4.2 item 8 at
/// `L`, holds for every later reading from `L` with `u >= u_L`, and stays established after
/// saving and loading for an image whose sectors before `L` are the bytes the pass read
/// (specification 4, 4.2 item 9, sacd-spec `cb9530b`). So a hinted reading from such an `L`
/// for `u >= u_L` is reported [`Speculation::Confirmed`] at once, without another pass,
/// when the index is bound to this disc (its key and TOC fingerprint, checked by
/// [`crate::Disc::set_seek_index`]) and sector `L`, read anyway, has the digest kept. That
/// sameness check is the index's trust model ([module documentation](self#trust)): it covers
/// the sectors before `L` by the disc's identity, not by reading them; an index saved for one
/// image and loaded for a re-rip of the same disc with the same TOC and a different sector
/// before `L` would be trusted. **Trust boundary:** saved confirmations, like saved exact
/// checkpoints, are trusted for any image whose TOC fingerprint and key match, so a re-rip
/// with different audio bytes would get confirmed readings that differ from its own; key
/// saved indexes by the image file's identity (path, size and modification time, or a
/// content hash) as well.
// Specification 7, 7.1 item 2 (sacd-spec `cb9530b`): saved locator samples, a constant
// number of bytes each, their number chosen by the caller and checked when loaded.
// Specification 7, 7.1 item 2 (sacd-spec `da6b900`): a constant number of bytes per
// existing audio sector, plus at most one 65 536-byte frame under assembly per saved state
// that holds one, their number chosen by the caller (the inline budget).
#[derive(Clone, Debug)]
pub struct AreaIndex {
    key: AreaKey,
    /// The area's existing audio sectors, `[start, end)`.
    start: u64,
    end: u64,
    interval: u32,
    inline_budget: usize,
    /// The checkpoints at `start + j x interval`, `j = 0, 1, ...`, without gaps.
    checkpoints: Vec<Checkpoint>,
    /// Stored frames under assembly.
    stored: Stored,
    end_state: Option<EndState>,
    /// The first [`MAX_MALFORMED_WARNINGS`] malformed sectors below the frontier.
    malformed: Vec<u32>,
    /// The image of the first cursor this index took checkpoints from ([`Image::id`],
    /// unique within the process; not saved), whose cursors alone it takes from then on.
    image_id: Option<u64>,
    /// Provisional readings waiting to be checked (not saved).
    claims: Vec<std::sync::Arc<Claim>>,
    /// Provisional checkpoints past the frontier, for provisional starts only (not saved).
    provisional: std::collections::BTreeMap<u64, Provisional>,
    /// Verdicts not yet taken.
    events: Vec<SeekEvent>,
    /// Seek hints: (sector, its first frame record's number), by increasing sector.
    samples: Vec<(u32, u32)>,
    hint_spacing: u32,
    max_hints: usize,
    /// The disc's TOC fingerprint ([`toc_fingerprint`]), once a disc kept the index.
    fingerprint: Option<u64>,
    /// Whether a disc of this process checked the fingerprint against its own TOC
    /// ([`AreaIndex::bind_fingerprint`]): only then are confirmations used or kept (4.2
    /// item 9). Not saved: a loaded index has it only once a disc has checked it.
    fingerprint_checked: bool,
    /// Established provisional starts (specification 4, 4.2 item 9): (`L`, `u_L`, digest of
    /// sector `L`), by increasing `L`, for an index with a fingerprint.
    confirmed: Vec<(u32, u32, u64)>,
}

/// Two indexes are equal when they hold the same reading state: the image they were
/// built from in this process is not part of it.
impl PartialEq for AreaIndex {
    fn eq(&self, other: &Self) -> bool {
        (self.key, self.start, self.end, self.interval, self.inline_budget)
            == (other.key, other.start, other.end, other.interval, other.inline_budget)
            && self.checkpoints == other.checkpoints
            && self.stored == other.stored
            && self.end_state == other.end_state
            && self.malformed == other.malformed
    }
}

impl Eq for AreaIndex {}

impl AreaIndex {
    /// An empty index of `area` in an image of `image_sectors` sectors: its frontier is the
    /// area's first audio sector.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidArgument`] if the interval is not 1 to [`MAX_INTERVAL`].
    pub fn new(area: &Area, image_sectors: u64, options: IndexOptions) -> Result<Self, Error> {
        if !(1..=MAX_INTERVAL).contains(&options.interval) {
            return Err(Error::InvalidArgument("seek index interval must be 1 to 65536"));
        }
        let (start, end) = audio_sector_range(area, image_sectors);
        Ok(AreaIndex {
            key: AreaKey::new(area, image_sectors),
            start,
            end,
            interval: options.interval,
            inline_budget: options.inline_budget,
            checkpoints: Vec::new(),
            stored: Stored::default(),
            end_state: None,
            malformed: Vec::new(),
            image_id: None,
            claims: Vec::new(),
            provisional: std::collections::BTreeMap::new(),
            events: Vec::new(),
            samples: Vec::new(),
            hint_spacing: options.hint_spacing,
            max_hints: options.max_hints.min(MAX_HINTS),
            fingerprint: None,
            fingerprint_checked: false,
            confirmed: Vec::new(),
        })
    }

    /// The options the index was made with.
    pub fn options(&self) -> IndexOptions {
        IndexOptions {
            interval: self.interval,
            inline_budget: self.inline_budget,
            hint_spacing: self.hint_spacing,
            max_hints: self.max_hints,
        }
    }

    /// The LSN up to which the index holds the scan's state: the area's first audio sector
    /// for an empty index, one past its last for a complete one.
    pub fn frontier(&self) -> u64 {
        if self.end_state.is_some() {
            self.end
        } else {
            self.checkpoint_lsn(self.checkpoints.len().saturating_sub(1))
        }
    }

    /// Whether the index covers the whole area: every range can then be opened from it.
    pub fn is_complete(&self) -> bool {
        self.end_state.is_some()
    }

    /// The number of checkpoints held.
    pub fn checkpoints(&self) -> usize {
        self.checkpoints.len()
    }

    /// The bytes the index holds, for the caller's accounting (see [Memory](Self#memory)).
    pub fn memory(&self) -> usize {
        std::mem::size_of::<Self>()
            + self.checkpoints.capacity() * std::mem::size_of::<Checkpoint>()
            + self.stored.memory()
            + self.malformed.capacity() * std::mem::size_of::<u32>()
            + self.samples.capacity() * std::mem::size_of::<(u32, u32)>()
            + self.confirmed.capacity() * std::mem::size_of::<(u32, u32, u64)>()
    }

    /// This index without its exact checkpoints (an empty frontier) but with its seek hints,
    /// saved confirmations and TOC fingerprint: a few kilobytes to save for an area instead of
    /// about 24 bytes per interval, for a caller that keeps many discs' state and accepts
    /// provisional (or, from saved confirmations, confirmed) readings after a remount.
    pub fn without_checkpoints(&self) -> AreaIndex {
        AreaIndex { samples: self.samples.clone(), confirmed: self.confirmed.clone(), ..self.empty_clone() }
    }

    /// A copy of the key, options, image and fingerprint, with nothing recorded.
    fn empty_clone(&self) -> AreaIndex {
        AreaIndex {
            key: self.key,
            start: self.start,
            end: self.end,
            interval: self.interval,
            inline_budget: self.inline_budget,
            checkpoints: Vec::new(),
            stored: Stored::default(),
            end_state: None,
            malformed: Vec::new(),
            image_id: self.image_id,
            claims: Vec::new(),
            provisional: std::collections::BTreeMap::new(),
            events: Vec::new(),
            samples: Vec::new(),
            hint_spacing: self.hint_spacing,
            max_hints: self.max_hints,
            fingerprint: self.fingerprint,
            fingerprint_checked: self.fingerprint_checked,
            confirmed: Vec::new(),
        }
    }

    /// The provisional starts confirmed and kept (see [Saved
    /// confirmations](Self#saved-confirmations)).
    pub fn confirmations(&self) -> usize {
        self.confirmed.len()
    }

    /// Keeps that a provisional reading from `lsn` for positions `u` or more was confirmed
    /// (4.2 item 9), with the digest of sector `lsn`: the smallest `u` per sector, at most
    /// [`IndexOptions::max_hints`] of them (the lowest sectors go first), and only for an
    /// index bound to a disc's TOC.
    fn keep_confirmation(&mut self, lsn: u64, u: u32, digest: u64) {
        let Ok(lsn) = u32::try_from(lsn) else { return };
        if !self.fingerprint_checked || self.max_hints == 0 {
            return;
        }
        match self.confirmed.binary_search_by_key(&lsn, |c| c.0) {
            Ok(i) if self.confirmed[i].2 == digest => self.confirmed[i].1 = self.confirmed[i].1.min(u),
            Ok(i) => self.confirmed[i] = (lsn, u, digest),
            Err(i) => self.confirmed.insert(i, (lsn, u, digest)),
        }
        if self.confirmed.len() > self.max_hints {
            self.confirmed.remove(0);
        }
    }

    /// The saved confirmation of a provisional start at `lsn` for positions `u` or more:
    /// the digest sector `lsn` must have (4.2 item 9: established for `u_L <= u`).
    pub(crate) fn confirmation(&self, lsn: u64, u: u32) -> Option<u64> {
        if !self.fingerprint_checked {
            return None;
        }
        let lsn = u32::try_from(lsn).ok()?;
        let i = self.confirmed.binary_search_by_key(&lsn, |c| c.0).ok()?;
        let (_, u_l, digest) = self.confirmed[i];
        (u_l <= u).then_some(digest)
    }

    /// The seek hints held (see [Seek hints](Self#seek-hints)).
    pub fn hints(&self) -> usize {
        self.samples.len()
    }

    /// A recorder of seek hints for a cursor made from this index, if it keeps any.
    pub(crate) fn hint_recorder(&self) -> Option<Box<HintRecorder>> {
        (self.hint_spacing > 0 && self.max_hints > 0).then(|| {
            Box::new(HintRecorder {
                spacing: self.hint_spacing,
                last: None,
                list: Vec::new(),
                tail: None,
                flushed: false,
            })
        })
    }

    /// Takes seek hints a cursor recorded (spaced as it recorded them, plus where its reading
    /// ended): merged by sector, and, past [`IndexOptions::max_hints`], thinned to three
    /// quarters of it (see [`AreaIndex::thin_hints`]).
    pub(crate) fn add_hints(&mut self, list: Vec<(u32, u32)>) {
        if list.is_empty() || self.max_hints == 0 {
            return;
        }
        let (start, end) = (self.start, self.end);
        let after = self.samples.last().map_or(0, |s| u64::from(s.0) + 1);
        let sorted = list.windows(2).all(|w| w[0].0 < w[1].0);
        let ahead = sorted && list.first().is_some_and(|s| u64::from(s.0) >= after);
        self.samples.extend(list.into_iter().filter(|&(l, _)| (start..end).contains(&u64::from(l))));
        if !ahead {
            self.samples.sort_unstable_by_key(|s| s.0);
            self.samples.dedup_by_key(|s| s.0);
        }
        if self.samples.len() > self.max_hints {
            // Down to three quarters, so that a long reading thins rarely.
            self.thin_hints(self.max_hints - self.max_hints / 4);
        }
    }

    /// Keeps at most `most` seek hints, dropping those closest (in frames) to the one before
    /// them: the regions read keep a hint each, and long reads get sparser.
    pub(crate) fn thin_hints(&mut self, most: usize) {
        let excess = self.samples.len().saturating_sub(most);
        if excess == 0 {
            return;
        }
        let gap = |i: usize| match i.checked_sub(1).map(|p| self.samples[p].1) {
            Some(p) if p < self.samples[i].1 => self.samples[i].1 - p,
            _ => u32::MAX,
        };
        let mut order: Vec<(u32, usize)> = (0..self.samples.len()).map(|i| (gap(i), i)).collect();
        order.sort_unstable();
        let mut drop = vec![false; self.samples.len()];
        for &(_, i) in order.iter().take(excess) {
            drop[i] = true;
        }
        let mut i = 0;
        self.samples.retain(|_| {
            i += 1;
            !drop[i - 1]
        });
    }

    /// Drops the seek hints: one did not match the image.
    pub(crate) fn drop_hints(&mut self) {
        self.samples = Vec::new();
    }

    /// The seek hint to begin a range `[first, end)` at (see [Seek hints](Self#seek-hints)):
    /// among the samples at most [`HINT_REACH`] frames below `first`, the one with the
    /// largest frame number (the last of those, if several) of a reading confirmed for
    /// `first` ([Saved confirmations](Self#saved-confirmations)) if any, else of all, and the end of the read to make
    /// there: through the first later sample numbered `end` or more, if at most
    /// [`HINT_REACH`] frames past it (`true`), or else the
    /// range's frames at the density of the samples before it (at least the area's average
    /// over `playtime` frames), plus a quarter and a few sectors (`false`).
    pub(crate) fn hint(&self, first: u32, end: u32, playtime: u32) -> Option<(u64, u32, u64, bool)> {
        let below =
            || self.samples.iter().enumerate().filter(|(_, s)| s.1 < first && first - s.1 <= HINT_REACH);
        // A hint whose reading was confirmed for this range first (4.2 item 9), then the
        // nearest.
        let (i, &(lsn, t)) = below()
            .filter(|(_, s)| self.confirmation(u64::from(s.0), first).is_some())
            .max_by_key(|(_, s)| (s.1, s.0))
            .or_else(|| below().max_by_key(|(_, s)| (s.1, s.0)))?;
        let lsn = u64::from(lsn);
        let next = self.samples[i + 1..].iter().find(|s| s.1 >= end);
        if let Some(&(l, _)) = next.filter(|s| s.1 - end <= HINT_REACH) {
            return Some((lsn, t, u64::from(l) + 1, true));
        }
        // From the last sample of this run below `end` (the range's sectors already read
        // there), at the density between the hint and it, or before the hint.
        let run = self.samples[i + 1..].iter().take_while(|s| s.1 > t && s.1 < end).last().copied();
        let (from, from_t) = run.map_or((lsn, t), |(l, n)| (u64::from(l), n));
        let average = (self.end - self.start, playtime.max(1));
        let local = match run {
            Some((l, n)) if n - t >= 3 => Some((u64::from(l) - lsn, n - t)),
            _ => i
                .checked_sub(1)
                .map(|p| self.samples[p])
                .filter(|&(pl, pt)| u64::from(pl) < lsn && pt < t)
                .map(|(pl, pt)| (lsn - u64::from(pl), t - pt)),
        };
        // The larger density: reading a few sectors too many costs less than another call.
        let (s, f) = match local {
            Some(l) if u128::from(l.0) * u128::from(average.1) > u128::from(average.0) * u128::from(l.1) => l,
            _ => average,
        };
        let span = u128::from(end - from_t) * u128::from(s) / u128::from(f.max(1));
        let span = u64::try_from(span + span / 4 + 4).unwrap_or(u64::MAX);
        Some((lsn, t, from.saturating_add(span), false))
    }

    /// Sets the disc's TOC fingerprint, or checks it against the one the index has.
    pub(crate) fn bind_fingerprint(&mut self, fingerprint: u64) -> Result<(), Error> {
        match self.fingerprint {
            Some(f) if f != fingerprint => {
                Err(Error::InvalidArgument("seek index of another disc (TOC differs)"))
            }
            _ => {
                self.fingerprint = Some(fingerprint);
                self.fingerprint_checked = true;
                Ok(())
            }
        }
    }

    /// Reads the area on from the frontier, about `max_sectors` sectors (at least to the
    /// next checkpoint, so that each call makes progress; plus a frame under assembly
    /// replayed to resume there, and up to the next read chunk), and
    /// records its checkpoints: whether the index is now complete. Building an index
    /// ahead of the reads that use it ("eager") costs one pass over the area in all
    /// (specification 7, 7.1 item 3), which can be split into calls of any size, for
    /// example on another thread with an image of its own; [`AreaIndex::merge`] then joins
    /// that index with one the reads of the first thread filled ([`AreaIndex::absorb`]).
    /// The index is of `image` from then on (see [One index per image](Self#one-index-per-image)).
    ///
    /// # Errors
    ///
    /// [`Error::InvalidArgument`] if `image` has another sector count than the index's, or
    /// is another image than the one the index was built from in this process;
    /// [`Error::Io`] if a read fails. The checkpoints recorded before stay.
    pub fn extend<R: Read + Seek>(&mut self, image: &mut Image<R>, max_sectors: u64) -> Result<bool, Error> {
        if image.sector_count() != self.key.image_sectors {
            return Err(Error::InvalidArgument("seek index of another image size"));
        }
        if self.image_id.is_some_and(|id| id != image.id()) {
            return Err(Error::InvalidArgument("seek index of another image"));
        }
        // Of this image from now on, even if there is nothing left to read.
        self.image_id = Some(image.id());
        if self.is_complete() {
            self.verify(image)?;
            return Ok(true);
        }
        // No seek hints: they are of what a caller read, which a pass would crowd out.
        let mut cursor = AreaCursor::resume(self, u32::MAX);
        // Past the next boundary, which is recorded when its sector is read.
        let next = self.checkpoint_lsn(self.checkpoints.len());
        let stop = self.frontier().saturating_add(max_sectors).max(next.saturating_add(1));
        let scanned = cursor.scan_to(image, stop);
        if let ResumedFrom::Discarded { .. } = cursor.resumed_from() {
            return Err(Error::InvalidArgument("seek index does not match the image"));
        }
        // A cursor of this index joins it.
        self.take_from(&cursor)?;
        scanned?;
        self.verify(image)?;
        Ok(self.is_complete())
    }

    pub(crate) fn key(&self) -> AreaKey {
        self.key
    }

    /// Whether the index is of `area` in an image of `image_sectors` sectors.
    pub(crate) fn check_key(&self, area: &Area, image_sectors: u64) -> Result<(), Error> {
        if self.key != AreaKey::new(area, image_sectors) {
            return Err(Error::InvalidArgument("seek index of another area or image"));
        }
        Ok(())
    }

    fn checkpoint_lsn(&self, j: usize) -> u64 {
        self.start + j as u64 * u64::from(self.interval)
    }

    /// The number of boundaries of the area, `ceil((end - start) / K)`.
    fn boundaries(&self) -> usize {
        (self.end - self.start).div_ceil(u64::from(self.interval)) as usize
    }

    /// Where a cursor of the range starting at frame `first` starts: the last checkpoint
    /// with `a <= first` (`a` grows with the LSN), or after the end when no frame at or
    /// after `first` is accepted.
    pub(crate) fn plan(&self, first: u32) -> Plan<'_> {
        if let Some(end) = self.end_state.filter(|e| first >= e.next_acceptable) {
            return Plan::End(end);
        }
        let j = self.checkpoints.partition_point(|c| c.next_acceptable <= first);
        let Some(j) = j.checked_sub(1) else { return Plan::Start };
        let checkpoint = self.checkpoints[j];
        let held = self.stored.get(j as u32);
        Plan::At { lsn: self.checkpoint_lsn(j), checkpoint, held }
    }

    /// The resume plan at checkpoint `j`, which must exist.
    pub(crate) fn plan_at(&self, j: usize) -> Plan<'_> {
        let checkpoint = self.checkpoints[j];
        Plan::At { lsn: self.checkpoint_lsn(j), checkpoint, held: self.stored.get(j as u32) }
    }

    /// The number of the last checkpoint at or before `lsn` (which must not lie past the
    /// frontier): `None` if there is none.
    pub(crate) fn checkpoint_before(&self, lsn: u64) -> Option<usize> {
        let j = ((lsn.checked_sub(self.start)?) / u64::from(self.interval)) as usize;
        (!self.checkpoints.is_empty()).then(|| j.min(self.checkpoints.len() - 1))
    }

    /// The malformed sectors before `lsn`, which must not lie past the frontier.
    pub(crate) fn malformed_below(&self, lsn: u64) -> impl Iterator<Item = u32> + '_ {
        self.malformed.iter().copied().take_while(move |&m| u64::from(m) < lsn)
    }

    /// A recorder of the checkpoints past the frontier, for a cursor that starts at `from`
    /// (at or before the frontier).
    pub(crate) fn recorder(&self, from: u64) -> Option<Box<Recorder>> {
        if self.end_state.is_some() {
            return None;
        }
        let first = self.checkpoints.len();
        Some(Box::new(Recorder {
            key: self.key,
            interval: self.interval,
            first: first as u32,
            next: self.checkpoint_lsn(first),
            from,
            // The cursor's own bound; this index charges only what it adds when it takes
            // the frames (a frame it holds a prefix of costs its growth).
            budget: self.inline_budget,
            checkpoints: Vec::new(),
            stored: Stored::default(),
            end_state: None,
            kept: false,
        }))
    }

    /// Takes the checkpoints `cursor` recorded past this index's frontier (any of
    /// [`crate::AreaCursor`], [`crate::TrackCursor`] or [`crate::TrackAudioCursor`]); a
    /// cursor made without an index recorded none. Checkpoints the index already holds
    /// are compared, not added. Frames under assembly past the inline budget are not
    /// stored: those checkpoints are replayed instead. The cursor then drops what it
    /// recorded (absorbing it again costs nothing until it records more), and the index
    /// is of the cursor's image from then on (see [One index per
    /// image](Self#one-index-per-image)).
    ///
    /// # Errors
    ///
    /// [`Error::InvalidArgument`], with the index unchanged:
    /// - if the cursor read another image than the one this index was built from in this
    ///   process (it then stops recording);
    /// - if it was made from an index of another area, image size or interval, if its
    ///   checkpoints do not join this index's (it started past the frontier), or if they
    ///   differ from those held (another image with the same key).
    pub fn absorb(&mut self, cursor: &mut impl crate::audio::SeekCursor) -> Result<(), Error> {
        let cursor = crate::audio::sealed::Sealed::area_cursor_mut(cursor);
        match self.take_from(cursor) {
            Ok(()) => {
                Self::drain(cursor);
                self.take_provisional(cursor);
                Ok(())
            }
            Err(e) => {
                if self.of_another_image(cursor) {
                    cursor.stop_recording();
                }
                Err(e)
            }
        }
    }

    /// Whether `cursor` read another image than the one this index is of.
    fn of_another_image(&self, cursor: &AreaCursor) -> bool {
        matches!((self.image_id, cursor.image_id()), (Some(a), Some(b)) if a != b)
    }

    /// Forgets the image this index was built from, as for an index loaded from bytes:
    /// the next cursor it takes checkpoints from, or the next `extend`, sets it again.
    pub(crate) fn forget_image(&mut self) {
        self.image_id = None;
    }

    /// [`AreaIndex::absorb`] without draining the cursor.
    pub(crate) fn take_from(&mut self, cursor: &AreaCursor) -> Result<(), Error> {
        let Some(r) = cursor.recorder() else { return Ok(()) };
        if self.of_another_image(cursor) {
            return Err(Error::InvalidArgument("cursor of another image than the seek index's"));
        }
        if r.key != self.key || r.interval != self.interval {
            return Err(Error::InvalidArgument("cursor of another area, image size or seek interval"));
        }
        if r.from > self.frontier() || r.first as usize > self.checkpoints.len() {
            return Err(Error::InvalidArgument("cursor's checkpoints do not join the seek index"));
        }
        let have = self.checkpoints.len();
        for (i, c) in r.checkpoints.iter().enumerate() {
            let j = r.first as usize + i;
            if j < have && self.checkpoints[j].next_acceptable != c.next_acceptable
                || j < have && self.checkpoints[j].malformed_before != c.malformed_before
            {
                return Err(Error::InvalidArgument("cursor's checkpoints differ from the seek index"));
            }
        }
        if matches!((self.end_state, r.end_state), (Some(a), Some(b)) if a != b) {
            return Err(Error::InvalidArgument("cursor's end state differs from the seek index"));
        }
        let old_frontier = self.frontier();
        let skip = have - r.first as usize;
        for (i, c) in r.checkpoints.iter().enumerate().skip(skip) {
            let j = r.first + i as u32;
            // A frame under assembly past the budget is replayed from its first sector
            // instead: still exact.
            let start = self.checkpoint_lsn(j as usize) - u64::from(c.back);
            self.stored.take(&r.stored, j, start, self.inline_budget);
            self.checkpoints.push(*c);
        }
        if r.end_state.is_some() && self.checkpoints.len() == self.boundaries() {
            self.end_state = r.end_state;
        }
        let frontier = self.frontier();
        if frontier > old_frontier && self.malformed.len() < MAX_MALFORMED_WARNINGS {
            // The cursor's warnings are those of a scan from the first sector.
            self.malformed = cursor
                .warnings()
                .iter()
                .filter_map(|w| w.lsn)
                .take_while(|&m| u64::from(m) < frontier)
                .take(MAX_MALFORMED_WARNINGS)
                .collect();
        }
        if self.image_id.is_none() {
            self.image_id = cursor.image_id();
        }
        self.prune_provisional();
        Ok(())
    }
}

impl AreaIndex {
    /// [`AreaIndex::absorb`], then drops what `cursor` recorded, so that absorbing it
    /// again costs nothing until it records more; a cursor whose checkpoints cannot join
    /// this index stops recording.
    pub(crate) fn absorb_drain(&mut self, cursor: &mut AreaCursor) {
        if self.take_from(cursor).is_err() {
            cursor.stop_recording();
            return;
        }
        Self::drain(cursor);
        self.take_provisional(cursor);
    }

    /// Drops what `cursor` recorded, once taken: it records on from there.
    pub(crate) fn drain(cursor: &mut AreaCursor) {
        if let Some(r) = cursor.recorder_mut() {
            if r.end_state.is_some() {
                cursor.stop_recording();
            } else {
                r.first += r.checkpoints.len() as u32;
                r.checkpoints.clear();
                r.stored = Stored::default();
            }
        }
    }

    /// The LSN a cursor of positions `first` or more would start at, `None` for one that
    /// reads nothing.
    pub(crate) fn plan_lsn(&self, first: u32) -> Option<u64> {
        match self.plan(first) {
            Plan::Start => Some(self.start),
            Plan::At { lsn, .. } => Some(lsn),
            Plan::End(_) => None,
        }
    }

    /// The checkpoint interval.
    pub(crate) fn interval(&self) -> u32 {
        self.interval
    }
}

impl AreaIndex {
    /// The provisional readings waiting to be checked ([`AreaIndex::verify`]).
    pub fn pending_claims(&self) -> usize {
        self.claims.len()
    }

    /// Takes the verdicts on provisional readings reached since the last call (see
    /// [`AreaIndex::verify`]).
    pub fn take_events(&mut self) -> Vec<SeekEvent> {
        std::mem::take(&mut self.events)
    }

    /// Whether the exact checkpoints reach the sector `lsn` of a provisional reading.
    fn reaches(&self, lsn: u64) -> bool {
        lsn != 0 && lsn <= self.frontier() && lsn < self.end
    }

    /// Whether [`AreaIndex::verify`] has a provisional reading to settle.
    pub(crate) fn has_reached_claims(&self) -> bool {
        self.claims.iter().any(|c| c.verdict().is_none() && self.reaches(c.lsn()))
    }

    /// Takes from `cursor` its provisional reading, to check, and the provisional
    /// checkpoints it recorded past the frontier: only for a cursor of this index's image.
    pub(crate) fn take_provisional(&mut self, cursor: &mut AreaCursor) {
        // Provisional readings and checkpoints are of the image the cursor read: an index
        // of another image refuses them, and one of no image yet is of that one from now on
        // (see One index per image), so that no other image can check them.
        match (self.image_id, cursor.image_id()) {
            (Some(id), Some(c)) if c != id => return,
            (None, Some(c)) if cursor.has_news() => self.image_id = Some(c),
            _ => {}
        }
        if let Some(claim) = cursor.unregistered_claim() {
            if self.claims.len() >= MAX_CLAIMS {
                let old = self.claims.remove(0);
                if old.settle(Verdict::Unverified) {
                    queue_events(&mut self.events, [old.event()]);
                }
            }
            self.claims.push(claim);
        }
        if cursor.hints_stale() {
            self.drop_hints();
        }
        self.add_hints(cursor.take_hints());
        let frontier = self.frontier();
        let most = self.boundaries();
        for (lsn, p) in cursor.take_provisional_checkpoints() {
            if lsn > frontier && self.provisional.len() < most {
                self.provisional.insert(lsn, p);
            }
        }
    }

    /// Drops the oldest pending readings past [`MAX_CLAIMS`], as unverified.
    pub(crate) fn cap_claims(&mut self) {
        while self.claims.len() > MAX_CLAIMS {
            let old = self.claims.remove(0);
            if old.settle(Verdict::Unverified) {
                queue_events(&mut self.events, [old.event()]);
            }
        }
    }

    /// Drops what the exact checkpoints now cover.
    fn prune_provisional(&mut self) {
        let frontier = self.frontier();
        self.provisional.retain(|&lsn, _| lsn > frontier);
    }

    /// A provisional start for positions `u` or more from the provisional checkpoints: the
    /// last one whose reading had delivered no frame numbered `u` or more and whose frame
    /// under assembly is none or numbered below `u` (so that, as far as that reading saw,
    /// (a) and (b) of 4.2 item 8 hold there), if a later one had delivered such a frame (so
    /// that `u` lies within what they cover), the two in one run of consecutive boundaries
    /// (one reading's: otherwise the first could lie at the end of a reading far before `u`).
    pub(crate) fn plan_provisional(&self, u: u32) -> Option<(u64, Provisional)> {
        let mut best = None;
        let mut prev: Option<u64> = None;
        for (&lsn, &p) in &self.provisional {
            if prev.is_some_and(|q| q + u64::from(self.interval) != lsn) {
                best = None;
            }
            prev = Some(lsn);
            if p.seen > u {
                return best;
            }
            if p.under.is_none_or(|n| n < u) {
                best = Some((lsn, p));
            }
        }
        None
    }

    /// Checks the provisional readings that the exact checkpoints now reach (specification
    /// 4, 4.2 item 8): for each, the state at its `L` of a reader from the first sector,
    /// rebuilt from the checkpoint at or before `L` (at most [`REPLAY_SECTORS`] plus the
    /// interval in sectors read through `image`). A reading is confirmed when (a) that
    /// reader's next acceptable frame number at `L` is at most `u` and (b) its frame under
    /// assembly there is none or numbered below `u`, and refuted ("possibly different")
    /// otherwise; its cursors see the verdict at once ([`crate::TrackCursor::speculation`]),
    /// and it becomes an event ([`AreaIndex::take_events`]). Refutations are logged at
    /// warning level. A confirmed reading is kept, with the digest of its sector `L` (one
    /// more sector read), for later readings from `L` (see [Saved
    /// confirmations](AreaIndex#saved-confirmations)). Returns the number of readings
    /// settled. [`AreaIndex::extend`] does
    /// this itself.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidArgument`] if `image` has another sector count than the index's, or
    /// is another image than the index's (see [One index per
    /// image](AreaIndex#one-index-per-image)); [`Error::Io`] if a read fails (the readings
    /// not yet checked stay pending).
    pub fn verify<R: Read + Seek>(&mut self, image: &mut Image<R>) -> Result<usize, Error> {
        if image.sector_count() != self.key.image_sectors {
            return Err(Error::InvalidArgument("seek index of another image size"));
        }
        if self.image_id.is_some_and(|id| id != image.id()) {
            return Err(Error::InvalidArgument("seek index of another image"));
        }
        // Checked against this image: the index is of it from now on.
        self.image_id = Some(image.id());
        let mut settled = 0;
        let mut i = 0;
        while i < self.claims.len() {
            let claim = std::sync::Arc::clone(&self.claims[i]);
            let lsn = claim.lsn();
            if claim.verdict().is_some() {
                self.claims.remove(i);
                continue;
            }
            if !self.reaches(lsn) {
                i += 1;
                continue;
            }
            // A reading of another image is never checked against this one.
            let foreign = claim.image().is_some_and(|id| id != image.id());
            let verdict = match if foreign { None } else { AreaCursor::state_at(self, lsn, image)? } {
                None => Verdict::Unverified,
                Some((a, held, _)) => {
                    let u = claim.first;
                    if a <= u && held.is_none_or(|g| g < u) {
                        if self.fingerprint_checked && lsn < self.end {
                            let d = digest(&crate::audio::read_sector(image, lsn)?);
                            self.keep_confirmation(lsn, u, d);
                        }
                        Verdict::Confirmed
                    } else {
                        Verdict::Refuted { exact_from: a.max(held.map_or(0, |g| g.saturating_add(1))) }
                    }
                }
            };
            self.claims.remove(i);
            if claim.settle(verdict) {
                settled += 1;
                let event = claim.event();
                match event.speculation {
                    Speculation::Refuted { first, last_returned, exact_from, .. } => sb_log!(
                        image.log(),
                        Warn,
                        "area {}: provisional reading from LSN {lsn} for frames {first}.. possibly different \
                         from the specification below frame {exact_from} (4.2 item 8; returned up to {:?})",
                        claim.slot,
                        last_returned
                    ),
                    _ => sb_log!(
                        image.log(),
                        Debug,
                        "area {}: provisional reading from LSN {lsn}: {:?}",
                        claim.slot,
                        event.speculation
                    ),
                }
                queue_events(&mut self.events, [event]);
            }
        }
        Ok(settled)
    }
}

/// The seek indexes a [`crate::Disc`] keeps, one per slot, each behind its own lock so that
/// cursors can be made and continued through `&Disc`: a read lock while a cursor is made
/// from an index, a write lock while checkpoints are taken into it. No log sink runs under
/// either. Kept apart from the rest of the disc so that discs sharing an image can share
/// it.
#[derive(Debug, Default)]
pub(crate) struct SeekIndexes {
    indexes: [std::sync::RwLock<Option<AreaIndex>>; 2],
    /// Verdicts on provisional readings, for [`crate::Disc::take_seek_events`].
    events: [std::sync::Mutex<Vec<SeekEvent>>; 2],
}

impl SeekIndexes {
    fn at(slot: crate::Slot) -> usize {
        match slot {
            crate::Slot::TwoChannel => 0,
            crate::Slot::Multichannel => 1,
        }
    }

    /// Runs `f` on the index of `slot`, if one is kept, under a read lock.
    pub(crate) fn read<T>(&self, slot: crate::Slot, f: impl FnOnce(Option<&AreaIndex>) -> T) -> T {
        // Nothing panics while a lock is held: the indexes stay consistent.
        let index = self.indexes[Self::at(slot)].read().unwrap_or_else(std::sync::PoisonError::into_inner);
        f(index.as_ref())
    }

    /// Runs `f` on the index of `slot` (or its absence) under a write lock.
    pub(crate) fn write<T>(&self, slot: crate::Slot, f: impl FnOnce(&mut Option<AreaIndex>) -> T) -> T {
        let mut index =
            self.indexes[Self::at(slot)].write().unwrap_or_else(std::sync::PoisonError::into_inner);
        f(&mut index)
    }

    /// Takes what `cursor` recorded into the index of its slot, if one is kept and the
    /// cursor read the image `image_id` (this disc's, shared by its clones and shares);
    /// costs a test when it recorded nothing new. A cursor that read another image (of the
    /// same size and layout, so that the key cannot tell) stops recording instead: its
    /// checkpoints are that image's.
    #[inline]
    pub(crate) fn absorb(&self, cursor: &mut AreaCursor, image_id: u64) {
        let kept = cursor.recorder().is_none_or(|r| r.kept);
        if kept && cursor.has_news() {
            if cursor.image_id().is_some_and(|id| id != image_id) {
                cursor.stop_recording();
                return;
            }
            let events = self.write(cursor.slot(), |index| match index {
                Some(index) => {
                    index.absorb_drain(cursor);
                    index.take_events()
                }
                None => {
                    cursor.stop_recording();
                    Vec::new()
                }
            });
            self.push_events(cursor.slot(), events);
        }
    }

    /// Queues verdicts for [`crate::Disc::take_seek_events`].
    pub(crate) fn push_events(&self, slot: crate::Slot, events: Vec<SeekEvent>) {
        if !events.is_empty() {
            let mut queue =
                self.events[Self::at(slot)].lock().unwrap_or_else(std::sync::PoisonError::into_inner);
            queue_events(&mut queue, events);
        }
    }

    /// Takes the queued verdicts of `slot`.
    pub(crate) fn take_events(&self, slot: crate::Slot) -> Vec<SeekEvent> {
        let mut queue = self.events[Self::at(slot)].lock().unwrap_or_else(std::sync::PoisonError::into_inner);
        std::mem::take(&mut *queue)
    }
}

/// The checkpoints a cursor records past an index's frontier, for [`AreaIndex::absorb`].
#[derive(Clone, Debug)]
pub(crate) struct Recorder {
    key: AreaKey,
    interval: u32,
    /// The number of the first checkpoint recorded.
    first: u32,
    /// The boundary to record next.
    next: u64,
    /// Where the cursor's scan started.
    from: u64,
    /// Bytes of frames under assembly still to store.
    budget: usize,
    checkpoints: Vec<Checkpoint>,
    stored: Stored,
    end_state: Option<EndState>,
    /// Made from the index a [`crate::Disc`] keeps, which takes the checkpoints; a cursor
    /// from a caller's index is left to the caller.
    pub(crate) kept: bool,
}

impl Recorder {
    /// Whether anything was recorded since the last [`AreaIndex::absorb_drain`].
    pub(crate) fn has_news(&self) -> bool {
        !self.checkpoints.is_empty() || self.end_state.is_some()
    }

    /// Whether the scan's state before sector `lsn` is to be recorded.
    #[inline]
    pub(crate) fn due(&self, lsn: u64) -> bool {
        lsn == self.next
    }

    /// Records the state before sector `lsn` (a due boundary), whose bytes are `sector`.
    pub(crate) fn record(
        &mut self,
        lsn: u64,
        next_acceptable: u32,
        malformed_before: u64,
        assembling: Option<Assembling<'_>>,
        sector: &[u8; SECTOR_SIZE],
    ) {
        let at = self.first + self.checkpoints.len() as u32;
        let mut back = 0;
        if let Some(a) = assembling {
            // The frame started in an audio sector at or before this one: below 2^32.
            back = u32::try_from(lsn - a.start_lsn).unwrap_or(u32::MAX).max(1);
            if u64::from(back) > REPLAY_SECTORS {
                self.stored.add(at, a.start_lsn, (a.number, a.kind, a.remaining), a.data, self.budget);
            }
        }
        self.checkpoints.push(Checkpoint { next_acceptable, back, malformed_before, digest: digest(sector) });
        self.next += u64::from(self.interval);
    }

    /// Records the end of the scan.
    pub(crate) fn finish(&mut self, next_acceptable: u32, malformed: u64) {
        self.end_state = Some(EndState { next_acceptable, malformed });
    }
}

/// A fingerprint of the disc's TOC as it bears on the area of `slot` (FNV-1a, 64-bit): it
/// tells a seek index saved for one disc from one loaded for another, even of the same
/// layout, at no cost in reads. It covers the image's sector count and sector format; the
/// master TOC's version, album set size and sequence number, stored catalogue numbers,
/// genres, area pointers, disc flags and date; and the area TOC's version, maximum byte
/// rate, sample frequency code, frame format, channel count, area configuration, maximum
/// available channels, mute flags, track attribute, play time, track offset, audio
/// sector range, and each track's number, start LSN, length, start frame, duration, flags
/// and ISRC. Text is not covered.
pub(crate) fn toc_fingerprint(toc: &crate::Toc, slot: crate::Slot) -> u64 {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    let mut put = |bytes: &[u8]| {
        for &b in bytes {
            h = (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3);
        }
    };
    put(&toc.sectors.to_le_bytes());
    put(&[match toc.sector_format {
        crate::SectorFormat::Plain => 0,
        crate::SectorFormat::Raw2054 => 1,
        crate::SectorFormat::Raw2064 => 2,
    }]);
    let m = &toc.master;
    put(&[m.version.major, m.version.minor]);
    put(&m.album_set_size.to_le_bytes());
    put(&m.album_sequence_number.to_le_bytes());
    for stored in [&m.album_catalog_number_stored, &m.disc_catalog_number_stored] {
        put(&(stored.len() as u32).to_le_bytes());
        put(stored);
    }
    for g in m.album_genres.iter().chain(&m.disc_genres) {
        put(&[g.category, g.index]);
    }
    for p in [m.two_channel, m.multichannel] {
        put(&p.toc1_lsn.to_le_bytes());
        put(&p.toc2_lsn.to_le_bytes());
        put(&p.toc_sectors.to_le_bytes());
    }
    put(&[m.disc_flags]);
    put(&m.date.year.to_le_bytes());
    put(&[m.date.month, m.date.day]);
    if let Some(a) = toc.area(slot) {
        put(&[a.version.major, a.version.minor]);
        put(&a.max_byte_rate.to_le_bytes());
        put(&[
            a.sample_frequency_code,
            a.frame_format,
            a.channel_count,
            a.area_config,
            a.max_available_channels,
            a.area_mute_flags,
            a.track_attribute,
            a.playtime.minutes,
            a.playtime.seconds,
            a.playtime.frames,
            a.track_offset,
        ]);
        put(&a.audio_start_lsn.to_le_bytes());
        put(&a.audio_end_lsn.to_le_bytes());
        put(&(a.tracks.len() as u32).to_le_bytes());
        for t in &a.tracks {
            put(&[t.number, t.start_flags, t.duration_flags]);
            put(&t.start_lsn.to_le_bytes());
            put(&t.length_sectors.to_le_bytes());
            put(&t.start_frame.to_le_bytes());
            put(&t.duration_frames.to_le_bytes());
            let isrc = t.isrc.as_deref().unwrap_or("");
            put(&(isrc.len() as u32).to_le_bytes());
            put(isrc.as_bytes());
        }
    }
    h
}

/// Whether the TOC places the audio sectors of the area of `slot` past the end of the
/// image, or over the other area's TOC copies or audio sectors ([`Suspect::AreaLayout`]).
pub(crate) fn layout_suspect(toc: &crate::Toc, slot: crate::Slot) -> bool {
    let Some(a) = toc.area(slot) else { return false };
    let (s, e) = (u64::from(a.audio_start_lsn), u64::from(a.audio_end_lsn));
    if e >= toc.sectors {
        return true;
    }
    let overlaps = |from: u64, to: u64| from <= e && s <= to && from <= to;
    let other = match slot {
        crate::Slot::TwoChannel => toc.master.multichannel,
        crate::Slot::Multichannel => toc.master.two_channel,
    };
    if other.is_used() {
        let len = u64::from(other.toc_sectors);
        for t in [other.toc1_lsn, other.toc2_lsn].into_iter().filter(|&t| t != 0) {
            if overlaps(u64::from(t), u64::from(t) + len - 1) {
                return true;
            }
        }
    }
    toc.areas
        .iter()
        .filter(|o| o.slot != slot)
        .any(|o| overlaps(u64::from(o.audio_start_lsn), u64::from(o.audio_end_lsn)))
}

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

    fn index(next: &[u32], end: Option<u32>) -> AreaIndex {
        AreaIndex {
            key: AreaKey::new(&crate::audio::tests_support::area(1).1, 200),
            start: 100,
            end: 200,
            interval: 10,
            inline_budget: 0,
            checkpoints: next
                .iter()
                .map(|&a| Checkpoint { next_acceptable: a, back: 0, malformed_before: 0, digest: 0 })
                .collect(),
            stored: Stored::default(),
            end_state: end.map(|a| EndState { next_acceptable: a, malformed: 0 }),
            malformed: Vec::new(),
            image_id: None,
            claims: Vec::new(),
            provisional: std::collections::BTreeMap::new(),
            events: Vec::new(),
            samples: Vec::new(),
            hint_spacing: DEFAULT_HINT_SPACING,
            max_hints: DEFAULT_MAX_HINTS,
            fingerprint: None,
            fingerprint_checked: false,
            confirmed: Vec::new(),
        }
    }

    fn at(p: Plan<'_>) -> Option<u64> {
        match p {
            Plan::At { lsn, .. } => Some(lsn),
            Plan::Start | Plan::End(_) => None,
        }
    }

    /// Specification 4, 4.5 item 6: a checkpoint whose straight-pass `a` is above `first`
    /// is never chosen, even when a later one has a smaller frame number in view.
    #[test]
    fn plan_takes_the_last_checkpoint_with_a_at_most_first() {
        // A huge timecode accepted between LSN 120 and 130 raises a past every later frame.
        let ix = index(&[0, 3, 9, 1_166_881, 1_166_881], None);
        assert_eq!(at(ix.plan(0)), Some(100));
        assert_eq!(at(ix.plan(2)), Some(100));
        assert_eq!(at(ix.plan(3)), Some(110));
        assert_eq!(at(ix.plan(8)), Some(110));
        assert_eq!(at(ix.plan(9)), Some(120));
        assert_eq!(at(ix.plan(1_166_880)), Some(120));
        assert_eq!(at(ix.plan(1_166_881)), Some(140));
        assert!(matches!(index(&[], None).plan(5), Plan::Start));
        let done = index(&[0, 3], Some(7));
        assert_eq!(at(done.plan(6)), Some(110));
        assert!(matches!(done.plan(7), Plan::End(EndState { next_acceptable: 7, .. })));
        assert_eq!(done.frontier(), 200);
        assert_eq!(ix.frontier(), 140);
        assert_eq!(index(&[], None).frontier(), 100);
    }

    /// A provisional start comes from one run of consecutive boundaries around `u`, never
    /// from the end of an earlier reading far before it.
    #[test]
    fn provisional_starts_stay_within_one_reading() {
        let mut ix = index(&[], None);
        let p = |seen| Provisional { back: 0, digest: 0, seen, under: None };
        // One reading over 110..130 (frames to 20), another over 160..180 (frames 50 on).
        for (lsn, seen) in [(110, 10), (120, 20), (160, 50), (170, 60)] {
            ix.provisional.insert(lsn, p(seen));
        }
        assert_eq!(ix.plan_provisional(15).map(|x| x.0), Some(110));
        assert_eq!(ix.plan_provisional(35), None, "between the readings");
        assert_eq!(ix.plan_provisional(55).map(|x| x.0), Some(160));
    }

    #[test]
    fn options_are_checked() {
        let (_, area, _) = crate::audio::tests_support::area(4);
        for k in [0, MAX_INTERVAL + 1] {
            let e = AreaIndex::new(&area, 4, IndexOptions::new().with_interval(k)).unwrap_err();
            assert!(matches!(e, Error::InvalidArgument(_)));
        }
        let ix = AreaIndex::new(&area, 4, IndexOptions::new().with_interval(MAX_INTERVAL)).unwrap();
        assert_eq!(ix.options().interval, MAX_INTERVAL);
        assert_eq!((ix.frontier(), ix.is_complete(), ix.checkpoints()), (0, false, 0));
        assert!(ix.memory() >= std::mem::size_of::<AreaIndex>());
    }

    /// Knots inside the interval steer the guess; knots outside it, or out of order with
    /// its bounds, are ignored (a hostile TOC costs probes, never the interval).
    #[test]
    fn bracket_takes_the_tightest_knots_inside() {
        let knots = [(150, 10), (200, 20), (300, 30), (900, 5), (50, 1)];
        assert_eq!(bracket((100, 0), (1000, 100), &knots, 25), ((200, 20), (300, 30)));
        assert_eq!(bracket((100, 0), (1000, 100), &knots, 35), ((300, 30), (1000, 100)));
        // (900, 5) is out of order: (50, 1) lies outside; (900, 5) is the nearest frame
        // number at or below 7, and nothing after it is above 7 but the bound.
        assert_eq!(bracket((100, 0), (1000, 100), &knots, 7), ((900, 5), (1000, 100)));
        assert_eq!(bracket((100, 0), (1000, 100), &knots, 4), ((100, 0), (900, 5)));
        // Only bounds narrower than the knots.
        assert_eq!(bracket((250, 24), (280, 28), &knots, 25), ((250, 24), (280, 28)));
        assert_eq!(bracket((100, 0), (1000, 100), &[], 7), ((100, 0), (1000, 100)));
    }

    /// Thinning keeps a hint per region read and drops the closest ones first.
    #[test]
    fn hints_thin_by_gap() {
        let mut ix = index(&[], None);
        ix.add_hints(vec![(110, 10), (111, 11), (112, 12), (150, 500), (151, 508), (190, 900)]);
        ix.thin_hints(4);
        assert_eq!(ix.samples.len(), 4, "{:?}", ix.samples);
        assert!(
            ix.samples.contains(&(110, 10))
                && ix.samples.contains(&(150, 500))
                && ix.samples.contains(&(190, 900))
        );
        assert_eq!(ix.hint(505, 520, 1000).map(|h| h.0), Some(150));
        assert_eq!(ix.hint(700, 710, 1000), None, "beyond the reach");
    }

    #[test]
    fn digest_is_fnv1a() {
        // FNV-1a of 2048 zero bytes, computed independently.
        let mut h: u64 = 0xcbf2_9ce4_8422_2325;
        for _ in 0..SECTOR_SIZE {
            h = h.wrapping_mul(0x0100_0000_01b3);
        }
        assert_eq!(digest(&[0; SECTOR_SIZE]), h);
        assert_ne!(digest(&[0; SECTOR_SIZE]), digest(&[1; SECTOR_SIZE]));
    }
}