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

//! Errors and diagnostics (specification 0, 0.8 and specification 7, 7.7).

use std::fmt;
use std::io;

/// A master TOC area slot (specification 3, 3.1).
///
/// Frozen: exhaustive on purpose, so a `match` needs no wildcard arm. The master TOC has
/// exactly two area slots, in fixed places; a third would be another format.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Slot {
    /// The 2-channel slot (master TOC offsets 64, 68 and 84).
    TwoChannel,
    /// The multichannel slot (master TOC offsets 72, 76 and 86).
    Multichannel,
}

impl Slot {
    /// Both slots, in processing order.
    pub const ALL: [Slot; 2] = [Slot::TwoChannel, Slot::Multichannel];

    /// The slot name used by the conformance corpus: `2ch` or `multichannel`.
    pub fn name(self) -> &'static str {
        match self {
            Slot::TwoChannel => "2ch",
            Slot::Multichannel => "multichannel",
        }
    }
}

impl fmt::Display for Slot {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

/// An error that stops an operation.
///
/// The first four variants are the image rejections of specification 7, 7.7.1. The
/// track variants are the per-track outcomes of 7.7.4.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// No `SACDMTOC` signature at LSN 510 in any sector format (`not-scarletbook`).
    #[error("not a Scarletbook image: no SACDMTOC at LSN 510")]
    NotScarletbook,
    /// The image ends before LSN 519 is complete (`master-toc-truncated`).
    #[error("master TOC truncated: the image ends before LSN 519")]
    MasterTocTruncated,
    /// The master TOC version major number is above 1 (`master-toc-version-unsupported`).
    #[error("master TOC version {major}.{minor} is not supported")]
    #[non_exhaustive]
    MasterTocVersionUnsupported {
        /// Stored major version.
        major: u8,
        /// Stored minor version.
        minor: u8,
    },
    /// No area slot yields an area (`no-audio-areas`).
    #[error("no readable audio area")]
    NoAudioAreas,
    /// The area's channel count is not 1 to 6 (`channel-count-unsupported`).
    #[error("track refused: the area has {channels} channels, only 1 to 6 are supported")]
    #[non_exhaustive]
    ChannelCountUnsupported {
        /// The area's stored channel count.
        channels: u8,
    },
    /// The track's duration is 0, or the frame range is empty (`track-empty`).
    #[error("track skipped: its duration is 0 frames")]
    TrackEmpty,
    /// The track (or frame range) ends beyond 7 frames per existing audio sector
    /// (`track-exceeds-capacity`).
    #[error("refused: it ends at frame {end_frame}, beyond the area capacity of {capacity} frames")]
    #[non_exhaustive]
    TrackExceedsCapacity {
        /// The track's (or range's) end frame number.
        end_frame: u32,
        /// The area's capacity in frames.
        capacity: u64,
    },
    /// The requested area is not in the TOC.
    #[error("no area in slot {0}")]
    NoSuchArea(Slot),
    /// The requested track does not exist in the area.
    #[error("no track {track} in area {slot}")]
    #[non_exhaustive]
    NoSuchTrack {
        /// The area's slot.
        slot: Slot,
        /// The requested track number.
        track: u32,
    },
    /// A requested frame range `[first, end)` is reversed or extends past the area's play
    /// time: it must satisfy `first <= end <= playtime` (specification 4, 4.7.1 item 3, a
    /// caller error). An empty range is [`Error::TrackEmpty`].
    #[error("frame range [{first}, {end}) is not within the area's timeline [0, {playtime})")]
    #[non_exhaustive]
    FrameRangeInvalid {
        /// The range's first frame number.
        first: u32,
        /// The range's end frame number (exclusive).
        end: u32,
        /// The area's play time in frames.
        playtime: u32,
    },
    /// A sector read extends past the image's last sector ([`crate::Image::read_sectors`]):
    /// it must satisfy `lsn + count <= sectors` (specification 1, 1.3).
    #[error("{count} sectors at LSN {lsn} are not all in the image's {sectors} sectors")]
    #[non_exhaustive]
    SectorRangeInvalid {
        /// The first sector asked for.
        lsn: u64,
        /// The number of sectors asked for.
        count: u64,
        /// The image's sector count.
        sectors: u64,
    },
    /// A DST lane count is not from 1 to [`crate::dst::MAX_LANES`]
    /// ([`crate::TrackAudioCursor::with_dst_lanes`]).
    #[error("{lanes} DST lanes: must be from 1 to {max}", max = crate::dst::MAX_LANES)]
    #[non_exhaustive]
    DstLanesInvalid {
        /// The count asked for.
        lanes: usize,
    },
    /// A caller-supplied argument is invalid (for example a buffer of the wrong size).
    #[error("invalid argument: {0}")]
    InvalidArgument(&'static str),
    /// The underlying reader failed.
    #[error("I/O error: {0}")]
    Io(#[from] io::Error),
    /// The call stopped because cancellation was requested through the image's
    /// [`crate::CancelToken`] (see [`crate::Disc::cancel_token`]). Nothing was lost: the
    /// cursor stays where it was, and continues once the request is withdrawn.
    #[error("cancelled")]
    Cancelled,
    /// The requested output file can't be written for this area with these options
    /// (specification 8). It is not an outcome of the image: other options, or another
    /// format, may write it.
    #[error("output refused: {0}")]
    OutputRefused(OutputRefusal),
    /// Sector `lsn` is unreadable ([`crate::UnreadableSectors`], #435): marked so, or
    /// reported so by the reader ([`crate::read_at::unreadable_error`]). Returned by
    /// [`crate::Image::read_sectors`], which gives no bytes in its place, and by
    /// [`crate::AreaIndex::extend`], which records no reading state at or past it.
    #[error("sector {lsn} is unreadable")]
    #[non_exhaustive]
    SectorUnreadable {
        /// The first unreadable sector met.
        lsn: u64,
    },
}

/// Why an output file can't be written ([`Error::OutputRefused`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum OutputRefusal {
    /// The area has no defined loudspeaker layout (specification 8, 8.1 item 5), and the
    /// options give no channel type or channel IDs for it (8.2.4 item 2).
    #[error(
        "the area's layout ({channels} channels, configuration {config:#04x}) is unspecified, and the options give no channel type for it"
    )]
    #[non_exhaustive]
    UnspecifiedLayout {
        /// The area's channel count.
        channels: u8,
        /// The area configuration byte, as stored.
        config: u8,
    },
    /// The file can't be an edited master (specification 8, 8.4.11): the check that fails.
    #[error("not an edited master: {0}")]
    NotEditedMaster(EditedMasterCheck),
}

