scarletbook 0.6.1

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

//! The master TOC (specification 2) and the area TOCs (specification 3).
//!
//! The model is read, not built: [`Toc`], [`MasterToc`], [`Area`], [`Track`], [`Locale`] and
//! the text structs are `#[non_exhaustive]`, so that later fields are not breaking changes.
//! Read their fields as usual; a pattern ends in `..`. The text structs can still be made
//! from [`Default`]:
//!
//! ```
//! use scarletbook::toc::{Track, TrackText};
//!
//! fn describe(track: &Track) -> (u8, Option<&str>) {
//!     let Track { number, text, .. } = track;
//!     (*number, text.title.as_deref())
//! }
//!
//! let mut text = TrackText::default();
//! text.title = Some("Title".to_string());
//! assert_eq!(text.title.as_deref(), Some("Title"));
//! # let _ = describe;
//! ```
//!
//! TOC fields keep the width stored on the disc, so an LSN here is a `u32`, while
//! [`Image`] and the [`seek`](crate::seek) module take and report sectors as
//! `u64`. `u64::from` converts one to the other.

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

use crate::error::{Error, Slot, Warning, WarningCode};
use crate::image::{Image, MASTER_TOC_LSN, ReadOutcome, SECTOR_SIZE, SectorFormat};
use crate::log::{Log, sb_log};
use crate::text::{self, Charset};

/// Largest area TOC in sectors (specification 3, 3.2).
pub const MAX_AREA_TOC_SECTORS: u16 = 128;

/// The complete table of contents of a disc image.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Toc {
    /// The image's stored sector format.
    pub sector_format: SectorFormat,
    /// The number of logical sectors in the image.
    pub sectors: u64,
    /// The master TOC.
    pub master: MasterToc,
    /// The areas, in slot order (specification 3, 3.1).
    pub areas: Vec<Area>,
}

impl Toc {
    /// The area that came from `slot`, if any.
    pub fn area(&self, slot: Slot) -> Option<&Area> {
        self.areas.iter().find(|a| a.slot == slot)
    }
}

/// A structure version number.
///
/// Frozen: exhaustive on purpose, so it can be built and matched without `..`. A version is
/// exactly the major and minor bytes at offsets 8 and 9 (specification 2, 2.3).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Version {
    /// Major number.
    pub major: u8,
    /// Minor number.
    pub minor: u8,
}

/// A genre entry (specification 2, 2.4).
///
/// Frozen: exhaustive on purpose, so it can be built and matched without `..`. A genre entry
/// is 4 bytes, and these are the only two of them the specification gives a meaning to.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Genre {
    /// The genre table (category) byte.
    pub category: u8,
    /// The genre index byte.
    pub index: u8,
}

impl Genre {
    fn parse(b: &[u8]) -> Genre {
        Genre { category: byte(b, 0), index: byte(b, 3) }
    }

    /// The informative name of a genre of the general table (1), if it has one.
    pub fn name(self) -> Option<&'static str> {
        if self.category != 1 {
            return None;
        }
        GENERAL_GENRES.get(usize::from(self.index)).copied()
    }
}

const GENERAL_GENRES: [&str; 30] = [
    "not used",
    "not defined",
    "Adult Contemporary",
    "Alternative Rock",
    "Children's Music",
    "Classical",
    "Contemporary Christian",
    "Country",
    "Dance",
    "Easy Listening",
    "Erotic",
    "Folk",
    "Gospel",
    "Hip Hop",
    "Jazz",
    "Latin",
    "Musical",
    "New Age",
    "Opera",
    "Operetta",
    "Pop Music",
    "Rap",
    "Reggae",
    "Rock Music",
    "Rhythm & Blues",
    "Sound Effects",
    "Sound Track",
    "Spoken Word",
    "World Music",
    "Blues",
];

/// A date as stored (specification 2, 2.3.2); 0 means "not set".
///
/// Frozen: exhaustive on purpose, so it can be built and matched without `..`. The stored date
/// is exactly a year, a month and a day, offsets 120 to 123.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Date {
    /// Year.
    pub year: u16,
    /// Month.
    pub month: u8,
    /// Day.
    pub day: u8,
}

/// A locale entry (specification 2, 2.5.1).
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Locale {
    /// The language code, every trailing U+0000 and U+0020 removed, as specification 2,
    /// 2.5.1 item 1 defines it. **It may contain control characters:** no other character is
    /// removed or replaced, so C0 (U+0000 included), U+007F (DEL) and U+0080 to U+009F (C1)
    /// are kept. The bytes 0x00 0x65 give U+0000 U+0065, which code that passes the string
    /// on as a NUL-terminated C string truncates to nothing. A caller that prints it or
    /// puts it in a tag or file name should escape or filter it for that use.
    /// [`Locale::language_code`] gives the two bytes as stored.
    pub language: String,
    /// The language code's two bytes as stored, nothing removed: tells an unset code
    /// (0x00 0x00) from one of spaces, which [`Locale::language`] reports alike.
    pub language_code: [u8; 2],
    /// The stored character set code byte.
    pub charset: u8,
}

impl Locale {
    fn parse(b: &[u8]) -> Locale {
        let code = [byte(b, 0), byte(b, 1)];
        Locale { language: text::language(code), language_code: code, charset: byte(b, 2) }
    }
}

/// A timecode (specification 0, 0.5).
///
/// Frozen: exhaustive on purpose, so it can be built and matched without `..`. A timecode is
/// exactly 3 bytes: minutes, seconds and frames.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Timecode {
    /// Minutes.
    pub minutes: u8,
    /// Seconds (not validated).
    pub seconds: u8,
    /// Frames (not validated).
    pub frames: u8,
}

impl Timecode {
    /// The timecode's frame number, `(m x 60 + s) x 75 + f`; at most 1 166 880.
    pub fn frame_number(self) -> u32 {
        (u32::from(self.minutes) * 60 + u32::from(self.seconds)) * 75 + u32::from(self.frames)
    }

    pub(crate) fn parse(b: &[u8]) -> Timecode {
        Timecode { minutes: byte(b, 0), seconds: byte(b, 1), frames: byte(b, 2) }
    }
}

/// Where the master TOC says an area's TOC copies are (specification 3, 3.1).
///
/// Frozen: exhaustive on purpose, so it can be built and matched without `..`. The master TOC
/// gives a slot exactly these three values, in fixed places.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct AreaPointer {
    /// TOC-1 LSN; 0 means the slot is unused.
    pub toc1_lsn: u32,
    /// TOC-2 LSN; 0 means no backup copy.
    pub toc2_lsn: u32,
    /// Area TOC size in sectors; 0 means the slot is unused.
    pub toc_sectors: u16,
}

impl AreaPointer {
    /// Whether the slot is used.
    pub fn is_used(self) -> bool {
        self.toc1_lsn != 0 && self.toc_sectors != 0
    }
}

