feat(disc): read a CD on macOS, through a reader split by platform

The disc feature was built entirely on Linux in a day, and the result did not
COMPILE on macOS at all: qbz_disc::cdda was cfg-gated to Linux while qbz-rip,
cdda_qt and audible_qt used its names unconditionally. Any macOS build has been
broken since qbz-disc landed.

ONE SET OF NAMES, two implementations that share no code. Linux talks to the
drive through ioctls and reads raw sectors; macOS does not have to, because the
OS mounts the disc and exposes one AIFF per track plus a .TOC.plist. qbz-rip,
audible_qt and cdda_qt needed no change, which is the test of whether the seam
was in the right place. Every other platform compiles and reports "no drive".

VERIFIED against the owner's Tool — Fear Inoculum, the USB drive moved from the
Linux box to the Mac mini:

  - the plist's Start Block includes the 150-sector lead-in that the kernel
    omits. Subtracting it reproduces the ioctl's numbers exactly, so both
    machines compute DiscID BeNBMsD8Du5NO2W61Yk.B2jwwIs- and fingerprint
    38bef21351f7fca3 — which is what lets a disc corrected on one be found on
    the other;
  - all seven tracks read on macOS md5 to exactly what metaflac reports for the
    FLACs the Linux path ripped from the same disc hours earlier.

TWO THINGS ONLY MEASUREMENT CAUGHT.

Byte order. "AIFF is big-endian" is true of the format and wrong here: macOS
writes AIFC with compression sowt, which is twos backwards and means the
samples are already little-endian. An unconditional swap produced audio that
passed every cheap statistic — 97 % non-zero, full-scale peak — and matched the
Linux rip nowhere. The COMM chunk is read and the swap is conditional.

Track resolution. audible_qt rebuilds its TocTrack from a CdRef, which carries
a device and a sector range and no track number, so it passes zero. Matching on
the number meant every CD track on macOS answered "could not read the disc"
while ripping, which passes a real number, worked — two paths disagreeing with
only one of them exercised. Resolution is by start_lsn, the address the seam
actually carries, with a regression test on a synthetic volume that fails with
NoDisc under the old rule.

One transient disagreement is recorded rather than smoothed over: reading all
seven tracks back to back once produced a different digest for the last track,
and three further reads matched. The read is not perfectly reproducible on a
marginal region, which is exactly the caveat this approach already states.

cc
This commit is contained in:
vicrodh committed 2026-08-21 18:57:03 -06:00
1 parent 70defb2e86
commit 8d4ed8e959
7 files changed
+1255 -492

No files matched your search

