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

//! Output files: the layout of a DSF or DSDIFF file holding a track, a frame range or a
//! track with pause (specification 8), for writers and for filesystems that serve such
//! files without writing them (issue #131). This module, and the [`Disc`] methods that
//! make a [`Layout`], come with the `output` feature, which is on by default.
//!
//! A [`Layout`] is computed from the TOC alone (8.2.5): it knows the file's exact size and
//! every byte that is not audio before any audio sector is read. Its audio is described,
//! not held: [`Layout::positions_for`] gives the timeline positions that a byte range of
//! the file needs, and [`Layout::fill`] produces that byte range from the positions'
//! content, which the caller supplies through a [`PositionSource`] (from its own cache, for
//! example). [`Layout::read_at`] does both from a [`Disc`].
//!
//! ```no_run
//! # fn main() -> Result<(), scarletbook::Error> {
//! use scarletbook::output::{Format, OutputOptions};
//! use scarletbook::{Disc, Slot};
//!
//! let file = std::fs::File::open("disc.iso")?;
//! let mut disc = Disc::open(std::io::BufReader::new(file))?;
//! let (first, end) = disc.track_range_with_pause(Slot::TwoChannel, 1)?;
//! let layout = disc.output_layout(Slot::TwoChannel, first, end, Format::Dsf, &OutputOptions::default())?;
//! let mut header = vec![0; 4096];
//! let n = layout.read_at(&mut disc, 0, &mut header)?;
//! println!("{} bytes; the first {n} read", layout.size());
//! # Ok(())
//! # }
//! ```
//!
//! Every point where the formats allow more than one valid output (specification 8, 8.6,
//! "writer's choices") is a field of [`OutputOptions`], with a documented default.
//! The departures from the DSDIFF document that some existing programs make (8.7) are made
//! only when named in [`OutputOptions::dsdiff_departures`]; a file written with one is not a
//! conforming DSDIFF file.
//!
//! # Writing an area's tracks as separate files
//!
//! This crate has no several-files writer, because the calls below are all a fast one needs
//! (issue [#202], which holds the figures). Each file is a [`Layout`] of the track's range
//! ([`Disc::track_range_with_pause`]), filled from that range's audio. The forms differ in
//! how each track's reading starts, which decides their speed and whether the bytes are
//! exact:
//!
//! - **One track after another, with [`Disc::continue_range_audio`].** It reads each audio
//!   sector once. It costs the same as writing the area as one file, so splitting a
//!   sequential loop gains nothing. Don't call [`Disc::range_audio`] for each track instead:
//!   without a seek index, each call scans the area from its first sector. That measured
//!   more than 2x slower on a 16-track stereo area, and less on areas with fewer tracks.
//! - **Workers, seek index first.** One pass builds the index
//!   ([`Disc::extend_seek_index`]). Workers then take the next track, each through its own
//!   [`Disc::share`], and every track starts from the index.
//! - **Workers, speculative with verify.** Workers read under [`SeekPolicy::Speculative`]
//!   while one more thread runs [`Disc::verify_speculation`], so they don't wait for that
//!   pass. The bytes are written before their verdict: see the table.
//!
//! Workers gained on real storage in the figures on #202, but on one machine only. Those
//! figures aren't from your machine, so measure there. On another machine, a consumer's own
//! per-track writer was slower with all threads than with one. The figures don't cover an
//! fsync per file, a cold image, a real disc, a DST area or a write through the C interface,
//! and waiting for writeback narrowed the gain.
//!
//! ## Which forms establish exactness
//!
//! | Form | Positions | Exact? |
//! |---|---|---|
//! | One after another, [`SeekPolicy::Exact`] | Those of the specification (4.2 item 2) | Yes |
//! | Workers, seek index first | Those of the specification (4.2 item 7) | Yes, for an index built from this image. For a saved one, only if you know it is of these bytes (4.2 item 9) |
//! | Workers, speculative with verify | Provisional when written (4.2 item 8) | Only once the pass is complete and every reading is [`Speculation::Exact`] or [`Speculation::Confirmed`]. Rewrite the file of any other |
//! | Workers, speculative, no verifying pass | Provisional (4.2 item 8) | **No.** A speed figure only, not a way to write files |
//!
//! A provisional position is exact only under conditions (a) and (b) of specification 4, 4.2
//! item 8, and only a pass over the sectors before the reading's start establishes them. No
//! read of that start or later sectors can, so neither can a check of the file: the hashes of
//! the speculative rows on #202 matched on three synthetic images, which says nothing about
//! another disc. Until the verdicts are in, don't hand out a file of the verified form.
//!
//! So the unverified row on #202 is not the speed of exact output, and the example below
//! leaves that form out.
//!
//! ## Example
//!
//! Each file here has the default [`OutputOptions`] and stands alone. Gapless files
//! ([`plan_dsf_chain`]) are not covered.
//!
//! ```no_run
//! use std::borrow::Cow;
//! use std::collections::VecDeque;
//! use std::fs::File;
//! use std::io::{BufReader, Read, Seek, Write};
//! use std::path::Path;
//! use std::sync::atomic::{AtomicUsize, Ordering};
//!
//! use scarletbook::audio::{AudioFrame, TrackAudio};
//! use scarletbook::output::{Format, OutputOptions, PositionSource};
//! use scarletbook::seek::{IndexOptions, SeekPolicy, Speculation, SpeculativeOptions};
//! use scarletbook::{CursorOptions, Disc, Error, FrameSpan, Slot, TrackAudioCursor};
//!
//! const BUFFER: usize = 4 << 20;
//!
//! /// The positions of one range in order, with the last few kept: `Layout::fill` may ask
//! /// for a position again.
//! struct Window<'a, R> {
//!     frames: TrackAudio<'a, R>,
//!     kept: VecDeque<AudioFrame>,
//! }
//!
//! impl<R: Read + Seek> PositionSource for Window<'_, R> {
//!     fn content(&mut self, t: u32) -> Result<Cow<'_, [u8]>, Error> {
//!         while self.kept.back().is_none_or(|f| f.number < t) {
//!             let frame = self.frames.next().ok_or(Error::InvalidArgument("past the range"))??;
//!             self.kept.push_back(frame);
//!         }
//!         while self.kept.front().is_some_and(|f| f.number.saturating_add(4) < t) {
//!             self.kept.pop_front();
//!         }
//!         let front = self.kept.front().map_or(t, |f| f.number);
//!         let i = t.checked_sub(front).ok_or(Error::InvalidArgument("no longer held"))?;
//!         let frame = self.kept.get(i as usize).ok_or(Error::InvalidArgument("not held"))?;
//!         Ok(Cow::Borrowed(&frame.data))
//!     }
//! }
//!
//! /// Writes the file of track `n`, continuing `prev` if there is one. Returns the reading's
//! /// state, which knows its verdict.
//! fn write_track<R: Read + Seek>(
//!     disc: &mut Disc<R>,
//!     slot: Slot,
//!     n: u32,
//!     prev: Option<TrackAudioCursor>,
//!     dir: &Path,
//!     buf: &mut [u8],
//! ) -> Result<TrackAudioCursor, Error> {
//!     let (first, end) = disc.track_range_with_pause(slot, n)?;
//!     let layout = disc.output_layout(slot, first, end, Format::Dsf, &OutputOptions::default())?;
//!     let cursor = match prev {
//!         Some(prev) => disc.continue_range_audio(prev, slot, first, end)?,
//!         None => disc.audio_cursor(slot, FrameSpan::Range(first, end), CursorOptions::new())?,
//!     };
//!     let mut source = Window { frames: disc.read_track_audio(cursor), kept: VecDeque::new() };
//!     let mut file = File::create(dir.join(format!("{n:03}.dsf")))?;
//!     let mut offset = 0;
//!     while offset < layout.size() {
//!         let filled = layout.fill(offset, buf, &mut source)?;
//!         file.write_all(&buf[..filled])?;
//!         offset += filled as u64;
//!     }
//!     Ok(source.frames.into_cursor())
//! }
//!
//! /// The area's track numbers.
//! fn track_numbers<R: Read + Seek>(disc: &Disc<R>, slot: Slot) -> Result<Vec<u32>, Error> {
//!     let area = disc.toc().area(slot).ok_or(Error::NoSuchArea(slot))?;
//!     Ok(area.tracks.iter().map(|t| u32::from(t.number)).collect())
//! }
//!
//! /// One track after another: exact, and each audio sector read once.
//! fn in_order(image: &Path, slot: Slot, dir: &Path) -> Result<(), Error> {
//!     let mut disc = Disc::open(BufReader::new(File::open(image)?))?;
//!     let mut buf = vec![0; BUFFER];
//!     let mut cursor = None;
//!     for n in track_numbers(&disc, slot)? {
//!         cursor = Some(write_track(&mut disc, slot, n, cursor.take(), dir, &mut buf)?);
//!     }
//!     Ok(())
//! }
//!
//! /// `workers` threads taking the next track, each through a disc of its own. Returns each
//! /// track's reading state.
//! fn write_from_workers(
//!     root: &Disc<BufReader<File>>,
//!     image: &Path,
//!     slot: Slot,
//!     dir: &Path,
//!     workers: usize,
//! ) -> Result<Vec<(u32, TrackAudioCursor)>, Error> {
//!     let numbers = track_numbers(root, slot)?;
//!     let next = AtomicUsize::new(0);
//!     std::thread::scope(|scope| {
//!         let work = || -> Result<Vec<(u32, TrackAudioCursor)>, Error> {
//!             let mut disc = root.share(BufReader::new(File::open(image)?))?;
//!             let mut buf = vec![0; BUFFER];
//!             let mut written = Vec::new();
//!             while let Some(&n) = numbers.get(next.fetch_add(1, Ordering::Relaxed)) {
//!                 written.push((n, write_track(&mut disc, slot, n, None, dir, &mut buf)?));
//!             }
//!             Ok(written)
//!         };
//!         let handles: Vec<_> =
//!             (0..workers.clamp(1, numbers.len().max(1))).map(|_| scope.spawn(work)).collect();
//!         let mut written = Vec::new();
//!         for handle in handles {
//!             written.extend(handle.join().expect("a worker panicked")?);
//!         }
//!         Ok(written)
//!     })
//! }
//!
//! /// Workers, seek index first: exact, at the cost of one more pass.
//! fn index_first(image: &Path, slot: Slot, dir: &Path, workers: usize) -> Result<(), Error> {
//!     let mut root = Disc::open(BufReader::new(File::open(image)?))?;
//!     root.enable_seek_index(slot, IndexOptions::new())?;
//!     while !root.extend_seek_index(slot, u64::MAX)? {}
//!     write_from_workers(&root, image, slot, dir, workers)?;
//!     Ok(())
//! }
//!
//! /// Workers, speculative with verify: the files are provisional until this returns, and
//! /// exact only when it returns `Ok`.
//! fn speculative_with_verify(image: &Path, slot: Slot, dir: &Path, workers: usize) -> Result<(), Error> {
//!     let mut root = Disc::open(BufReader::new(File::open(image)?))?;
//!     // Without a seek index, no reading is ever checked.
//!     root.enable_seek_index(slot, IndexOptions::new())?;
//!     root.set_seek_policy(slot, SeekPolicy::Speculative(SpeculativeOptions::new()))?;
//!     let written = std::thread::scope(|scope| {
//!         let verifier = scope.spawn(|| -> Result<(), Error> {
//!             let mut disc = root.share(BufReader::new(File::open(image)?))?;
//!             while !disc.verify_speculation(slot, u64::MAX)? {}
//!             Ok(())
//!         });
//!         let written = write_from_workers(&root, image, slot, dir, workers);
//!         verifier.join().expect("the verifier panicked")?;
//!         written
//!     })?;
//!     // Once more, for a reading that began while that pass was ending: it has no verdict yet.
//!     while !root.verify_speculation(slot, u64::MAX)? {}
//!     // Each reading's own state, not the events: a reading with no verdict has no event.
//!     root.set_seek_policy(slot, SeekPolicy::Exact)?;
//!     let mut buf = vec![0; BUFFER];
//!     for (n, reading) in written {
//!         if !matches!(reading.speculation(), Speculation::Exact | Speculation::Confirmed { .. }) {
//!             write_track(&mut root, slot, n, None, dir, &mut buf)?;
//!         }
//!     }
//!     Ok(())
//! }
//!
//! fn main() -> Result<(), Error> {
//!     let (image, slot, dir) = (Path::new("disc.iso"), Slot::TwoChannel, Path::new("out"));
//!     in_order(image, slot, dir)?;
//!     index_first(image, slot, dir, 8)?;
//!     speculative_with_verify(image, slot, dir, 8)
//! }
//! ```
//!
//! [#202]: https://github.com/aclater/scarletbook-rs/issues/202
//! [`Speculation::Exact`]: crate::seek::Speculation::Exact
//! [`Speculation::Confirmed`]: crate::seek::Speculation::Confirmed
//! [`SeekPolicy::Exact`]: crate::seek::SeekPolicy::Exact
//! [`SeekPolicy::Speculative`]: crate::seek::SeekPolicy::Speculative