macro_rules! text_struct {
    (
        $(#[$meta:meta])* $name:ident, $(#[$imeta:meta])* $item:ident { $($(#[$fmeta:meta])* $field:ident = $key:literal => $variant:ident),* $(,)? }
    ) => {
        $(#[$meta])*
        ///
        /// **Items may contain control characters.** Every field, [`Self::get`] and
        /// [`Self::iter`] return an item as specification 2, 2.6.4 item 3 defines it: each
        /// code point below U+0020 (C0) is replaced with a space, so U+001B (ESC) is the only
        /// escape-sequence starter removed, while U+007F (DEL) and U+0080 to U+009F (C1) are
        /// kept. U+009B (CSI), for example, starts a terminal control sequence on terminals
        /// that honour 8-bit controls. A caller that prints an item or puts it in a tag or
        /// file name should escape or filter it for that use.
        #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
        #[non_exhaustive]
        pub struct $name {
            $($(#[$fmeta])* pub $field: Option<String>,)*
        }

        /// Identifies one text item.
        $(#[$imeta])*
        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
        pub enum $item {
            $($(#[$fmeta])* $variant,)*
        }

        impl $item {
            /// Every item, in table order.
            pub const ALL: &'static [$item] = &[$($item::$variant),*];

            /// The item's name in the conformance manifest.
            pub fn name(self) -> &'static str {
                match self { $($item::$variant => $key,)* }
            }
        }

        impl $name {
            /// The text of one item, if present.
            pub fn get(&self, item: $item) -> Option<&str> {
                match item { $($item::$variant => self.$field.as_deref(),)* }
            }

            fn slot(&mut self, item: $item) -> &mut Option<String> {
                match item { $($item::$variant => &mut self.$field,)* }
            }

            /// The present items and their text, in table order.
            pub fn iter(&self) -> impl Iterator<Item = ($item, &str)> + '_ {
                $item::ALL.iter().filter_map(move |&i| self.get(i).map(|t| (i, t)))
            }

            /// Whether no item is present.
            pub fn is_empty(&self) -> bool {
                self.iter().next().is_none()
            }
        }
    };
}

text_struct! {
    /// Disc text: the 16 items of the first text channel (specification 2, 2.5.4).
    DiscText,
    ///
    /// Frozen: exhaustive on purpose, so a `match` needs no wildcard arm. The disc text
    /// sector has exactly these 16 string offsets, in fixed places (specification 2, 2.5.4),
    /// with no room for another. [`DiscText`] has one field for each item, so no field can be
    /// added to it while this enum is frozen.
    DiscTextItem {
        /// Album title.
        album_title = "album_title" => AlbumTitle,
        /// Album artist.
        album_artist = "album_artist" => AlbumArtist,
        /// Album publisher.
        album_publisher = "album_publisher" => AlbumPublisher,
        /// Album copyright.
        album_copyright = "album_copyright" => AlbumCopyright,
        /// Album title, phonetic.
        album_title_phonetic = "album_title_phonetic" => AlbumTitlePhonetic,
        /// Album artist, phonetic.
        album_artist_phonetic = "album_artist_phonetic" => AlbumArtistPhonetic,
        /// Album publisher, phonetic.
        album_publisher_phonetic = "album_publisher_phonetic" => AlbumPublisherPhonetic,
        /// Album copyright, phonetic.
        album_copyright_phonetic = "album_copyright_phonetic" => AlbumCopyrightPhonetic,
        /// Disc title.
        disc_title = "disc_title" => DiscTitle,
        /// Disc artist.
        disc_artist = "disc_artist" => DiscArtist,
        /// Disc publisher.
        disc_publisher = "disc_publisher" => DiscPublisher,
        /// Disc copyright.
        disc_copyright = "disc_copyright" => DiscCopyright,
        /// Disc title, phonetic.
        disc_title_phonetic = "disc_title_phonetic" => DiscTitlePhonetic,
        /// Disc artist, phonetic.
        disc_artist_phonetic = "disc_artist_phonetic" => DiscArtistPhonetic,
        /// Disc publisher, phonetic.
        disc_publisher_phonetic = "disc_publisher_phonetic" => DiscPublisherPhonetic,
        /// Disc copyright, phonetic.
        disc_copyright_phonetic = "disc_copyright_phonetic" => DiscCopyrightPhonetic,
    }
}

text_struct! {
    /// Area text (specification 3, 3.6).
    AreaText,
    ///
    /// Frozen: exhaustive on purpose, so a `match` needs no wildcard arm. The area TOC has
    /// exactly these four string offsets, in fixed places (specification 3, 3.3 and 3.6).
    /// [`AreaText`] has one field for each item, so no field can be added to it while this
    /// enum is frozen.
    AreaTextItem {
        /// Area description.
        description = "description" => Description,
        /// Area copyright.
        copyright = "copyright" => Copyright,
        /// Area description, phonetic.
        description_phonetic = "description_phonetic" => DescriptionPhonetic,
        /// Area copyright, phonetic.
        copyright_phonetic = "copyright_phonetic" => CopyrightPhonetic,
    }
}

text_struct! {
    /// Track text (specification 3, 3.8).
    TrackText,
    #[non_exhaustive]
    TrackTextItem {
        /// Title (type 0x01).
        title = "title" => Title,
        /// Performer (type 0x02).
        performer = "performer" => Performer,
        /// Songwriter (type 0x03).
        songwriter = "songwriter" => Songwriter,
        /// Composer (type 0x04).
        composer = "composer" => Composer,
        /// Arranger (type 0x05).
        arranger = "arranger" => Arranger,
        /// Message (type 0x06).
        message = "message" => Message,
        /// Extra message (type 0x07).
        extra_message = "extra_message" => ExtraMessage,
        /// Title, phonetic (type 0x81).
        title_phonetic = "title_phonetic" => TitlePhonetic,
        /// Performer, phonetic (type 0x82).
        performer_phonetic = "performer_phonetic" => PerformerPhonetic,
        /// Songwriter, phonetic (type 0x83).
        songwriter_phonetic = "songwriter_phonetic" => SongwriterPhonetic,
        /// Composer, phonetic (type 0x84).
        composer_phonetic = "composer_phonetic" => ComposerPhonetic,
        /// Arranger, phonetic (type 0x85).
        arranger_phonetic = "arranger_phonetic" => ArrangerPhonetic,
        /// Message, phonetic (type 0x86).
        message_phonetic = "message_phonetic" => MessagePhonetic,
        /// Extra message, phonetic (type 0x87).
        extra_message_phonetic = "extra_message_phonetic" => ExtraMessagePhonetic,
    }
}

impl TrackTextItem {
    /// The item for a stored item type byte, if the type is defined.
    pub fn from_type(t: u8) -> Option<TrackTextItem> {
        let base = t & 0x7F;
        if !(1..=7).contains(&base) {
            return None;
        }
        let idx = usize::from(base - 1) + if t & 0x80 != 0 { 7 } else { 0 };
        TrackTextItem::ALL.get(idx).copied()
    }
}

/// The master TOC (specification 2).
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct MasterToc {
    /// Version (offsets 8 and 9).
    pub version: Version,
    /// Album set size (offset 16).
    pub album_set_size: u16,
    /// Album sequence number (offset 18).
    pub album_sequence_number: u16,
    /// Album catalogue number (offset 24), a fixed text field as specification 2, 2.6.5
    /// defines it: the bytes up to the first 0x00, with whitespace trimmed from the ends.
    /// **It may contain control characters:** C0, U+007F (DEL) and U+0080 to U+009F (C1)
    /// are kept (2.6.5 item 4). Such characters reach whatever the string is passed to: U+009B (CSI), for example, starts a
    /// terminal control sequence on terminals that honour 8-bit controls. A caller that prints
    /// the value or puts it in a tag or file name should escape or filter it for that use.
    /// [`MasterToc::album_catalog_number_stored`] gives the bytes as stored.
    pub album_catalog_number: String,
    /// The album catalogue number's bytes as stored, up to the first 0x00 (all 16 if there
    /// is none), padding kept: step 1 of the fixed text field rules (specification 2,
    /// 2.6.5), before the bytes are mapped and trimmed.
    pub album_catalog_number_stored: Vec<u8>,
    /// Album genres (offset 40).
    pub album_genres: [Genre; 4],
    /// The 2-channel slot's pointers.
    pub two_channel: AreaPointer,
    /// The multichannel slot's pointers.
    pub multichannel: AreaPointer,
    /// Disc flags byte (offset 80).
    pub disc_flags: u8,
    /// Disc catalogue number (offset 88), a fixed text field, as
    /// [`MasterToc::album_catalog_number`]: **it may contain control characters** (C0, DEL
    /// and C1, specification 2, 2.6.5 item 4); escape or filter it before printing it or
    /// putting it in a tag or file name. [`MasterToc::disc_catalog_number_stored`] gives the
    /// bytes as stored.
    pub disc_catalog_number: String,
    /// The disc catalogue number's bytes as stored, as for
    /// [`MasterToc::album_catalog_number_stored`].
    pub disc_catalog_number_stored: Vec<u8>,
    /// Disc genres (offset 104).
    pub disc_genres: [Genre; 4],
    /// Date (offsets 120 to 123).
    pub date: Date,
    /// Stored text channel count (offset 128).
    pub text_channel_count: u8,
    /// The reported locale list: the first `min(count, 8)` entries.
    pub locales: Vec<Locale>,
    /// Character set code of locale entry 0 (offset 138), used for disc text.
    pub text_charset: u8,
    /// Disc text of the first text channel.
    pub text: DiscText,
    /// Bytes 8 to 2047 of the manufacturer sector, if its signature is present.
    pub manufacturer: Option<Vec<u8>>,
}

impl MasterToc {
    /// Bit 7 of the disc flags: the disc also has a CD layer.
    pub fn hybrid(&self) -> bool {
        self.disc_flags & 0x80 != 0
    }

    /// The pointers of a slot.
    pub fn pointer(&self, slot: Slot) -> AreaPointer {
        match slot {
            Slot::TwoChannel => self.two_channel,
            Slot::Multichannel => self.multichannel,
        }
    }
}

/// An area's kind, from its TOC signature (specification 3, 3.3).
///
/// Frozen: exhaustive on purpose, so a `match` needs no wildcard arm. An area TOC has one of
/// exactly two signatures. A slot can hold either: see [`Area::kind`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AreaKind {
    /// `TWOCHTOC`.
    TwoChannel,
    /// `MULCHTOC`.
    Multichannel,
}

impl AreaKind {
    /// The signature string.
    pub fn signature(self) -> &'static str {
        match self {
            AreaKind::TwoChannel => "TWOCHTOC",
            AreaKind::Multichannel => "MULCHTOC",
        }
    }
}

/// An audio area (specification 3).
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Area {
    /// The master TOC slot it came from, which is how every call taking a [`Slot`] finds
    /// this area.
    pub slot: Slot,
    /// Its kind, from the signature, not from the slot (specification 3, 3.1 rule 3). A slot
    /// can yield an area of the other kind, and both slots can yield areas of the same kind,
    /// so use `slot` to address an area and `kind` to describe it.
    pub kind: AreaKind,
    /// Version (offsets 8 and 9).
    pub version: Version,
    /// LSN of the TOC copy used.
    pub toc_lsn: u32,
    /// Area TOC size in sectors, from the master TOC.
    pub toc_sectors: u16,
    /// Maximum byte rate (offset 16).
    pub max_byte_rate: u32,
    /// Sample frequency code (offset 20); 4 is DSD64.
    pub sample_frequency_code: u8,
    /// Frame format, the low 4 bits of offset 21 (informative only).
    pub frame_format: u8,
    /// Channel count (offset 32).
    pub channel_count: u8,
    /// Area configuration byte (offset 33); the low 3 bits are the loudspeaker configuration.
    /// See [`Area::loudspeaker_layout`].
    pub area_config: u8,
    /// Maximum available channels (offset 34).
    pub max_available_channels: u8,
    /// Area mute flags (offset 35).
    pub area_mute_flags: u8,
    /// Track attribute, the low 4 bits of offset 48.
    pub track_attribute: u8,
    /// Total area play time (offset 64).
    pub playtime: Timecode,
    /// Track offset (offset 68).
    pub track_offset: u8,
    /// First audio LSN (offset 72).
    pub audio_start_lsn: u32,
    /// Last audio LSN, inclusive (offset 76).
    pub audio_end_lsn: u32,
    /// Stored text channel count (offset 80).
    pub text_channel_count: u8,
    /// The reported locale list: the first `min(count, 10)` entries.
    pub locales: Vec<Locale>,
    /// Character set code of area locale entry 0 (offset 90), used for all area text.
    pub text_charset: u8,
    /// Area text.
    pub text: AreaText,
    /// The tracks, numbered 1 to the track count.
    pub tracks: Vec<Track>,
}

impl Area {
    /// The play time as a frame number.
    pub fn playtime_frames(&self) -> u32 {
        self.playtime.frame_number()
    }

    /// The track with the given number (1-based).
    pub fn track(&self, number: u32) -> Option<&Track> {
        number.checked_sub(1).and_then(|i| self.tracks.get(i as usize))
    }

    /// The loudspeaker layout given by the channel count and the low 3 bits of the area
    /// configuration byte (specification 3, 3.4.1 item 2).
    pub fn loudspeaker_layout(&self) -> LoudspeakerLayout {
        LoudspeakerLayout::new(self.channel_count, self.area_config)
    }

    /// The loudspeaker of each channel, in the order the channels appear in a decoded
    /// frame, or `None` when the area has no defined loudspeaker layout. See
    /// [`LoudspeakerLayout::speakers`]; the order is informative.
    pub fn channel_speakers(&self) -> Option<&'static [Speaker]> {
        self.loudspeaker_layout().speakers()
    }
}

/// The loudspeaker layout of an area (specification 3, 3.4.1 item 2).
///
/// The specification defines three combinations of channel count and loudspeaker
/// configuration (the low 3 bits of the area configuration byte); any other combination
/// has no defined layout and is [`Unspecified`](LoudspeakerLayout::Unspecified), with both
/// fields as stored. Neither field changes how audio is decoded, apart from the channel
/// count (item 3).
///
/// | Channel count | Configuration | Layout |
/// |---|---|---|
/// | 2 | 0 | [`Stereo`](LoudspeakerLayout::Stereo) |
/// | 5 | 3 | [`ThreeTwo`](LoudspeakerLayout::ThreeTwo) |
/// | 6 | 4 | [`FivePointOne`](LoudspeakerLayout::FivePointOne) |
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LoudspeakerLayout {
    /// Stereo: 2 channels, configuration 0.
    Stereo,
    /// 5-channel (3/2): 5 channels, configuration 3.
    ThreeTwo,
    /// 5.1-channel: 6 channels, configuration 4.
    FivePointOne,
    /// Any other combination: no defined loudspeaker layout.
    #[non_exhaustive]
    Unspecified {
        /// The channel count, as stored.
        channels: u8,
        /// The whole area configuration byte, as stored, high bits included.
        config: u8,
    },
}

impl LoudspeakerLayout {
    /// The layout of a channel count and an area configuration byte. Only the low 3 bits
    /// of `config` select the layout; an [`Unspecified`](LoudspeakerLayout::Unspecified)
    /// layout keeps the whole byte.
    pub fn new(channels: u8, config: u8) -> Self {
        match (channels, config & 0x07) {
            (2, 0) => LoudspeakerLayout::Stereo,
            (5, 3) => LoudspeakerLayout::ThreeTwo,
            (6, 4) => LoudspeakerLayout::FivePointOne,
            _ => LoudspeakerLayout::Unspecified { channels, config },
        }
    }

    /// The loudspeaker of each channel, in the order the channels appear in a decoded
    /// frame, or `None` for [`Unspecified`](LoudspeakerLayout::Unspecified).
    ///
    /// The order is informative (specification 3, 3.4.1 item 2): it is the order existing
    /// tools use when they label the channels of extracted audio, and nothing else in the
    /// specifications depends on it.
    ///
    /// A consumer writing `WAVE_FORMAT_EXTENSIBLE` files might build the channel mask from
    /// it; whether surround channels take the back or the side bits is the consumer's
    /// choice (this uses the back bits). `Speaker` can gain variants, so a loudspeaker this
    /// function doesn't know gives no mask, rather than a mask without it:
    ///
    /// ```
    /// use scarletbook::toc::{LoudspeakerLayout, Speaker};
    ///
    /// fn wav_mask(speakers: &[Speaker]) -> Option<u32> {
    ///     speakers.iter().try_fold(0, |mask, s| {
    ///         let bit = match s {
    ///             Speaker::FrontLeft => 0x1,
    ///             Speaker::FrontRight => 0x2,
    ///             Speaker::Centre => 0x4,
    ///             Speaker::LowFrequencyEffects => 0x8,
    ///             Speaker::SurroundLeft => 0x10,
    ///             Speaker::SurroundRight => 0x20,
    ///             _ => return None,
    ///         };
    ///         Some(mask | bit)
    ///     })
    /// }
    ///
    /// assert_eq!(LoudspeakerLayout::Stereo.speakers().and_then(wav_mask), Some(0x3));
    /// assert_eq!(LoudspeakerLayout::ThreeTwo.speakers().and_then(wav_mask), Some(0x37));
    /// assert_eq!(LoudspeakerLayout::FivePointOne.speakers().and_then(wav_mask), Some(0x3F));
    /// assert_eq!(LoudspeakerLayout::new(4, 0).speakers(), None);
    /// ```
    pub fn speakers(self) -> Option<&'static [Speaker]> {
        use Speaker::*;
        match self {
            LoudspeakerLayout::Stereo => Some(&[FrontLeft, FrontRight]),
            LoudspeakerLayout::ThreeTwo => {
                Some(&[FrontLeft, FrontRight, Centre, SurroundLeft, SurroundRight])
            }
            LoudspeakerLayout::FivePointOne => {
                Some(&[FrontLeft, FrontRight, Centre, LowFrequencyEffects, SurroundLeft, SurroundRight])
            }
            LoudspeakerLayout::Unspecified { .. } => None,
        }
    }
}

/// A loudspeaker of a defined layout (specification 3, 3.4.1 item 2).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Speaker {
    /// Front left; "left" in stereo.
    FrontLeft,
    /// Front right; "right" in stereo.
    FrontRight,
    /// Centre.
    Centre,
    /// Low-frequency effects.
    LowFrequencyEffects,
    /// Surround left.
    SurroundLeft,
    /// Surround right.
    SurroundRight,
}

