Skip to main content

scarletbook/
error.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Errors and diagnostics (specification 0, 0.8 and specification 7, 7.7).
4
5use std::fmt;
6use std::io;
7
8/// A master TOC area slot (specification 3, 3.1).
9///
10/// Frozen: exhaustive on purpose, so a `match` needs no wildcard arm. The master TOC has
11/// exactly two area slots, in fixed places; a third would be another format.
12#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
13pub enum Slot {
14    /// The 2-channel slot (master TOC offsets 64, 68 and 84).
15    TwoChannel,
16    /// The multichannel slot (master TOC offsets 72, 76 and 86).
17    Multichannel,
18}
19
20impl Slot {
21    /// Both slots, in processing order.
22    pub const ALL: [Slot; 2] = [Slot::TwoChannel, Slot::Multichannel];
23
24    /// The slot name used by the conformance corpus: `2ch` or `multichannel`.
25    pub fn name(self) -> &'static str {
26        match self {
27            Slot::TwoChannel => "2ch",
28            Slot::Multichannel => "multichannel",
29        }
30    }
31}
32
33impl fmt::Display for Slot {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        f.write_str(self.name())
36    }
37}
38
39/// An error that stops an operation.
40///
41/// The first four variants are the image rejections of specification 7, 7.7.1. The
42/// track variants are the per-track outcomes of 7.7.4.
43#[derive(Debug, thiserror::Error)]
44#[non_exhaustive]
45pub enum Error {
46    /// No `SACDMTOC` signature at LSN 510 in any sector format (`not-scarletbook`).
47    #[error("not a Scarletbook image: no SACDMTOC at LSN 510")]
48    NotScarletbook,
49    /// The image ends before LSN 519 is complete (`master-toc-truncated`).
50    #[error("master TOC truncated: the image ends before LSN 519")]
51    MasterTocTruncated,
52    /// The master TOC version major number is above 1 (`master-toc-version-unsupported`).
53    #[error("master TOC version {major}.{minor} is not supported")]
54    #[non_exhaustive]
55    MasterTocVersionUnsupported {
56        /// Stored major version.
57        major: u8,
58        /// Stored minor version.
59        minor: u8,
60    },
61    /// No area slot yields an area (`no-audio-areas`).
62    #[error("no readable audio area")]
63    NoAudioAreas,
64    /// The area's channel count is not 1 to 6 (`channel-count-unsupported`).
65    #[error("track refused: the area has {channels} channels, only 1 to 6 are supported")]
66    #[non_exhaustive]
67    ChannelCountUnsupported {
68        /// The area's stored channel count.
69        channels: u8,
70    },
71    /// The track's duration is 0, or the frame range is empty (`track-empty`).
72    #[error("track skipped: its duration is 0 frames")]
73    TrackEmpty,
74    /// The track (or frame range) ends beyond 7 frames per existing audio sector
75    /// (`track-exceeds-capacity`).
76    #[error("refused: it ends at frame {end_frame}, beyond the area capacity of {capacity} frames")]
77    #[non_exhaustive]
78    TrackExceedsCapacity {
79        /// The track's (or range's) end frame number.
80        end_frame: u32,
81        /// The area's capacity in frames.
82        capacity: u64,
83    },
84    /// The requested area is not in the TOC.
85    #[error("no area in slot {0}")]
86    NoSuchArea(Slot),
87    /// The requested track does not exist in the area.
88    #[error("no track {track} in area {slot}")]
89    #[non_exhaustive]
90    NoSuchTrack {
91        /// The area's slot.
92        slot: Slot,
93        /// The requested track number.
94        track: u32,
95    },
96    /// A requested frame range `[first, end)` is reversed or extends past the area's play
97    /// time: it must satisfy `first <= end <= playtime` (specification 4, 4.7.1 item 3, a
98    /// caller error). An empty range is [`Error::TrackEmpty`].
99    #[error("frame range [{first}, {end}) is not within the area's timeline [0, {playtime})")]
100    #[non_exhaustive]
101    FrameRangeInvalid {
102        /// The range's first frame number.
103        first: u32,
104        /// The range's end frame number (exclusive).
105        end: u32,
106        /// The area's play time in frames.
107        playtime: u32,
108    },
109    /// A sector read extends past the image's last sector ([`crate::Image::read_sectors`]):
110    /// it must satisfy `lsn + count <= sectors` (specification 1, 1.3).
111    #[error("{count} sectors at LSN {lsn} are not all in the image's {sectors} sectors")]
112    #[non_exhaustive]
113    SectorRangeInvalid {
114        /// The first sector asked for.
115        lsn: u64,
116        /// The number of sectors asked for.
117        count: u64,
118        /// The image's sector count.
119        sectors: u64,
120    },
121    /// A DST lane count is not from 1 to [`crate::dst::MAX_LANES`]
122    /// ([`crate::TrackAudioCursor::with_dst_lanes`]).
123    #[error("{lanes} DST lanes: must be from 1 to {max}", max = crate::dst::MAX_LANES)]
124    #[non_exhaustive]
125    DstLanesInvalid {
126        /// The count asked for.
127        lanes: usize,
128    },
129    /// A caller-supplied argument is invalid (for example a buffer of the wrong size).
130    #[error("invalid argument: {0}")]
131    InvalidArgument(&'static str),
132    /// The underlying reader failed.
133    #[error("I/O error: {0}")]
134    Io(#[from] io::Error),
135    /// The call stopped because cancellation was requested through the image's
136    /// [`crate::CancelToken`] (see [`crate::Disc::cancel_token`]). Nothing was lost: the
137    /// cursor stays where it was, and continues once the request is withdrawn.
138    #[error("cancelled")]
139    Cancelled,
140    /// The requested output file can't be written for this area with these options
141    /// (specification 8). It is not an outcome of the image: other options, or another
142    /// format, may write it.
143    #[error("output refused: {0}")]
144    OutputRefused(OutputRefusal),
145    /// Sector `lsn` is unreadable ([`crate::UnreadableSectors`], #435): marked so, or
146    /// reported so by the reader ([`crate::read_at::unreadable_error`]). Returned by
147    /// [`crate::Image::read_sectors`], which gives no bytes in its place, and by
148    /// [`crate::AreaIndex::extend`], which records no reading state at or past it.
149    #[error("sector {lsn} is unreadable")]
150    #[non_exhaustive]
151    SectorUnreadable {
152        /// The first unreadable sector met.
153        lsn: u64,
154    },
155}
156
157/// Why an output file can't be written ([`Error::OutputRefused`]).
158#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
159#[non_exhaustive]
160pub enum OutputRefusal {
161    /// The area has no defined loudspeaker layout (specification 8, 8.1 item 5), and the
162    /// options give no channel type or channel IDs for it (8.2.4 item 2).
163    #[error(
164        "the area's layout ({channels} channels, configuration {config:#04x}) is unspecified, and the options give no channel type for it"
165    )]
166    #[non_exhaustive]
167    UnspecifiedLayout {
168        /// The area's channel count.
169        channels: u8,
170        /// The area configuration byte, as stored.
171        config: u8,
172    },
173    /// The file can't be an edited master (specification 8, 8.4.11): the check that fails.
174    #[error("not an edited master: {0}")]
175    NotEditedMaster(EditedMasterCheck),
176}
177
178/// A requirement of an edited master (specification 8, 8.4.11) that an area or range
179/// fails ([`OutputRefusal::NotEditedMaster`]).
180#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
181#[non_exhaustive]
182pub enum EditedMasterCheck {
183    /// The range is not the play range `[0, P)` (8.4.11, first paragraph).
184    #[error("it holds only the play range of an area")]
185    Range,
186    /// The layout is not stereo, 3/2 or 5.1 (item 2).
187    #[error("the area's loudspeaker layout is unspecified")]
188    Layout,
189    /// The area has no track, or more than 255 (item 5).
190    #[error("the area must have 1 to 255 tracks")]
191    TrackCount,
192    /// A track's duration is below 75 frames (item 5).
193    #[error("track {track} is shorter than 75 frames")]
194    #[non_exhaustive]
195    TrackTooShort {
196        /// The track's number.
197        track: u8,
198    },
199    /// The tracks are out of order, overlap or are empty (item 5, 8.4.10 item 2).
200    #[error("the tracks are out of order or overlap")]
201    TracksNotInOrder,
202    /// The program is longer than 255 minutes, 59 seconds and 74 frames (item 6).
203    #[error("the program is longer than 255:59:74")]
204    ProgramTooLong,
205}
206
207/// Broad classes of [`Error`], for callers (and the FFI) that map errors to codes.
208#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
209#[non_exhaustive]
210pub enum ErrorClass {
211    /// The image was rejected (specification 7, 7.7.1).
212    Rejected,
213    /// A track was refused (no audio, an error).
214    TrackRefused,
215    /// A track was skipped (no audio, not an error).
216    TrackSkipped,
217    /// The caller asked for something that does not exist or passed a bad argument.
218    Usage,
219    /// The reader failed.
220    Io,
221    /// Cancellation was requested ([`Error::Cancelled`]).
222    Cancelled,
223}
224
225impl Error {
226    /// The diagnostic code of specification 7, if this error has one.
227    pub fn code(&self) -> Option<&'static str> {
228        Some(match self {
229            Error::NotScarletbook => "not-scarletbook",
230            Error::MasterTocTruncated => "master-toc-truncated",
231            Error::MasterTocVersionUnsupported { .. } => "master-toc-version-unsupported",
232            Error::NoAudioAreas => "no-audio-areas",
233            Error::ChannelCountUnsupported { .. } => "channel-count-unsupported",
234            Error::TrackEmpty => "track-empty",
235            Error::TrackExceedsCapacity { .. } => "track-exceeds-capacity",
236            Error::NoSuchArea(_)
237            | Error::NoSuchTrack { .. }
238            | Error::FrameRangeInvalid { .. }
239            | Error::SectorRangeInvalid { .. }
240            | Error::DstLanesInvalid { .. }
241            | Error::InvalidArgument(_)
242            | Error::Io(_)
243            | Error::Cancelled
244            | Error::OutputRefused(_)
245            | Error::SectorUnreadable { .. } => {
246                return None;
247            }
248        })
249    }
250
251    /// The class of this error.
252    pub fn class(&self) -> ErrorClass {
253        match self {
254            Error::NotScarletbook
255            | Error::MasterTocTruncated
256            | Error::MasterTocVersionUnsupported { .. }
257            | Error::NoAudioAreas => ErrorClass::Rejected,
258            Error::ChannelCountUnsupported { .. } | Error::TrackExceedsCapacity { .. } => {
259                ErrorClass::TrackRefused
260            }
261            Error::TrackEmpty => ErrorClass::TrackSkipped,
262            Error::NoSuchArea(_)
263            | Error::NoSuchTrack { .. }
264            | Error::FrameRangeInvalid { .. }
265            | Error::SectorRangeInvalid { .. }
266            | Error::DstLanesInvalid { .. }
267            | Error::InvalidArgument(_)
268            | Error::OutputRefused(_) => ErrorClass::Usage,
269            Error::Io(_) | Error::SectorUnreadable { .. } => ErrorClass::Io,
270            Error::Cancelled => ErrorClass::Cancelled,
271        }
272    }
273}
274
275/// The warning codes of specification 7, 7.7.2 and 7.7.3.
276#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
277#[non_exhaustive]
278pub enum WarningCode {
279    /// No `SACDText` at LSN 511 and the text channel count is above 0.
280    MasterTextMissing,
281    /// No `SACD_Man` at LSN 519.
282    ManufacturerMissing,
283    /// Area TOC size above 128 sectors (area skipped).
284    AreaTocTooLarge,
285    /// TOC-1 cannot be read.
286    AreaToc1Unreadable,
287    /// TOC-2 is set but cannot be read.
288    AreaToc2Unreadable,
289    /// Both copies were read and differ.
290    AreaTocCopiesDiffer,
291    /// Neither TOC copy can be read (area skipped).
292    AreaTocUnreadable,
293    /// The chosen copy's signature is neither `TWOCHTOC` nor `MULCHTOC` (area skipped).
294    AreaSignatureInvalid,
295    /// No `SACDTRL1` or no `SACDTRL2` in the sub-structure walk (area skipped).
296    AreaTrackListMissing,
297    /// A `SACD_IGL` extends past the end of the area TOC (area skipped).
298    AreaTocMalformed,
299    /// The last audio LSN is below the first (area skipped).
300    AreaAudioRangeReversed,
301    /// A track text offset points too close to the end of the area TOC.
302    TrackTextOffsetInvalid,
303    /// A track text item of unknown type with a non-empty string.
304    TrackTextTypeUnknown,
305    /// A track ends after the area play time; it was clamped.
306    TrackPastPlaytime,
307    /// A track start LSN lies outside the area's audio range.
308    TrackLsnOutsideArea,
309    /// A malformed audio sector (optional).
310    AudioSectorMalformed,
311    /// A master TOC copy at LSN 520 or 530 differs from LSN 510 (optional; reported at
312    /// most once, specification 1, 1.5.1 item 3).
313    MasterTocCopiesDiffer,
314    /// A sample frequency code other than 4 (optional).
315    SampleFrequencyUnknown,
316}
317
318impl WarningCode {
319    /// The diagnostic code string of specification 7.
320    pub fn code(self) -> &'static str {
321        match self {
322            WarningCode::MasterTextMissing => "master-text-missing",
323            WarningCode::ManufacturerMissing => "manufacturer-missing",
324            WarningCode::AreaTocTooLarge => "area-toc-too-large",
325            WarningCode::AreaToc1Unreadable => "area-toc1-unreadable",
326            WarningCode::AreaToc2Unreadable => "area-toc2-unreadable",
327            WarningCode::AreaTocCopiesDiffer => "area-toc-copies-differ",
328            WarningCode::AreaTocUnreadable => "area-toc-unreadable",
329            WarningCode::AreaSignatureInvalid => "area-signature-invalid",
330            WarningCode::AreaTrackListMissing => "area-track-list-missing",
331            WarningCode::AreaTocMalformed => "area-toc-malformed",
332            WarningCode::AreaAudioRangeReversed => "area-audio-range-reversed",
333            WarningCode::TrackTextOffsetInvalid => "track-text-offset-invalid",
334            WarningCode::TrackTextTypeUnknown => "track-text-type-unknown",
335            WarningCode::TrackPastPlaytime => "track-past-playtime",
336            WarningCode::TrackLsnOutsideArea => "track-lsn-outside-area",
337            WarningCode::AudioSectorMalformed => "audio-sector-malformed",
338            WarningCode::MasterTocCopiesDiffer => "master-toc-copies-differ",
339            WarningCode::SampleFrequencyUnknown => "sample-frequency-unknown",
340        }
341    }
342
343    /// Whether the warning means the area was skipped (specification 7, 7.7.2).
344    pub fn skips_area(self) -> bool {
345        matches!(
346            self,
347            WarningCode::AreaTocTooLarge
348                | WarningCode::AreaTocUnreadable
349                | WarningCode::AreaSignatureInvalid
350                | WarningCode::AreaTrackListMissing
351                | WarningCode::AreaTocMalformed
352                | WarningCode::AreaAudioRangeReversed
353        )
354    }
355}
356
357impl fmt::Display for WarningCode {
358    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
359        f.write_str(self.code())
360    }
361}
362
363/// A warning: a code with the slot, track and LSN it concerns, where they apply.
364#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
365#[non_exhaustive]
366pub struct Warning {
367    /// The diagnostic code.
368    pub code: WarningCode,
369    /// The area slot the warning concerns, if any.
370    pub slot: Option<Slot>,
371    /// The track number (1-based) the warning concerns, if any.
372    pub track: Option<u8>,
373    /// The LSN the warning concerns, if any (`audio-sector-malformed`).
374    pub lsn: Option<u32>,
375}
376
377impl Warning {
378    pub(crate) fn disc(code: WarningCode) -> Self {
379        Warning { code, slot: None, track: None, lsn: None }
380    }
381
382    pub(crate) fn area(code: WarningCode, slot: Slot) -> Self {
383        Warning { code, slot: Some(slot), track: None, lsn: None }
384    }
385
386    pub(crate) fn track(code: WarningCode, slot: Slot, track: u8) -> Self {
387        Warning { code, slot: Some(slot), track: Some(track), lsn: None }
388    }
389}
390
391impl fmt::Display for Warning {
392    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
393        f.write_str(self.code.code())?;
394        if let Some(slot) = self.slot {
395            write!(f, " (area {slot}")?;
396            if let Some(track) = self.track {
397                write!(f, ", track {track}")?;
398            }
399            if let Some(lsn) = self.lsn {
400                write!(f, ", LSN {lsn}")?;
401            }
402            f.write_str(")")?;
403        }
404        Ok(())
405    }
406}