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

//! Stored sector formats, format detection and LSN addressing (specification 1).

use std::io::{self, Read, Seek, SeekFrom};
use std::sync::atomic::{AtomicU64, Ordering};

use crate::control::CancelToken;
use crate::error::Error;
use crate::log::{Log, sb_log};
use crate::read_at::{ReadAt, ReadAtReader};

/// Size of a logical sector in bytes (specification 0, 0.3).
pub const SECTOR_SIZE: usize = 2048;

/// LSN of the first master TOC sector (specification 1, 1.5).
pub const MASTER_TOC_LSN: u32 = 510;

/// How logical sectors are stored in an image file (specification 1, 1.2).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SectorFormat {
    /// 2048 bytes per stored sector, data at offset 0.
    Plain,
    /// 2054 bytes per stored sector, data at offset 6.
    Raw2054,
    /// 2064 bytes per stored sector, data at offset 12.
    Raw2064,
}

impl SectorFormat {
    /// The detection order of specification 1, 1.4.
    pub const DETECTION_ORDER: [SectorFormat; 3] =
        [SectorFormat::Plain, SectorFormat::Raw2064, SectorFormat::Raw2054];

    /// Stored sector size `P` in bytes.
    pub fn stored_size(self) -> u64 {
        match self {
            SectorFormat::Plain => 2048,
            SectorFormat::Raw2054 => 2054,
            SectorFormat::Raw2064 => 2064,
        }
    }

    /// Offset `D` of the user data within a stored sector.
    pub fn data_offset(self) -> u64 {
        match self {
            SectorFormat::Plain => 0,
            SectorFormat::Raw2054 => 6,
            SectorFormat::Raw2064 => 12,
        }
    }
}

/// A disc image: a reader, its sector format and its sector count.
///
/// Reads follow specification 1, 1.3: a read of `n` sectors at `a` succeeds only if
/// `a + n <= N`, and a failing read returns no data.
#[derive(Debug)]
pub struct Image<R> {
    reader: R,
    id: u64,
    format: SectorFormat,
    len: u64,
    sectors: u64,
    /// Where the reader is positioned, if known, to avoid redundant seeks.
    pos: Option<u64>,
    /// The stored sectors of a raw read, before their user data is copied out: allocated
    /// by the first raw read and reused by the next, released once a disc has read its TOC
    /// ([`Image::release_buffer`]).
    scratch: Vec<u8>,
    log: Log,
    /// Shared with the images of the same source made from this one.
    cancel: CancelToken,
}

/// The outcome of a sector read that did not fail with an I/O error.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ReadOutcome {
    /// All sectors existed and were copied.
    Ok,
    /// At least one sector does not exist; nothing was copied.
    OutOfRange,
}

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

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

    /// The sector format, chosen by the caller instead of detected (specification 1, 1.4
    /// item 5). The master TOC signature is then checked by the TOC parser.
    pub fn with_format(mut self, format: SectorFormat) -> Self {
        self.format = Some(format);
        self
    }

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

    /// Opens the image.
    ///
    /// # Errors
    ///
    /// [`Error::Io`] if the reader fails; without a chosen format,
    /// [`Error::NotScarletbook`] if no format matches.
    pub fn open<R: Read + Seek>(self, reader: R) -> Result<Image<R>, Error> {
        match self.format {
            Some(format) => Image::open_format(reader, format, self.log),
            None => Image::detect(reader, self.log),
        }
    }
}

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

impl<R: Read + Seek> Image<R> {
    /// Opens an image, detecting its sector format (specification 1, 1.4), logging nothing.
    /// [`Image::options`] chooses a format or a log.
    ///
    /// # Errors
    ///
    /// [`Error::NotScarletbook`] if no format matches, [`Error::Io`] if the reader fails.
    pub fn open(reader: R) -> Result<Self, Error> {
        Image::options().open(reader)
    }

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

    fn detect(mut reader: R, log: Log) -> Result<Self, Error> {
        let len = match reader.seek(SeekFrom::End(0)) {
            Ok(len) => len,
            Err(e) => {
                sb_log!(&log, Error, "image length: seek to the end failed: {e}");
                return Err(e.into());
            }
        };
        sb_log!(&log, Debug, "image length {len} bytes; probing sector formats");
        let mut sig = [0u8; 8];
        for format in SectorFormat::DETECTION_ORDER {
            // 510 x P + D + 8 is at most about 1 MB: no overflow.
            let at = u64::from(MASTER_TOC_LSN) * format.stored_size() + format.data_offset();
            if at + 8 > len {
                sb_log!(&log, Debug, "format {format:?}: signature bytes {at}..{} past the end", at + 8);
                continue;
            }
            if let Err(e) = reader.seek(SeekFrom::Start(at)).and_then(|_| reader.read_exact(&mut sig)) {
                sb_log!(&log, Error, "format {format:?}: read of bytes {at}..{} failed: {e}", at + 8);
                return Err(e.into());
            }
            if &sig == b"SACDMTOC" {
                let image = Self::new(reader, format, len, log);
                sb_log!(
                    &image.log,
                    Info,
                    "sector format {format:?} detected (signature at byte {at}): {} bytes per sector, data at \
                     offset {}, {} sectors",
                    format.stored_size(),
                    format.data_offset(),
                    image.sectors
                );
                return Ok(image);
            }
            sb_log!(&log, Debug, "format {format:?}: no signature at byte {at}");
        }
        sb_log!(&log, Info, "no sector format matches: not a Scarletbook image");
        Err(Error::NotScarletbook)
    }