/// A track (specification 3, 3.9.1).
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Track {
    /// Track number, 1 to the track count.
    pub number: u8,
    /// Start LSN, as stored.
    pub start_lsn: u32,
    /// Length in sectors, as stored.
    pub length_sectors: u32,
    /// Start frame number, after clamping (specification 3, 3.9.2).
    pub start_frame: u32,
    /// Duration in frames, after clamping.
    pub duration_frames: u32,
    /// Start flags byte.
    pub start_flags: u8,
    /// Duration flags byte.
    pub duration_flags: u8,
    /// ISRC, if any: a fixed text field as specification 2, 2.6.5 and specification 3, 3.7.3
    /// define it, the bytes up to the first 0x00 with whitespace trimmed from the ends; its
    /// syntax is not validated. **It may contain control characters:** C0, U+007F (DEL) and
    /// U+0080 to U+009F (C1) are kept (2.6.5 item 4). Such characters reach whatever the string is passed to: U+009B (CSI), for example, starts a
    /// terminal control sequence on terminals that honour 8-bit controls. A caller that prints
    /// the value or puts it in a tag or file name should escape or filter it for that use.
    pub isrc: Option<String>,
    /// Genre, if the area has a `SACD_IGL`.
    pub genre: Option<Genre>,
    /// Track text.
    pub text: TrackText,
}

