scarletbook 0.6.2

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

//! A disc: an image with its parsed TOC.

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

use crate::audio::{
    self, AreaCapacity, AreaCursor, AreaFrames, Continuation, CursorOptions, FrameSpan, TrackAudio,
    TrackAudioCursor, TrackCursor, TrackFrames,
};
use crate::control::CancelToken;
use crate::error::{Error, Slot, Warning};
use crate::image::{Image, ImageOptions, SectorFormat};
use crate::log::{Log, sb_log};
use crate::read_at::{ReadAt, ReadAtReader};
use crate::seek::{AreaIndex, IndexOptions, SeekIndexes, SeekPolicy, Speculation};
use crate::toc::{self, Timecode, Toc, TocDigests, TocStored};

/// An opened disc image with its table of contents.
///
/// Opening reads only the master TOC and the area TOCs. Audio is read on demand.
///
/// # Which call
///
/// | To | Decoded audio | Frames as stored |
/// |---|---|---|
/// | read a track | [`Disc::track_audio`] | [`Disc::track_frames`] |
/// | read a frame range | [`Disc::range_audio`] | [`Disc::range_frames`] |
/// | read every accepted frame of an area | | [`Disc::stored_frame_list`] |
/// | hold the reading without a borrow | [`TrackAudio::into_cursor`] | [`TrackFrames::into_cursor`] |
/// | open a cursor from `&self` | [`Disc::audio_cursor`] | [`Disc::frames_cursor`], [`Disc::stored_frame_list_cursor`] |
/// | read a cursor | [`Disc::read_track_audio`] | [`Disc::read_frames`] |
/// | go on to a later track | [`Disc::continue_track_audio`] | [`Disc::continue_track_frames`] |
/// | go on to a later range | [`Disc::continue_range_audio`] | [`Disc::continue_range_frames`] |
///
/// For decoded audio with the stored bytes in one pass, use [`TrackAudio::keep_stored`] and
/// [`TrackAudio::next_with_stored`]. To start a cursor from your own seek index, or with
/// another seek policy for that one cursor, use [`CursorOptions`]. [`Disc::area_frames`] is
/// the diagnostic form of [`Disc::stored_frame_list`].
///
/// Without a `Disc`, use [`TrackAudioCursor::new`] or [`TrackCursor::new`] for a track,
/// [`TrackAudioCursor::open_range`] or [`TrackCursor::open_range`] for a range,
/// [`AreaCursor::new`] for an area, and `continue_to` and `continue_to_range` to go on.
///
/// # Several readers
///
/// A disc reads through one reader with one position, so its reads take `&mut self`. For
/// reads of one image on several threads at once, give each thread a disc of its own made
/// from this one: [`Disc::share`] with another reader of the same image, or `clone` for a
/// disc read through a [`ReadAtReader`] (no I/O). They share the parsed TOC, warnings,
/// sector format and log, and the image identifier ([`Image::id`]), so a cursor made or
/// read through one may be read through any other: they read the same bytes.
///
/// ```no_run
/// # fn main() -> Result<(), scarletbook::Error> {
/// use std::sync::Arc;
/// use scarletbook::{Disc, ReadAtReader, Slot};
///
/// let file = Arc::new(std::fs::File::open("disc.iso")?);
/// let disc = Disc::open(ReadAtReader::new(file))?;
/// let count = disc.toc().area(Slot::TwoChannel).map_or(0, |a| a.tracks.len()) as u32;
/// std::thread::scope(|s| {
///     for n in 1..=count {
///         let mut disc = disc.clone();
///         s.spawn(move || -> Result<(), scarletbook::Error> {
///             for frame in disc.track_audio(Slot::TwoChannel, n)? {
///                 let _frame = frame?;
///             }
///             Ok(())
///         });
///     }
/// });
/// # Ok(())
/// # }
/// ```
///
/// # Seeking
///
/// With a seek index enabled for an area ([`Disc::enable_seek_index`] or
/// [`Disc::set_seek_index`]; off by default), every track and range cursor of that area
/// this disc, or any disc made from it by [`Disc::share`] or `clone`, makes or continues
/// starts from the index (one index per area, which they all use and grow, from any
/// thread) (see [`crate::seek`]), and the
/// borrowing iterators ([`TrackAudio`], [`TrackFrames`]) and continuations hand the
/// checkpoints their cursors record back to it as they read. The frames, statuses, counts
/// and warnings are exactly those without an index; once the index covers a range, opening
/// it reads at most a few dozen sectors before the range's own, wherever it lies. A
/// continuation starts from the index instead of the area's first sector when the earlier
/// cursor's state cannot be reused, and also when the index starts the range more than two
/// checkpoints past that cursor's scan (until it first reads, a cursor moved ahead so
/// reports the malformed sectors and warnings of the scan it was moved from, as a reused
/// one would). The stored frame list and [`Disc::area_frames`] always scan from the area's
/// first sector.
///
/// ```no_run
/// # fn main() -> Result<(), scarletbook::Error> {
/// use scarletbook::{AreaIndex, Disc, IndexOptions, Slot};
/// let mut disc = Disc::open(std::io::BufReader::new(std::fs::File::open("disc.iso")?))?;
/// disc.enable_seek_index(Slot::TwoChannel, IndexOptions::new())?;
/// // Built by reads as they go, or at once in steps: one pass over the area.
/// while !disc.extend_seek_index(Slot::TwoChannel, 64 * 1024)? {}
/// for frame in disc.range_audio(Slot::TwoChannel, 200_000, 200_075)? {
///     let _frame = frame?;
/// }
/// // Kept for the next time: checked again when loaded, and as it is used.
/// let saved = disc.seek_index(Slot::TwoChannel).map(|i| i.to_bytes()).unwrap_or_default();
/// let area = disc.toc().area(Slot::TwoChannel).ok_or(scarletbook::Error::NoSuchArea(Slot::TwoChannel))?;
/// let index = AreaIndex::from_bytes(area, disc.toc().sectors, &saved, scarletbook::seek::DEFAULT_INLINE_BUDGET)?;
/// disc.set_seek_index(Slot::TwoChannel, index)?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct Disc<R> {
    image: Image<R>,
    shared: Arc<DiscShared>,
    /// The seek policy of each slot, this handle's own ([`Disc::set_seek_policy`]).
    policy: [SeekPolicy; 2],
}

/// What the discs made from one by [`Disc::share`] and `clone` have in common: parsed
/// once, read by all of them, from any thread.
///
/// State of the image that every one of its discs should see (for example per-area seek
/// indexes, #68) belongs here, behind its own lock, rather than in [`Disc`].
#[derive(Debug)]
struct DiscShared {
    toc: Toc,
    warnings: Vec<Warning>,
    /// The digests of the TOC sectors the parse used, against which [`Disc::share`]
    /// checks another reader.
    digests: TocDigests,
    /// TOC fields as stored that the TOC gives only as interpreted.
    stored: TocStored,
    /// The seek index of each slot, if enabled: one for every disc of the image, so that
    /// they all use and grow the same index.
    seek: SeekIndexes,
}