/// A requirement of an edited master (specification 8, 8.4.11) that an area or range
/// fails ([`OutputRefusal::NotEditedMaster`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum EditedMasterCheck {
    /// The range is not the play range `[0, P)` (8.4.11, first paragraph).
    #[error("it holds only the play range of an area")]
    Range,
    /// The layout is not stereo, 3/2 or 5.1 (item 2).
    #[error("the area's loudspeaker layout is unspecified")]
    Layout,
    /// The area has no track, or more than 255 (item 5).
    #[error("the area must have 1 to 255 tracks")]
    TrackCount,
    /// A track's duration is below 75 frames (item 5).
    #[error("track {track} is shorter than 75 frames")]
    #[non_exhaustive]
    TrackTooShort {
        /// The track's number.
        track: u8,
    },
    /// The tracks are out of order, overlap or are empty (item 5, 8.4.10 item 2).
    #[error("the tracks are out of order or overlap")]
    TracksNotInOrder,
    /// The program is longer than 255 minutes, 59 seconds and 74 frames (item 6).
    #[error("the program is longer than 255:59:74")]
    ProgramTooLong,
}

/// Broad classes of [`Error`], for callers (and the FFI) that map errors to codes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorClass {
    /// The image was rejected (specification 7, 7.7.1).
    Rejected,
    /// A track was refused (no audio, an error).
    TrackRefused,
    /// A track was skipped (no audio, not an error).
    TrackSkipped,
    /// The caller asked for something that does not exist or passed a bad argument.
    Usage,
    /// The reader failed.
    Io,
    /// Cancellation was requested ([`Error::Cancelled`]).
    Cancelled,
}