impl Track {
    /// The end frame number, `start_frame + duration_frames` (at most the play time).
    pub fn end_frame(&self) -> u32 {
        self.start_frame.saturating_add(self.duration_frames)
    }
}

fn byte(b: &[u8], at: usize) -> u8 {
    b.get(at).copied().unwrap_or(0)
}

fn be16(b: &[u8], at: usize) -> u16 {
    u16::from_be_bytes([byte(b, at), byte(b, at.saturating_add(1))])
}

fn be32(b: &[u8], at: usize) -> u32 {
    let a = |i: usize| byte(b, at.saturating_add(i));
    u32::from_be_bytes([a(0), a(1), a(2), a(3)])
}

fn sub(b: &[u8], at: usize, len: usize) -> &[u8] {
    b.get(at..at.saturating_add(len)).unwrap_or(&[])
}

fn genres(b: &[u8], at: usize) -> [Genre; 4] {
    std::array::from_fn(|i| Genre::parse(sub(b, at + 4 * i, 4)))
}

/// The warnings met while reading the TOC, each also logged as it is met.
struct Warnings {
    list: Vec<Warning>,
    log: Log,
}

impl Warnings {
    fn push(&mut self, w: Warning) {
        sb_log!(&self.log, Warn, "warning: {w}");
        self.list.push(w);
    }
}