/// How to open a [`Disc`]: [`Disc::options`], then what differs from the default, then
/// [`DiscOptions::open`].
///
/// ```no_run
/// use scarletbook::{Disc, SectorFormat, log::Log};
/// # fn main() -> Result<(), scarletbook::Error> {
/// let file = std::fs::File::open("disc.iso")?;
/// let disc = Disc::options().with_format(SectorFormat::Raw2064).with_log(Log::none()).open(file)?;
/// # let _ = disc;
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug, Default)]
pub struct DiscOptions {
    image: ImageOptions,
}

impl DiscOptions {
    /// The default: the sector format is detected, and nothing is logged.
    pub fn new() -> Self {
        Self::default()
    }

    /// The sector format, chosen by the caller instead of detected
    /// ([`ImageOptions::with_format`]).
    pub fn with_format(mut self, format: SectorFormat) -> Self {
        self.image = self.image.with_format(format);
        self
    }

    /// Where to report from the start, sector format detection included (see [`crate::log`]).
    pub fn with_log(mut self, log: Log) -> Self {
        self.image = self.image.with_log(log);
        self
    }

    /// Opens the disc image and parses its TOC.
    ///
    /// # Errors
    ///
    /// One of the rejections of specification 7, 7.7.1, or [`Error::Io`].
    pub fn open<R: Read + Seek>(self, reader: R) -> Result<Disc<R>, Error> {
        Disc::from_image(self.image.open(reader)?)
    }
}

impl Disc<()> {
    /// The options for opening a disc with a sector format or log of the caller's:
    /// `Disc::options().with_format(f).with_log(l).open(reader)`.
    pub fn options() -> DiscOptions {
        DiscOptions::new()
    }
}

impl<R: Read + Seek> Disc<R> {
    /// Opens a disc image, detecting its sector format, logging nothing. [`Disc::options`]
    /// chooses a format or a log.
    ///
    /// # Errors
    ///
    /// One of the rejections of specification 7, 7.7.1, or [`Error::Io`].
    pub fn open(reader: R) -> Result<Self, Error> {
        Disc::options().open(reader)
    }