impl Error {
    /// The diagnostic code of specification 7, if this error has one.
    pub fn code(&self) -> Option<&'static str> {
        Some(match self {
            Error::NotScarletbook => "not-scarletbook",
            Error::MasterTocTruncated => "master-toc-truncated",
            Error::MasterTocVersionUnsupported { .. } => "master-toc-version-unsupported",
            Error::NoAudioAreas => "no-audio-areas",
            Error::ChannelCountUnsupported { .. } => "channel-count-unsupported",
            Error::TrackEmpty => "track-empty",
            Error::TrackExceedsCapacity { .. } => "track-exceeds-capacity",
            Error::NoSuchArea(_)
            | Error::NoSuchTrack { .. }
            | Error::FrameRangeInvalid { .. }
            | Error::SectorRangeInvalid { .. }
            | Error::DstLanesInvalid { .. }
            | Error::InvalidArgument(_)
            | Error::Io(_)
            | Error::Cancelled
            | Error::OutputRefused(_)
            | Error::SectorUnreadable { .. } => {
                return None;
            }
        })
    }

    /// The class of this error.
    pub fn class(&self) -> ErrorClass {
        match self {
            Error::NotScarletbook
            | Error::MasterTocTruncated
            | Error::MasterTocVersionUnsupported { .. }
            | Error::NoAudioAreas => ErrorClass::Rejected,
            Error::ChannelCountUnsupported { .. } | Error::TrackExceedsCapacity { .. } => {
                ErrorClass::TrackRefused
            }
            Error::TrackEmpty => ErrorClass::TrackSkipped,
            Error::NoSuchArea(_)
            | Error::NoSuchTrack { .. }
            | Error::FrameRangeInvalid { .. }
            | Error::SectorRangeInvalid { .. }
            | Error::DstLanesInvalid { .. }
            | Error::InvalidArgument(_)
            | Error::OutputRefused(_) => ErrorClass::Usage,
            Error::Io(_) | Error::SectorUnreadable { .. } => ErrorClass::Io,
            Error::Cancelled => ErrorClass::Cancelled,
        }
    }
}

/// The warning codes of specification 7, 7.7.2 and 7.7.3.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum WarningCode {
    /// No `SACDText` at LSN 511 and the text channel count is above 0.
    MasterTextMissing,
    /// No `SACD_Man` at LSN 519.
    ManufacturerMissing,
    /// Area TOC size above 128 sectors (area skipped).
    AreaTocTooLarge,
    /// TOC-1 cannot be read.
    AreaToc1Unreadable,
    /// TOC-2 is set but cannot be read.
    AreaToc2Unreadable,
    /// Both copies were read and differ.
    AreaTocCopiesDiffer,
    /// Neither TOC copy can be read (area skipped).
    AreaTocUnreadable,
    /// The chosen copy's signature is neither `TWOCHTOC` nor `MULCHTOC` (area skipped).
    AreaSignatureInvalid,
    /// No `SACDTRL1` or no `SACDTRL2` in the sub-structure walk (area skipped).
    AreaTrackListMissing,
    /// A `SACD_IGL` extends past the end of the area TOC (area skipped).
    AreaTocMalformed,
    /// The last audio LSN is below the first (area skipped).
    AreaAudioRangeReversed,
    /// A track text offset points too close to the end of the area TOC.
    TrackTextOffsetInvalid,
    /// A track text item of unknown type with a non-empty string.
    TrackTextTypeUnknown,
    /// A track ends after the area play time; it was clamped.
    TrackPastPlaytime,
    /// A track start LSN lies outside the area's audio range.
    TrackLsnOutsideArea,
    /// A malformed audio sector (optional).
    AudioSectorMalformed,
    /// A master TOC copy at LSN 520 or 530 differs from LSN 510 (optional; reported at
    /// most once, specification 1, 1.5.1 item 3).
    MasterTocCopiesDiffer,
    /// A sample frequency code other than 4 (optional).
    SampleFrequencyUnknown,
}