/// Reads the whole TOC (specifications 2 and 3), returning it with its warnings.
pub(crate) fn read_toc<R: Read + Seek>(
    img: &mut Image<R>,
) -> Result<(Toc, Vec<Warning>, TocDigests, TocStored), Error> {
    let log = img.log().clone();
    sb_log!(
        &log,
        Info,
        "reading the TOC: sector format {:?}, {} sectors ({} bytes)",
        img.format(),
        img.sector_count(),
        img.len()
    );
    let mut warnings = Warnings { list: Vec::new(), log };
    let (master, master_digest) = read_master(img, &mut warnings)?;
    let mut areas = Vec::new();
    let mut area_digests = Vec::new();
    let mut stored = TocStored::default();
    for slot in Slot::ALL {
        let ptr = master.pointer(slot);
        if !ptr.is_used() {
            sb_log!(&warnings.log, Info, "area {slot}: slot unused");
            continue;
        }
        if let Some((area, digest, timecodes)) = read_area(img, slot, ptr, &mut warnings)? {
            area_digests.push(digest);
            stored.track_timecodes.push((slot, timecodes));
            sb_log!(
                &warnings.log,
                Info,
                "area {slot}: {} area, {} channels, sample frequency code {}, audio LSN {}..={}, {} tracks, \
                 play time {} frames",
                area.kind.signature(),
                area.channel_count,
                area.sample_frequency_code,
                area.audio_start_lsn,
                area.audio_end_lsn,
                area.tracks.len(),
                area.playtime_frames()
            );
            areas.push(area);
        } else {
            sb_log!(&warnings.log, Info, "area {slot}: skipped");
        }
    }
    if areas.is_empty() {
        sb_log!(&warnings.log, Info, "rejected: no audio areas");
        return Err(Error::NoAudioAreas);
    }
    sb_log!(&warnings.log, Info, "TOC read: {} areas, {} warnings", areas.len(), warnings.list.len());
    let digests = TocDigests { master: master_digest, areas: area_digests };
    Ok((
        Toc { sector_format: img.format(), sectors: img.sector_count(), master, areas },
        warnings.list,
        digests,
        stored,
    ))
}

/// TOC fields as stored that [`Toc`] gives only as interpreted: each track's start and
/// duration timecodes of `SACDTRL2` (specification 3, 3.7.2), before the clamping of
/// 3.9.2, per area in [`Toc::areas`] order. Kept beside the TOC rather than in [`Track`],
/// whose fields are all public (a new field would break code that builds one).
#[derive(Debug, Default)]
pub(crate) struct TocStored {
    track_timecodes: Vec<(Slot, Vec<TrackTimecodes>)>,
}

/// A track's start and duration timecodes as stored.
type TrackTimecodes = (Timecode, Timecode);

impl TocStored {
    /// The stored start and duration timecodes of track `number` (1-based) of the area from
    /// `slot`.
    pub(crate) fn track_timecodes(&self, slot: Slot, number: u32) -> Option<(Timecode, Timecode)> {
        let (_, list) = self.track_timecodes.iter().find(|(s, _)| *s == slot)?;
        list.get(usize::try_from(number).ok()?.checked_sub(1)?).copied()
    }
}

/// Digests of the TOC sectors a parse used: the master TOC sector at LSN 510 and, for each
/// area in [`Toc::areas`] order, the area TOC copy used (`toc_sectors` sectors at
/// `toc_lsn`). Two images with different digests are different images.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct TocDigests {
    master: u64,
    areas: Vec<u64>,
}

impl TocDigests {
    /// The digests of the same sectors of `img`, for the areas of `toc`: `None` if any of
    /// them does not exist there.
    ///
    /// # Errors
    ///
    /// [`Error::Io`] if a read fails.
    pub(crate) fn of<R: Read + Seek>(img: &mut Image<R>, toc: &Toc) -> Result<Option<Self>, Error> {
        let mut sector = vec![0u8; SECTOR_SIZE];
        if img.read_into(u64::from(MASTER_TOC_LSN), &mut sector)? == ReadOutcome::OutOfRange {
            return Ok(None);
        }
        let master = toc_digest(&sector);
        let mut areas = Vec::with_capacity(toc.areas.len());
        for area in &toc.areas {
            // At most MAX_AREA_TOC_SECTORS sectors: the parse refused larger copies.
            let Some(copy) = read_copy(img, area.toc_lsn, area.toc_sectors)? else { return Ok(None) };
            areas.push(toc_digest(&copy));
        }
        Ok(Some(TocDigests { master, areas }))
    }
}

/// A 64-bit digest of TOC sectors, to tell images apart within a process (it is never
/// stored); not a defence against forgery.
///
/// Four lanes take the 8-byte little-endian words in turn, each lane folding a word in with
/// `(lane ^ word) * K`, rotated; the lanes and the length are then folded together. Each
/// step is a bijection of the lane for a given word and of the word for a given lane, so
/// two inputs of one length that differ in a single word never collide. The lanes are
/// independent, so the digest runs several bytes per cycle where byte-wise FNV-1a ran one
/// byte per multiply (#132). The bytes after the last whole 32-byte block (none for whole
/// sectors) are folded in one at a time.
fn toc_digest(bytes: &[u8]) -> u64 {
    // The golden-ratio constant 2^64 / phi, odd: multiplying by it is a bijection.
    const K: u64 = 0x9e37_79b9_7f4a_7c15;
    let mix = |h: u64, w: u64| (h ^ w).wrapping_mul(K).rotate_left(31);
    let mut lanes: [u64; 4] = [0, 1, 2, 3];
    let mut blocks = bytes.chunks_exact(32);
    for block in &mut blocks {
        for (lane, word) in lanes.iter_mut().zip(block.chunks_exact(8)) {
            *lane = mix(*lane, u64::from_le_bytes(word.try_into().unwrap_or([0; 8])));
        }
    }
    let mut h = lanes.iter().fold(bytes.len() as u64, |h, &lane| mix(h, lane));
    for &b in blocks.remainder() {
        h = mix(h, u64::from(b));
    }
    // Spread the last word over every bit.
    h ^= h >> 32;
    h = h.wrapping_mul(K);
    h ^ (h >> 29)
}