mod dsdiff;
mod dsdiff_dst;
mod dsdiff_text;
mod dsf;
mod id3;
mod markers;
mod tags;

use std::borrow::Cow;
use std::collections::{BTreeSet, VecDeque};
use std::io::{Read, Seek};
use std::ops::Range;

use crate::audio::{
    self, AudioFrame, FRAME_BYTES_PER_CHANNEL, FrameContent, TrackAudio, TrackFrame, TrackFrames,
};
use crate::disc::Disc;
use crate::dispatch::{self, Isa};
use crate::dst::DstDecoder;
use crate::error::{Error, Slot};
use crate::toc::{Area, Toc, TocDigests, Track};

pub use dsdiff::{CallerChunk, DsdiffDeparture, LocalChunk, PropertyChunk};
pub use dsdiff_dst::{DstIndexOffset, DstLengths, InvalidDst};
pub use dsdiff_text::{Comment, CommentKind};
pub use dsf::{DsfBitsPerSample, DsfChainFile, plan_dsf_chain};
pub use id3::{AlbumArtistFrame, ArrangerFrame, DateFrame, Id3Encoding, Id3Options, MAX_TAG_BYTES};
pub use markers::{InfoChunk, Marker, MarkerKind, MarkerText, Markers};
pub use tags::{ArtistTitleSource, GenreSources, TagItem, TagSet, TextSource};

/// An output file format (specification 8).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Format {
    /// DSF (8.2), with the ID3v2 tag of [`OutputOptions::tags`] (8.2.6, 8.3).
    Dsf,
    /// DSDIFF with plain DSD sound data (8.4.5).
    DsdiffDsd,
    /// DSDIFF with DST sound data (8.4.6): the positions' DST equivalents, unchanged. Its
    /// layout needs the frame lengths as well as the TOC: see [`Layout::new_dst`].
    DsdiffDst,
}

/// Which track a file holds (specification 8, 8.1 item 7; W29), for the per-track tag
/// items and the one-track markers.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SourceTrack {
    /// The track whose `[s_i, s_i + d_i)` or track with pause is the range (the
    /// lowest-numbered one, if several are), or none: a frame range that is neither, and the
    /// play range `[0, P)`, which holds the whole area.
    Auto,
    /// None.
    None,
    /// The track with this number, which must overlap the range.
    Track(u8),
}

/// The tag of a file (specification 8, 8.2.6 and 8.3; W3).
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Tags {
    /// The items of [`TagSet::from_toc`] for the file.
    FromToc,
    /// These items: for example [`TagSet::from_toc`]'s, changed.
    Set(TagSet),
    /// This tag, written as it is: for DSF an ID3v2.4 tag, checked only for its header,
    /// its size and [`MAX_TAG_BYTES`]; or an ID3v2.3 tag, checked only for the header of
    /// 8.2.6 item 4 (version 03 00, the low five flag bits 0, a 28-bit size of `m - 10`)
    /// and [`MAX_TAG_BYTES`]. Anything else is refused with [`Error::InvalidArgument`]
    /// when a layout is made.
    Raw(Vec<u8>),
    /// No tag.
    None,
}