    /// Opens an image with a sector format chosen by the caller (specification 1, 1.4
    /// item 5). The master TOC signature is then checked by the TOC parser.
    ///
    /// # Errors
    ///
    /// [`Error::Io`] if the reader fails.
    #[deprecated(
        since = "0.6.0",
        note = "use `Image::options().with_format(format).open(reader)`; to be removed before 1.0"
    )]
    pub fn with_format(reader: R, format: SectorFormat) -> Result<Self, Error> {
        Image::options().with_format(format).open(reader)
    }

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

    fn open_format(mut reader: R, format: SectorFormat, log: Log) -> Result<Self, Error> {
        let len = match reader.seek(SeekFrom::End(0)) {
            Ok(len) => len,
            Err(e) => {
                sb_log!(&log, Error, "image length: seek to the end failed: {e}");
                return Err(e.into());
            }
        };
        let image = Self::new(reader, format, len, log);
        sb_log!(
            &image.log,
            Info,
            "sector format {format:?} chosen by the caller: {} bytes per sector, data at offset {}, {} sectors \
             ({len} bytes)",
            format.stored_size(),
            format.data_offset(),
            image.sectors
        );
        Ok(image)
    }

    fn new(reader: R, format: SectorFormat, len: u64, log: Log) -> Self {
        static NEXT_ID: AtomicU64 = AtomicU64::new(1);
        Image {
            reader,
            id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
            format,
            len,
            sectors: len / format.stored_size(),
            pos: None,
            scratch: Vec::new(),
            log,
            cancel: CancelToken::new(),
        }
    }

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

    /// Replaces the log this image reports to. Decoding jobs already started keep the log
    /// they started with.
    pub fn set_log(&mut self, log: Log) {
        self.log = log;
    }

    /// An identifier of this image, unique within the process except that the images of
    /// [`crate::Disc::share`] and of `clone` (for a [`ReadAtReader`]) have their original's:
    /// they read the same bytes. Audio cursors bind to the identifier of the image they
    /// first read and refuse an image with any other.
    pub fn id(&self) -> u64 {
        self.id
    }

    /// The cancellation request of this image's reads (see [`CancelToken`]), shared with
    /// the images of [`crate::Disc::share`] and of `clone`.
    pub fn cancel_token(&self) -> CancelToken {
        self.cancel.clone()
    }

    /// [`crate::Error::Cancelled`] if cancellation of this image's reads is requested.
    #[inline]
    pub(crate) fn check_cancel(&self) -> Result<(), Error> {
        self.cancel.check()
    }

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

    /// The number of logical sectors `N` (specification 1, 1.3).
    pub fn sector_count(&self) -> u64 {
        self.sectors
    }

    /// The image length in bytes.
    pub fn len(&self) -> u64 {
        self.len
    }

    /// Whether the image is empty.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// The same image read through `reader`, which the caller checks holds the same bytes:
    /// this image's format, sector count and identifier, with a position and buffer of its
    /// own, reporting to `log`.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidArgument`] if `reader` has another length, [`Error::Io`] if finding
    /// its length fails.
    pub(crate) fn share<R2: Read + Seek>(&self, mut reader: R2, log: Log) -> Result<Image<R2>, Error> {
        let len = match reader.seek(SeekFrom::End(0)) {
            Ok(len) => len,
            Err(e) => {
                sb_log!(&log, Error, "shared reader: seek to the end failed: {e}");
                return Err(e.into());
            }
        };
        if len != self.len {
            sb_log!(&log, Info, "shared reader refused: {len} bytes, the image has {}", self.len);
            return Err(Error::InvalidArgument("shared reader of another image"));
        }
        Ok(self.with_reader(reader, log))
    }

    fn with_reader<R2>(&self, reader: R2, log: Log) -> Image<R2> {
        Image {
            reader,
            id: self.id,
            format: self.format,
            len: self.len,
            sectors: self.sectors,
            pos: None,
            scratch: Vec::new(),
            log,
            cancel: self.cancel.clone(),
        }
    }

    /// Frees the read buffer of raw sector formats, which the next raw read allocates
    /// again: a disc opened only for its TOC keeps none (#228).
    pub(crate) fn release_buffer(&mut self) {
        self.scratch = Vec::new();
    }

    /// The capacity of the read buffer of raw sector formats.
    #[cfg(test)]
    pub(crate) fn buffer_capacity(&self) -> usize {
        self.scratch.capacity()
    }

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

    /// Whether a read of `count` sectors at `lsn` would succeed (specification 1, 1.3).
    pub fn contains(&self, lsn: u64, count: u64) -> bool {
        lsn.checked_add(count).is_some_and(|end| end <= self.sectors)
    }

    /// Reads `buf.len() / 2048` logical sectors starting at `lsn` into `buf`. A range that
    /// is not all in the image is refused before anything is read (specification 1, 1.3).
    /// `buf.len()` must be a multiple of 2048. An empty `buf` reads nothing and succeeds for
    /// any `lsn` up to [`Image::sector_count`], as `sb_disc_read_sectors` does with a count
    /// of 0.
    ///
    /// # Errors
    ///
    /// [`Error::SectorRangeInvalid`] if any of the sectors does not exist, with `buf` left
    /// as it was. [`Error::InvalidArgument`] for a bad buffer length. [`Error::Io`] if the
    /// reader fails (including a reader that is shorter than it reported), after which what
    /// `buf` holds is unspecified.
    pub fn read_sectors(&mut self, lsn: u64, buf: &mut [u8]) -> Result<(), Error> {
        if buf.len() % SECTOR_SIZE != 0 {
            return Err(Error::InvalidArgument("buffer length must be a multiple of 2048"));
        }
        if buf.is_empty() && self.contains(lsn, 0) {
            return Ok(());
        }
        match self.read_into(lsn, buf)? {
            ReadOutcome::Ok => Ok(()),
            ReadOutcome::OutOfRange => Err(Error::SectorRangeInvalid {
                lsn,
                count: (buf.len() / SECTOR_SIZE) as u64,
                sectors: self.sectors,
            }),
        }
    }

    pub(crate) fn read_into(&mut self, lsn: u64, buf: &mut [u8]) -> io::Result<ReadOutcome> {
        let count = (buf.len() / SECTOR_SIZE) as u64;
        if !self.contains(lsn, count) {
            sb_log!(
                &self.log,
                Debug,
                "read of {count} sectors at LSN {lsn}: past the last sector ({})",
                self.sectors
            );
            return Ok(ReadOutcome::OutOfRange);
        }
        let p = self.format.stored_size();
        let d = self.format.data_offset();
        // lsn + count <= N <= len / P, so lsn x P <= len: no overflow.
        let start = lsn * p;
        sb_log!(&self.log, Debug, "read {count} sectors at LSN {lsn}: bytes {start}..{}", start + count * p);
        let result = if self.format == SectorFormat::Plain {
            self.seek_to(start).and_then(|()| self.reader.read_exact(buf)).map(|()| start + buf.len() as u64)
        } else {
            self.read_raw(start, count, p, d, buf)
        };
        match result {
            Ok(end) => {
                self.pos = Some(end);
                Ok(ReadOutcome::Ok)
            }
            Err(e) => {
                sb_log!(&self.log, Error, "read of {count} sectors at LSN {lsn} (byte {start}) failed: {e}");
                self.pos = None;
                Err(e)
            }
        }
    }

    fn read_raw(&mut self, start: u64, count: u64, p: u64, d: u64, buf: &mut [u8]) -> io::Result<u64> {
        // Read whole stored sectors in bounded chunks and copy out the user data.
        const CHUNK_SECTORS: usize = 64;
        self.seek_to(start)?;
        let p_usize = p as usize;
        let d_usize = d as usize;
        let mut done = 0usize;
        let total = count as usize;
        while done < total {
            let n = CHUNK_SECTORS.min(total - done);
            self.scratch.resize(n * p_usize, 0);
            self.reader.read_exact(&mut self.scratch)?;
            for (i, stored) in self.scratch.chunks_exact(p_usize).enumerate() {
                let dst_start = (done + i) * SECTOR_SIZE;
                let (Some(dst), Some(src)) = (
                    buf.get_mut(dst_start..dst_start + SECTOR_SIZE),
                    stored.get(d_usize..d_usize + SECTOR_SIZE),
                ) else {
                    return Err(io::Error::other("internal sector copy out of range"));
                };
                dst.copy_from_slice(src);
            }
            done += n;
        }
        Ok(start + count * p)
    }

    fn seek_to(&mut self, at: u64) -> io::Result<()> {
        if self.pos != Some(at) {
            self.pos = None;
            self.reader.seek(SeekFrom::Start(at))?;
            self.pos = Some(at);
        }
        Ok(())
    }
}