fn read_master<R: Read + Seek>(
    img: &mut Image<R>,
    warnings: &mut Warnings,
) -> Result<(MasterToc, u64), Error> {
    let mut buf = vec![0u8; 10 * SECTOR_SIZE];
    if img.read_into(u64::from(MASTER_TOC_LSN), &mut buf)? == ReadOutcome::OutOfRange {
        sb_log!(&warnings.log, Info, "rejected: master TOC at LSN {MASTER_TOC_LSN} truncated");
        return Err(Error::MasterTocTruncated);
    }
    let s0 = sub(&buf, 0, SECTOR_SIZE);
    if sub(s0, 0, 8) != b"SACDMTOC" {
        sb_log!(&warnings.log, Info, "rejected: no master TOC signature at LSN {MASTER_TOC_LSN}");
        return Err(Error::NotScarletbook);
    }
    let version = Version { major: byte(s0, 8), minor: byte(s0, 9) };
    if version.major > 1 {
        sb_log!(&warnings.log, Info, "rejected: master TOC version {}.{}", version.major, version.minor);
        return Err(Error::MasterTocVersionUnsupported { major: version.major, minor: version.minor });
    }
    sb_log!(
        &warnings.log,
        Info,
        "master TOC at LSN {MASTER_TOC_LSN} used, version {}.{}",
        version.major,
        version.minor
    );
    // LSN 510 is accepted: compare the copies (specification 1, 1.5.1 item 3).
    if master_copies_differ(img, &buf) {
        warnings.push(Warning::disc(WarningCode::MasterTocCopiesDiffer));
    }
    let text_channel_count = byte(s0, 128);
    let locales =
        (0..usize::from(text_channel_count.min(8))).map(|i| Locale::parse(sub(s0, 136 + 4 * i, 4))).collect();
    let text_charset = byte(s0, 138);

    let s1 = sub(&buf, SECTOR_SIZE, SECTOR_SIZE);
    let mut disc_text = DiscText::default();
    if sub(s1, 0, 8) == b"SACDText" {
        let cs = Charset::from_code(text_charset);
        for (i, &item) in DiscTextItem::ALL.iter().enumerate() {
            let off = usize::from(be16(s1, 16 + 2 * i));
            if off == 0 || off >= SECTOR_SIZE {
                continue;
            }
            *disc_text.slot(item) = text::text_string(s1, off, cs);
        }
    } else if text_channel_count > 0 {
        warnings.push(Warning::disc(WarningCode::MasterTextMissing));
    }

    let s9 = sub(&buf, 9 * SECTOR_SIZE, SECTOR_SIZE);
    let manufacturer = if sub(s9, 0, 8) == b"SACD_Man" {
        Some(sub(s9, 8, SECTOR_SIZE - 8).to_vec())
    } else {
        warnings.push(Warning::disc(WarningCode::ManufacturerMissing));
        None
    };

    let pointer = |lsn1: usize, lsn2: usize, size: usize| AreaPointer {
        toc1_lsn: be32(s0, lsn1),
        toc2_lsn: be32(s0, lsn2),
        toc_sectors: be16(s0, size),
    };
    let master = MasterToc {
        version,
        album_set_size: be16(s0, 16),
        album_sequence_number: be16(s0, 18),
        album_catalog_number: text::fixed_text(sub(s0, 24, 16)),
        album_catalog_number_stored: text::fixed_bytes(sub(s0, 24, 16)).to_vec(),
        album_genres: genres(s0, 40),
        two_channel: pointer(64, 68, 84),
        multichannel: pointer(72, 76, 86),
        disc_flags: byte(s0, 80),
        disc_catalog_number: text::fixed_text(sub(s0, 88, 16)),
        disc_catalog_number_stored: text::fixed_bytes(sub(s0, 88, 16)).to_vec(),
        disc_genres: genres(s0, 104),
        date: Date { year: be16(s0, 120), month: byte(s0, 122), day: byte(s0, 123) },
        text_channel_count,
        locales,
        text_charset,
        text: disc_text,
        manufacturer,
    };
    Ok((master, toc_digest(s0)))
}

/// LSNs of the master TOC copies (specification 1, 1.5).
const MASTER_TOC_COPIES: [u32; 2] = [520, 530];

/// Whether a master TOC copy that can be read differs from LSN 510 to 519 in any of its
/// 20 480 bytes (specification 1, 1.5.1 item 3).
///
/// A copy whose read fails, for any reason (missing sectors or an I/O error), is not
/// compared and causes no warning: the outcome of the image is exactly what LSN 510 to
/// 519 yield (1.5.1 item 2), so the optional comparison can never reject it.
fn master_copies_differ<R: Read + Seek>(img: &mut Image<R>, master: &[u8]) -> bool {
    let mut copy = vec![0u8; master.len()];
    MASTER_TOC_COPIES.iter().any(|&lsn| {
        let differs = match img.read_into(u64::from(lsn), &mut copy) {
            Ok(ReadOutcome::Ok) => Some(copy != master),
            _ => None,
        };
        let outcome = match differs {
            Some(true) => "differs from LSN 510",
            Some(false) => "same as LSN 510",
            None => "unreadable, not compared",
        };
        sb_log!(img.log(), Debug, "master TOC copy at LSN {lsn}: {outcome}");
        differs == Some(true)
    })
}

/// Reads one area TOC copy; `None` if any sector is missing.
fn read_copy<R: Read + Seek>(img: &mut Image<R>, lsn: u32, sectors: u16) -> Result<Option<Vec<u8>>, Error> {
    let mut buf = vec![0u8; usize::from(sectors) * SECTOR_SIZE];
    Ok(match img.read_into(u64::from(lsn), &mut buf)? {
        ReadOutcome::Ok => Some(buf),
        ReadOutcome::OutOfRange => None,
    })
}

/// Positions recorded by the sub-structure walk (specification 3, 3.7.0).
#[derive(Default)]
struct Chain {
    ttxt: Option<usize>,
    igl: Option<usize>,
    trl1: Option<usize>,
    trl2: Option<usize>,
}

fn walk(z: &[u8]) -> Chain {
    let e = z.len();
    let mut chain = Chain::default();
    let mut p = SECTOR_SIZE;
    while p + 8 <= e {
        match sub(z, p, 8) {
            b"SACDTTxt" => {
                chain.ttxt.get_or_insert(p);
                p += SECTOR_SIZE;
            }
            b"SACD_IGL" => {
                chain.igl = Some(p);
                p += 2 * SECTOR_SIZE;
            }
            b"SACD_ACC" => p += 32 * SECTOR_SIZE,
            b"SACDTRL1" => {
                chain.trl1 = Some(p);
                p += SECTOR_SIZE;
            }
            b"SACDTRL2" => {
                chain.trl2 = Some(p);
                p += SECTOR_SIZE;
            }
            _ => break,
        }
    }
    chain
}