/// The writer's choices of specification 8, 8.6 ("W" numbers below are its rows), each
/// with its default.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct OutputOptions {
    /// W1, DSF bits per sample (8.2.3). Default [`DsfBitsPerSample::One`]: each DSD byte
    /// with its bits reversed, earliest sample in bit 0.
    pub dsf_bits_per_sample: DsfBitsPerSample,
    /// W2, the DSF channel type of an area whose layout is unspecified (8.2.4 item 2). It
    /// must be a type with the area's channel count: 1 for 1 channel, 2 for 2, 3 for 3,
    /// 4 or 5 for 4, 6 for 5 and 7 for 6. Default `None`: such an area is refused with
    /// [`crate::OutputRefusal::UnspecifiedLayout`]. Areas with a defined layout ignore it.
    pub dsf_unspecified_channel_type: Option<u32>,
    /// W14, the order of the chunks inside the DSDIFF property chunk (8.4.3): each
    /// [`PropertyChunk`] once. Chunks that aren't written are skipped. Default
    /// [`PropertyChunk::TABLE_ORDER`]: `FS  `, `CHNL`, `CMPR`, `ABSS`, `LSCO`.
    pub dsdiff_property_order: [PropertyChunk; 5],
    /// W15, the DSDIFF channel IDs of an area whose layout is unspecified (8.4.4 item 2):
    /// one distinct number from 0 to 999 per channel, written as `C000` to `C999`. Default
    /// `None`: `C000`, `C001`, ... in channel order.
    pub dsdiff_unspecified_channel_numbers: Option<Vec<u16>>,
    /// W15, whether an area whose layout is unspecified gets an `LSCO` chunk with 65 535
    /// ("undefined channel set-up", 8.4.4 item 2). Default `false`: no `LSCO`.
    pub dsdiff_unspecified_loudspeaker_configuration: bool,
    /// W16, whether an area with a defined layout gets an `LSCO` chunk (8.4.3, 8.4.4).
    /// Default `true`.
    pub dsdiff_loudspeaker_configuration: bool,
    /// W17, the frame count `A` of the DSDIFF absolute start time (8.4.8): the `ABSS`
    /// chunk gives the time of frame `A`, and `A + N` must be at most 6 479 999. Default
    /// `None`: no `ABSS`, which means `A = 0`. `Some(first)` makes times equal timeline
    /// positions.
    pub dsdiff_absolute_start: Option<u32>,
    /// W13, the order of the DSDIFF local chunks after `FVER` (8.4.2): each chunk the file
    /// holds once, `PROP` before the sound data; chunks the file doesn't hold are ignored.
    /// Default [`LocalChunk::DEFAULT_ORDER`]: `PROP`, the sound data, `DSTI`.
    pub dsdiff_local_order: Vec<LocalChunk>,
    /// W19, whether each `DSTF` chunk is followed by a `DSTC` chunk with the CRC of the
    /// position's content (8.4.6.1). Producing one needs the position decoded. Default
    /// `false`.
    pub dsdiff_dst_crc: bool,
    /// W20, whether a DST file has a `DSTI` sound index (8.4.6.2), which the DSDIFF document
    /// recommends. Default `true`.
    pub dsdiff_dst_index: bool,
    /// W21, what a `DSTI` entry's offset points at (8.4.6.2 item 3). Default
    /// [`DstIndexOffset::ChunkHeader`], the `DSTF` chunk's first byte; the other reading,
    /// [`DstIndexOffset::FrameData`], is 12 bytes later.
    pub dsdiff_dst_index_offset: DstIndexOffset,
    /// W29, the file's source track (8.1 item 7). Default [`SourceTrack::Auto`]. An edited
    /// master, which holds the whole area, has none.
    pub source_track: SourceTrack,
    /// Whether a DSDIFF file is an edited master (8.4.11). One is the play range `[0, P)` of
    /// an area with a defined layout and 1 to 255 tracks of at least 75 frames, in order,
    /// in a program of at most 255:59:74; any other gives
    /// [`crate::OutputRefusal::NotEditedMaster`]. It always has `ABSS` (the time of
    /// [`OutputOptions::dsdiff_absolute_start`], or 0), and `DIIN` with `EMID` and the
    /// program's markers, whatever [`OutputOptions::dsdiff_edited_master_info`] says. It
    /// needs `LSCO` ([`OutputOptions::dsdiff_loudspeaker_configuration`]) and the markers of
    /// the TOC: without either, it is an [`Error::InvalidArgument`]; so is a DSF file.
    /// Default `false`.
    pub dsdiff_edited_master: bool,
    /// W24, whether a DSDIFF file has an edited master information chunk `DIIN` (8.4.8),
    /// with `EMID` (unless [`OutputOptions::dsdiff_edited_master_id_written`] says no) and
    /// the markers of [`OutputOptions::dsdiff_markers`]. Default `false` (an edited master
    /// always has one).
    pub dsdiff_edited_master_info: bool,
    /// W24, the text of `EMID`: text bytes 0x20 to 0x7E. Default empty. The DSDIFF document recommends
    /// something unique per file.
    pub dsdiff_edited_master_id: String,
    /// The markers of `DIIN` (8.4.10). Default [`Markers::FromToc`].
    pub dsdiff_markers: Markers,
    /// W28, whether a file with a source track has a one-track program (8.4.10 item 3).
    /// Default `false`.
    pub dsdiff_source_track_markers: bool,
    /// W30, whether a frame range without a source track has its clipped program (8.4.10
    /// item 4). Default `false`.
    pub dsdiff_clipped_program: bool,
    /// W22, whether the data size `D` of `MARK` (and of `DIAR` and `DITI`) counts the pad
    /// byte after odd-length text (8.4.7 item 6); the file's bytes are the same either way.
    /// Default `false`, as for every other chunk (8.4.1 item 1).
    pub dsdiff_text_pad_counted: bool,
    /// W3, the tag of a DSF file. Default [`Tags::FromToc`]; a set with no frame writes no
    /// tag (8.2.6 item 3).
    pub tags: Tags,
    /// W11, whether album items come from the disc's text or the album's (8.3.5). Default
    /// [`TextSource::DiscThenAlbum`].
    pub text_source: TextSource,
    /// W11, which genre entries the genre item takes (8.3.5, 8.3.7). Default all.
    pub genres: GenreSources,
    /// W4 to W12, the ID3 writer's choices.
    pub id3: Id3Options,
    /// W24, whether `DIIN` has the artist (`DIAR`) and title (`DITI`): the items of the
    /// tag ([`OutputOptions::tags`]; none for raw or no tags) that
    /// [`OutputOptions::dsdiff_artist_title_source`] names, by default album artist and album.
    /// Default `None`: in an edited master, as the DSDIFF document recommends; otherwise
    /// not.
    pub dsdiff_artist_title: Option<bool>,
    /// W14, the order of the chunks inside `DIIN` (8.4.8): each [`InfoChunk`] once; chunks
    /// that aren't written are skipped. Default [`InfoChunk::TABLE_ORDER`]: `EMID`, the markers, `DIAR`, `DITI`.
    pub dsdiff_info_order: [InfoChunk; 4],
    /// W23, the text of the markers made from the TOC (8.4.7 item 5). Default
    /// [`MarkerText::Empty`].
    pub dsdiff_marker_text: MarkerText,
    /// W25, the comments of `COMT` (8.4.8), in order. Default none, and so no `COMT`.
    pub dsdiff_comments: Vec<Comment>,
    /// W26, the text byte that replaces a code point outside U+0020 to U+007E in DSDIFF
    /// text (8.4.9); `None` removes it. Default `Some(b'?')`. Departure
    /// [`DsdiffDeparture::D2`] ignores it: every code point it doesn't write is removed (8.7).
    pub dsdiff_text_replacement: Option<u8>,
    /// W31, whether a `DIAR`, `DITI` or comment whose text is empty, or becomes empty under
    /// W26 (or [`DsdiffDeparture::D2`]), is written with `k = 0` (8.4.8). Default `false`:
    /// it is left out.
    pub dsdiff_empty_text: bool,
    /// W33, the caller chunks of a DSDIFF file (8.4.2 item 5, at sacd-spec `e069569`), in
    /// order, after the last local chunk; the same ID may appear more than once, and an
    /// edited master may have them. Their space counts in the `FRM8` size and they are part
    /// of the last [`RegionKind::Trailer`] region. A DSF file ignores them. Default none.
    pub dsdiff_caller_chunks: Vec<CallerChunk>,
    /// W24, whether `DIIN` has `EMID` in a file that is not an edited master (8.4.8 as of
    /// sacd-spec e069569: `DIIN` may hold any of its chunks without the others). Default
    /// `true`. An edited master requires `EMID` (8.4.11 item 1): `false` with
    /// [`OutputOptions::dsdiff_edited_master`] is an [`Error::InvalidArgument`]. Without
    /// `EMID`, markers, artist or title, `DIIN` is empty: see
    /// [`OutputOptions::dsdiff_empty_info`].
    pub dsdiff_edited_master_id_written: bool,
    /// W24, which items fill `DIAR` and `DITI` when [`OutputOptions::dsdiff_artist_title`]
    /// writes them (8.4.8 as of sacd-spec e069569). Default [`ArtistTitleSource::Album`],
    /// the album artist and album items.
    pub dsdiff_artist_title_source: ArtistTitleSource,
    /// W34, whether a `DIIN` that would hold none of its chunks (no `EMID`, markers, `DIAR`
    /// or `DITI`; possible only outside an edited master) is written with `D = 0`, 12 bytes,
    /// or left out (8.4.8 at sacd-spec 048aa1a). Both say the file has no edited master
    /// information. Default `true`: written.
    pub dsdiff_empty_info: bool,
    /// The departures from the DSDIFF document of specification 8, 8.7, that a DSDIFF file
    /// makes, each named by its number. Default none.
    ///
    /// **A DSDIFF file written with any departure is not a conforming DSDIFF file**: it does
    /// not conform to the DSDIFF document or to specification 8. The departures exist only to
    /// reproduce the files some existing programs write; see [`DsdiffDeparture`]. DSF files
    /// ignore them.
    pub dsdiff_departures: BTreeSet<DsdiffDeparture>,
    /// W32, what a DSF file holds (8.2.7, sacd-spec e069569, fa558a8 and 67b8563): with this and
    /// [`OutputOptions::dsf_chain_end`], the byte range of the range `[a_i, b_i)` in a
    /// chain whose first range starts at frame `a_1`, this. Default `None`: the range of
    /// positions itself. [`plan_dsf_chain`] gives both values per file. The byte range is
    /// always one of 8.2.7 item 3's `[p_i, p_{i+1})`, that of the chain `[a_1, a_i)`,
    /// `[a_i, b_i)`, `[b_i, b_K)` (each part present when not empty), which 8.1 item 2
    /// checks: no other byte range can be made (8.2.7 item 2).
    pub dsf_chain_first: Option<u32>,
    /// W32, the end `b_K` of the chain's last range (8.2.7 item 3); the file is the last of
    /// its chain when its range ends there. Both are set or neither, with
    /// `a_1 <= a_i < b_i <= b_K`, `[b_i, b_K)` passing the checks of 8.1 item 2 (a chain
    /// is split where they fail), and only for DSF; otherwise the layout is an
    /// [`Error::InvalidArgument`]. Default `None`.
    pub dsf_chain_end: Option<u32>,
}