/// Another reader of the same source, with a position and buffer of its own and the same
/// format, sector count, identifier and log: no I/O. Cheap when the source is (`&T`,
/// `Arc<T>`); see [`ReadAtReader`].
impl<A: ReadAt + Clone> Clone for Image<ReadAtReader<A>> {
    fn clone(&self) -> Self {
        self.with_reader(self.reader.clone(), self.log.clone())
    }
}

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

    fn image_with_sig(format: SectorFormat, sectors: u64) -> Vec<u8> {
        let p = format.stored_size() as usize;
        let mut v = vec![0u8; sectors as usize * p];
        let at = 510 * p + format.data_offset() as usize;
        if let Some(sig) = v.get_mut(at..at + 8) {
            sig.copy_from_slice(b"SACDMTOC");
        }
        v
    }

    #[test]
    fn detects_each_format() {
        for f in SectorFormat::DETECTION_ORDER {
            let img = Image::open(Cursor::new(image_with_sig(f, 520))).unwrap();
            assert_eq!(img.format(), f);
            assert_eq!(img.sector_count(), 520);
        }
    }

    #[test]
    fn options_choose_the_format_or_detect_it() {
        let f = SectorFormat::Raw2054;
        let detected = Image::options().open(Cursor::new(image_with_sig(f, 511))).unwrap();
        assert_eq!(detected.format(), f);
        // Chosen: no signature is looked for, and the sector count follows the format.
        let chosen = Image::options().with_format(f).open(Cursor::new(vec![0u8; 2 * 2054])).unwrap();
        assert_eq!((chosen.format(), chosen.sector_count()), (f, 2));
        assert!(matches!(Image::options().open(Cursor::new(vec![0u8; 8])), Err(Error::NotScarletbook)));
    }

    #[test]
    #[allow(deprecated)]
    fn old_constructors_still_work() {
        let f = SectorFormat::Raw2064;
        let reader = || Cursor::new(image_with_sig(f, 511));
        assert_eq!(Image::open_with_log(reader(), Log::none()).unwrap().format(), f);
        assert_eq!(Image::with_format(reader(), f).unwrap().format(), f);
        assert_eq!(Image::with_format_and_log(reader(), f, Log::none()).unwrap().format(), f);
    }

    #[test]
    fn detection_needs_only_eight_bytes() {
        let mut v = image_with_sig(SectorFormat::Plain, 511);
        v.truncate(510 * 2048 + 8);
        let img = Image::open(Cursor::new(v)).unwrap();
        assert_eq!(img.sector_count(), 510);
        let v = vec![0u8; 510 * 2048 + 7];
        assert!(matches!(Image::open(Cursor::new(v)), Err(Error::NotScarletbook)));
    }

    #[test]
    fn reads_raw_sectors_and_fails_whole_reads() {
        let f = SectorFormat::Raw2064;
        let mut v = image_with_sig(f, 3);
        // Put a marker in the user data of sector 2.
        let at = 2 * 2064 + 12;
        v[at] = 0xAB;
        v[at + 2047] = 0xCD;
        // Partial trailing sector does not count.
        v.extend_from_slice(&[0u8; 2063]);
        let mut img = Image::options().with_format(f).open(Cursor::new(v)).unwrap();
        assert_eq!(img.sector_count(), 3);
        let mut buf = vec![0u8; 2048];
        img.read_sectors(2, &mut buf).unwrap();
        assert_eq!((buf[0], buf[2047]), (0xAB, 0xCD));
        let mut two = vec![7u8; 4096];
        let e = img.read_sectors(2, &mut two).unwrap_err();
        assert!(matches!(e, Error::SectorRangeInvalid { lsn: 2, count: 2, sectors: 3 }), "{e:?}");
        assert_eq!(e.class(), crate::ErrorClass::Usage);
        assert_eq!(e.code(), None);
        assert!(two.iter().all(|&b| b == 7), "a refused read writes nothing");
        let e = img.read_sectors(u64::MAX, &mut buf).unwrap_err();
        assert!(matches!(e, Error::SectorRangeInvalid { lsn: u64::MAX, count: 1, sectors: 3 }), "{e:?}");
    }

    #[test]
    fn empty_reads_succeed_up_to_the_sector_count() {
        let mut img =
            Image::options().with_format(SectorFormat::Plain).open(Cursor::new(vec![0u8; 2 * 2048])).unwrap();
        img.read_sectors(0, &mut []).unwrap();
        img.read_sectors(2, &mut []).unwrap();
        let e = img.read_sectors(3, &mut []).unwrap_err();
        assert!(matches!(e, Error::SectorRangeInvalid { lsn: 3, count: 0, sectors: 2 }), "{e:?}");
        assert!(matches!(img.read_sectors(0, &mut [0u8; 2047]), Err(Error::InvalidArgument(_))));
    }
}