fn read_area<R: Read + Seek>(
    img: &mut Image<R>,
    slot: Slot,
    ptr: AreaPointer,
    warnings: &mut Warnings,
) -> Result<Option<(Area, u64, Vec<TrackTimecodes>)>, Error> {
    let skip = |warnings: &mut Warnings, code| {
        warnings.push(Warning::area(code, slot));
        Ok(None)
    };
    let t = ptr.toc_sectors;
    if t > MAX_AREA_TOC_SECTORS {
        return skip(warnings, WarningCode::AreaTocTooLarge);
    }
    sb_log!(
        img.log(),
        Debug,
        "area {slot}: TOC-1 at LSN {}, TOC-2 at LSN {}, {t} sectors",
        ptr.toc1_lsn,
        ptr.toc2_lsn
    );
    let toc1 = read_copy(img, ptr.toc1_lsn, t)?;
    if toc1.is_none() {
        warnings.push(Warning::area(WarningCode::AreaToc1Unreadable, slot));
    }
    let toc2 = if ptr.toc2_lsn != 0 {
        let c = read_copy(img, ptr.toc2_lsn, t)?;
        if c.is_none() {
            warnings.push(Warning::area(WarningCode::AreaToc2Unreadable, slot));
        }
        c
    } else {
        None
    };
    let (z, toc_lsn) = match (toc1, toc2) {
        (Some(a), b) => {
            let other = match b {
                Some(b) if b != a => {
                    warnings.push(Warning::area(WarningCode::AreaTocCopiesDiffer, slot));
                    "TOC-2 differs"
                }
                Some(_) => "TOC-2 identical",
                None if ptr.toc2_lsn == 0 => "no TOC-2",
                None => "TOC-2 unreadable",
            };
            sb_log!(img.log(), Info, "area {slot}: TOC-1 at LSN {} used ({other})", ptr.toc1_lsn);
            (a, ptr.toc1_lsn)
        }
        (None, Some(b)) => {
            sb_log!(img.log(), Info, "area {slot}: TOC-2 at LSN {} used (TOC-1 unreadable)", ptr.toc2_lsn);
            (b, ptr.toc2_lsn)
        }
        (None, None) => return skip(warnings, WarningCode::AreaTocUnreadable),
    };
    let e = z.len();

    let kind = match sub(&z, 0, 8) {
        b"TWOCHTOC" => AreaKind::TwoChannel,
        b"MULCHTOC" => AreaKind::Multichannel,
        _ => return skip(warnings, WarningCode::AreaSignatureInvalid),
    };
    let chain = walk(&z);
    let (Some(trl1), Some(trl2)) = (chain.trl1, chain.trl2) else {
        return skip(warnings, WarningCode::AreaTrackListMissing);
    };
    let track_count = byte(&z, 69);
    if let Some(g) = chain.igl {
        if track_count >= 1 && g + 2 * SECTOR_SIZE > e {
            return skip(warnings, WarningCode::AreaTocMalformed);
        }
    }
    let audio_start_lsn = be32(&z, 72);
    let audio_end_lsn = be32(&z, 76);
    if audio_end_lsn < audio_start_lsn {
        return skip(warnings, WarningCode::AreaAudioRangeReversed);
    }

    // The area survives; its own warnings can now be reported.
    let text_charset = byte(&z, 90);
    let cs = Charset::from_code(text_charset);
    let text_channel_count = byte(&z, 80);
    let locales =
        (0..usize::from(text_channel_count.min(10))).map(|i| Locale::parse(sub(&z, 88 + 4 * i, 4))).collect();
    let mut area_text = AreaText::default();
    for (i, &item) in AreaTextItem::ALL.iter().enumerate() {
        let off = usize::from(be16(&z, 144 + 2 * i));
        if off != 0 && off < e {
            *area_text.slot(item) = text::text_string(&z, off, cs);
        }
    }
    let sample_frequency_code = byte(&z, 20);
    if sample_frequency_code != 4 {
        warnings.push(Warning::area(WarningCode::SampleFrequencyUnknown, slot));
    }
    let playtime = Timecode::parse(sub(&z, 64, 3));
    let p_frames = playtime.frame_number();

    let mut tracks = Vec::with_capacity(usize::from(track_count));
    let mut timecodes = Vec::with_capacity(usize::from(track_count));
    for i in 0..usize::from(track_count) {
        // Track numbers are 1 to 255: i is at most 254.
        let number = u8::try_from(i + 1).unwrap_or(u8::MAX);
        let start_tc = Timecode::parse(sub(&z, trl2 + 8 + 4 * i, 3));
        let dur_tc = Timecode::parse(sub(&z, trl2 + 1028 + 4 * i, 3));
        timecodes.push((start_tc, dur_tc));
        let (mut start_frame, mut duration_frames) = (start_tc.frame_number(), dur_tc.frame_number());
        if start_frame + duration_frames > p_frames {
            start_frame = start_frame.min(p_frames);
            duration_frames = duration_frames.min(p_frames - start_frame);
            warnings.push(Warning::track(WarningCode::TrackPastPlaytime, slot, number));
        }
        let start_lsn = be32(&z, trl1 + 8 + 4 * i);
        if !(audio_start_lsn..=audio_end_lsn).contains(&start_lsn) {
            warnings.push(Warning::track(WarningCode::TrackLsnOutsideArea, slot, number));
        }
        let (isrc, genre) = match chain.igl {
            Some(g) => {
                let isrc = text::fixed_text(sub(&z, g + 8 + 12 * i, 12));
                ((!isrc.is_empty()).then_some(isrc), Some(Genre::parse(sub(&z, g + 3072 + 4 * i, 4))))
            }
            None => (None, None),
        };
        let text = match chain.ttxt {
            Some(b) => track_text(&z, b, i, cs, slot, number, warnings),
            None => TrackText::default(),
        };
        tracks.push(Track {
            number,
            start_lsn,
            length_sectors: be32(&z, trl1 + 1028 + 4 * i),
            start_frame,
            duration_frames,
            start_flags: byte(&z, trl2 + 11 + 4 * i),
            duration_flags: byte(&z, trl2 + 1031 + 4 * i),
            isrc,
            genre,
            text,
        });
    }

    let area = Area {
        slot,
        kind,
        version: Version { major: byte(&z, 8), minor: byte(&z, 9) },
        toc_lsn,
        toc_sectors: t,
        max_byte_rate: be32(&z, 16),
        sample_frequency_code,
        frame_format: byte(&z, 21) & 0x0F,
        channel_count: byte(&z, 32),
        area_config: byte(&z, 33),
        max_available_channels: byte(&z, 34),
        area_mute_flags: byte(&z, 35),
        track_attribute: byte(&z, 48) & 0x0F,
        playtime,
        track_offset: byte(&z, 68),
        audio_start_lsn,
        audio_end_lsn,
        text_channel_count,
        locales,
        text_charset,
        text: area_text,
        tracks,
    };
    Ok(Some((area, toc_digest(&z), timecodes)))
}