    /// Opens a disc image, detecting its sector format, and reports to `log` from the
    /// detection on (see [`crate::log`]).
    ///
    /// # Errors
    ///
    /// As [`Disc::open`].
    #[deprecated(
        since = "0.6.0",
        note = "use `Disc::options().with_log(log).open(reader)`; to be removed before 1.0"
    )]
    pub fn open_with_log(reader: R, log: Log) -> Result<Self, Error> {
        Disc::options().with_log(log).open(reader)
    }

    /// Opens a disc image in a sector format chosen by the caller.
    ///
    /// # Errors
    ///
    /// As [`Disc::open`].
    #[deprecated(
        since = "0.6.0",
        note = "use `Disc::options().with_format(format).open(reader)`; to be removed before 1.0"
    )]
    pub fn open_with_format(reader: R, format: SectorFormat) -> Result<Self, Error> {
        Disc::options().with_format(format).open(reader)
    }

    /// Opens a disc image in a sector format chosen by the caller, and reports to `log`
    /// from the start (see [`crate::log`]).
    ///
    /// # Errors
    ///
    /// As [`Disc::open`].
    #[deprecated(
        since = "0.6.0",
        note = "use `Disc::options().with_format(format).with_log(log).open(reader)`; to be removed before 1.0"
    )]
    pub fn open_with_format_and_log(reader: R, format: SectorFormat, log: Log) -> Result<Self, Error> {
        Disc::options().with_format(format).with_log(log).open(reader)
    }

    /// Parses the TOC of an image, reporting to the image's log ([`Image::set_log`]).
    ///
    /// # Errors
    ///
    /// As [`Disc::open`].
    pub fn from_image(mut image: Image<R>) -> Result<Self, Error> {
        let (toc, warnings, digests, stored) = toc::read_toc(&mut image)?;
        // Audio reads allocate their own: a disc kept only for its TOC keeps no buffer.
        image.release_buffer();
        Ok(Disc {
            image,
            shared: Arc::new(DiscShared { toc, warnings, digests, stored, seek: SeekIndexes::default() }),
            policy: [SeekPolicy::Exact; 2],
        })
    }

    /// A disc of the same image read through `reader`, with a position of its own, sharing
    /// this disc's TOC, warnings, sector format, image identifier and log (see [Several
    /// readers](Disc#several-readers)). Cursors of either disc may be read through the
    /// other. [`Disc::set_log`] on one does not change the other's.
    ///
    /// `reader` is checked: it must have the image's length, and the master TOC sector
    /// (LSN 510) and the area TOC copies the parse used must hold the same bytes (by a
    /// 64-bit digest). This catches another file given by mistake; it cannot prove that the
    /// audio sectors are the same, which stays the caller's responsibility.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidArgument`] if `reader` is of another image, [`Error::Io`] if it
    /// fails.
    pub fn share<R2: Read + Seek>(&self, reader: R2) -> Result<Disc<R2>, Error> {
        self.share_with_log(reader, self.log().clone())
    }

    /// [`Disc::share`], with the new disc reporting to `log` (see [`crate::log`]), the
    /// check of `reader` included.
    ///
    /// # Errors
    ///
    /// As [`Disc::share`].
    pub fn share_with_log<R2: Read + Seek>(&self, reader: R2, log: Log) -> Result<Disc<R2>, Error> {
        let mut image = self.image.share(reader, log)?;
        if TocDigests::of(&mut image, &self.shared.toc)?.as_ref() != Some(&self.shared.digests) {
            sb_log!(image.log(), Info, "shared reader refused: its TOC sectors differ from the image's");
            return Err(Error::InvalidArgument("shared reader of another image"));
        }
        sb_log!(image.log(), Debug, "shared reader checked: same length and TOC sectors");
        image.release_buffer();
        Ok(Disc { image, shared: Arc::clone(&self.shared), policy: self.policy })
    }

    /// The table of contents.
    pub fn toc(&self) -> &Toc {
        &self.shared.toc
    }

    /// The digests of the TOC sectors the parse used, which tell images apart.
    #[cfg(feature = "output")]
    pub(crate) fn toc_digests(&self) -> &TocDigests {
        &self.shared.digests
    }

    /// The log this disc reports to.
    pub fn log(&self) -> &Log {
        self.image.log()
    }

    /// Replaces the log this disc reports to, from the next call on. Audio cursors report
    /// to the log of the disc they read through; decoding jobs already started on the pool
    /// (`parallel` feature) keep the log they started with.
    pub fn set_log(&mut self, log: Log) {
        self.image.set_log(log);
    }

    /// The cancellation request of this disc's reads, to cancel them from another thread
    /// (see [`CancelToken`]). Every disc of the image ([`Disc::share`], `clone`) has the
    /// same: cancelling stops the reads of all of them and their cursors.
    pub fn cancel_token(&self) -> CancelToken {
        self.image.cancel_token()
    }

    /// The start and duration timecodes of track `number` (1-based) of the area from `slot`
    /// as stored in the area TOC's `SACDTRL2` (specification 3, 3.7.2), byte for byte:
    /// before the clamping of 3.9.2 and whatever their range, so that a stored timecode
    /// such as 255:255:255 is given as stored.
    /// [`crate::Track::start_frame`] and [`crate::Track::duration_frames`] are their frame
    /// numbers after clamping. The area's play time as stored is [`crate::Area::playtime`].
    ///
    /// # Errors
    ///
    /// [`Error::NoSuchArea`] or [`Error::NoSuchTrack`].
    pub fn track_timecodes_stored(&self, slot: Slot, number: u32) -> Result<(Timecode, Timecode), Error> {
        self.find_track(slot, number)?;
        self.shared.stored.track_timecodes(slot, number).ok_or(Error::NoSuchTrack { slot, track: number })
    }

    /// The warnings emitted while reading the TOC (specification 7, 7.7.3).
    pub fn warnings(&self) -> &[Warning] {
        &self.shared.warnings
    }

    /// Keeps a seek index of the area from `slot`, empty to begin with, and makes and
    /// continues that area's cursors from it (see [Seeking](Self#seeking)); an index
    /// already kept is replaced. Every disc of the image ([`Disc::share`], `clone`) keeps
    /// the same index: this, [`Disc::set_seek_index`] and [`Disc::take_seek_index`] change
    /// it for all of them.
    ///
    /// # Errors
    ///
    /// [`Error::NoSuchArea`], or [`Error::InvalidArgument`] for invalid options.
    pub fn enable_seek_index(&mut self, slot: Slot, options: IndexOptions) -> Result<(), Error> {
        let area = self.shared.toc.area(slot).ok_or(Error::NoSuchArea(slot))?;
        let mut index = AreaIndex::new(area, self.image.sector_count(), options)?;
        index.bind_fingerprint(crate::seek::toc_fingerprint(&self.shared.toc, slot))?;
        sb_log!(self.log(), Debug, "area {slot}: seek index enabled, interval {} sectors", options.interval);
        self.shared.seek.write(slot, |kept| *kept = Some(index));
        Ok(())
    }

    /// Keeps `index` (for example one loaded with [`AreaIndex::from_bytes`]) as the seek
    /// index of the area from `slot`, as [`Disc::enable_seek_index`] does an empty one. It
    /// is trusted to be of this disc's image (see [One index per
    /// image](AreaIndex#one-index-per-image)): whatever image it was built from in this
    /// process, it takes this disc's from then on.
    ///
    /// An index a disc kept before (saved with [`AreaIndex::to_bytes`] from version 2 of
    /// its format on) holds a fingerprint of that disc's TOC (the master TOC, the area TOC
    /// and the image's sector count; see [`AreaIndex#seek-hints`]): an index of another disc
    /// of the same layout is refused. One without (made with [`AreaIndex::new`], or saved
    /// in version 1) takes this disc's. Saved confirmations and exact checkpoints are then
    /// trusted for this image whenever the TOC fingerprint and key match, so a re-rip with
    /// different audio bytes would get confirmed or exact 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.
    ///
    /// Verdicts `index` holds that [`AreaIndex::take_events`] has not taken go to
    /// [`Disc::take_seek_events`].
    ///
    /// # Errors
    ///
    /// [`Error::NoSuchArea`], or [`Error::InvalidArgument`] if `index` is of another area
    /// or image size, or of a disc with another TOC.
    pub fn set_seek_index(&mut self, slot: Slot, mut index: AreaIndex) -> Result<(), Error> {
        let area = self.shared.toc.area(slot).ok_or(Error::NoSuchArea(slot))?;
        index.check_key(area, self.image.sector_count())?;
        index.bind_fingerprint(crate::seek::toc_fingerprint(&self.shared.toc, slot))?;
        // Trusted to be of this image, as a loaded one is: it is this image's from its
        // first absorb on.
        index.forget_image();
        sb_log!(
            self.log(),
            Debug,
            "area {slot}: seek index set, frontier LSN {}{}",
            index.frontier(),
            if index.is_complete() { ", complete" } else { "" }
        );
        // A kept index holds no verdicts (see `extend_seek_index`).
        self.shared.seek.push_events(slot, index.take_events());
        self.shared.seek.write(slot, |kept| *kept = Some(index));
        Ok(())
    }

    /// Sets how this disc handle starts ranges of the area from `slot` that its seek index
    /// (if any) cannot reach cheaply: [`SeekPolicy::Exact`] (the default) or
    /// [`SeekPolicy::Speculative`], which allows provisional reading (specification 4, 4.2
    /// item 8, sacd-spec `82eac6c`; see [`SeekPolicy`] for what it guarantees). The policy is
    /// this handle's: discs made from it by [`Disc::share`] and `clone` start with a copy,
    /// and each may change its own. It applies to the cursors this handle makes and
    /// continues from then on.
    ///
    /// # Errors
    ///
    /// [`Error::NoSuchArea`].
    pub fn set_seek_policy(&mut self, slot: Slot, policy: SeekPolicy) -> Result<(), Error> {
        self.shared.toc.area(slot).ok_or(Error::NoSuchArea(slot))?;
        sb_log!(self.log(), Debug, "area {slot}: seek policy {policy:?}");
        self.policy[slot_index(slot)] = policy;
        Ok(())
    }

    /// The seek policy of the area from `slot` for this handle.
    pub fn seek_policy(&self, slot: Slot) -> SeekPolicy {
        self.policy[slot_index(slot)]
    }

    /// The seek policy the cursors of the area from `slot` are made with: this handle's,
    /// with the area's layout checked against the TOC ([`crate::Suspect::AreaLayout`]).
    fn cursor_policy(&self, slot: Slot) -> SeekPolicy {
        match self.seek_policy(slot) {
            SeekPolicy::Speculative(mut options) => {
                options.layout_suspect = crate::seek::layout_suspect(&self.shared.toc, slot);
                SeekPolicy::Speculative(options)
            }
            exact => exact,
        }
    }

    /// Stops keeping a seek index of the area from `slot`, and returns it.
    pub fn take_seek_index(&mut self, slot: Slot) -> Option<AreaIndex> {
        self.shared.seek.write(slot, Option::take)
    }

    /// A copy of the seek index of the area from `slot`, if one is kept: to save it
    /// ([`AreaIndex::to_bytes`]) or to merge it with another.
    pub fn seek_index(&self, slot: Slot) -> Option<AreaIndex> {
        self.shared.seek.read(slot, |kept| kept.cloned())
    }

    /// Reads the area from `slot` on from its seek index's frontier, about `max_sectors`
    /// sectors, recording checkpoints (see [`AreaIndex::extend`]): whether the index is
    /// now complete. Reading a whole area this way builds the index for all its ranges at
    /// the cost of one pass. It also checks the provisional readings the index now reaches
    /// ([`AreaIndex::verify`]): their verdicts go to [`Disc::take_seek_events`] and to the
    /// cursors that made them. A complete index says nothing of a reading registered during
    /// this call, which [`Disc::verify_speculation`] does account for.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidArgument`] if no seek index is kept for `slot` or it does not match
    /// the image, [`Error::Io`] if a read fails.
    pub fn extend_seek_index(&mut self, slot: Slot, max_sectors: u64) -> Result<bool, Error> {
        // A copy is extended, then merged back: the index stays usable meanwhile (by discs
        // that share it) and no lock is held while the image is read.
        let Some(mut index) = self.seek_index(slot) else {
            return Err(Error::InvalidArgument("no seek index kept for the area"));
        };
        let result = index.extend(&mut self.image, max_sectors);
        self.shared.seek.push_events(slot, index.take_events());
        // A kept index holds no verdicts: a merge past the cap settles some, which go to the
        // queue now. Left there, each later copy would queue them again.
        let merged = self.shared.seek.write(slot, |kept| match kept {
            Some(kept) => kept.merge(&index).map(|()| (kept.is_complete(), kept.take_events())),
            None => Ok((false, Vec::new())),
        });
        match (result, merged) {
            (Err(e), _) | (Ok(_), Err(e)) => Err(e),
            (Ok(_), Ok((complete, events))) => {
                self.shared.seek.push_events(slot, events);
                Ok(complete)
            }
        }
    }

    /// Builds the seek index of the area from `slot` by about `max_sectors` more sectors
    /// and checks the provisional readings it then reaches (specification 4, 4.2 item 8):
    /// [`Disc::extend_seek_index`], named for what a caller of [`SeekPolicy::Speculative`]
    /// runs it for, typically in a loop on a clone of the disc in another thread.
    ///
    /// Returns `true` when, at this call's last look at the index, the index was complete
    /// and every provisional reading it held had its verdict. Returns `false` otherwise, with
    /// nothing wrong: call again. That includes a complete index holding a reading that
    /// another disc registered during this call, which this call's check did not see.
    ///
    /// `true` covers only the readings the index held by then. A reading joins the index when
    /// its first frame is read through a disc's iterators or
    /// [`Disc::absorb_seek_checkpoints`], and one that joins later, even before this call
    /// returns, has no verdict and no event until a later call. A caller that must have every
    /// verdict runs its `while !disc.verify_speculation(..)? {}` loop once more after its
    /// readers have finished, then checks each reading's own `speculation()`: a reading with
    /// no verdict has no event.
    ///
    /// Each call makes one round: about `max_sectors` sectors of the pass (at least to the
    /// next checkpoint, so that 0 makes progress), then the check of the readings the index
    /// reached and held when the round began. `max_sectors` does not limit those checks: each
    /// reads a bounded number of sectors, and the number of readings waiting is bounded too.
    /// Once no disc registers new readings, a loop ends: every `false` either added a
    /// checkpoint or came from a reading that the next call checks.
    ///
    /// # Errors
    ///
    /// As [`Disc::extend_seek_index`].
    pub fn verify_speculation(&mut self, slot: Slot, max_sectors: u64) -> Result<bool, Error> {
        let complete = self.extend_seek_index(slot, max_sectors)?;
        // A reading registered during the round is not in the copy it checked: not done yet.
        // The next call checks it, within its own budget.
        let unchecked = |kept: Option<&AreaIndex>| kept.is_some_and(AreaIndex::has_reached_claims);
        Ok(complete && !self.shared.seek.read(slot, unchecked))
    }

    /// Takes the verdicts on provisional readings of the area from `slot` reached since the
    /// last call, by this disc or any disc made from it by [`Disc::share`] or `clone`
    /// (they share the queue): [`Speculation::Confirmed`], [`Speculation::Refuted`] (the
    /// positions below its `exact_from` are possibly different from the specification's:
    /// drop or re-read what was served from them; an exact read of them is now cheap, from
    /// the index) or [`Speculation::Unverified`]. A provisional reading is checked only
    /// when the disc keeps a seek index of its area ([`Disc::enable_seek_index`]).
    pub fn take_seek_events(&self, slot: Slot) -> Vec<crate::seek::SeekEvent> {
        self.shared.seek.take_events(slot)
    }

    /// Takes into the seek index of its area the checkpoints `cursor` recorded, for a
    /// cursor read without this disc's iterators (with [`TrackAudioCursor::next_frame`]
    /// on [`Disc::image_mut`]); the iterators and continuations do this themselves. Only
    /// cursors made from the index by a disc of this image (this one, or one made by
    /// [`Disc::share`] or `clone`) that read this image are taken. Nothing happens for
    /// others: cursors made from a caller's index or without one, and cursors whose
    /// checkpoints do not join the index. A cursor of another image (of the same size and
    /// layout) stops recording instead, so that its checkpoints never reach this index.
    pub fn absorb_seek_checkpoints(&self, cursor: &mut impl crate::audio::SeekCursor) {
        self.shared.seek.absorb(crate::audio::sealed::Sealed::area_cursor_mut(cursor), self.image.id());
    }

    /// The diagnostic form of [`Disc::stored_frame_list`]: the accepted frames of the area
    /// from `slot`, read from its audio sectors (specification 4, 4.2 to 4.5), whatever the
    /// area's channel count, without the list's channel check. To read a disc's stored
    /// frames, use [`Disc::stored_frame_list`].
    ///
    /// # Errors
    ///
    /// [`Error::NoSuchArea`] if the TOC has no area from that slot.
    pub fn area_frames(&mut self, slot: Slot) -> Result<AreaFrames<'_, R>, Error> {
        let area = self.shared.toc.area(slot).ok_or(Error::NoSuchArea(slot))?;
        Ok(AreaFrames::new(&mut self.image, area))
    }

    /// The **stored frame list** of the area from `slot` (specification 4, 4.6.1 item 2):
    /// every accepted frame of the area in frame number order, frames numbered at or past
    /// the play time included, each with its number, kind and bytes as stored. Every audio
    /// sector is processed, with no early stop; positions not in the list are missing.
    /// There are no DST equivalents for the list (4.6.1 item 4: only for tracks and ranges).
    ///
    /// These are the frames of [`Disc::area_frames`], offered only for an area whose
    /// channel count is 1 to 6 (4.6.1 item 1).
    ///
    /// # Errors
    ///
    /// [`Error::NoSuchArea`] or [`Error::ChannelCountUnsupported`].
    pub fn stored_frame_list(&mut self, slot: Slot) -> Result<AreaFrames<'_, R>, Error> {
        let cursor = self.stored_frame_list_cursor(slot)?;
        Ok(AreaFrames::with_cursor(&mut self.image, cursor))
    }

    /// The reading state of [`Disc::stored_frame_list`], for callers that cannot hold the
    /// borrow; advance it with [`AreaCursor::next_frame`], passing [`Disc::image_mut`].
    ///
    /// # Errors
    ///
    /// As [`Disc::stored_frame_list`].
    pub fn stored_frame_list_cursor(&self, slot: Slot) -> Result<AreaCursor, Error> {
        let area = self.shared.toc.area(slot).ok_or(Error::NoSuchArea(slot))?;
        audio::check_channels(area)
            .inspect_err(|e| sb_log!(self.log(), Info, "area {slot} stored frame list: {e}"))?;
        sb_log!(
            self.log(),
            Info,
            "area {slot} stored frame list ({} channels), new scan of the area",
            area.channel_count
        );
        Ok(AreaCursor::new(area, self.image.sector_count()))
    }

    /// What the TOC of the area from `slot` claims against the audio sectors this image
    /// holds (specification 4, 4.2 and 4.8): see [`audio::area_capacity`] and
    /// [`AreaCapacity`]. It reads nothing: the figures come from the TOC and the image
    /// size known since the disc was opened. The consumer chooses the threshold, for
    /// example on [`AreaCapacity::frames_per_sector`].
    ///
    /// # Errors
    ///
    /// [`Error::NoSuchArea`] if the TOC has no area from that slot.
    pub fn area_capacity(&self, slot: Slot) -> Result<AreaCapacity, Error> {
        let area = self.shared.toc.area(slot).ok_or(Error::NoSuchArea(slot))?;
        Ok(audio::area_capacity(area, self.image.sector_count()))
    }

    /// Whether track `number` of the area from `slot` produces audio (specification 4,
    /// 4.8).
    ///
    /// # Errors
    ///
    /// The per-track outcomes [`Error::ChannelCountUnsupported`], [`Error::TrackEmpty`]
    /// and [`Error::TrackExceedsCapacity`], or [`Error::NoSuchArea`] /
    /// [`Error::NoSuchTrack`].
    pub fn check_track(&self, slot: Slot, number: u32) -> Result<(), Error> {
        let (area, track) = self.find_track(slot, number)?;
        audio::check_track(area, track, self.image.sector_count())
            .inspect_err(|e| sb_log!(self.log(), Info, "area {slot} track {number}: no audio: {e}"))
    }

    /// The track a slot and number name, with its area; logs a track that does not exist.
    fn find_track(&self, slot: Slot, number: u32) -> Result<(&crate::Area, &crate::Track), Error> {
        audio::find_track(&self.shared.toc.areas, slot, number)
            .inspect_err(|e| sb_log!(self.log(), Info, "area {slot} track {number}: {e}"))
    }

    /// A cursor of the range `[first, end)` of `area`, already checked: from the area's
    /// seek index if one is kept, else a new scan, with `policy`; logs the opening of `what`
    /// (track `track`, if one).
    fn disc_index_cursor(
        &self,
        area: &crate::Area,
        (first, end): (u32, u32),
        track: Option<u32>,
        what: &str,
        policy: SeekPolicy,
    ) -> TrackCursor {
        let n = self.image.sector_count();
        let (cursor, how) = self.shared.seek.read(area.slot, |index| {
            let mut cursor = TrackCursor::start_with(area, (first, end), n, index, policy);
            if index.is_some() {
                cursor.area_mut().keep_for_disc();
            }
            let how = match (cursor.speculation(), index) {
                (Speculation::Exact, Some(_)) => "from the seek index",
                (Speculation::Exact, None) => "new scan of the area",
                // Chosen on the first read, logged then.
                _ => "provisional start allowed (4.2 item 8)",
            };
            (cursor, how)
        });
        // Logged after the lock is released.
        audio::log_open(self.log(), area, track, (first, end), what, how);
        cursor
    }

    /// The timeline positions of track `number` (1-based) of the area from `slot`, each
    /// holding a plain DSD frame, a DST frame or nothing (specification 4, 4.6 and 4.7).
    ///
    /// Plain DSD frames are passed through unchanged; see [`Disc::track_audio`] for
    /// decoded audio.
    ///
    /// # Errors
    ///
    /// As [`Disc::check_track`].
    pub fn track_frames(&mut self, slot: Slot, number: u32) -> Result<TrackFrames<'_, R>, Error> {
        let cursor = self.frames_cursor(slot, FrameSpan::Track(number), CursorOptions::new())?;
        Ok(TrackFrames::with_cursor(&mut self.image, cursor, Some(&self.shared.seek)))
    }

    /// The reading state of a track or frame range's positions (see [`Disc::track_frames`]
    /// and [`Disc::range_frames`]), from a shared borrow, for callers that cannot hold the
    /// iterator's; read it with [`Disc::read_frames`]. With `&mut self`,
    /// [`TrackFrames::into_cursor`] gives the same. See [`CursorOptions`] for the seek index
    /// and policy; by default they are the disc's for the area.
    ///
    /// # Errors
    ///
    /// As [`Disc::check_track`] or [`Disc::check_range`], then [`Error::InvalidArgument`] if
    /// the options' index is of another area or image size.
    pub fn frames_cursor(
        &self,
        slot: Slot,
        span: FrameSpan,
        options: CursorOptions<'_>,
    ) -> Result<TrackCursor, Error> {
        self.open_cursor(slot, span, options, "frames")
    }

    /// The cursor of `span`, after its checks: from the seek index of `options` or else the
    /// disc's, with the policy of `options` or else the disc's; logs the opening of `what`.
    fn open_cursor(
        &self,
        slot: Slot,
        span: FrameSpan,
        options: CursorOptions<'_>,
        what: &str,
    ) -> Result<TrackCursor, Error> {
        let (area, range, track) = match span {
            FrameSpan::Track(number) => {
                self.check_track(slot, number)?;
                let (area, track) = audio::find_track(&self.shared.toc.areas, slot, number)?;
                (area, (track.start_frame, track.end_frame()), Some(number))
            }
            FrameSpan::Range(first, end) => {
                self.check_range(slot, first, end)?;
                (self.shared.toc.area(slot).ok_or(Error::NoSuchArea(slot))?, (first, end), None)
            }
        };
        let policy = match options.policy() {
            Some(SeekPolicy::Speculative(mut o)) => {
                o.layout_suspect = crate::seek::layout_suspect(&self.shared.toc, slot);
                SeekPolicy::Speculative(o)
            }
            Some(policy) => policy,
            None => self.cursor_policy(slot),
        };
        let Some(index) = options.index() else {
            return Ok(self.disc_index_cursor(area, range, track, what, policy));
        };
        let n = self.image.sector_count();
        let (first, end) = range;
        index.check_key(area, n).inspect_err(|e| match track {
            Some(number) => sb_log!(self.log(), Info, "area {slot} track {number}: {e}"),
            None => sb_log!(self.log(), Info, "area {slot} range: frames {first}..{end}: {e}"),
        })?;
        audio::log_open(self.log(), area, track, range, what, "from the seek index");
        Ok(TrackCursor::start_with(area, range, n, Some(index), policy))
    }

    /// [`Disc::frames_cursor`] of a track.
    ///
    /// # Errors
    ///
    /// As [`Disc::check_track`].
    #[deprecated(
        since = "0.6.0",
        note = "use `Disc::frames_cursor` with `FrameSpan::Track(number)`, or `Disc::track_frames` and `into_cursor`"
    )]
    pub fn track_frames_cursor(&self, slot: Slot, number: u32) -> Result<TrackCursor, Error> {
        self.frames_cursor(slot, FrameSpan::Track(number), CursorOptions::new())
    }

    /// The timeline positions of the frame range `[first, end)` of the area from `slot`,
    /// without decoding: for each position, its frame number and the frame as stored (DST
    /// bytes, plain DSD bytes) or nothing, exactly the frames that [`Disc::range_audio`]
    /// decodes. The whole area is `[0, P)` with `P` the area's play time.
    ///
    /// # Errors
    ///
    /// As [`Disc::check_range`].
    pub fn range_frames(&mut self, slot: Slot, first: u32, end: u32) -> Result<TrackFrames<'_, R>, Error> {
        let cursor = self.frames_cursor(slot, FrameSpan::Range(first, end), CursorOptions::new())?;
        Ok(TrackFrames::with_cursor(&mut self.image, cursor, Some(&self.shared.seek)))
    }

    /// [`Disc::frames_cursor`] of a frame range.
    ///
    /// # Errors
    ///
    /// As [`Disc::check_range`].
    #[deprecated(
        since = "0.6.0",
        note = "use `Disc::frames_cursor` with `FrameSpan::Range(first, end)`, or `Disc::range_frames` and `into_cursor`"
    )]
    pub fn range_frames_cursor(&self, slot: Slot, first: u32, end: u32) -> Result<TrackCursor, Error> {
        self.frames_cursor(slot, FrameSpan::Range(first, end), CursorOptions::new())
    }

    /// The reading state of track `number`'s positions, continuing `prev` (the state of an
    /// earlier track or range) without rescanning the area when the result is the same,
    /// as [`Disc::continue_track_audio`] does for decoded audio.
    ///
    /// # Errors
    ///
    /// As [`Disc::check_track`].
    pub fn continue_track_frames(
        &self,
        prev: TrackCursor,
        slot: Slot,
        number: u32,
    ) -> Result<TrackCursor, Error> {
        Ok(self.track_continuation(slot, number)?.frames(prev))
    }

    /// The reading state of the positions of the frame range `[first, end)`, continuing
    /// `prev` as [`Disc::continue_range_audio`] does for decoded audio.
    ///
    /// # Errors
    ///
    /// As [`Disc::check_range`].
    pub fn continue_range_frames(
        &self,
        prev: TrackCursor,
        slot: Slot,
        first: u32,
        end: u32,
    ) -> Result<TrackCursor, Error> {
        Ok(self.range_continuation(slot, first, end)?.frames(prev))
    }

    /// The borrowing iterator over a track (or range) reading state of this disc.
    pub fn read_frames(&mut self, cursor: TrackCursor) -> TrackFrames<'_, R> {
        TrackFrames::with_cursor(&mut self.image, cursor, Some(&self.shared.seek))
    }

    /// The decoded audio of track `number` (1-based) of the area from `slot`: every
    /// timeline position as `C x 4704` interleaved DSD bytes, DST frames decoded and
    /// missing or invalid frames filled (specification 4, 4.6).
    ///
    /// # Errors
    ///
    /// As [`Disc::check_track`].
    pub fn track_audio(&mut self, slot: Slot, number: u32) -> Result<TrackAudio<'_, R>, Error> {
        let cursor = self.audio_cursor(slot, FrameSpan::Track(number), CursorOptions::new())?;
        Ok(TrackAudio::with_cursor(&mut self.image, cursor, Some(&self.shared.seek)))
    }

    /// Whether the frame range `[first, end)` of the area from `slot` produces audio: it
    /// must lie in the area's play range, `first <= end <= P` with `P` the area's play
    /// time ([`crate::Area::playtime_frames`]), and pass the checks of specification 4,
    /// 4.8 as a track would (4.7.1; see [`audio::check_range`]).
    ///
    /// # Errors
    ///
    /// [`Error::ChannelCountUnsupported`], [`Error::FrameRangeInvalid`],
    /// [`Error::TrackEmpty`] and [`Error::TrackExceedsCapacity`], or [`Error::NoSuchArea`].
    pub fn check_range(&self, slot: Slot, first: u32, end: u32) -> Result<(), Error> {
        self.shared
            .toc
            .area(slot)
            .ok_or(Error::NoSuchArea(slot))
            .and_then(|area| audio::check_range(area, first, end, self.image.sector_count()))
            .inspect_err(|e| {
                sb_log!(self.log(), Info, "area {slot} range: frames {first}..{end}: no audio: {e}")
            })
    }

    /// The decoded audio of the frame range `[first, end)` of the area from `slot`: every
    /// timeline position from `first` to `end - 1`, exactly as [`Disc::track_audio`] gives
    /// a track's. The whole area, pauses included, is `[0, P)` with `P` the area's play
    /// time. For a track with pause (specification 4, 4.7.1 item 5: track 1 from frame 0,
    /// every other track from its own start; every track to the larger of its own end and
    /// the next-numbered track's start, the last to the play time; used as they are when
    /// tracks overlap or are out of order), use the range from
    /// [`Disc::track_range_with_pause`].
    ///
    /// # Errors
    ///
    /// As [`Disc::check_range`].
    pub fn range_audio(&mut self, slot: Slot, first: u32, end: u32) -> Result<TrackAudio<'_, R>, Error> {
        let cursor = self.audio_cursor(slot, FrameSpan::Range(first, end), CursorOptions::new())?;
        Ok(TrackAudio::with_cursor(&mut self.image, cursor, Some(&self.shared.seek)))
    }

    /// The decoding state of a track or frame range (see [`Disc::track_audio`] and
    /// [`Disc::range_audio`]), from a shared borrow, for callers that cannot hold the
    /// iterator's (for example across an FFI boundary); read it with
    /// [`Disc::read_track_audio`], or advance it with [`TrackAudioCursor::next_frame`],
    /// passing this disc's [`Disc::image_mut`]. With `&mut self`,
    /// [`TrackAudio::into_cursor`] gives the same. See [`CursorOptions`] for the seek index
    /// and policy; by default they are the disc's for the area.
    ///
    /// # Errors
    ///
    /// As [`Disc::frames_cursor`].
    pub fn audio_cursor(
        &self,
        slot: Slot,
        span: FrameSpan,
        options: CursorOptions<'_>,
    ) -> Result<TrackAudioCursor, Error> {
        Ok(TrackAudioCursor::from_frames(self.open_cursor(slot, span, options, "decoded audio")?))
    }

    /// [`Disc::audio_cursor`] of a frame range.
    ///
    /// # Errors
    ///
    /// As [`Disc::check_range`].
    #[deprecated(
        since = "0.6.0",
        note = "use `Disc::audio_cursor` with `FrameSpan::Range(first, end)`, or `Disc::range_audio` and `into_cursor`"
    )]
    pub fn range_audio_cursor(&self, slot: Slot, first: u32, end: u32) -> Result<TrackAudioCursor, Error> {
        self.audio_cursor(slot, FrameSpan::Range(first, end), CursorOptions::new())
    }

    /// [`Disc::audio_cursor`] of a frame range, from the caller's seek `index` rather than
    /// the disc's ([`CursorOptions::with_index`]).
    ///
    /// # Errors
    ///
    /// As [`Disc::check_range`], then [`Error::InvalidArgument`] if `index` is of another
    /// area or image size.
    #[deprecated(
        since = "0.6.0",
        note = "use `Disc::audio_cursor` with `FrameSpan::Range(first, end)` and `CursorOptions::new().with_index(index)`"
    )]
    pub fn range_audio_cursor_indexed(
        &self,
        slot: Slot,
        first: u32,
        end: u32,
        index: &AreaIndex,
    ) -> Result<TrackAudioCursor, Error> {
        self.audio_cursor(slot, FrameSpan::Range(first, end), CursorOptions::new().with_index(index))
    }

    /// [`Disc::frames_cursor`] of a frame range, from the caller's seek `index` rather than
    /// the disc's ([`CursorOptions::with_index`]).
    ///
    /// # Errors
    ///
    /// As [`Disc::check_range`], then [`Error::InvalidArgument`] if `index` is of another
    /// area or image size.
    #[deprecated(
        since = "0.6.0",
        note = "use `Disc::frames_cursor` with `FrameSpan::Range(first, end)` and `CursorOptions::new().with_index(index)`"
    )]
    pub fn range_frames_cursor_indexed(
        &self,
        slot: Slot,
        first: u32,
        end: u32,
        index: &AreaIndex,
    ) -> Result<TrackCursor, Error> {
        self.frames_cursor(slot, FrameSpan::Range(first, end), CursorOptions::new().with_index(index))
    }

    /// The decoding state of the frame range `[first, end)` of the area from `slot`,
    /// continuing `prev` (a cursor of an earlier track or range) without rescanning the
    /// area when the result is the same, as [`Disc::continue_track_audio`] does for
    /// tracks. A range that fails [`Disc::check_range`] consumes `prev` without reuse.
    ///
    /// # Errors
    ///
    /// As [`Disc::check_range`].
    pub fn continue_range_audio(
        &self,
        prev: TrackAudioCursor,
        slot: Slot,
        first: u32,
        end: u32,
    ) -> Result<TrackAudioCursor, Error> {
        Ok(self.range_continuation(slot, first, end)?.audio(prev))
    }

    /// [`Disc::audio_cursor`] of a track.
    ///
    /// # Errors
    ///
    /// As [`Disc::check_track`].
    #[deprecated(
        since = "0.6.0",
        note = "use `Disc::audio_cursor` with `FrameSpan::Track(number)`, or `Disc::track_audio` and `into_cursor`"
    )]
    pub fn track_audio_cursor(&self, slot: Slot, number: u32) -> Result<TrackAudioCursor, Error> {
        self.audio_cursor(slot, FrameSpan::Track(number), CursorOptions::new())
    }

    /// The decoding state of track `number` of the area from `slot`, continuing `prev`
    /// (a cursor of an earlier track) without rescanning the area when the result is
    /// the same. Reading an area's tracks in increasing order this way reads each audio
    /// sector once. The state is reused when the track is in the same area of the same
    /// image and starts at or after the cursor's position, and no read has failed; the
    /// frames are always exactly those of a fresh scan (specification 4, 4.2 item 5). Frames
    /// of `prev` not yet returned are dropped, and the counts start again at 0. A track that
    /// fails [`Disc::check_track`] consumes `prev` without reuse, so check first to keep it.
    ///
    /// ```no_run
    /// # fn main() -> Result<(), scarletbook::Error> {
    /// # let mut disc = scarletbook::Disc::open(std::io::Cursor::new(Vec::new()))?;
    /// use scarletbook::{CursorOptions, FrameSpan, Slot};
    /// let count = disc.toc().area(Slot::TwoChannel).map_or(0, |a| a.tracks.len()) as u32;
    /// let mut cursor = None;
    /// for n in 1..=count {
    ///     if disc.check_track(Slot::TwoChannel, n).is_err() {
    ///         continue; // a track without audio; keep the cursor for the next one
    ///     }
    ///     let next = match cursor.take() {
    ///         Some(prev) => disc.continue_track_audio(prev, Slot::TwoChannel, n)?,
    ///         None => disc.audio_cursor(Slot::TwoChannel, FrameSpan::Track(n), CursorOptions::new())?,
    ///     };
    ///     let mut audio = disc.read_track_audio(next);
    ///     for frame in audio.by_ref() {
    ///         let _frame = frame?;
    ///     }
    ///     cursor = Some(audio.into_cursor());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// As [`Disc::check_track`].
    pub fn continue_track_audio(
        &self,
        prev: TrackAudioCursor,
        slot: Slot,
        number: u32,
    ) -> Result<TrackAudioCursor, Error> {
        Ok(self.track_continuation(slot, number)?.audio(prev))
    }

    /// Track `number` of the area from `slot`, checked ([`Disc::check_track`]), for a
    /// cursor to continue into without failing: [`Continuation::audio`] does what
    /// [`Disc::continue_track_audio`] does once the checks have passed. A caller that must
    /// not give up `prev` unless the continuation succeeds checks first, then hands it
    /// over.
    ///
    /// # Errors
    ///
    /// As [`Disc::check_track`].
    pub fn track_continuation(&self, slot: Slot, number: u32) -> Result<Continuation<'_>, Error> {
        self.check_track(slot, number)?;
        let (area, track) = audio::find_track(&self.shared.toc.areas, slot, number)?;
        let n = self.image.sector_count();
        let range = (track.start_frame, track.end_frame());
        // A cursor from another disc is never continued, whatever its layout.
        Ok(Continuation::new(
            area,
            range,
            (n, Some(self.image.id())),
            self.log(),
            Some(number),
            (&self.shared.seek, self.cursor_policy(area.slot)),
        ))
    }

    /// The frame range `[first, end)` of the area from `slot`, checked
    /// ([`Disc::check_range`]), for a cursor to continue into without failing (see
    /// [`Disc::track_continuation`]).
    ///
    /// # Errors
    ///
    /// As [`Disc::check_range`].
    pub fn range_continuation(&self, slot: Slot, first: u32, end: u32) -> Result<Continuation<'_>, Error> {
        self.check_range(slot, first, end)?;
        let area = self.shared.toc.area(slot).ok_or(Error::NoSuchArea(slot))?;
        let n = self.image.sector_count();
        // A cursor from another disc is never continued, whatever its layout.
        Ok(Continuation::new(
            area,
            (first, end),
            (n, Some(self.image.id())),
            self.log(),
            None,
            (&self.shared.seek, self.cursor_policy(area.slot)),
        ))
    }

    /// Track `number`'s track with pause (specification 4, 4.7.1 item 5): see
    /// [`audio::track_range_with_pause`].
    /// Pass it to [`Disc::range_audio`].
    ///
    /// # Errors
    ///
    /// [`Error::NoSuchArea`] or [`Error::NoSuchTrack`].
    pub fn track_range_with_pause(&self, slot: Slot, number: u32) -> Result<(u32, u32), Error> {
        let (area, _) = self.find_track(slot, number)?;
        audio::track_range_with_pause(area, number)
            .ok_or(Error::NoSuchTrack { slot, track: number })
            .inspect_err(|e| sb_log!(self.log(), Info, "area {slot} track {number}: {e}"))
    }

    /// The borrowing iterator over a track (or range) decoding state of this disc.
    pub fn read_track_audio(&mut self, cursor: TrackAudioCursor) -> TrackAudio<'_, R> {
        TrackAudio::with_cursor(&mut self.image, cursor, Some(&self.shared.seek))
    }

    /// The underlying image.
    pub fn image_mut(&mut self) -> &mut Image<R> {
        &mut self.image
    }

    /// Consumes the disc and returns the reader.
    pub fn into_inner(self) -> R {
        self.image.into_inner()
    }
}