impl WarningCode {
    /// The diagnostic code string of specification 7.
    pub fn code(self) -> &'static str {
        match self {
            WarningCode::MasterTextMissing => "master-text-missing",
            WarningCode::ManufacturerMissing => "manufacturer-missing",
            WarningCode::AreaTocTooLarge => "area-toc-too-large",
            WarningCode::AreaToc1Unreadable => "area-toc1-unreadable",
            WarningCode::AreaToc2Unreadable => "area-toc2-unreadable",
            WarningCode::AreaTocCopiesDiffer => "area-toc-copies-differ",
            WarningCode::AreaTocUnreadable => "area-toc-unreadable",
            WarningCode::AreaSignatureInvalid => "area-signature-invalid",
            WarningCode::AreaTrackListMissing => "area-track-list-missing",
            WarningCode::AreaTocMalformed => "area-toc-malformed",
            WarningCode::AreaAudioRangeReversed => "area-audio-range-reversed",
            WarningCode::TrackTextOffsetInvalid => "track-text-offset-invalid",
            WarningCode::TrackTextTypeUnknown => "track-text-type-unknown",
            WarningCode::TrackPastPlaytime => "track-past-playtime",
            WarningCode::TrackLsnOutsideArea => "track-lsn-outside-area",
            WarningCode::AudioSectorMalformed => "audio-sector-malformed",
            WarningCode::MasterTocCopiesDiffer => "master-toc-copies-differ",
            WarningCode::SampleFrequencyUnknown => "sample-frequency-unknown",
        }
    }

    /// Whether the warning means the area was skipped (specification 7, 7.7.2).
    pub fn skips_area(self) -> bool {
        matches!(
            self,
            WarningCode::AreaTocTooLarge
                | WarningCode::AreaTocUnreadable
                | WarningCode::AreaSignatureInvalid
                | WarningCode::AreaTrackListMissing
                | WarningCode::AreaTocMalformed
                | WarningCode::AreaAudioRangeReversed
        )
    }
}

impl fmt::Display for WarningCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.code())
    }
}

/// A warning: a code with the slot, track and LSN it concerns, where they apply.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Warning {
    /// The diagnostic code.
    pub code: WarningCode,
    /// The area slot the warning concerns, if any.
    pub slot: Option<Slot>,
    /// The track number (1-based) the warning concerns, if any.
    pub track: Option<u8>,
    /// The LSN the warning concerns, if any (`audio-sector-malformed`).
    pub lsn: Option<u32>,
}

impl Warning {
    pub(crate) fn disc(code: WarningCode) -> Self {
        Warning { code, slot: None, track: None, lsn: None }
    }

    pub(crate) fn area(code: WarningCode, slot: Slot) -> Self {
        Warning { code, slot: Some(slot), track: None, lsn: None }
    }

    pub(crate) fn track(code: WarningCode, slot: Slot, track: u8) -> Self {
        Warning { code, slot: Some(slot), track: Some(track), lsn: None }
    }
}

impl fmt::Display for Warning {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.code.code())?;
        if let Some(slot) = self.slot {
            write!(f, " (area {slot}")?;
            if let Some(track) = self.track {
                write!(f, ", track {track}")?;
            }
            if let Some(lsn) = self.lsn {
                write!(f, ", LSN {lsn}")?;
            }
            f.write_str(")")?;
        }
        Ok(())
    }
}