/// Parses one track's text (specification 3, 3.8.1).
fn track_text(
    z: &[u8],
    b: usize,
    i: usize,
    cs: Charset,
    slot: Slot,
    number: u8,
    warnings: &mut Warnings,
) -> TrackText {
    let e = z.len();
    let mut out = TrackText::default();
    let offset = usize::from(be16(z, b + 8 + 2 * i));
    if offset == 0 {
        return out;
    }
    let mut q = b + offset;
    if q + 4 > e {
        warnings.push(Warning::track(WarningCode::TrackTextOffsetInvalid, slot, number));
        return out;
    }
    let k = byte(z, q);
    q += 4;
    let mut warned_type = false;
    for j in 0..k {
        if q + 2 > e {
            break;
        }
        let item_type = byte(z, q);
        q += 2;
        let bytes = text::string_bytes(z, q);
        let r = bytes.len();
        if r > 0 {
            match TrackTextItem::from_type(item_type) {
                Some(item) => *out.slot(item) = text::decode_string(bytes, cs),
                None if !warned_type => {
                    warned_type = true;
                    warnings.push(Warning::track(WarningCode::TrackTextTypeUnknown, slot, number));
                }
                None => {}
            }
        }
        if j + 1 < k {
            let from = q + r;
            q = z.get(from..).and_then(|rest| rest.iter().position(|&x| x != 0)).map_or(e, |n| from + n);
        }
    }
    out
}

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

    #[test]
    fn toc_digest_tells_small_changes_apart() {
        let mut bytes: Vec<u8> = (0..2 * SECTOR_SIZE).map(|i| (i * 7 % 251) as u8).collect();
        let mut seen = std::collections::HashSet::from([toc_digest(&bytes)]);
        // One bit flipped at a time, across both sectors and every bit position.
        for i in (0..bytes.len()).step_by(61) {
            bytes[i] ^= 1 << (i % 8);
            assert!(seen.insert(toc_digest(&bytes)), "flip at byte {i}");
            bytes[i] ^= 1 << (i % 8);
        }
        // Two words swapped, a different length, a tail shorter than a block.
        bytes.swap(0, 8);
        assert!(seen.insert(toc_digest(&bytes)));
        assert!(seen.insert(toc_digest(&bytes[..SECTOR_SIZE])));
        assert!(seen.insert(toc_digest(&bytes[..SECTOR_SIZE + 5])));
        assert!(seen.insert(toc_digest(&[])));
        assert_ne!(toc_digest(&[0; SECTOR_SIZE]), toc_digest(&[0; SECTOR_SIZE + 1]));
    }

    #[test]
    fn track_text_item_types() {
        assert_eq!(TrackTextItem::from_type(0x01), Some(TrackTextItem::Title));
        assert_eq!(TrackTextItem::from_type(0x07), Some(TrackTextItem::ExtraMessage));
        assert_eq!(TrackTextItem::from_type(0x81), Some(TrackTextItem::TitlePhonetic));
        assert_eq!(TrackTextItem::from_type(0x87), Some(TrackTextItem::ExtraMessagePhonetic));
        for t in [0x00, 0x08, 0x41, 0x80, 0x88, 0xC1, 0xFF] {
            assert_eq!(TrackTextItem::from_type(t), None, "{t:#x}");
        }
    }

    #[test]
    fn loudspeaker_layouts() {
        use Speaker::*;
        assert_eq!(LoudspeakerLayout::new(2, 0), LoudspeakerLayout::Stereo);
        assert_eq!(LoudspeakerLayout::new(5, 3), LoudspeakerLayout::ThreeTwo);
        assert_eq!(LoudspeakerLayout::new(6, 4), LoudspeakerLayout::FivePointOne);
        assert_eq!(LoudspeakerLayout::Stereo.speakers(), Some(&[FrontLeft, FrontRight][..]));
        assert_eq!(
            LoudspeakerLayout::ThreeTwo.speakers(),
            Some(&[FrontLeft, FrontRight, Centre, SurroundLeft, SurroundRight][..])
        );
        assert_eq!(
            LoudspeakerLayout::FivePointOne.speakers(),
            Some(&[FrontLeft, FrontRight, Centre, LowFrequencyEffects, SurroundLeft, SurroundRight][..])
        );
        // Only the low 3 bits select the layout.
        for high in [0x08, 0x10, 0x80, 0xF8] {
            assert_eq!(LoudspeakerLayout::new(2, high), LoudspeakerLayout::Stereo, "{high:#x}");
            assert_eq!(LoudspeakerLayout::new(5, high | 3), LoudspeakerLayout::ThreeTwo, "{high:#x}");
            assert_eq!(LoudspeakerLayout::new(6, high | 4), LoudspeakerLayout::FivePointOne, "{high:#x}");
        }
        // Every other combination is unspecified and keeps both fields as stored.
        let mut defined = 0;
        for channels in 0..=u8::MAX {
            for config in 0..=u8::MAX {
                let layout = LoudspeakerLayout::new(channels, config);
                if matches!((channels, config & 7), (2, 0) | (5, 3) | (6, 4)) {
                    defined += 1;
                    assert_eq!(layout.speakers().map(<[Speaker]>::len), Some(usize::from(channels)));
                } else {
                    assert_eq!(layout, LoudspeakerLayout::Unspecified { channels, config });
                    assert_eq!(layout.speakers(), None);
                }
            }
        }
        assert_eq!(defined, 3 * 32);
    }

    #[test]
    fn timecode_frame_numbers() {
        let tc = Timecode { minutes: 255, seconds: 255, frames: 255 };
        assert_eq!(tc.frame_number(), 1_166_880);
        assert_eq!(Timecode { minutes: 0, seconds: 1, frames: 2 }.frame_number(), 77);
    }

    #[test]
    fn walk_stops_and_records() {
        let mut z = vec![0u8; 6 * SECTOR_SIZE];
        z[2048..2056].copy_from_slice(b"SACDTTxt");
        z[4096..4104].copy_from_slice(b"SACDTTxt");
        z[6144..6152].copy_from_slice(b"SACDTRL1");
        z[8192..8200].copy_from_slice(b"SACDTRL2");
        z[10240..10248].copy_from_slice(b"SACD_IGL");
        let c = walk(&z);
        assert_eq!((c.ttxt, c.trl1, c.trl2, c.igl), (Some(2048), Some(6144), Some(8192), Some(10240)));
        z[4096..4104].copy_from_slice(b"XXXXXXXX");
        let c = walk(&z);
        assert_eq!((c.ttxt, c.trl1), (Some(2048), None));
    }
}