/// A disc of the same image through another reader of the same source (see [Several
/// readers](Disc#several-readers)): no I/O and no check, the source being the same.
impl<A: ReadAt + Clone> Clone for Disc<ReadAtReader<A>> {
    fn clone(&self) -> Self {
        Disc { image: self.image.clone(), shared: Arc::clone(&self.shared), policy: self.policy }
    }
}

fn slot_index(slot: Slot) -> usize {
    match slot {
        Slot::TwoChannel => 0,
        Slot::Multichannel => 1,
    }
}

// Also loaded by `dispatch`'s tests, which only build with the `output` feature.
#[cfg(test)]
#[allow(clippy::duplicate_mod)]
#[path = "../tests/common/mod.rs"]
mod common;

#[cfg(test)]
mod tests {
    use std::io::Cursor;

    use super::common::{PFrame, S, Spec, TrackSpec, pack};
    use super::*;
    use crate::ReadAtReader;
    use crate::audio::FRAME_BYTES_PER_CHANNEL;

    /// A synthetic plain image of 9 positions.
    fn plain_image() -> Vec<u8> {
        let frames: Vec<PFrame> = (0..9)
            .map(|number| PFrame {
                number,
                dst: false,
                data: (0..2 * FRAME_BYTES_PER_CHANNEL).map(|i| (i as u32 * 7 + number * 13) as u8).collect(),
            })
            .collect();
        let tracks = vec![TrackSpec { start: 0, duration: 4 }, TrackSpec { start: 4, duration: 5 }];
        Spec { channels: 2, playtime: 9, tracks, audio: pack(&frames) }.build()
    }