impl Default for OutputOptions {
    fn default() -> Self {
        OutputOptions {
            dsf_bits_per_sample: DsfBitsPerSample::One,
            dsf_unspecified_channel_type: None,
            dsdiff_property_order: PropertyChunk::TABLE_ORDER,
            dsdiff_unspecified_channel_numbers: None,
            dsdiff_unspecified_loudspeaker_configuration: false,
            dsdiff_loudspeaker_configuration: true,
            dsdiff_absolute_start: None,
            dsdiff_local_order: LocalChunk::DEFAULT_ORDER.to_vec(),
            dsdiff_dst_crc: false,
            dsdiff_dst_index: true,
            dsdiff_dst_index_offset: DstIndexOffset::ChunkHeader,
            source_track: SourceTrack::Auto,
            dsdiff_edited_master: false,
            dsdiff_edited_master_info: false,
            dsdiff_edited_master_id: String::new(),
            dsdiff_markers: Markers::FromToc,
            dsdiff_source_track_markers: false,
            dsdiff_clipped_program: false,
            dsdiff_text_pad_counted: false,
            tags: Tags::FromToc,
            text_source: TextSource::DiscThenAlbum,
            genres: GenreSources::default(),
            id3: Id3Options::default(),
            dsdiff_artist_title: None,
            dsdiff_info_order: InfoChunk::TABLE_ORDER,
            dsdiff_marker_text: MarkerText::Empty,
            dsdiff_comments: Vec::new(),
            dsdiff_text_replacement: Some(b'?'),
            dsdiff_empty_text: false,
            dsdiff_caller_chunks: Vec::new(),
            dsdiff_edited_master_id_written: true,
            dsdiff_artist_title_source: ArtistTitleSource::Album,
            dsdiff_empty_info: true,
            dsdiff_departures: BTreeSet::new(),
            dsf_chain_first: None,
            dsf_chain_end: None,
        }
    }
}

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

    /// These options with DSF bits per sample `bits` (W1).
    pub fn with_dsf_bits_per_sample(self, bits: DsfBitsPerSample) -> Self {
        OutputOptions { dsf_bits_per_sample: bits, ..self }
    }

    /// These options with DSF channel type `channel_type` for unspecified layouts (W2).
    pub fn with_dsf_unspecified_channel_type(self, channel_type: Option<u32>) -> Self {
        OutputOptions { dsf_unspecified_channel_type: channel_type, ..self }
    }

    /// These options with DSDIFF property chunk order `order` (W14).
    pub fn with_dsdiff_property_order(self, order: [PropertyChunk; 5]) -> Self {
        OutputOptions { dsdiff_property_order: order, ..self }
    }

    /// These options with DSDIFF channel numbers `numbers` for unspecified layouts (W15).
    pub fn with_dsdiff_unspecified_channel_numbers(self, numbers: Option<Vec<u16>>) -> Self {
        OutputOptions { dsdiff_unspecified_channel_numbers: numbers, ..self }
    }

    /// These options with or without `LSCO` 65 535 for unspecified layouts (W15).
    pub fn with_dsdiff_unspecified_loudspeaker_configuration(self, write: bool) -> Self {
        OutputOptions { dsdiff_unspecified_loudspeaker_configuration: write, ..self }
    }

    /// These options with or without `LSCO` for defined layouts (W16).
    pub fn with_dsdiff_loudspeaker_configuration(self, write: bool) -> Self {
        OutputOptions { dsdiff_loudspeaker_configuration: write, ..self }
    }

    /// These options with DSDIFF absolute start frame `frame` (W17).
    pub fn with_dsdiff_absolute_start(self, frame: Option<u32>) -> Self {
        OutputOptions { dsdiff_absolute_start: frame, ..self }
    }

    /// These options with DSDIFF local chunk order `order` (W13).
    pub fn with_dsdiff_local_order(self, order: Vec<LocalChunk>) -> Self {
        OutputOptions { dsdiff_local_order: order, ..self }
    }

    /// These options with or without `DSTC` frame CRCs (W19).
    pub fn with_dsdiff_dst_crc(self, write: bool) -> Self {
        OutputOptions { dsdiff_dst_crc: write, ..self }
    }

    /// These options with or without a `DSTI` sound index (W20).
    pub fn with_dsdiff_dst_index(self, write: bool) -> Self {
        OutputOptions { dsdiff_dst_index: write, ..self }
    }

    /// These options with tag `tags` (W3).
    pub fn with_tags(self, tags: Tags) -> Self {
        OutputOptions { tags, ..self }
    }

    /// These options with album items from `source` (W11).
    pub fn with_text_source(self, source: TextSource) -> Self {
        OutputOptions { text_source: source, ..self }
    }

    /// These options with genre entries from `genres` (W11).
    pub fn with_genres(self, genres: GenreSources) -> Self {
        OutputOptions { genres, ..self }
    }

    /// These options with ID3 choices `id3` (W4 to W12).
    pub fn with_id3(self, id3: Id3Options) -> Self {
        OutputOptions { id3, ..self }
    }

    /// These options with or without the DSDIFF artist and title (W24).
    pub fn with_dsdiff_artist_title(self, write: Option<bool>) -> Self {
        OutputOptions { dsdiff_artist_title: write, ..self }
    }

    /// These options with `DIIN` chunk order `order` (W14).
    pub fn with_dsdiff_info_order(self, order: [InfoChunk; 4]) -> Self {
        OutputOptions { dsdiff_info_order: order, ..self }
    }

    /// These options with marker text `text` (W23).
    pub fn with_dsdiff_marker_text(self, text: MarkerText) -> Self {
        OutputOptions { dsdiff_marker_text: text, ..self }
    }

    /// These options with DSDIFF comments `comments` (W25).
    pub fn with_dsdiff_comments(self, comments: Vec<Comment>) -> Self {
        OutputOptions { dsdiff_comments: comments, ..self }
    }

    /// These options with DSDIFF text replacement `replacement` (W26).
    pub fn with_dsdiff_text_replacement(self, replacement: Option<u8>) -> Self {
        OutputOptions { dsdiff_text_replacement: replacement, ..self }
    }

    /// These options with empty DSDIFF text written, or not (W31).
    pub fn with_dsdiff_empty_text(self, write: bool) -> Self {
        OutputOptions { dsdiff_empty_text: write, ..self }
    }

    /// These options with source track `track` (W29).
    pub fn with_source_track(self, track: SourceTrack) -> Self {
        OutputOptions { source_track: track, ..self }
    }

    /// These options for an edited master, or not (8.4.11).
    pub fn with_dsdiff_edited_master(self, edited_master: bool) -> Self {
        OutputOptions { dsdiff_edited_master: edited_master, ..self }
    }

    /// These options with or without `DIIN` (W24).
    pub fn with_dsdiff_edited_master_info(self, write: bool) -> Self {
        OutputOptions { dsdiff_edited_master_info: write, ..self }
    }

    /// These options with `EMID` text `id` (W24).
    pub fn with_dsdiff_edited_master_id(self, id: String) -> Self {
        OutputOptions { dsdiff_edited_master_id: id, ..self }
    }

    /// These options with markers `markers`.
    pub fn with_dsdiff_markers(self, markers: Markers) -> Self {
        OutputOptions { dsdiff_markers: markers, ..self }
    }

    /// These options with or without one-track programs (W28).
    pub fn with_dsdiff_source_track_markers(self, write: bool) -> Self {
        OutputOptions { dsdiff_source_track_markers: write, ..self }
    }

    /// These options with or without clipped programs (W30).
    pub fn with_dsdiff_clipped_program(self, write: bool) -> Self {
        OutputOptions { dsdiff_clipped_program: write, ..self }
    }

    /// These options with the text pad counted in `D`, or not (W22).
    pub fn with_dsdiff_text_pad_counted(self, counted: bool) -> Self {
        OutputOptions { dsdiff_text_pad_counted: counted, ..self }
    }

    /// These options with `DSTI` offsets pointing at `offset` (W21).
    pub fn with_dsdiff_dst_index_offset(self, offset: DstIndexOffset) -> Self {
        OutputOptions { dsdiff_dst_index_offset: offset, ..self }
    }

    /// These options with DSDIFF caller chunks `chunks` (W33).
    pub fn with_dsdiff_caller_chunks(self, chunks: Vec<CallerChunk>) -> Self {
        OutputOptions { dsdiff_caller_chunks: chunks, ..self }
    }

    /// These options with or without `EMID` outside an edited master (W24).
    pub fn with_dsdiff_edited_master_id_written(self, write: bool) -> Self {
        OutputOptions { dsdiff_edited_master_id_written: write, ..self }
    }

    /// These options with `DIAR` and `DITI` from `source` (W24).
    pub fn with_dsdiff_artist_title_source(self, source: ArtistTitleSource) -> Self {
        OutputOptions { dsdiff_artist_title_source: source, ..self }
    }

    /// These options with an empty `DIIN` written, or left out (W34).
    pub fn with_dsdiff_empty_info(self, write: bool) -> Self {
        OutputOptions { dsdiff_empty_info: write, ..self }
    }

    /// These options with the DSDIFF departures `departures` (8.7) and no others.
    ///
    /// **A DSDIFF file written with any departure is not a conforming DSDIFF file**
    /// ([`OutputOptions::dsdiff_departures`]).
    pub fn with_dsdiff_departures(self, departures: impl IntoIterator<Item = DsdiffDeparture>) -> Self {
        OutputOptions { dsdiff_departures: departures.into_iter().collect(), ..self }
    }

    /// Whether a DSDIFF file makes departure `d` (8.7).
    pub(crate) fn departs(&self, d: DsdiffDeparture) -> bool {
        self.dsdiff_departures.contains(&d)
    }

    /// These options for the byte range of a DSF file in the chain `[a_1, b_K)` (W32,
    /// 8.2.7), such as [`DsfChainFile::chain`], or for a range of positions (`None`).
    pub fn with_dsf_chain(self, chain: Option<(u32, u32)>) -> Self {
        OutputOptions { dsf_chain_first: chain.map(|c| c.0), dsf_chain_end: chain.map(|c| c.1), ..self }
    }
}

