Skip to main content

scarletbook/
lib.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! A clean-room reader for Super Audio CD (Scarletbook) disc images.
4//!
5//! Written only from the specifications of `aclater/sacd-spec`; section numbers in the
6//! documentation refer to them. Every value read from an image is treated as hostile:
7//! no input makes this crate panic, loop without bound or allocate without bound.
8//!
9//! ```no_run
10//! # fn main() -> Result<(), scarletbook::Error> {
11//! let file = std::fs::File::open("disc.iso")?;
12//! let disc = scarletbook::Disc::open(std::io::BufReader::new(file))?;
13//! for area in &disc.toc().areas {
14//!     println!("{}: {} tracks", area.slot, area.tracks.len());
15//! }
16//! # Ok(())
17//! # }
18//! ```
19//!
20//! # Threads
21//!
22//! Every public type of this crate is [`Send`] and [`Sync`], except that those holding a
23//! reader follow the reader:
24//!
25//! | Type | `Send` if | `Sync` if |
26//! |---|---|---|
27//! | [`Disc<R>`], [`Image<R>`], [`AreaFrames<R>`], [`TrackFrames<R>`], [`TrackAudio<R>`] | `R: Send` | `R: Sync` |
28//! | [`ReadAtReader<A>`] | `A: Send` | `A: Sync` |
29//! | [`Locked<R>`](read_at::Locked) | `R: Send` | `R: Send` |
30//!
31//! This is part of the API, not an accident of the fields: assertions in this crate's
32//! source stop it building if a type loses one of these. It is a statement about what the
33//! compiler allows, so here is what it means for reading:
34//!
35//! - **Reading is one thread per [`Disc`].** A disc has one reader with one position, so
36//!   its reads take `&mut self`. Its `&self` methods (the TOC, making a cursor) may run on
37//!   several threads at once when `R: Sync`.
38//! - **To read one image on several threads at once,** give each a disc of its own
39//!   ([`Disc::share`], or `clone` of a disc read through a [`ReadAtReader`]): see
40//!   [Several readers](Disc#several-readers). A [`ReadAt`] source is called from several
41//!   threads at once when it is `Sync`.
42//! - **Cursors hold no reader.** [`TrackAudioCursor`], [`TrackCursor`] and [`AreaCursor`]
43//!   can move between threads, and be read through any disc of the same image. A
44//!   borrowing iterator can move only with the `&mut` disc it borrows.
45//! - **Results own their bytes.** [`TrackFrame`], [`AudioFrame`] and [`AreaFrame`] borrow
46//!   nothing, so a frame can go to a worker thread and its decoded result come back.
47//! - **A [`DstDecoder`] decodes one frame at a time** (`&mut self`): one per worker. It holds
48//!   only buffers, so it can also move between threads.
49//! - **Made to be used while another thread reads:** [`CancelToken`], [`Progress`], and the
50//!   per-area seek index that a disc and the discs made from it share.
51//! - **A [`Log`](log::Log) sink must be `Send + Sync`,** since with the `parallel` feature it
52//!   is also called from the threads that decode.
53//!
54//! The crate uses no thread of its own without the `parallel` feature. Its global state
55//! carries nothing from one image to another: atomic counters that number images and
56//! provisional readings, the charset tables, built once on first use, and with `parallel`,
57//! a decoder cached on each thread that decodes. With `parallel`, a cursor not given a pool
58//! of its own (`DecodeOn`) uses rayon's current pool, by default its global one.
59//!
60//! **Stack.** Calls may use up to 68 KiB of the calling thread's stack (measured on x86-64
61//! Linux in release builds; `Layout::read_at` of the `output` module, over a DST area on a
62//! CPU with AVX2, is the deepest), and the reader, [`ReadAt`] source or [`Log`](log::Log)
63//! sink they call runs on top of that: give threads that call this crate at least 136 KiB. The
64//! threads that decode with `parallel` use about 20 KiB of the 2 MiB that rayon gives them
65//! (Rust's default, or `RUST_MIN_STACK`). Unoptimised builds of this crate need far more:
66//! on a CPU with AVX2, decoding a DST frame then takes about 1.2 MiB and `Layout::read_at`
67//! about 1.6 MiB (with debug info), within the 2 MiB of a new Rust thread but not of a
68//! smaller one. A debug build that runs this crate on threads with less stack can build it
69//! optimised (`[profile.dev.package.scarletbook] opt-level = 2`, as this repository does)
70//! or set `RUST_MIN_STACK`.
71
72// `unsafe` is denied everywhere except in `dispatch`, which calls the AVX2 build of the
73// DST decoder and of the output path after checking for its features (CONTRIBUTING).
74#![deny(unsafe_code)]
75#![warn(missing_docs)]
76#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))]
77
78// The test encoder shared with the integration tests names the crate (`dispatch` tests).
79#[cfg(test)]
80extern crate self as scarletbook;
81
82pub mod audio;
83mod control;
84mod disc;
85mod dispatch;
86pub mod dst;
87mod error;
88mod image;
89pub mod log;
90#[cfg(feature = "output")]
91pub mod output;
92pub mod read_at;
93pub mod seek;
94pub mod text;
95pub mod toc;
96
97#[cfg(feature = "parallel")]
98pub use audio::DecodeOn;
99pub use audio::{
100    AreaCapacity, AreaCursor, AreaFrame, AreaFrames, AudioFrame, Continuation, CursorOptions, Demuxer,
101    FrameContent, FrameKind, FrameSpan, FrameStatus, Opening, Stored, TrackAudio, TrackAudioCursor,
102    TrackCursor, TrackFrame, TrackFrames,
103};
104pub use control::{CancelToken, Progress, UnreadableSectors};
105pub use disc::{Disc, DiscOptions};
106pub use dst::{DstDecoder, DstError};
107pub use error::{EditedMasterCheck, Error, ErrorClass, OutputRefusal, Slot, Warning, WarningCode};
108pub use image::{Image, ImageOptions, MASTER_TOC_LSN, SECTOR_SIZE, SectorFormat};
109pub use read_at::{ReadAt, ReadAtReader};
110pub use seek::{
111    AreaIndex, IndexOptions, ResumedFrom, SeekEvent, SeekPolicy, Speculation, SpeculativeOptions, Suspect,
112};
113pub use toc::{Area, AreaKind, LoudspeakerLayout, MasterToc, Speaker, Toc, Track};
114
115// The guarantees of "Threads" above: losing one of these fails the build (#39).
116const _: () = {
117    const fn send<T: Send>() {}
118    const fn sync<T: Sync>() {}
119    const fn both<T: Send + Sync>() {}
120
121    // These hold for every reader with the bound, not only the ones named below.
122    const fn with_send_reader<'a, R: Send + 'a>() {
123        send::<Disc<R>>();
124        send::<Image<R>>();
125        send::<AreaFrames<'a, R>>();
126        send::<TrackFrames<'a, R>>();
127        send::<TrackAudio<'a, R>>();
128        send::<ReadAtReader<R>>();
129        both::<read_at::Locked<R>>();
130    }
131    const fn with_sync_reader<'a, R: Sync + 'a>() {
132        sync::<Disc<R>>();
133        sync::<Image<R>>();
134        sync::<AreaFrames<'a, R>>();
135        sync::<TrackFrames<'a, R>>();
136        sync::<TrackAudio<'a, R>>();
137        sync::<ReadAtReader<R>>();
138    }
139    with_send_reader::<std::fs::File>();
140    with_sync_reader::<std::fs::File>();
141
142    // Reading.
143    both::<AreaCursor>();
144    both::<TrackCursor>();
145    both::<TrackAudioCursor>();
146    both::<Continuation<'_>>();
147    both::<Opening>();
148    both::<Demuxer>();
149    both::<DstDecoder>();
150    both::<AreaFrame>();
151    both::<TrackFrame>();
152    both::<AudioFrame>();
153    both::<FrameContent>();
154    both::<FrameKind>();
155    both::<FrameStatus>();
156    both::<Stored>();
157    both::<SectorFormat>();
158    both::<DiscOptions>();
159    both::<ImageOptions>();
160    both::<CancelToken>();
161    both::<UnreadableSectors>();
162    both::<Progress>();
163    both::<log::Log>();
164    both::<log::Level>();
165    both::<text::Charset>();
166    #[cfg(feature = "parallel")]
167    both::<DecodeOn>();
168
169    // Errors and warnings.
170    both::<Error>();
171    both::<DstError>();
172    both::<ErrorClass>();
173    both::<OutputRefusal>();
174    both::<EditedMasterCheck>();
175    both::<Slot>();
176    both::<Warning>();
177    both::<WarningCode>();
178
179    // The TOC.
180    both::<Toc>();
181    both::<MasterToc>();
182    both::<Area>();
183    both::<Track>();
184    both::<AreaKind>();
185    both::<LoudspeakerLayout>();
186    both::<Speaker>();
187    both::<toc::Version>();
188    both::<toc::Genre>();
189    both::<toc::Date>();
190    both::<toc::Locale>();
191    both::<toc::Timecode>();
192    both::<toc::AreaPointer>();
193    both::<toc::DiscText>();
194    both::<toc::AreaText>();
195    both::<toc::TrackText>();
196    both::<toc::DiscTextItem>();
197    both::<toc::AreaTextItem>();
198    both::<toc::TrackTextItem>();
199
200    // Seeking.
201    both::<AreaIndex>();
202    both::<IndexOptions>();
203    both::<ResumedFrom>();
204    both::<SeekEvent>();
205    both::<SeekPolicy>();
206    both::<Speculation>();
207    both::<SpeculativeOptions>();
208    both::<Suspect>();
209
210    // Output.
211    #[cfg(feature = "output")]
212    {
213        both::<output::OutputOptions>();
214        both::<output::Layout>();
215        both::<output::Region>();
216        both::<output::RegionKind>();
217        both::<output::Input>();
218        both::<output::Format>();
219        both::<output::SourceTrack>();
220        both::<output::Tags>();
221        both::<output::TagSet>();
222        both::<output::Id3Options>();
223        both::<output::GenreSources>();
224        both::<output::Marker>();
225        both::<output::Comment>();
226        both::<output::CallerChunk>();
227        both::<output::DsfChainFile>();
228        both::<output::DstLengths>();
229        both::<output::AlbumArtistFrame>();
230        both::<output::ArrangerFrame>();
231        both::<output::ArtistTitleSource>();
232        both::<output::CommentKind>();
233        both::<output::DateFrame>();
234        both::<output::DsdiffDeparture>();
235        both::<output::DsfBitsPerSample>();
236        both::<output::DstIndexOffset>();
237        both::<output::Id3Encoding>();
238        both::<output::InfoChunk>();
239        both::<output::InvalidDst>();
240        both::<output::LocalChunk>();
241        both::<output::MarkerKind>();
242        both::<output::MarkerText>();
243        both::<output::Markers>();
244        both::<output::PropertyChunk>();
245        both::<output::TagItem>();
246        both::<output::TextSource>();
247    }
248};