+26
View File
@@ -5897,6 +5897,19 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
[[package]]
name = "plist"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da1d65da6dd5d1e44199ac0f58712d241c0f439f80adea8924d832384087f85"
dependencies = [
"base64",
"indexmap",
"quick-xml 0.41.0",
"serde",
"time",
]
[[package]]
name = "png"
version = "0.17.16"
@@ -6433,10 +6446,14 @@ name = "qbz-disc"
version = "2.0.2"
dependencies = [
"base64",
"dirs 6.0.0",
"libc",
"log",
"plist",
"reqwest",
"rusqlite",
"rustls",
"serde",
"serde_json",
"sha1",
"thiserror 2.0.18",
@@ -7044,6 +7061,15 @@ dependencies = [
"serde",
]
[[package]]
name = "quick-xml"
version = "0.41.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1"
dependencies = [
"memchr",
]
[[package]]
name = "quote"
version = "1.0.45"
+12
View File
@@ -8,10 +8,22 @@ log = { workspace = true }
thiserror = { workspace = true }
sha1 = "0.10"
base64 = { workspace = true }
# The disc MEMORY (src/store.rs). SQLite rather than a JSON file because the
# app already speaks it everywhere and a row-at-a-time upsert is what the
# "never overwrite a human" rule needs.
rusqlite = { version = "0.31", features = ["bundled"] }
serde = { workspace = true }
serde_json = { workspace = true }
dirs = "6"
[target.'cfg(target_os = "linux")'.dependencies]
libc = "0.2"
# macOS hands the table of contents over as a `.TOC.plist` beside the audio
# files. It is a BINARY plist in practice, so it is parsed rather than read.
[target.'cfg(target_os = "macos")'.dependencies]
plist = "1"
[dev-dependencies]
reqwest = { workspace = true }
tokio = { workspace = true }
+70 -489
View File
@@ -1,504 +1,85 @@
//! CD-DA off a real drive, through the kernel's own ioctls.
//! Reading a CD, whichever way this platform offers.
//!
//! No libcdio. Not because libcdio is bad — it is better at RIPPING than this
//! will ever be — but because this path PLAYS a clean disc, and for that the
//! kernel interface is enough while a native library would have to be built
//! into Flatpak, Snap and AppImage. Both approaches need the same `--device`
//! permission in a sandbox; only one needs the library shipped.
//! ONE set of names — `list_devices`, `read_toc`, `TrackReader`, `read_audio`,
//! `drive_model` — over two implementations that share no code at all:
//!
//! WHAT THIS IS NOT: accurate extraction. There is no overlap synchronisation,
//! no cache modelling, no jitter verification, no scratch reconstruction. On a
//! clean disc that is fine for playback; on a marginal one it can click, and
//! an unreadable sector surfaces as an ERROR rather than a hole full of zeros.
//! Silence that pretends to be audio is the one outcome bit-perfect playback
//! must never produce.
//! * **Linux** ([`crate::cdda_linux`]) talks to the drive through the
//! kernel's ioctls and reads raw sectors.
//! * **macOS** ([`crate::cdda_macos`]) does not: the OS mounts the disc and
//! exposes one AIFF per track, so the "read" is a file read.
//!
//! MEASURED on the owner's USB drive with Tool — *Fear Inoculum* (2026-08-20),
//! before any of this existed:
//! - `cd-info` reports access mode IOCTL; the TOC reads back 7 audio tracks,
//! lead-out at LSN 356568;
//! - `CDROMREADAUDIO` over 20 frames from LSN 4000 returned 47 040 bytes,
//! 99 % non-zero samples, peak 14559 — real audio, not silence;
//! - the drive hands back LITTLE-endian samples. Neighbouring samples差
//! average 73.5 read as LE against 20 971 read as BE, a 285x margin. So
//! the bytes go straight into a little-endian WAV with no swap. That is
//! measured for THIS drive; `looks_byte_swapped` below keeps the check
//! available as a diagnostic rather than as an article of faith.
//! This facade exists so nothing above it branches on the platform. `qbz-rip`,
//! `audible_qt` and `cdda_qt` were written against the Linux names and needed
//! no change when macOS arrived, which is the test of whether a seam is in the
//! right place.
//!
//! The two readers agree on the ANSWER even though they agree on nothing else:
//! measured on the same disc the same afternoon, both produce DiscID
//! `BeNBMsD8Du5NO2W61Yk.B2jwwIs-` and fingerprint `38bef21351f7fca3` (see
//! [`crate::toc`]).
//!
//! ON EVERY OTHER PLATFORM the calls are present and report "no drive". A
//! Windows build must COMPILE — the disc feature is one view of many — and the
//! honest failure is an empty drive list, not a crate that will not build.
use std::os::fd::{AsRawFd, OwnedFd};
use std::path::{Path, PathBuf};
pub use crate::toc::{CdError, Toc, TocTrack};
// --- ioctl numbers and layouts (uapi/linux/cdrom.h) -------------------------
const CDROMREADTOCHDR: libc::c_ulong = 0x5305;
const CDROMREADTOCENTRY: libc::c_ulong = 0x5306;
const CDROMREADAUDIO: libc::c_ulong = 0x530e;
const CDROM_DRIVE_STATUS: libc::c_ulong = 0x5326;
const CDROM_LBA: u8 = 0x01;
/// The lead-out's pseudo track number: its start is the end of the last track.
const CDROM_LEADOUT: u8 = 0xAA;
const CDS_DISC_OK: libc::c_int = 4;
/// `cdte_ctrl` bit 2 marks a DATA track. A mixed-mode disc carries one and it
/// must be skipped: handing its bytes to an audio path produces noise.
const CTRL_DATA: u8 = 0x04;
/// The kernel accepts 1..=75 frames per `CDROMREADAUDIO` call.
/// The kernel accepts 1..=75 frames per `CDROMREADAUDIO` call; the macOS
/// reader uses the same chunk size so both platforms hand callers the same
/// shape of buffer.
pub const MAX_FRAMES_PER_READ: u32 = 75;
#[repr(C)]
#[derive(Default)]
struct CdromTocHdr {
trk0: u8,
trk1: u8,
#[cfg(target_os = "linux")]
pub use crate::cdda_linux::{
drive_model, list_devices, looks_byte_swapped, read_audio, read_toc, TrackReader,
};
#[cfg(target_os = "macos")]
pub use crate::cdda_macos::{drive_model, list_devices, read_audio, read_toc, TrackReader};
/// The byte-order diagnostic is Linux's — it exists because a DRIVE can hand
/// back either order and this crate measured which. On macOS the OS produced
/// the file, AIFF's order is defined by the format, and there is nothing to
/// sniff; the reader normalises and the question does not arise.
#[cfg(not(target_os = "linux"))]
pub fn looks_byte_swapped(_pcm: &[u8]) -> bool {
false
}
#[repr(C)]
#[derive(Default)]
struct CdromTocEntry {
track: u8,
/// adr in the low nibble, ctrl in the high one — a C bitfield, read whole.
adr_ctrl: u8,
format: u8,
_pad: u8,
addr_lba: i32,
datamode: u8,
_pad2: [u8; 3],
}
#[repr(C)]
struct CdromReadAudio {
addr_lba: i32,
addr_format: u8,
_pad: [u8; 3],
nframes: libc::c_int,
buf: *mut u8,
}
#[derive(Debug, thiserror::Error)]
pub enum CdError {
#[error("no optical drive found")]
NoDrive,
#[error("cannot open {0}: {1}")]
Open(PathBuf, std::io::Error),
#[error("no disc in the drive")]
NoDisc,
#[error("the disc has no audio tracks")]
NotAudio,
#[error("the drive refused to read audio at sector {lsn}: {source}")]
Read {
lsn: u32,
#[source]
source: std::io::Error,
},
#[error("reading the table of contents failed: {0}")]
Toc(std::io::Error),
}
/// One entry of the disc's table of contents.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TocTrack {
pub number: u8,
pub start_lsn: u32,
/// Sectors up to the next track (or the lead-out for the last one).
pub sectors: u32,
/// False for the data track of a mixed-mode disc.
pub is_audio: bool,
}
impl TocTrack {
pub fn duration_secs(&self) -> u64 {
crate::sectors_to_secs(self.sectors)
}
/// PCM frames (sample pairs) this track decodes to.
pub fn frames(&self) -> u64 {
self.sectors as u64 * 588
}
}
#[derive(Debug, Clone)]
pub struct Toc {
pub device: PathBuf,
pub tracks: Vec<TocTrack>,
pub leadout_lsn: u32,
}
impl Toc {
/// The AUDIO tracks, in disc order. A caller that wants to play something
/// should use this and never `tracks` — the data track of an enhanced CD
/// lives in the latter.
pub fn audio_tracks(&self) -> impl Iterator<Item = &TocTrack> {
self.tracks.iter().filter(|t| t.is_audio)
}
/// A stable identity for the MEDIUM, not the drive.
///
/// `/dev/sr0` names a piece of hardware; two different discs in it are two
/// different sessions, and a persisted queue that resolves against the
/// drive would happily play track 3 of whatever is loaded now. The digest
/// is over every track's start and length plus the lead-out, which is what
/// a disc actually is. (The disc's own MCN would be tidier — the owner's
/// Fear Inoculum reports all zeros, so it is not dependable.)
pub fn fingerprint(&self) -> String {
// FNV-1a: no dependency, and this only has to be stable and
// collision-resistant enough to tell two albums apart.
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
let mut eat = |v: u32| {
for b in v.to_le_bytes() {
h ^= b as u64;
h = h.wrapping_mul(0x1000_0000_01b3);
}
};
for t in &self.tracks {
eat(t.start_lsn);
eat(t.sectors);
eat(t.number as u32);
}
eat(self.leadout_lsn);
format!("{h:016x}")
}
}
/// Optical devices the kernel is showing, most conventional first.
///
/// `/dev/sr0` is NOT hardcoded anywhere in this crate: a box can have several
/// drives, and `/dev/cdrom` is a udev symlink that may point at any of them.
pub fn list_devices() -> Vec<PathBuf> {
let mut out = Vec::new();
for n in 0..8 {
let p = PathBuf::from(format!("/dev/sr{n}"));
if p.exists() {
out.push(p);
}
}
if out.is_empty() {
let alt = PathBuf::from("/dev/cdrom");
if alt.exists() {
out.push(alt);
}
}
out
}
fn open_device(dev: &Path) -> Result<OwnedFd, CdError> {
// O_NONBLOCK is required, not optional: without it `open` on an optical
// device BLOCKS until a disc is loaded and spun up, which on an empty tray
// means hanging forever.
let c = std::ffi::CString::new(dev.as_os_str().as_encoded_bytes())
.map_err(|_| CdError::Open(dev.to_path_buf(), std::io::Error::other("bad path")))?;
let fd = unsafe { libc::open(c.as_ptr(), libc::O_RDONLY | libc::O_NONBLOCK) };
if fd < 0 {
return Err(CdError::Open(
dev.to_path_buf(),
std::io::Error::last_os_error(),
));
}
Ok(unsafe { <OwnedFd as std::os::fd::FromRawFd>::from_raw_fd(fd) })
}
/// Read the table of contents, skipping data tracks by their control bits.
pub fn read_toc(dev: &Path) -> Result<Toc, CdError> {
let fd = open_device(dev)?;
let raw = fd.as_raw_fd();
let status = unsafe { libc::ioctl(raw, CDROM_DRIVE_STATUS, 0) };
if status != CDS_DISC_OK {
return Err(CdError::NoDisc);
}
let mut hdr = CdromTocHdr::default();
if unsafe { libc::ioctl(raw, CDROMREADTOCHDR, &mut hdr) } < 0 {
return Err(CdError::Toc(std::io::Error::last_os_error()));
}
let entry_lba = |n: u8| -> Result<(u32, u8), CdError> {
let mut e = CdromTocEntry {
track: n,
format: CDROM_LBA,
..Default::default()
};
if unsafe { libc::ioctl(raw, CDROMREADTOCENTRY, &mut e) } < 0 {
return Err(CdError::Toc(std::io::Error::last_os_error()));
}
Ok((e.addr_lba.max(0) as u32, e.adr_ctrl >> 4))
};
let (leadout_lsn, _) = entry_lba(CDROM_LEADOUT)?;
let mut raw_tracks: Vec<(u8, u32, bool)> = Vec::new();
for n in hdr.trk0..=hdr.trk1 {
let (lba, ctrl) = entry_lba(n)?;
raw_tracks.push((n, lba, ctrl & CTRL_DATA == 0));
}
// A track's length is the gap to whatever starts next — the following
// track, or the lead-out for the last one. The TOC does not carry lengths.
let mut tracks = Vec::with_capacity(raw_tracks.len());
for (i, &(number, start_lsn, is_audio)) in raw_tracks.iter().enumerate() {
let next = raw_tracks
.get(i + 1)
.map(|t| t.1)
.unwrap_or(leadout_lsn);
tracks.push(TocTrack {
number,
start_lsn,
sectors: next.saturating_sub(start_lsn),
is_audio,
});
}
if !tracks.iter().any(|t| t.is_audio) {
return Err(CdError::NotAudio);
}
Ok(Toc {
device: dev.to_path_buf(),
tracks,
leadout_lsn,
})
}
/// Read `frames` sectors starting at `lsn` into `out`, which is resized to fit.
///
/// Retries a few times before giving up: a marginal sector often reads on a
/// second attempt, and the alternative to a retry here is a click. What it
/// will NOT do is return zeros — an unrecoverable sector is an error, and the
/// caller stops the track rather than playing silence over it.
pub fn read_audio(dev: &Path, lsn: u32, frames: u32, out: &mut Vec<u8>) -> Result<(), CdError> {
let frames = frames.clamp(1, MAX_FRAMES_PER_READ);
out.resize(frames as usize * crate::CDDA_SECTOR_BYTES, 0);
let fd = open_device(dev)?;
read_audio_fd(fd.as_raw_fd(), dev, lsn, frames, out)
}
fn read_audio_fd(
raw: libc::c_int,
dev: &Path,
lsn: u32,
frames: u32,
out: &mut [u8],
) -> Result<(), CdError> {
let mut last = std::io::Error::other("no attempt made");
for attempt in 0..3 {
let mut arg = CdromReadAudio {
addr_lba: lsn as i32,
addr_format: CDROM_LBA,
_pad: [0; 3],
nframes: frames as libc::c_int,
buf: out.as_mut_ptr(),
};
if unsafe { libc::ioctl(raw, CDROMREADAUDIO, &mut arg) } >= 0 {
if attempt > 0 {
log::info!("[cdda] sector {lsn} read on attempt {}", attempt + 1);
}
return Ok(());
}
last = std::io::Error::last_os_error();
}
log::warn!(
"[cdda] {} refused sector {lsn} after 3 attempts: {last}",
dev.display()
);
Err(CdError::Read { lsn, source: last })
}
/// An open reader positioned on one track, so a whole track is read through a
/// SINGLE file descriptor instead of re-opening the device 4000 times.
pub struct TrackReader {
fd: OwnedFd,
device: PathBuf,
next_lsn: u32,
end_lsn: u32,
}
impl TrackReader {
pub fn open(dev: &Path, track: &TocTrack) -> Result<Self, CdError> {
Ok(Self {
fd: open_device(dev)?,
device: dev.to_path_buf(),
next_lsn: track.start_lsn,
end_lsn: track.start_lsn + track.sectors,
})
}
pub fn finished(&self) -> bool {
self.next_lsn >= self.end_lsn
}
/// Next chunk of raw CD-DA bytes, up to `MAX_FRAMES_PER_READ` sectors.
/// `Ok(0)` means the track is done.
pub fn next_chunk(&mut self, out: &mut Vec<u8>) -> Result<usize, CdError> {
if self.finished() {
out.clear();
return Ok(0);
}
let frames = (self.end_lsn - self.next_lsn).min(MAX_FRAMES_PER_READ);
out.resize(frames as usize * crate::CDDA_SECTOR_BYTES, 0);
read_audio_fd(
self.fd.as_raw_fd(),
&self.device,
self.next_lsn,
frames,
out,
)?;
self.next_lsn += frames;
Ok(out.len())
}
}
/// Diagnostic: does this buffer look byte-swapped?
///
/// Audio is continuous, so neighbouring samples differ by little; a wrong
/// endianness turns that into noise. Measured on the owner's drive the ratio
/// was 285x in favour of little-endian, so this returns false there. It exists
/// because "every drive is little-endian" is a claim about ONE drive, and the
/// honest way to hold it is as something checkable rather than assumed.
pub fn looks_byte_swapped(pcm: &[u8]) -> bool {
let step = |swap: bool| -> f64 {
let mut total = 0f64;
let mut n = 0u32;
let mut prev: Option<i16> = None;
// Left channel only: 4 bytes per frame, take the first pair.
for f in pcm.chunks_exact(4) {
let s = if swap {
i16::from_be_bytes([f[0], f[1]])
} else {
i16::from_le_bytes([f[0], f[1]])
};
if let Some(p) = prev {
total += (s as i32 - p as i32).unsigned_abs() as f64;
n += 1;
}
prev = Some(s);
}
if n == 0 {
0.0
} else {
total / n as f64
}
};
let le = step(false);
let be = step(true);
be > 0.0 && le > be
}
#[cfg(test)]
mod tests {
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
mod unsupported {
use super::*;
use std::path::{Path, PathBuf};
fn toc(entries: &[(u8, u32, bool)], leadout: u32) -> Toc {
let mut tracks = Vec::new();
for (i, &(number, start_lsn, is_audio)) in entries.iter().enumerate() {
let next = entries.get(i + 1).map(|e| e.1).unwrap_or(leadout);
tracks.push(TocTrack {
number,
start_lsn,
sectors: next - start_lsn,
is_audio,
});
pub fn list_devices() -> Vec<PathBuf> {
Vec::new()
}
pub fn drive_model(_dev: &Path) -> Option<String> {
None
}
pub fn read_toc(_dev: &Path) -> Result<Toc, CdError> {
Err(CdError::NoDrive)
}
pub fn read_audio(
_dev: &Path,
_lsn: u32,
_frames: u32,
_out: &mut Vec<u8>,
) -> Result<(), CdError> {
Err(CdError::NoDrive)
}
/// Present so callers compile; every construction fails.
pub struct TrackReader(());
impl TrackReader {
pub fn open(_dev: &Path, _track: &TocTrack) -> Result<Self, CdError> {
Err(CdError::NoDrive)
}
Toc {
device: PathBuf::from("/dev/null"),
tracks,
leadout_lsn: leadout,
pub fn next_chunk(&mut self, _out: &mut Vec<u8>) -> Result<usize, CdError> {
Err(CdError::NoDrive)
}
}
/// The REAL table of contents of the owner's disc, read 2026-08-20.
fn fear_inoculum() -> Toc {
toc(
&[
(1, 0, true),
(2, 46_577, true),
(3, 100_047, true),
(4, 157_373, true),
(5, 218_718, true),
(6, 264_120, true),
(7, 285_735, true),
],
356_568,
)
}
#[test]
fn track_lengths_come_from_the_gaps_and_the_leadout() {
let t = fear_inoculum();
// Track 1 = 10:21, and the LAST track has to reach the lead-out or the
// longest song on the disc would be cut short.
assert_eq!(t.tracks[0].sectors, 46_577);
assert_eq!(t.tracks[0].duration_secs(), 621);
assert_eq!(t.tracks[6].sectors, 70_833);
assert_eq!(t.tracks[6].duration_secs(), 944);
assert_eq!(t.tracks.len(), 7);
}
#[test]
fn a_data_track_is_never_offered_as_audio() {
// Enhanced CD: three songs then a data track.
let t = toc(&[(1, 0, true), (2, 20_000, true), (3, 40_000, false)], 60_000);
assert_eq!(t.tracks.len(), 3);
assert_eq!(t.audio_tracks().count(), 2);
assert!(t.audio_tracks().all(|x| x.number != 3));
}
#[test]
fn the_fingerprint_identifies_the_MEDIUM_not_the_drive() {
let a = fear_inoculum();
let mut b = fear_inoculum();
b.device = PathBuf::from("/dev/sr3");
// Same disc in a different drive: same identity.
assert_eq!(a.fingerprint(), b.fingerprint());
// A different disc with the same track COUNT must not collide — this
// is the case that would resolve a persisted queue onto the wrong
// album.
let other = toc(
&[
(1, 0, true),
(2, 46_500, true),
(3, 100_047, true),
(4, 157_373, true),
(5, 218_718, true),
(6, 264_120, true),
(7, 285_735, true),
],
356_568,
);
assert_ne!(a.fingerprint(), other.fingerprint());
}
#[test]
fn frames_per_track_match_the_wav_the_player_will_be_promised() {
let t = fear_inoculum();
let first = &t.tracks[0];
assert_eq!(first.frames(), 46_577 * 588);
// 10:21 of 44.1k stereo 16-bit — the size the streaming path declares.
assert_eq!(
crate::wav_total_size_16(first.frames(), 2),
44 + 46_577 * 588 * 4
);
}
#[test]
fn a_read_is_clamped_to_what_the_kernel_accepts() {
// The ioctl takes 1..=75 frames; asking for more is not a silent
// truncation somewhere deep, it is clamped here where it is visible.
assert_eq!(MAX_FRAMES_PER_READ, 75);
}
#[test]
fn the_endianness_probe_agrees_with_the_measured_drive() {
// A smooth ramp is what real audio looks like read the RIGHT way.
let mut pcm = Vec::new();
for i in 0..2000i16 {
let s = (i.wrapping_mul(7)) % 3000;
pcm.extend_from_slice(&s.to_le_bytes()); // L
pcm.extend_from_slice(&s.to_le_bytes()); // R
}
assert!(!looks_byte_swapped(&pcm), "little-endian audio flagged as swapped");
let swapped: Vec<u8> = pcm
.chunks_exact(2)
.flat_map(|p| [p[1], p[0]])
.collect();
assert!(looks_byte_swapped(&swapped), "byte-swapped audio not detected");
}
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
pub use unsupported::{drive_model, list_devices, read_audio, read_toc, TrackReader};
+448
View File
@@ -0,0 +1,448 @@
//! CD-DA off a real drive on LINUX, through the kernel's own ioctls.
//!
//! No libcdio. Not because libcdio is bad — it is better at RIPPING than this
//! will ever be — but because this path PLAYS a clean disc, and for that the
//! kernel interface is enough while a native library would have to be built
//! into Flatpak, Snap and AppImage. Both approaches need the same `--device`
//! permission in a sandbox; only one needs the library shipped.
//!
//! WHAT THIS IS NOT: accurate extraction. There is no overlap synchronisation,
//! no cache modelling, no jitter verification, no scratch reconstruction. On a
//! clean disc that is fine for playback; on a marginal one it can click, and
//! an unreadable sector surfaces as an ERROR rather than a hole full of zeros.
//! Silence that pretends to be audio is the one outcome bit-perfect playback
//! must never produce.
//!
//! MEASURED on the owner's USB drive with Tool — *Fear Inoculum* (2026-08-20),
//! before any of this existed:
//! - `cd-info` reports access mode IOCTL; the TOC reads back 7 audio tracks,
//! lead-out at LSN 356568;
//! - `CDROMREADAUDIO` over 20 frames from LSN 4000 returned 47 040 bytes,
//! 99 % non-zero samples, peak 14559 — real audio, not silence;
//! - the drive hands back LITTLE-endian samples. Neighbouring samples差
//! average 73.5 read as LE against 20 971 read as BE, a 285x margin. So
//! the bytes go straight into a little-endian WAV with no swap. That is
//! measured for THIS drive; `looks_byte_swapped` below keeps the check
//! available as a diagnostic rather than as an article of faith.
use std::os::fd::{AsRawFd, OwnedFd};
use std::path::{Path, PathBuf};
use crate::toc::{CdError, Toc, TocTrack};
// --- ioctl numbers and layouts (uapi/linux/cdrom.h) -------------------------
const CDROMREADTOCHDR: libc::c_ulong = 0x5305;
const CDROMREADTOCENTRY: libc::c_ulong = 0x5306;
const CDROMREADAUDIO: libc::c_ulong = 0x530e;
const CDROM_DRIVE_STATUS: libc::c_ulong = 0x5326;
const CDROM_LBA: u8 = 0x01;
/// The lead-out's pseudo track number: its start is the end of the last track.
const CDROM_LEADOUT: u8 = 0xAA;
const CDS_DISC_OK: libc::c_int = 4;
/// `cdte_ctrl` bit 2 marks a DATA track. A mixed-mode disc carries one and it
/// must be skipped: handing its bytes to an audio path produces noise.
const CTRL_DATA: u8 = 0x04;
/// The kernel accepts 1..=75 frames per `CDROMREADAUDIO` call.
pub const MAX_FRAMES_PER_READ: u32 = 75;
#[repr(C)]
#[derive(Default)]
struct CdromTocHdr {
trk0: u8,
trk1: u8,
}
#[repr(C)]
#[derive(Default)]
struct CdromTocEntry {
track: u8,
/// adr in the low nibble, ctrl in the high one — a C bitfield, read whole.
adr_ctrl: u8,
format: u8,
_pad: u8,
addr_lba: i32,
datamode: u8,
_pad2: [u8; 3],
}
#[repr(C)]
struct CdromReadAudio {
addr_lba: i32,
addr_format: u8,
_pad: [u8; 3],
nframes: libc::c_int,
buf: *mut u8,
}
/// Optical devices the kernel is showing, most conventional first.
///
/// `/dev/sr0` is NOT hardcoded anywhere in this crate: a box can have several
/// drives, and `/dev/cdrom` is a udev symlink that may point at any of them.
pub fn list_devices() -> Vec<PathBuf> {
let mut out = Vec::new();
for n in 0..8 {
let p = PathBuf::from(format!("/dev/sr{n}"));
if p.exists() {
out.push(p);
}
}
if out.is_empty() {
let alt = PathBuf::from("/dev/cdrom");
if alt.exists() {
out.push(alt);
}
}
out
}
/// "HL-DT-ST BD-RE BU40N" — the drive as the kernel names it, or `None`.
///
/// A rip log without the drive in it cannot answer the question people
/// actually ask of one two years later ("which reader produced this?"), and
/// the answer is sitting in sysfs. Best-effort by design: a missing file, a
/// container with no `/sys`, or a device name that is a symlink somewhere
/// unexpected all mean "unknown", never an error.
pub fn drive_model(dev: &Path) -> Option<String> {
// `/dev/cdrom` is a symlink; resolve it or the sysfs name is wrong.
let real = std::fs::canonicalize(dev).unwrap_or_else(|_| dev.to_path_buf());
let name = real.file_name()?.to_string_lossy().into_owned();
let base = PathBuf::from("/sys/block").join(&name).join("device");
let read = |f: &str| {
std::fs::read_to_string(base.join(f))
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
};
match (read("vendor"), read("model")) {
(Some(v), Some(m)) => Some(format!("{v} {m}")),
(None, Some(m)) => Some(m),
(Some(v), None) => Some(v),
(None, None) => None,
}
}
fn open_device(dev: &Path) -> Result<OwnedFd, CdError> {
// O_NONBLOCK is required, not optional: without it `open` on an optical
// device BLOCKS until a disc is loaded and spun up, which on an empty tray
// means hanging forever.
let c = std::ffi::CString::new(dev.as_os_str().as_encoded_bytes())
.map_err(|_| CdError::Open(dev.to_path_buf(), std::io::Error::other("bad path")))?;
let fd = unsafe { libc::open(c.as_ptr(), libc::O_RDONLY | libc::O_NONBLOCK) };
if fd < 0 {
return Err(CdError::Open(
dev.to_path_buf(),
std::io::Error::last_os_error(),
));
}
Ok(unsafe { <OwnedFd as std::os::fd::FromRawFd>::from_raw_fd(fd) })
}
/// Read the table of contents, skipping data tracks by their control bits.
pub fn read_toc(dev: &Path) -> Result<Toc, CdError> {
let fd = open_device(dev)?;
let raw = fd.as_raw_fd();
let status = unsafe { libc::ioctl(raw, CDROM_DRIVE_STATUS, 0) };
if status != CDS_DISC_OK {
return Err(CdError::NoDisc);
}
let mut hdr = CdromTocHdr::default();
if unsafe { libc::ioctl(raw, CDROMREADTOCHDR, &mut hdr) } < 0 {
return Err(CdError::Toc(std::io::Error::last_os_error()));
}
let entry_lba = |n: u8| -> Result<(u32, u8), CdError> {
let mut e = CdromTocEntry {
track: n,
format: CDROM_LBA,
..Default::default()
};
if unsafe { libc::ioctl(raw, CDROMREADTOCENTRY, &mut e) } < 0 {
return Err(CdError::Toc(std::io::Error::last_os_error()));
}
Ok((e.addr_lba.max(0) as u32, e.adr_ctrl >> 4))
};
let (leadout_lsn, _) = entry_lba(CDROM_LEADOUT)?;
let mut raw_tracks: Vec<(u8, u32, bool)> = Vec::new();
for n in hdr.trk0..=hdr.trk1 {
let (lba, ctrl) = entry_lba(n)?;
raw_tracks.push((n, lba, ctrl & CTRL_DATA == 0));
}
// A track's length is the gap to whatever starts next — the following
// track, or the lead-out for the last one. The TOC does not carry lengths.
let mut tracks = Vec::with_capacity(raw_tracks.len());
for (i, &(number, start_lsn, is_audio)) in raw_tracks.iter().enumerate() {
let next = raw_tracks
.get(i + 1)
.map(|t| t.1)
.unwrap_or(leadout_lsn);
tracks.push(TocTrack {
number,
start_lsn,
sectors: next.saturating_sub(start_lsn),
is_audio,
});
}
if !tracks.iter().any(|t| t.is_audio) {
return Err(CdError::NotAudio);
}
Ok(Toc {
device: dev.to_path_buf(),
tracks,
leadout_lsn,
})
}
/// Read `frames` sectors starting at `lsn` into `out`, which is resized to fit.
///
/// Retries a few times before giving up: a marginal sector often reads on a
/// second attempt, and the alternative to a retry here is a click. What it
/// will NOT do is return zeros — an unrecoverable sector is an error, and the
/// caller stops the track rather than playing silence over it.
pub fn read_audio(dev: &Path, lsn: u32, frames: u32, out: &mut Vec<u8>) -> Result<(), CdError> {
let frames = frames.clamp(1, MAX_FRAMES_PER_READ);
out.resize(frames as usize * crate::CDDA_SECTOR_BYTES, 0);
let fd = open_device(dev)?;
read_audio_fd(fd.as_raw_fd(), dev, lsn, frames, out)
}
fn read_audio_fd(
raw: libc::c_int,
dev: &Path,
lsn: u32,
frames: u32,
out: &mut [u8],
) -> Result<(), CdError> {
let mut last = std::io::Error::other("no attempt made");
for attempt in 0..3 {
let mut arg = CdromReadAudio {
addr_lba: lsn as i32,
addr_format: CDROM_LBA,
_pad: [0; 3],
nframes: frames as libc::c_int,
buf: out.as_mut_ptr(),
};
if unsafe { libc::ioctl(raw, CDROMREADAUDIO, &mut arg) } >= 0 {
if attempt > 0 {
log::info!("[cdda] sector {lsn} read on attempt {}", attempt + 1);
}
return Ok(());
}
last = std::io::Error::last_os_error();
}
log::warn!(
"[cdda] {} refused sector {lsn} after 3 attempts: {last}",
dev.display()
);
Err(CdError::Read { lsn, source: last })
}
/// An open reader positioned on one track, so a whole track is read through a
/// SINGLE file descriptor instead of re-opening the device 4000 times.
pub struct TrackReader {
fd: OwnedFd,
device: PathBuf,
next_lsn: u32,
end_lsn: u32,
}
impl TrackReader {
pub fn open(dev: &Path, track: &TocTrack) -> Result<Self, CdError> {
Ok(Self {
fd: open_device(dev)?,
device: dev.to_path_buf(),
next_lsn: track.start_lsn,
end_lsn: track.start_lsn + track.sectors,
})
}
pub fn finished(&self) -> bool {
self.next_lsn >= self.end_lsn
}
/// Next chunk of raw CD-DA bytes, up to `MAX_FRAMES_PER_READ` sectors.
/// `Ok(0)` means the track is done.
pub fn next_chunk(&mut self, out: &mut Vec<u8>) -> Result<usize, CdError> {
if self.finished() {
out.clear();
return Ok(0);
}
let frames = (self.end_lsn - self.next_lsn).min(MAX_FRAMES_PER_READ);
out.resize(frames as usize * crate::CDDA_SECTOR_BYTES, 0);
read_audio_fd(
self.fd.as_raw_fd(),
&self.device,
self.next_lsn,
frames,
out,
)?;
self.next_lsn += frames;
Ok(out.len())
}
}
/// Diagnostic: does this buffer look byte-swapped?
///
/// Audio is continuous, so neighbouring samples differ by little; a wrong
/// endianness turns that into noise. Measured on the owner's drive the ratio
/// was 285x in favour of little-endian, so this returns false there. It exists
/// because "every drive is little-endian" is a claim about ONE drive, and the
/// honest way to hold it is as something checkable rather than assumed.
pub fn looks_byte_swapped(pcm: &[u8]) -> bool {
let step = |swap: bool| -> f64 {
let mut total = 0f64;
let mut n = 0u32;
let mut prev: Option<i16> = None;
// Left channel only: 4 bytes per frame, take the first pair.
for f in pcm.chunks_exact(4) {
let s = if swap {
i16::from_be_bytes([f[0], f[1]])
} else {
i16::from_le_bytes([f[0], f[1]])
};
if let Some(p) = prev {
total += (s as i32 - p as i32).unsigned_abs() as f64;
n += 1;
}
prev = Some(s);
}
if n == 0 {
0.0
} else {
total / n as f64
}
};
let le = step(false);
let be = step(true);
be > 0.0 && le > be
}
#[cfg(test)]
mod tests {
use super::*;
fn toc(entries: &[(u8, u32, bool)], leadout: u32) -> Toc {
let mut tracks = Vec::new();
for (i, &(number, start_lsn, is_audio)) in entries.iter().enumerate() {
let next = entries.get(i + 1).map(|e| e.1).unwrap_or(leadout);
tracks.push(TocTrack {
number,
start_lsn,
sectors: next - start_lsn,
is_audio,
});
}
Toc {
device: PathBuf::from("/dev/null"),
tracks,
leadout_lsn: leadout,
}
}
/// The REAL table of contents of the owner's disc, read 2026-08-20.
fn fear_inoculum() -> Toc {
toc(
&[
(1, 0, true),
(2, 46_577, true),
(3, 100_047, true),
(4, 157_373, true),
(5, 218_718, true),
(6, 264_120, true),
(7, 285_735, true),
],
356_568,
)
}
#[test]
fn track_lengths_come_from_the_gaps_and_the_leadout() {
let t = fear_inoculum();
// Track 1 = 10:21, and the LAST track has to reach the lead-out or the
// longest song on the disc would be cut short.
assert_eq!(t.tracks[0].sectors, 46_577);
assert_eq!(t.tracks[0].duration_secs(), 621);
assert_eq!(t.tracks[6].sectors, 70_833);
assert_eq!(t.tracks[6].duration_secs(), 944);
assert_eq!(t.tracks.len(), 7);
}
#[test]
fn a_data_track_is_never_offered_as_audio() {
// Enhanced CD: three songs then a data track.
let t = toc(&[(1, 0, true), (2, 20_000, true), (3, 40_000, false)], 60_000);
assert_eq!(t.tracks.len(), 3);
assert_eq!(t.audio_tracks().count(), 2);
assert!(t.audio_tracks().all(|x| x.number != 3));
}
#[test]
fn the_fingerprint_identifies_the_MEDIUM_not_the_drive() {
let a = fear_inoculum();
let mut b = fear_inoculum();
b.device = PathBuf::from("/dev/sr3");
// Same disc in a different drive: same identity.
assert_eq!(a.fingerprint(), b.fingerprint());
// A different disc with the same track COUNT must not collide — this
// is the case that would resolve a persisted queue onto the wrong
// album.
let other = toc(
&[
(1, 0, true),
(2, 46_500, true),
(3, 100_047, true),
(4, 157_373, true),
(5, 218_718, true),
(6, 264_120, true),
(7, 285_735, true),
],
356_568,
);
assert_ne!(a.fingerprint(), other.fingerprint());
}
#[test]
fn frames_per_track_match_the_wav_the_player_will_be_promised() {
let t = fear_inoculum();
let first = &t.tracks[0];
assert_eq!(first.frames(), 46_577 * 588);
// 10:21 of 44.1k stereo 16-bit — the size the streaming path declares.
assert_eq!(
crate::wav_total_size_16(first.frames(), 2),
44 + 46_577 * 588 * 4
);
}
#[test]
fn a_read_is_clamped_to_what_the_kernel_accepts() {
// The ioctl takes 1..=75 frames; asking for more is not a silent
// truncation somewhere deep, it is clamped here where it is visible.
assert_eq!(MAX_FRAMES_PER_READ, 75);
}
#[test]
fn the_endianness_probe_agrees_with_the_measured_drive() {
// A smooth ramp is what real audio looks like read the RIGHT way.
let mut pcm = Vec::new();
for i in 0..2000i16 {
let s = (i.wrapping_mul(7)) % 3000;
pcm.extend_from_slice(&s.to_le_bytes()); // L
pcm.extend_from_slice(&s.to_le_bytes()); // R
}
assert!(!looks_byte_swapped(&pcm), "little-endian audio flagged as swapped");
let swapped: Vec<u8> = pcm
.chunks_exact(2)
.flat_map(|p| [p[1], p[0]])
.collect();
assert!(looks_byte_swapped(&swapped), "byte-swapped audio not detected");
}
}
+585
View File
@@ -0,0 +1,585 @@
//! CD-DA on macOS, where the operating system has already done the reading.
//!
//! macOS MOUNTS an audio CD. There is no raw-sector ioctl to reach for and no
//! device node worth opening: the disc appears at `/Volumes/<name>/` as one
//! AIFF per track, plus a `.TOC.plist` describing the geometry. So the "read"
//! here is a file read, and the seam that makes it fit — [`crate::CdRef`]
//! naming a device and a sector range — keeps working because the sector range
//! maps onto a byte range in the AIFF exactly.
//!
//! WHAT THE "DEVICE" IS. On Linux it is `/dev/sr0`. Here it is the mounted
//! VOLUME (`/Volumes/Fear Inoculum`). Both are "where this disc is", both are
//! a `PathBuf`, and nothing above this layer has to know which kind it holds.
//!
//! MEASURED on the Mac mini with the owner's Tool — *Fear Inoculum*
//! (2026-08-21), USB drive moved over from the Linux box:
//!
//! - `.TOC.plist` gives `Start Block` WITH the 150-sector lead-in included
//! (track 1 starts at 150, lead-out at 356718) where the Linux ioctl
//! reports it without (0 and 356568). Subtracting `LEAD_IN` reproduces the
//! kernel's numbers EXACTLY: same per-track LSNs, same sector counts, and
//! therefore the same DiscID `BeNBMsD8Du5NO2W61Yk.B2jwwIs-` and the same
//! fingerprint `38bef21351f7fca3`. That equality is the point — a disc
//! corrected on one machine is found on the other.
//! - The files are named `<n> <title>.aiff` when the Music app has looked
//! the disc up, and `<n> Audio Track.aiff` when it has not. Only the
//! LEADING INTEGER is dependable, so that is all this matches on. The
//! titles in those names are deliberately ignored: QBZ does its own
//! DiscID lookup, and taking Apple's guess would make the naming depend on
//! whether some other app happened to have network access.
//!
//! BYTE ORDER, and it is NOT what the format's reputation suggests. AIFF is
//! big-endian by definition — Apple, 68k era — so the obvious reading is to
//! swap every pair on the way out. That is wrong here, and measuring caught it:
//! macOS writes **AIFC with compression type `sowt`**, which is `twos`
//! spelled backwards and means the samples are ALREADY little-endian. An
//! unconditional swap produced audio that looked perfectly healthy by every
//! cheap statistic (97 % non-zero, full-scale peak) and did not match the
//! Linux rip of the same track by a single byte.
//!
//! So the COMM chunk is read and the swap is CONDITIONAL. VERIFIED END TO END,
//! all seven tracks of the owner's disc: the PCM this file yields on macOS
//! md5s to exactly what `metaflac --show-md5sum` reports for the FLACs the
//! Linux ioctl path ripped from the same disc hours earlier. Two operating
//! systems, two read paths that share no code, one identical stream of samples.
//!
//! ONE TRANSIENT DISAGREEMENT, and it is worth knowing about. Reading all
//! seven tracks back to back once produced a different digest for the LAST
//! track; three further reads of that track all matched. So the read is not
//! perfectly reproducible on a marginal region — which is precisely the
//! caveat `cdda_linux` states about this whole approach (no overlap
//! synchronisation, no jitter verification, no scratch reconstruction). It is
//! also why the rip log must not claim more than it does.
//!
//! And a difference in what "0 read errors" MEANS here: on Linux an unreadable
//! sector fails the ioctl and aborts. On macOS the OS did the reading, so a
//! failure surfaces only if the file read fails — a drive that quietly hands
//! back wrong-but-valid bytes is invisible to both, and to EAC in burst mode.
use std::io::{Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use crate::toc::{CdError, Toc, TocTrack};
/// Sectors of lead-in that macOS includes in every `Start Block` and the
/// kernel does not. It is not a fudge factor: 150 sectors is two seconds, the
/// Red Book lead-in, and the MusicBrainz DiscID is defined in terms of the
/// numbers WITH it — which is why `discid::disc_id` adds it back.
const LEAD_IN: u32 = 150;
/// Mounted audio CDs, one entry per volume that has a `.TOC.plist`.
///
/// The plist is the discriminator rather than the file extension: a volume
/// full of AIFFs somebody copied to a USB stick is not a disc, and offering to
/// rip it would be offering to copy files the user already has.
pub fn list_devices() -> Vec<PathBuf> {
let mut out = Vec::new();
let Ok(entries) = std::fs::read_dir("/Volumes") else {
return out;
};
for e in entries.flatten() {
let p = e.path();
if p.join(".TOC.plist").is_file() {
out.push(p);
}
}
out.sort();
out
}
/// The drive behind a mounted volume, for the rip log.
///
/// `diskutil` knows, but shelling out for one cosmetic line in a log is not
/// worth the process — and on this path the OS did the reading anyway, so the
/// honest answer is that the drive is not what produced these bytes. The log's
/// non-Linux arm says so in words instead.
pub fn drive_model(_dev: &Path) -> Option<String> {
None
}
/// Read the table of contents out of the volume's `.TOC.plist`.
pub fn read_toc(dev: &Path) -> Result<Toc, CdError> {
let path = dev.join(".TOC.plist");
let raw = std::fs::read(&path).map_err(|e| CdError::Open(path.clone(), e))?;
let value: plist::Value = plist::from_bytes(&raw)
.map_err(|e| CdError::Toc(std::io::Error::other(format!("{path:?}: {e}"))))?;
let sessions = value
.as_dictionary()
.and_then(|d| d.get("Sessions"))
.and_then(|s| s.as_array())
.ok_or_else(|| CdError::Toc(std::io::Error::other("no Sessions in .TOC.plist")))?;
// A hybrid disc can carry several sessions; the audio one is session 1 and
// is what a CD player sees. Anything past it is data by construction.
let session = sessions
.first()
.and_then(|s| s.as_dictionary())
.ok_or_else(|| CdError::Toc(std::io::Error::other("empty Sessions")))?;
let leadout = session
.get("Leadout Block")
.and_then(|v| v.as_unsigned_integer())
.ok_or_else(|| CdError::Toc(std::io::Error::other("no Leadout Block")))?
as u32;
let array = session
.get("Track Array")
.and_then(|v| v.as_array())
.ok_or_else(|| CdError::Toc(std::io::Error::other("no Track Array")))?;
// (number, start, is_audio), in disc order.
let mut raw_tracks: Vec<(u8, u32, bool)> = Vec::new();
for t in array {
let Some(d) = t.as_dictionary() else { continue };
let (Some(point), Some(start)) = (
d.get("Point").and_then(|v| v.as_unsigned_integer()),
d.get("Start Block").and_then(|v| v.as_unsigned_integer()),
) else {
continue;
};
// `Data` true is the data track of a mixed-mode disc — the same track
// the Linux path skips by its `cdte_ctrl` bit.
let is_audio = !d.get("Data").and_then(|v| v.as_boolean()).unwrap_or(false);
raw_tracks.push((point as u8, start as u32, is_audio));
}
raw_tracks.sort_by_key(|t| t.1);
if raw_tracks.is_empty() {
return Err(CdError::NotAudio);
}
if !raw_tracks.iter().any(|t| t.2) {
return Err(CdError::NotAudio);
}
// A track's length is the distance to the NEXT track's start, and the last
// one runs to the lead-out — computed AFTER the lead-in is removed so the
// subtraction cannot underflow on track 1.
let starts: Vec<u32> = raw_tracks
.iter()
.map(|t| t.1.saturating_sub(LEAD_IN))
.collect();
let leadout = leadout.saturating_sub(LEAD_IN);
let tracks = raw_tracks
.iter()
.enumerate()
.map(|(i, (number, _, is_audio))| {
let start = starts[i];
let end = starts.get(i + 1).copied().unwrap_or(leadout);
TocTrack {
number: *number,
start_lsn: start,
sectors: end.saturating_sub(start),
is_audio: *is_audio,
}
})
.collect();
Ok(Toc {
device: dev.to_path_buf(),
tracks,
leadout_lsn: leadout,
})
}
/// The AIFF the OS mounted for one track number.
///
/// Matched on the LEADING INTEGER of the file name and nothing else: the rest
/// is whatever the Music app decided to call it, which depends on a lookup QBZ
/// did not make and may not have happened at all.
fn track_file(dev: &Path, number: u8) -> Option<PathBuf> {
let entries = std::fs::read_dir(dev).ok()?;
for e in entries.flatten() {
let p = e.path();
let ext = p.extension()?.to_string_lossy().to_ascii_lowercase();
if ext != "aiff" && ext != "aif" {
continue;
}
let name = p.file_name()?.to_string_lossy().into_owned();
let digits: String = name.chars().take_while(|c| c.is_ascii_digit()).collect();
if digits.parse::<u8>().ok() == Some(number) {
return Some(p);
}
}
None
}
/// Where the audio sits inside an AIFF/AIFC, and which way round its bytes are.
///
/// A hand-rolled walk of the IFF chunks rather than a decoder dependency: the
/// payload is raw PCM and the questions are only "where does SSND's data
/// begin", "how long is it" and "is it big-endian". `offset`/`blockSize` in
/// SSND are almost always zero but are honoured anyway, because a file that
/// sets them and is read as if it had not is off by that many bytes for its
/// whole length.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct AudioExtent {
at: u64,
len: u64,
/// The samples need swapping to reach little-endian.
big_endian: bool,
}
fn aiff_audio_extent(file: &mut std::fs::File) -> Result<AudioExtent, std::io::Error> {
let mut header = [0u8; 12];
file.read_exact(&mut header)?;
if &header[0..4] != b"FORM" {
return Err(std::io::Error::other("not an IFF file"));
}
let is_aifc = &header[8..12] == b"AIFC";
if &header[8..12] != b"AIFF" && !is_aifc {
return Err(std::io::Error::other("not an AIFF"));
}
// Plain AIFF has no compression field and is big-endian by definition.
// AIFC declares one, and macOS writes `sowt` — little-endian.
let mut big_endian = true;
let mut pos = 12u64;
loop {
let mut ch = [0u8; 8];
file.seek(SeekFrom::Start(pos))?;
if file.read_exact(&mut ch).is_err() {
return Err(std::io::Error::other("no SSND chunk"));
}
let size = u32::from_be_bytes([ch[4], ch[5], ch[6], ch[7]]) as u64;
if &ch[0..4] == b"COMM" && is_aifc && size >= 22 {
// channels(2) frames(4) bits(2) rate(10) = 18, then the 4-byte
// compression id.
let mut body = [0u8; 22];
file.read_exact(&mut body)?;
big_endian = match &body[18..22] {
// Little-endian two's complement: `twos` written backwards,
// which is the joke and the definition.
b"sowt" => false,
// `NONE` and `twos` are the big-endian spellings; anything
// else is a codec this reader does not decode, and the honest
// move is to say so rather than emit noise.
b"NONE" | b"twos" | b"raw " => true,
other => {
return Err(std::io::Error::other(format!(
"unsupported AIFC compression {:?}",
String::from_utf8_lossy(other)
)))
}
};
}
if &ch[0..4] == b"SSND" {
let mut ssnd = [0u8; 8];
file.read_exact(&mut ssnd)?;
let offset = u32::from_be_bytes([ssnd[0], ssnd[1], ssnd[2], ssnd[3]]) as u64;
return Ok(AudioExtent {
at: pos + 8 + 8 + offset,
len: size.saturating_sub(8 + offset),
big_endian,
});
}
// IFF chunks are word-aligned: an odd size is followed by a pad byte.
pos += 8 + size + (size & 1);
}
}
/// Reads one track's audio out of the mounted AIFF, in the sector-sized
/// chunks the Linux path hands back.
///
/// The API is the Linux `TrackReader`'s, deliberately: `audible_qt` and
/// `qbz-rip` drive both platforms through the same two calls.
pub struct TrackReader {
file: std::fs::File,
/// Byte offset of the next read, absolute in the file.
at: u64,
/// One past the last audio byte of this track.
end: u64,
/// The file's samples are big-endian and need swapping on the way out.
/// FALSE on every disc macOS mounts (`sowt`), and honoured anyway because
/// a plain AIFF is a legal thing to find here.
big_endian: bool,
}
impl TrackReader {
/// Open a reader over the audio at this track's SECTOR RANGE.
///
/// Resolved by `start_lsn`, NOT by `number`, and that is not a preference:
/// `audible_qt::play_cd_track` rebuilds a `TocTrack` from a [`crate::CdRef`]
/// — which carries a device and a sector range and no track number — and
/// fills the number in as ZERO. On Linux nothing reads it. Here, matching
/// on it meant every CD track answered "could not read the disc", and the
/// caller was right: the sector range IS the address, so that is what this
/// resolves.
///
/// A start INSIDE a track is honoured too, so a caller that asks for a
/// sector part-way in gets that offset rather than the track's beginning.
pub fn open(dev: &Path, track: &TocTrack) -> Result<Self, CdError> {
let toc = read_toc(dev)?;
let owner = toc
.tracks
.iter()
.find(|t| track.start_lsn >= t.start_lsn && track.start_lsn < t.start_lsn + t.sectors)
// A zero-length or out-of-range request still gets the track whose
// start matches exactly, which is what a caller passing a whole
// track means.
.or_else(|| toc.tracks.iter().find(|t| t.start_lsn == track.start_lsn))
.ok_or(CdError::NoDisc)?;
let into_track =
(track.start_lsn - owner.start_lsn) as u64 * crate::CDDA_SECTOR_BYTES as u64;
let path = track_file(dev, owner.number).ok_or(CdError::NoDisc)?;
let mut file =
std::fs::File::open(&path).map_err(|e| CdError::Open(path.clone(), e))?;
let extent = aiff_audio_extent(&mut file).map_err(|e| CdError::Open(path.clone(), e))?;
// The TOC's sector count is the LENGTH, and the SSND payload is only a
// ceiling. Measured: SSND carries 570 frames MORE than COMM declares
// on every track of this disc (2280 bytes of padding), so trusting the
// payload size would append a fifth of a second of tail to each track
// and break the digest match with the Linux rip. COMM's frame count
// agrees with the TOC exactly, on all seven.
let want = track.sectors as u64 * crate::CDDA_SECTOR_BYTES as u64;
let available = extent.len.saturating_sub(into_track);
let len = want.min(available);
let at = extent.at + into_track;
file.seek(SeekFrom::Start(at))
.map_err(|e| CdError::Open(path.clone(), e))?;
Ok(Self {
file,
at,
end: at + len,
big_endian: extent.big_endian,
})
}
/// Append the next chunk to `out` (cleared first), returning its length.
/// Zero means the track is done.
pub fn next_chunk(&mut self, out: &mut Vec<u8>) -> Result<usize, CdError> {
out.clear();
if self.at >= self.end {
return Ok(0);
}
let want = (crate::cdda::MAX_FRAMES_PER_READ as u64
* crate::CDDA_SECTOR_BYTES as u64)
.min(self.end - self.at) as usize;
out.resize(want, 0);
self.file
.read_exact(out)
.map_err(|e| CdError::Read { lsn: 0, source: e })?;
self.at += want as u64;
// Only when the FILE says so. macOS writes `sowt` (little-endian), so
// this does nothing on a mounted CD — and doing it unconditionally,
// which is what "AIFF is big-endian" suggests, silently produced audio
// that passed every cheap sanity check and matched nothing.
if self.big_endian {
for pair in out.chunks_exact_mut(2) {
pair.swap(0, 1);
}
}
Ok(want)
}
}
/// Sector-addressed read, for parity with the Linux entry point.
pub fn read_audio(dev: &Path, lsn: u32, frames: u32, out: &mut Vec<u8>) -> Result<(), CdError> {
let toc = read_toc(dev)?;
let track = toc
.tracks
.iter()
.find(|t| lsn >= t.start_lsn && lsn < t.start_lsn + t.sectors)
.ok_or(CdError::NoDisc)?;
// `open` resolves and seeks by `start_lsn`, so asking for the requested
// sector directly is enough — there is no second offset to apply here.
let mut reader = TrackReader::open(
dev,
&TocTrack {
number: track.number,
start_lsn: lsn,
sectors: frames,
is_audio: true,
},
)?;
out.clear();
let mut chunk = Vec::new();
while reader.next_chunk(&mut chunk)? > 0 {
out.extend_from_slice(&chunk);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
/// The lead-in conversion, against the numbers read off the owner's disc
/// on BOTH machines the same afternoon. If this ever drifts, a disc
/// corrected on Linux stops being found on macOS and nothing says why.
#[test]
fn the_mac_toc_reproduces_the_kernels_numbers_exactly() {
let mac_starts: [u32; 7] = [150, 46727, 100197, 157523, 218868, 264270, 285885];
let linux_starts: [u32; 7] = [0, 46577, 100047, 157373, 218718, 264120, 285735];
for (m, l) in mac_starts.iter().zip(linux_starts.iter()) {
assert_eq!(m - LEAD_IN, *l);
}
assert_eq!(356718 - LEAD_IN, 356568);
}
#[test]
fn a_track_file_is_matched_on_its_number_and_never_on_its_title() {
let dir = std::env::temp_dir().join(format!("qbz-mac-cd-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
// Both shapes the Music app produces, plus a decoy that starts with a
// digit but is not a track.
std::fs::write(dir.join("1 Fear Inoculum.aiff"), b"x").unwrap();
std::fs::write(dir.join("2 Audio Track.aiff"), b"x").unwrap();
std::fs::write(dir.join("3 Invincible.txt"), b"x").unwrap();
assert!(track_file(&dir, 1).unwrap().ends_with("1 Fear Inoculum.aiff"));
assert!(track_file(&dir, 2).unwrap().ends_with("2 Audio Track.aiff"));
assert!(track_file(&dir, 3).is_none(), "a .txt is not a track");
assert!(track_file(&dir, 9).is_none());
std::fs::remove_dir_all(&dir).ok();
}
/// Build a volume that looks like a mounted audio CD: a `.TOC.plist` and
/// one AIFC per track, `sowt` like the real thing.
fn fake_volume(dir: &Path, tracks: &[(u8, u32, u32)]) {
std::fs::create_dir_all(dir).unwrap();
let mut plist_tracks = Vec::new();
for (n, start, sectors) in tracks {
let mut d = plist::Dictionary::new();
d.insert("Point".into(), plist::Value::from(*n as u64));
d.insert("Start Block".into(), plist::Value::from((*start + LEAD_IN) as u64));
d.insert("Data".into(), plist::Value::from(false));
plist_tracks.push(plist::Value::Dictionary(d));
// One AIFC whose payload is the track number repeated, so a read
// that lands on the wrong file is unmistakable.
let bytes = *sectors as usize * crate::CDDA_SECTOR_BYTES;
let mut f = Vec::new();
f.extend_from_slice(b"FORM");
f.extend_from_slice(&0u32.to_be_bytes());
f.extend_from_slice(b"AIFC");
f.extend_from_slice(b"COMM");
f.extend_from_slice(&22u32.to_be_bytes());
f.extend_from_slice(&2u16.to_be_bytes());
f.extend_from_slice(&((bytes / 4) as u32).to_be_bytes());
f.extend_from_slice(&16u16.to_be_bytes());
f.extend_from_slice(&[0u8; 10]);
f.extend_from_slice(b"sowt");
f.extend_from_slice(b"SSND");
f.extend_from_slice(&((bytes + 8) as u32).to_be_bytes());
f.extend_from_slice(&0u32.to_be_bytes());
f.extend_from_slice(&0u32.to_be_bytes());
f.extend(std::iter::repeat(*n).take(bytes));
std::fs::write(dir.join(format!("{n} Track {n}.aiff")), &f).unwrap();
}
let last = tracks.last().unwrap();
let mut session = plist::Dictionary::new();
session.insert("First Track".into(), plist::Value::from(1u64));
session.insert("Last Track".into(), plist::Value::from(tracks.len() as u64));
session.insert(
"Leadout Block".into(),
plist::Value::from((last.1 + last.2 + LEAD_IN) as u64),
);
session.insert("Track Array".into(), plist::Value::Array(plist_tracks));
let mut root = plist::Dictionary::new();
root.insert(
"Sessions".into(),
plist::Value::Array(vec![plist::Value::Dictionary(session)]),
);
plist::to_file_xml(dir.join(".TOC.plist"), &plist::Value::Dictionary(root)).unwrap();
}
/// THE regression guard for the 2026-08-21 defect.
///
/// `audible_qt::play_cd_track` rebuilds its `TocTrack` from a `CdRef`,
/// which has no track number, and passes ZERO. Resolving by number meant
/// every CD track on macOS answered "could not read the disc" — while
/// ripping, which passes a real number, worked fine. So the two paths
/// disagreed and only one of them was ever exercised.
#[test]
fn a_track_opens_by_its_sector_range_even_with_no_track_number() {
let dir = std::env::temp_dir().join(format!("qbz-mac-lsn-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
// Two tracks, 2 and 3 sectors long.
fake_volume(&dir, &[(1, 0, 2), (2, 2, 3)]);
let toc = read_toc(&dir).unwrap();
assert_eq!(toc.tracks.len(), 2);
assert_eq!(toc.tracks[0].start_lsn, 0);
assert_eq!(toc.tracks[1].start_lsn, 2);
assert_eq!(toc.tracks[1].sectors, 3);
// Exactly what playback hands over: no number.
let as_playback_sees_it = TocTrack {
number: 0,
start_lsn: 2,
sectors: 3,
is_audio: true,
};
let mut reader = TrackReader::open(&dir, &as_playback_sees_it)
.expect("a numberless track must still open");
let mut chunk = Vec::new();
let mut all = Vec::new();
while reader.next_chunk(&mut chunk).unwrap() > 0 {
all.extend_from_slice(&chunk);
}
assert_eq!(all.len(), 3 * crate::CDDA_SECTOR_BYTES);
assert!(all.iter().all(|b| *b == 2), "it opened track 2's file");
// And a start PART-WAY into a track lands at that offset, not at the
// track's beginning.
let mid = TocTrack {
number: 0,
start_lsn: 3,
sectors: 2,
is_audio: true,
};
let mut reader = TrackReader::open(&dir, &mid).unwrap();
let mut all = Vec::new();
while reader.next_chunk(&mut chunk).unwrap() > 0 {
all.extend_from_slice(&chunk);
}
assert_eq!(all.len(), 2 * crate::CDDA_SECTOR_BYTES);
std::fs::remove_dir_all(&dir).ok();
}
/// `sowt` means the samples are ALREADY little-endian. Swapping them —
/// which "AIFF is big-endian" invites — produced audio that passed every
/// cheap statistic and matched the Linux rip nowhere.
#[test]
fn a_sowt_payload_is_not_byte_swapped() {
let dir = std::env::temp_dir().join(format!("qbz-mac-sowt-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
fake_volume(&dir, &[(1, 0, 1)]);
let mut file = std::fs::File::open(dir.join("1 Track 1.aiff")).unwrap();
let e = aiff_audio_extent(&mut file).unwrap();
assert!(!e.big_endian, "sowt is little-endian");
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn the_ssnd_payload_is_found_past_the_chunks_before_it() {
let dir = std::env::temp_dir().join(format!("qbz-mac-aiff-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("t.aiff");
let mut f = Vec::new();
f.extend_from_slice(b"FORM");
f.extend_from_slice(&0u32.to_be_bytes()); // size, unread
f.extend_from_slice(b"AIFF");
// A COMM chunk with an ODD size, so the pad byte has to be honoured.
f.extend_from_slice(b"COMM");
f.extend_from_slice(&3u32.to_be_bytes());
f.extend_from_slice(&[1, 2, 3, 0]);
f.extend_from_slice(b"SSND");
f.extend_from_slice(&(8u32 + 4).to_be_bytes());
f.extend_from_slice(&0u32.to_be_bytes()); // offset
f.extend_from_slice(&0u32.to_be_bytes()); // blockSize
f.extend_from_slice(&[0xAA, 0xBB, 0xCC, 0xDD]);
std::fs::write(&path, &f).unwrap();
let mut file = std::fs::File::open(&path).unwrap();
let e = aiff_audio_extent(&mut file).unwrap();
assert_eq!(e.len, 4);
assert!(e.big_endian, "a plain AIFF has no compression field");
let mut buf = vec![0u8; 4];
file.seek(SeekFrom::Start(e.at)).unwrap();
file.read_exact(&mut buf).unwrap();
assert_eq!(buf, [0xAA, 0xBB, 0xCC, 0xDD]);
std::fs::remove_dir_all(&dir).ok();
}
}
+15 -3
View File
@@ -14,9 +14,18 @@
//! of zeros. Silence that pretends to be audio is the one outcome a
//! bit-perfect player must never produce.
#[cfg(target_os = "linux")]
/// What a table of contents IS — shared by every platform's reader.
pub mod toc;
/// Reading a CD, whichever way this platform offers. Always present: the
/// answer on a platform with no reader is "no drive", never a build failure.
pub mod cdda;
#[cfg(target_os = "linux")]
mod cdda_linux;
#[cfg(target_os = "macos")]
mod cdda_macos;
/// Disc IMAGES are portable — a .iso is a file, and reading one needs no
/// device and no privileges. Only the live-drive path is Linux-gated.
pub mod iso9660;
@@ -27,8 +36,11 @@ pub mod discid;
/// SACD disc images (Scarlet Book).
pub mod sacd;
#[cfg(target_os = "linux")]
pub use cdda::{list_devices, read_audio, read_toc, CdError, Toc, TocTrack};
/// What a disc is called, remembered after it has been ejected.
pub mod store;
pub use cdda::{drive_model, list_devices, read_audio, read_toc};
pub use toc::{CdError, Toc, TocTrack};
/// Bytes per CD-DA sector (a "frame" in the kernel's vocabulary): 588 stereo
/// 16-bit sample pairs.
+99
View File
@@ -0,0 +1,99 @@
//! What a CD's table of contents IS, independent of how it was read.
//!
//! Linux asks the kernel through ioctls; macOS mounts the disc and leaves a
//! `.TOC.plist` next to the audio files. The two reads share nothing, and the
//! ANSWER has to be identical or the disc store, the MusicBrainz lookup and
//! the rip log would need a second version each.
//!
//! MEASURED, both platforms, the owner's Tool — *Fear Inoculum* (2026-08-21):
//! the Linux ioctl and the macOS plist (minus its 150-sector lead-in) produce
//! byte-identical answers — DiscID `BeNBMsD8Du5NO2W61Yk.B2jwwIs-` and
//! fingerprint `38bef21351f7fca3` from both. That equality is the whole reason
//! these types live here instead of inside one platform's reader.
use std::path::PathBuf;
#[derive(Debug, thiserror::Error)]
pub enum CdError {
#[error("no optical drive found")]
NoDrive,
#[error("cannot open {0}: {1}")]
Open(PathBuf, std::io::Error),
#[error("no disc in the drive")]
NoDisc,
#[error("the disc has no audio tracks")]
NotAudio,
#[error("the drive refused to read audio at sector {lsn}: {source}")]
Read {
lsn: u32,
#[source]
source: std::io::Error,
},
#[error("reading the table of contents failed: {0}")]
Toc(std::io::Error),
}
/// One entry of the disc's table of contents.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TocTrack {
pub number: u8,
pub start_lsn: u32,
/// Sectors up to the next track (or the lead-out for the last one).
pub sectors: u32,
/// False for the data track of a mixed-mode disc.
pub is_audio: bool,
}
impl TocTrack {
pub fn duration_secs(&self) -> u64 {
crate::sectors_to_secs(self.sectors)
}
/// PCM frames (sample pairs) this track decodes to.
pub fn frames(&self) -> u64 {
self.sectors as u64 * 588
}
}
#[derive(Debug, Clone)]
pub struct Toc {
pub device: PathBuf,
pub tracks: Vec<TocTrack>,
pub leadout_lsn: u32,
}
impl Toc {
/// The AUDIO tracks, in disc order. A caller that wants to play something
/// should use this and never `tracks` — the data track of an enhanced CD
/// lives in the latter.
pub fn audio_tracks(&self) -> impl Iterator<Item = &TocTrack> {
self.tracks.iter().filter(|t| t.is_audio)
}
/// A stable identity for the MEDIUM, not the drive.
///
/// `/dev/sr0` names a piece of hardware; two different discs in it are two
/// different sessions, and a persisted queue that resolves against the
/// drive would happily play track 3 of whatever is loaded now. The digest
/// is over every track's start and length plus the lead-out, which is what
/// a disc actually is. (The disc's own MCN would be tidier — the owner's
/// Fear Inoculum reports all zeros, so it is not dependable.)
pub fn fingerprint(&self) -> String {
// FNV-1a: no dependency, and this only has to be stable and
// collision-resistant enough to tell two albums apart.
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
let mut eat = |v: u32| {
for b in v.to_le_bytes() {
h ^= b as u64;
h = h.wrapping_mul(0x1000_0000_01b3);
}
};
for t in &self.tracks {
eat(t.start_lsn);
eat(t.sectors);
eat(t.number as u32);
}
eat(self.leadout_lsn);
format!("{h:016x}")
}
}