/// What a region of an output file holds.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RegionKind {
    /// Chunk headers and other bytes before the sound data.
    Header,
    /// The sound data: audio of the range's positions, and the framing and padding the
    /// format puts among it.
    SoundData,
    /// Chunks after the sound data, such as a DST sound index or caller chunks.
    Trailer,
}

/// One contiguous region of an output file.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Region {
    /// What it holds.
    pub kind: RegionKind,
    /// Its first byte's offset in the file.
    pub offset: u64,
    /// Its length in bytes.
    pub len: u64,
}

/// The contents behind a [`Region`].
#[derive(Clone, Debug)]
enum Part {
    /// Bytes built with the layout.
    Bytes(Vec<u8>),
    /// DSF sound data (8.2.2).
    Dsf(dsf::DsfData),
    /// DSDIFF plain DSD sound data (8.4.5).
    Dsd(dsdiff::DsdData),
    /// DSDIFF DST sound data (8.4.6).
    Dst(dsdiff_dst::DstData),
}

/// The content of timeline positions, which [`Layout::fill`] reads.
pub trait PositionSource {
    /// The content of position `t` (specification 4, 4.6): `C x 4704` bytes in interleaved
    /// layout. [`Layout::fill`] asks only for positions of [`Layout::positions_for`] of the
    /// bytes it fills, mostly in increasing order; it may ask for a position again.
    ///
    /// # Errors
    ///
    /// Any error is returned by [`Layout::fill`] unchanged.
    fn content(&mut self, t: u32) -> Result<Cow<'_, [u8]>, Error>;

    /// The DST equivalent of position `t` (specification 4, 4.6.1 item 3), as the file
    /// holds it: for a [`Format::DsdiffDst`] layout whose lengths are
    /// [`InvalidDst::Replaced`], an invalid DST frame's is the 0x55 fill's (4.6.1 item 5).
    /// Its length must be the one [`DstLengths`] gave. [`Layout::fill`] asks for it only
    /// for DST layouts ([`Layout::input`]).
    ///
    /// # Errors
    ///
    /// Any error is returned by [`Layout::fill`] unchanged. The default gives
    /// [`Error::InvalidArgument`]: a source of content only.
    fn dst_equivalent(&mut self, t: u32) -> Result<Cow<'_, [u8]>, Error> {
        let _ = t;
        Err(Error::InvalidArgument("this source gives no DST equivalents"))
    }
}