    /// `plain` stored with `format`'s sector size.
    fn stored(plain: &[u8], format: SectorFormat) -> Vec<u8> {
        let (p, d) = (format.stored_size() as usize, format.data_offset() as usize);
        let mut out = vec![0u8; plain.len() / S * p];
        for (i, sector) in plain.chunks_exact(S).enumerate() {
            out[i * p + d..i * p + d + S].copy_from_slice(sector);
        }
        out
    }

    /// The area's frames; under Miri, which is slow, its first only.
    fn frames<R: Read + Seek>(disc: &mut Disc<R>) -> Vec<crate::AreaFrame> {
        let count = if cfg!(miri) { 1 } else { usize::MAX };
        disc.area_frames(Slot::TwoChannel).unwrap().take(count).map(Result::unwrap).collect()
    }

    /// A raw image's discs keep no read buffer once the TOC is read (#228): opened,
    /// shared or cloned. The first audio read allocates one, and reads what a plain image
    /// gives. Under Miri, which is slow, one raw format and one read of one frame: the
    /// buffer checks without the comparison of the frames.
    #[test]
    fn raw_disc_keeps_no_read_buffer_after_toc() {
        let plain = plain_image();
        let want = (!cfg!(miri)).then(|| frames(&mut Disc::open(Cursor::new(plain.as_slice())).unwrap()));
        let formats: &[SectorFormat] = if cfg!(miri) {
            &[SectorFormat::Raw2064]
        } else {
            &[SectorFormat::Raw2064, SectorFormat::Raw2054]
        };
        for &format in formats {
            let bytes = stored(&plain, format);
            let mut disc = Disc::open(Cursor::new(bytes.as_slice())).unwrap();
            assert_eq!(disc.image.format(), format);
            assert_eq!(disc.image.buffer_capacity(), 0);
            let mut shared = disc.share(Cursor::new(bytes.as_slice())).unwrap();
            assert_eq!(shared.image.buffer_capacity(), 0);
            let mut source = Disc::open(ReadAtReader::new(bytes.as_slice())).unwrap();
            let mut cloned = source.clone();
            assert_eq!((source.image.buffer_capacity(), cloned.image.buffer_capacity()), (0, 0));
            let first = frames(&mut disc);
            assert!(!first.is_empty());
            assert!(disc.image.buffer_capacity() > 0);
            if let Some(want) = &want {
                assert_eq!(&first, want);
                assert_eq!(&frames(&mut disc), want);
                assert_eq!(&frames(&mut shared), want);
                assert_eq!(&frames(&mut source), want);
                assert_eq!(&frames(&mut cloned), want);
            }
        }
    }
}