/// What [`Layout::fill`] asks a [`PositionSource`] for.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Input {
    /// Content (specification 4, 4.6) only.
    Content,
    /// DST equivalents only.
    DstEquivalents,
    /// DST equivalents, and content for the frame CRCs.
    DstEquivalentsAndContent,
}

/// The layout of one output file: one format, one frame range `[first, end)` of one area
/// (specification 8, 8.1 item 2).
#[derive(Clone, Debug)]
pub struct Layout {
    format: Format,
    slot: Slot,
    first: u32,
    end: u32,
    channels: u8,
    size: u64,
    regions: Vec<Region>,
    parts: Vec<Part>,
    /// For DST layouts, what invalid DST frames are given as.
    invalid: Option<InvalidDst>,
    crc: bool,
    /// The image's TOC digests, for a layout made from a [`Disc`]: [`Layout::read_at`]
    /// refuses a disc of another image.
    image: Option<TocDigests>,
    /// The source track's number (8.1 item 7).
    source: Option<u8>,
    /// For a DSF file holding a byte range, its chain `[a_1, b_K)` (8.2.7).
    chain: Option<(u32, u32)>,
    /// The first position the file reads: `first`, or `first - 1` for a file of a chain
    /// that starts with the end of the range before it (8.2.7 item 4).
    base: u32,
}

impl Layout {
    /// The layout of the frame range `[first, end)` of `area` as a `format` file.
    /// `image_sectors` is the image's logical sector count, which bounds the area's
    /// capacity; [`Disc::output_layout`] passes it for you.
    ///
    /// # Errors
    ///
    /// The errors of [`audio::check_range`], which apply first (8.1 item 2);
    /// [`Error::OutputRefused`] when the format can't hold the area with these options;
    /// [`Error::InvalidArgument`] when an option is invalid for the area.
    pub fn new(
        toc: &Toc,
        slot: Slot,
        first: u32,
        end: u32,
        format: Format,
        options: &OutputOptions,
    ) -> Result<Layout, Error> {
        let area = toc.area(slot).ok_or(Error::NoSuchArea(slot))?;
        audio::check_range(area, first, end, toc.sectors)?;
        if options.dsdiff_edited_master && format == Format::Dsf {
            return Err(Error::InvalidArgument("an edited master is a DSDIFF file"));
        }
        let chain = match (options.dsf_chain_first, options.dsf_chain_end) {
            (None, None) => None,
            (Some(a1), Some(last)) => {
                if format != Format::Dsf {
                    return Err(Error::InvalidArgument("a byte range of a chain is DSF only"));
                }
                // With `first < end` from the checks, a1 <= first - 1 whenever p < 4704 first.
                if a1 > first || end > last {
                    return Err(Error::InvalidArgument("the range must be within its chain"));
                }
                // The rest of the chain must pass the checks of 8.1 item 2, or 8.2.7 item 3
                // splits it at `end` and this file is the last. If `[end, last)` passes, so
                // does every range of the chain after this one.
                if last > end && audio::check_range(area, end, last, toc.sectors).is_err() {
                    return Err(Error::InvalidArgument(
                        "the chain's ranges after this one are skipped or refused: it ends here",
                    ));
                }
                Some((a1, last))
            }
            _ => return Err(Error::InvalidArgument("a chain needs both its first frame and its end")),
        };
        let mut layout = Layout {
            format,
            slot: area.slot,
            first,
            end,
            channels: area.channel_count,
            size: 0,
            regions: Vec::new(),
            parts: Vec::new(),
            invalid: None,
            crc: false,
            image: None,
            source: if options.dsdiff_edited_master {
                None
            } else {
                source_track(area, first, end, options.source_track)?
            },
            chain,
            base: first,
        };
        match format {
            Format::Dsf => {
                let tag = layout.tag(toc, area, options)?;
                dsf::build(&mut layout, area, options, tag)?
            }
            Format::DsdiffDsd => dsdiff::build_dsd(&mut layout, toc, area, options)?,
            Format::DsdiffDst => {
                return Err(Error::InvalidArgument("a DST layout needs the frame lengths: Layout::new_dst"));
            }
        }
        Ok(layout)
    }

    /// The layout of a [`Format::DsdiffDst`] file holding the range of `lengths` of `area`
    /// (specification 8, 8.4.6): every size and the sound index follow from the lengths
    /// (8.4.6 "Sizes").
    ///
    /// # Errors
    ///
    /// As [`Layout::new`], and [`Error::InvalidArgument`] if `lengths` are of another area
    /// or range.
    pub fn new_dst(toc: &Toc, lengths: &DstLengths, options: &OutputOptions) -> Result<Layout, Error> {
        let area = toc.area(lengths.slot()).ok_or(Error::NoSuchArea(lengths.slot()))?;
        let (first, end) = lengths.range();
        audio::check_range(area, first, end, toc.sectors)?;
        if options.dsf_chain_first.is_some() || options.dsf_chain_end.is_some() {
            return Err(Error::InvalidArgument("a byte range of a chain is DSF only"));
        }
        let mut layout = Layout {
            format: Format::DsdiffDst,
            slot: area.slot,
            first,
            end,
            channels: area.channel_count,
            size: 0,
            regions: Vec::new(),
            parts: Vec::new(),
            invalid: Some(lengths.invalid()),
            crc: options.dsdiff_dst_crc,
            image: None,
            source: if options.dsdiff_edited_master {
                None
            } else {
                source_track(area, first, end, options.source_track)?
            },
            chain: None,
            base: first,
        };
        let data = dsdiff_dst::DstData::new(&layout, lengths, options)?;
        dsdiff::assemble(&mut layout, toc, area, options, dsdiff::Sound::Dst(data))?;
        Ok(layout)
    }

    /// Appends a region; regions are pushed in file order.
    fn push(&mut self, kind: RegionKind, len: u64, part: Part) {
        self.regions.push(Region { kind, offset: self.size, len });
        self.parts.push(part);
        self.size += len;
    }

    /// The file's size in bytes.
    pub fn size(&self) -> u64 {
        self.size
    }

    /// The format.
    pub fn format(&self) -> Format {
        self.format
    }

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

    /// The frame range `[first, end)` the file holds. For a DSF file of a chain (8.2.7,
    /// [`OutputOptions::dsf_chain_first`]), it is the range `[a_i, b_i)` the file's byte
    /// range is made from, which gives its source track (8.2.7 item 6).
    pub fn range(&self) -> (u32, u32) {
        (self.first, self.end)
    }

    /// For a DSF file, the bytes `[p, q)` of each channel's byte timeline it holds
    /// (specification 8, 8.2.7 items 1 and 2): `[4704 first, 4704 end)` for a range of
    /// positions, and the byte range of 8.2.7 item 3 for a file of a chain. `None` for
    /// DSDIFF.
    pub fn byte_range(&self) -> Option<(u64, u64)> {
        self.parts.iter().find_map(|p| match p {
            Part::Dsf(d) => Some(d.bytes()),
            _ => None,
        })
    }

    /// The DSF tag of the options (8.2.6, 8.3), if any.
    fn tag(&self, toc: &Toc, area: &Area, options: &OutputOptions) -> Result<Option<Vec<u8>>, Error> {
        let source = self.source.and_then(|n| area.track(u32::from(n)));
        match &options.tags {
            Tags::None => Ok(None),
            Tags::Raw(bytes) => id3::check_raw(bytes).map(|()| Some(bytes.clone())),
            Tags::FromToc => id3::tag(&TagSet::from_toc(toc, area, source, options), &options.id3),
            Tags::Set(set) => id3::tag(set, &options.id3),
        }
    }

    /// The number of the file's source track (specification 8, 8.1 item 7), if it has one.
    pub fn source_track(&self) -> Option<u8> {
        self.source
    }

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

    /// What [`Layout::fill`] asks its source for.
    pub fn input(&self) -> Input {
        match (self.invalid, self.crc) {
            (None, _) => Input::Content,
            (Some(_), false) => Input::DstEquivalents,
            (Some(_), true) => Input::DstEquivalentsAndContent,
        }
    }

    /// The file's regions, in order, covering `[0, size)`.
    pub fn regions(&self) -> &[Region] {
        &self.regions
    }

    /// The memory the layout holds, in bytes (approximate, without allocator overhead).
    pub fn memory(&self) -> usize {
        let parts: usize = self
            .parts
            .iter()
            .map(|p| match p {
                Part::Bytes(b) => b.len(),
                Part::Dst(d) => d.memory(),
                Part::Dsf(_) | Part::Dsd(_) => 0,
            })
            .sum();
        size_of::<Self>() + parts + self.regions.len() * (size_of::<Region>() + size_of::<Part>())
    }

    /// The timeline positions that [`Layout::fill`] may read to produce the file's bytes
    /// `range` (clipped to the file), as a frame range within [`Layout::range`]; empty when
    /// those bytes need no audio. A DSF file of a chain whose byte range starts before
    /// `4704 first` also reads position `first - 1`, the end of the range before it (8.2.7
    /// item 4).
    pub fn positions_for(&self, range: Range<u64>) -> Range<u32> {
        let mut lo = u32::MAX;
        let mut hi = 0;
        for (region, part) in self.regions.iter().zip(&self.parts) {
            let start = range.start.max(region.offset);
            let end = range.end.min(region.offset + region.len);
            if start >= end {
                continue;
            }
            let p = match part {
                Part::Bytes(_) => continue,
                Part::Dsf(d) => d.positions(start - region.offset..end - region.offset),
                Part::Dsd(d) => d.positions(start - region.offset..end - region.offset),
                Part::Dst(d) => d.positions(start - region.offset..end - region.offset),
            };
            if !p.is_empty() {
                lo = lo.min(p.start);
                hi = hi.max(p.end);
            }
        }
        if lo >= hi { self.first..self.first } else { self.base + lo..self.base + hi }
    }

    /// Fills `out` with the file's bytes from `offset`, reading the content of positions
    /// from `source`, and returns how many bytes it filled: `out.len()`, or fewer at the
    /// end of the file (0 from the end on).
    ///
    /// # Errors
    ///
    /// The errors of `source`, and [`Error::InvalidArgument`] if it gives content of the
    /// wrong size. `out` is then partly filled.
    ///
    /// A DSF read asks only for the positions of the stream bytes it covers
    /// ([`Layout::positions_for`]), so a failing position that holds none of the bytes read
    /// doesn't fail it.
    pub fn fill(&self, offset: u64, out: &mut [u8], source: &mut dyn PositionSource) -> Result<usize, Error> {
        self.fill_with(Isa::detect(), offset, out, source)
    }

    /// [`Layout::fill`] with the instruction set `isa` (see [`crate::dispatch`]).
    pub(crate) fn fill_with(
        &self,
        isa: Isa,
        offset: u64,
        out: &mut [u8],
        source: &mut dyn PositionSource,
    ) -> Result<usize, Error> {
        dispatch::output_path(isa, Fill { layout: self, offset, out, source })
    }

    /// [`Layout::fill`], inlined into the dispatch point with everything it calls on the
    /// hot path.
    #[inline(always)]
    fn fill_inner(
        &self,
        offset: u64,
        out: &mut [u8],
        source: &mut dyn PositionSource,
    ) -> Result<usize, Error> {
        let len =
            usize::try_from(self.size.saturating_sub(offset)).map_or(out.len(), |rest| rest.min(out.len()));
        let out = &mut out[..len];
        let mut source = Checked { inner: source, len: usize::from(self.channels) * FRAME_BYTES_PER_CHANNEL };
        let mut done = 0;
        for (region, part) in self.regions.iter().zip(&self.parts) {
            if done == len {
                break;
            }
            let at = offset + done as u64;
            if at >= region.offset + region.len {
                continue;
            }
            let rel = at - region.offset;
            let n = usize::try_from(region.len - rel).map_or(len - done, |rest| rest.min(len - done));
            let dst = &mut out[done..done + n];
            match part {
                Part::Bytes(b) => {
                    let rel = rel as usize; // below `b.len()`
                    dst.copy_from_slice(&b[rel..rel + n]);
                }
                Part::Dsf(d) => d.fill(rel, dst, self.base, &mut source)?,
                Part::Dsd(d) => d.fill(rel, dst, self.first, &mut source)?,
                Part::Dst(d) => d.fill(rel, dst, self.first, &mut source)?,
            }
            done += n;
        }
        Ok(len)
    }

    /// Reads the file's bytes from `offset` into `out` as [`Layout::fill`] does, taking the
    /// positions' content from `disc` (decoded, with its seek index when one is enabled).
    /// `disc` must be a disc of the image the layout was made from: for a layout of
    /// [`Disc::output_layout`] or [`Disc::output_layout_dst`], that is checked against the
    /// digests of the TOC sectors (as [`Disc::share`] checks a reader), at no cost.
    ///
    /// # Errors
    ///
    /// The errors of [`Disc::range_audio`], and [`Error::InvalidArgument`] if `disc` is of
    /// another image, has no such area, or one of another channel count.
    pub fn read_at<R: Read + Seek>(
        &self,
        disc: &mut Disc<R>,
        offset: u64,
        out: &mut [u8],
    ) -> Result<usize, Error> {
        self.read_at_with(Isa::detect(), disc, offset, out)
    }

    /// [`Layout::read_at`] with the instruction set `isa` (see [`crate::dispatch`]).
    pub(crate) fn read_at_with<R: Read + Seek>(
        &self,
        isa: Isa,
        disc: &mut Disc<R>,
        offset: u64,
        out: &mut [u8],
    ) -> Result<usize, Error> {
        dispatch::output_path(isa, ReadAt { layout: self, disc, offset, out })
    }

    /// [`Layout::read_at`], inlined into the dispatch point.
    #[inline(always)]
    fn read_at_inner<R: Read + Seek>(
        &self,
        disc: &mut Disc<R>,
        offset: u64,
        out: &mut [u8],
    ) -> Result<usize, Error> {
        if self.image.as_ref().is_some_and(|d| d != disc.toc_digests()) {
            return Err(Error::InvalidArgument("the layout is of another image"));
        }
        let area = disc.toc().area(self.slot).ok_or(Error::NoSuchArea(self.slot))?;
        if area.channel_count != self.channels {
            return Err(Error::InvalidArgument("the layout is of another area"));
        }
        let end = offset.saturating_add(out.len() as u64).min(self.size);
        let positions = self.positions_for(offset..end);
        if positions.is_empty() {
            return self.fill_inner(offset, out, &mut NoPositions);
        }
        match self.invalid {
            None => {
                let frames = disc.range_audio(self.slot, positions.start, positions.end)?;
                self.fill_inner(offset, out, &mut Window { frames, window: VecDeque::new() })
            }
            Some(invalid) => {
                let frames = disc.range_frames(self.slot, positions.start, positions.end)?;
                let mut source = StoredWindow {
                    frames,
                    window: VecDeque::new(),
                    decoder: DstDecoder::new(),
                    channels: self.channels,
                    invalid,
                };
                self.fill_inner(offset, out, &mut source)
            }
        }
    }
}

impl<R: Read + Seek> Disc<R> {
    /// The [`Layout`] of the frame range `[first, end)` of the area from `slot` as a
    /// `format` file (specification 8). A track's range is
    /// `(start_frame, start_frame + duration_frames)`; a track with pause's is
    /// [`Disc::track_range_with_pause`]'s.
    ///
    /// # Errors
    ///
    /// [`Error::NoSuchArea`], then those of [`Layout::new`].
    pub fn output_layout(
        &self,
        slot: Slot,
        first: u32,
        end: u32,
        format: Format,
        options: &OutputOptions,
    ) -> Result<Layout, Error> {
        let mut layout = Layout::new(self.toc(), slot, first, end, format, options)?;
        layout.image = Some(self.toc_digests().clone());
        Ok(layout)
    }

    /// The DSF files of a chain of ranges of the area from `slot` (specification 8, 8.2.7;
    /// see [`plan_dsf_chain`]), with `bounds` `a_1, ..., a_K, b_K`. Each file's layout is
    /// [`Disc::output_layout`] of its range with [`OutputOptions::with_dsf_chain`].
    ///
    /// # Errors
    ///
    /// Those of [`plan_dsf_chain`].
    pub fn plan_dsf_chain(
        &self,
        slot: Slot,
        bounds: &[u32],
    ) -> Result<Vec<Result<DsfChainFile, Error>>, Error> {
        plan_dsf_chain(self.toc(), slot, bounds)
    }

    /// The [`Format::DsdiffDst`] [`Layout`] of the range of `lengths` of their area (see
    /// [`Layout::new_dst`]).
    ///
    /// # Errors
    ///
    /// [`Error::NoSuchArea`], then those of [`Layout::new_dst`].
    pub fn output_layout_dst(&self, lengths: &DstLengths, options: &OutputOptions) -> Result<Layout, Error> {
        let mut layout = Layout::new_dst(self.toc(), lengths, options)?;
        layout.image = Some(self.toc_digests().clone());
        Ok(layout)
    }
}

/// [`Layout::fill`] as work of the dispatch point ([`dispatch::output_path`]).
struct Fill<'a, 'b> {
    layout: &'a Layout,
    offset: u64,
    out: &'a mut [u8],
    source: &'a mut (dyn PositionSource + 'b),
}

impl dispatch::Work for Fill<'_, '_> {
    type Output = Result<usize, Error>;
    #[inline(always)]
    fn run(self) -> Self::Output {
        self.layout.fill_inner(self.offset, self.out, self.source)
    }
}

/// [`Layout::read_at`] as work of the dispatch point ([`dispatch::output_path`]).
struct ReadAt<'a, R> {
    layout: &'a Layout,
    disc: &'a mut Disc<R>,
    offset: u64,
    out: &'a mut [u8],
}

impl<R: Read + Seek> crate::dispatch::Work for ReadAt<'_, R> {
    type Output = Result<usize, Error>;
    #[inline(always)]
    fn run(self) -> Self::Output {
        self.layout.read_at_inner(self.disc, self.offset, self.out)
    }
}

/// The source track of `[first, end)` of `area` (8.1 item 7, W29).
fn source_track(area: &Area, first: u32, end: u32, choice: SourceTrack) -> Result<Option<u8>, Error> {
    match choice {
        SourceTrack::None => Ok(None),
        SourceTrack::Track(n) => {
            let t: &Track =
                area.track(u32::from(n)).ok_or(Error::NoSuchTrack { slot: area.slot, track: n.into() })?;
            if t.start_frame.max(first) < t.end_frame().min(end) {
                Ok(Some(n))
            } else {
                Err(Error::InvalidArgument("the source track must overlap the range"))
            }
        }
        SourceTrack::Auto if (first, end) == (0, area.playtime_frames()) => Ok(None),
        SourceTrack::Auto => Ok(area
            .tracks
            .iter()
            .find(|t| {
                let with_pause = audio::track_range_with_pause(area, u32::from(t.number));
                (t.start_frame, t.end_frame()) == (first, end) || with_pause == Some((first, end))
            })
            .map(|t| t.number)),
    }
}

/// A source whose content sizes are checked.
struct Checked<'a> {
    inner: &'a mut dyn PositionSource,
    len: usize,
}

impl Checked<'_> {
    fn content(&mut self, t: u32) -> Result<Cow<'_, [u8]>, Error> {
        let len = self.len;
        let c = self.inner.content(t)?;
        if c.len() != len {
            return Err(Error::InvalidArgument("position content must be C x 4704 bytes"));
        }
        Ok(c)
    }

    fn dst_equivalent(&mut self, t: u32) -> Result<Cow<'_, [u8]>, Error> {
        self.inner.dst_equivalent(t)
    }
}

/// The source of a read that needs no positions.
struct NoPositions;

impl PositionSource for NoPositions {
    fn content(&mut self, _t: u32) -> Result<Cow<'_, [u8]>, Error> {
        Err(Error::InvalidArgument("no position is needed"))
    }
}

/// Positions kept behind the latest one asked for: a DSF row reads at most 2 positions
/// per channel, from the row's first position again for each channel.
const WINDOW: u32 = 4;

/// Decoded positions of one range, read in order, with the last few kept.
struct Window<'a, R> {
    frames: TrackAudio<'a, R>,
    window: VecDeque<AudioFrame>,
}

impl<R: Read + Seek> PositionSource for Window<'_, R> {
    fn content(&mut self, t: u32) -> Result<Cow<'_, [u8]>, Error> {
        while self.window.back().is_none_or(|f| f.number < t) {
            let frame = self.frames.next().ok_or(Error::InvalidArgument("position past the range"))??;
            self.window.push_back(frame);
        }
        while self.window.front().is_some_and(|f| f.number.saturating_add(WINDOW) < t) {
            self.window.pop_front();
        }
        let front = self.window.front().map_or(t, |f| f.number);
        let i = t.checked_sub(front).ok_or(Error::InvalidArgument("position no longer held"))?;
        let frame = self.window.get(i as usize).ok_or(Error::InvalidArgument("position not held"))?;
        Ok(Cow::Borrowed(&frame.data))
    }
}

/// A stored position, with its content once decoded.
struct Stored {
    frame: TrackFrame,
    decoded: Option<AudioFrame>,
}

/// Stored positions of one range, read in order, with the last few kept, decoded only
/// when content is asked for or invalid frames are replaced.
struct StoredWindow<'a, R> {
    frames: TrackFrames<'a, R>,
    window: VecDeque<Stored>,
    decoder: DstDecoder,
    channels: u8,
    invalid: InvalidDst,
}

impl<R: Read + Seek> StoredWindow<'_, R> {
    fn get(&mut self, t: u32, decode: bool) -> Result<&Stored, Error> {
        while self.window.back().is_none_or(|f| f.frame.number < t) {
            let frame = self.frames.next().ok_or(Error::InvalidArgument("position past the range"))??;
            self.window.push_back(Stored { frame, decoded: None });
        }
        while self.window.front().is_some_and(|f| f.frame.number.saturating_add(WINDOW) < t) {
            self.window.pop_front();
        }
        let front = self.window.front().map_or(t, |f| f.frame.number);
        let i = t.checked_sub(front).ok_or(Error::InvalidArgument("position no longer held"))?;
        let held = self.window.get_mut(i as usize).ok_or(Error::InvalidArgument("position not held"))?;
        if decode && held.decoded.is_none() {
            held.decoded = Some(audio::decode_frame(&mut self.decoder, held.frame.clone(), self.channels)?);
        }
        Ok(held)
    }
}

impl<R: Read + Seek> PositionSource for StoredWindow<'_, R> {
    fn content(&mut self, t: u32) -> Result<Cow<'_, [u8]>, Error> {
        let held = self.get(t, true)?;
        Ok(Cow::Borrowed(held.decoded.as_ref().map_or(&[][..], |d| &d.data)))
    }

    fn dst_equivalent(&mut self, t: u32) -> Result<Cow<'_, [u8]>, Error> {
        let channels = self.channels;
        let replace = self.invalid == InvalidDst::Replaced;
        let held = self.get(t, replace)?;
        let invalid = matches!(held.frame.content, FrameContent::Dst(_))
            && held.decoded.as_ref().is_some_and(|d| matches!(d.status, audio::FrameStatus::Invalid(_)));
        if invalid {
            return Ok(Cow::Owned(dsdiff_dst::replaced(channels)));
        }
        held.frame.content.dst_equivalent(channels)
    }
}