fix(sacd): support images with 2064-byte physical sectors

Detect sector layout from Master TOC signatures and strip physical framing while preserving logical addressing, bounds and file mutation checks. Add reader and scanner regressions with synchronized CI presence guards.

Verified full decoding of 53 tracks across five real images, seek and previous-reader comparisons, isolated release UI opening and scanning, and disc, DSD, library and Qt tests.

cx
This commit is contained in:
vicrodh committed 2026-09-06 17:29:06 -06:00
1 parent 0ce4e1fa04
commit 8f2050d703
5 files changed
+478 -29

No files matched your search

+3 -1
View File
@@ -11,7 +11,9 @@
# snapshot/plan/apply/ledger/local copy, additive blacklist
# merge), plus QConnect controller handoff/read-vs-write,
# proto3-zero cursor, manual skip/loop/shuffle/autoplay and
# consecutive-log repetition regression checks. ~5 min cold.
# consecutive-log repetition regression checks, plus SACD
# 2048/2064-sector TOC/frame/seek equivalence and scanner import/
# failed-read preservation. ~5 min cold.
# qt-gate — the Qt frontend: the five static QML audits, `cargo test -p
# qbz-qt`, the Slint-free dep-graph gate, and an OFFSCREEN BOOT of
# debug AND release binaries (including process liveness).
+98 -28
View File
@@ -11,6 +11,8 @@
//! WHAT IS SUPPORTED: DSD64 stereo areas, either flat or DST-compressed, in
//! raw Scarlet Book dumps and ISO/UDF hybrid images. Every pointer and audio
//! extent is bounded by the image; nothing is inferred from an ISO 9660 layer.
//! Images may store 2048-byte logical sectors directly or retain the 12-byte
//! header and 4-byte trailer of each 2064-byte physical sector.
use std::fs::{File, Metadata};
use std::io::{Read, Seek, SeekFrom};
@@ -77,8 +79,10 @@ pub enum SacdError {
MissingFrameStart { track: u8, lsn: u64 },
#[error("{0} is not a regular file")]
NotRegularFile(PathBuf),
#[error("SACD image length {0} is not a whole number of 2048-byte sectors")]
#[error("SACD image length {0} contains a partial sector in the detected layout")]
InvalidImageLength(u64),
#[error("SACD image has Master TOC signatures in conflicting sector layouts")]
AmbiguousSectorLayout,
#[error("SACD image changed while it was being read: {0}")]
ImageChangedDuringRead(PathBuf),
}
@@ -177,10 +181,34 @@ struct SectorImage {
file: File,
path: PathBuf,
bytes: u64,
layout: SectorLayout,
master_signature_found: bool,
stamp: ImageStamp,
sectors_since_check: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SectorLayout {
Logical2048,
Physical2064,
}
impl SectorLayout {
fn stride(self) -> u64 {
match self {
Self::Logical2048 => SECTOR,
Self::Physical2064 => 2064,
}
}
fn payload_offset(self) -> u64 {
match self {
Self::Logical2048 => 0,
Self::Physical2064 => 12,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct ImageStamp {
bytes: u64,
@@ -226,17 +254,60 @@ impl SectorImage {
return Err(SacdError::NotRegularFile(path.to_path_buf()));
}
let bytes = metadata.len();
Ok(Self {
let mut image = Self {
file,
path: path.to_path_buf(),
bytes,
layout: SectorLayout::Logical2048,
master_signature_found: false,
stamp: ImageStamp::from_metadata(&metadata),
sectors_since_check: 0,
})
};
let layout = image.detect_layout()?;
image.master_signature_found = layout.is_some();
image.layout = layout.unwrap_or(SectorLayout::Logical2048);
image.verify_unchanged()?;
Ok(image)
}
/// File size alone cannot distinguish layouts: a 2064-byte dump with a
/// multiple of 128 sectors is also divisible by 2048. Probe all three
/// Master positions, including backups and signed but truncated images.
/// Full geometry validation remains the responsibility of the TOC parser.
fn detect_layout(&mut self) -> Result<Option<SectorLayout>, SacdError> {
let mut selected = None;
for layout in [SectorLayout::Logical2048, SectorLayout::Physical2064] {
for lsn in MASTER_TOC_COPIES {
let offset = lsn * layout.stride() + layout.payload_offset();
if offset + 8 > self.bytes {
continue;
}
let mut signature = [0u8; 8];
self.file
.seek(SeekFrom::Start(offset))
.and_then(|_| self.file.read_exact(&mut signature))
.map_err(|source| SacdError::Iso(IsoError::Read { lsn, source }))?;
if &signature == b"SACDMTOC" {
if selected.is_some_and(|previous| previous != layout) {
return Err(SacdError::AmbiguousSectorLayout);
}
selected = Some(layout);
break;
}
}
}
Ok(selected)
}
fn validate_length(&self) -> Result<(), SacdError> {
if self.bytes % self.layout.stride() != 0 {
return Err(SacdError::InvalidImageLength(self.bytes));
}
Ok(())
}
fn sectors(&self) -> u64 {
self.bytes / SECTOR
self.bytes / self.layout.stride()
}
fn has_complete_sector(&self, lsn: u64) -> bool {
@@ -263,14 +334,24 @@ impl SectorImage {
),
}));
}
let stride = self.layout.stride() as usize;
let bytes = count
.checked_mul(SECTOR as usize)
.checked_mul(stride)
.ok_or(SacdError::MalformedToc("byte count overflows"))?;
let mut out = vec![0u8; bytes];
self.file
.seek(SeekFrom::Start(lsn * SECTOR))
.seek(SeekFrom::Start(lsn * self.layout.stride()))
.and_then(|_| self.file.read_exact(&mut out))
.map_err(|source| SacdError::Iso(IsoError::Read { lsn, source }))?;
if self.layout == SectorLayout::Physical2064 {
// Read contiguous physical sectors once, then compact their payloads
// in place. Headers/trailers must never reach TOC or audio parsing.
for index in 0..count {
let from = index * stride + self.layout.payload_offset() as usize;
out.copy_within(from..from + SECTOR as usize, index * SECTOR as usize);
}
out.truncate(count * SECTOR as usize);
}
self.sectors_since_check = self.sectors_since_check.saturating_add(count_u64);
// A one-second cadence avoids a metadata syscall for every 1/75 s
// audio frame while still detecting in-place writes and path swaps
@@ -421,28 +502,13 @@ pub enum SacdSniff {
/// Master TOC, not the optional ISO 9660 compatibility layer.
pub fn sniff_sacd_image(path: &Path) -> Result<SacdSniff, SacdError> {
let mut image = SectorImage::open(path)?;
if !MASTER_TOC_COPIES
.into_iter()
.any(|lsn| image.has_complete_sector(lsn))
{
return Ok(SacdSniff::NotSacd);
}
if image.bytes % SECTOR != 0 {
// Preserve the useful distinction between an arbitrary odd-sized file
// and a signed SACD image with a truncated tail. Do this before the
// full Master parse so another malformed field cannot hide truncation.
for lsn in MASTER_TOC_COPIES {
if image.has_complete_sector(lsn) {
let first = image.read_sectors(lsn, 1)?;
if &first[..8] == b"SACDMTOC" {
image.verify_unchanged()?;
return Err(SacdError::InvalidImageLength(image.bytes));
}
}
}
if !image.master_signature_found {
image.verify_unchanged()?;
return Ok(SacdSniff::NotSacd);
}
// A signed image with a truncated tail is an error, not an ordinary ISO
// to ignore/prune. This also covers a signature in a partial Master sector.
image.validate_length()?;
let result = match select_master_toc(&mut image)? {
Some(_) => SacdSniff::Sacd,
None => SacdSniff::NotSacd,
@@ -459,9 +525,7 @@ pub fn is_sacd_image(path: &Path) -> bool {
/// Read the stereo area's table of contents out of a disc image.
pub fn read_area(path: &Path) -> Result<SacdArea, SacdError> {
let mut image = SectorImage::open(path)?;
if image.bytes % SECTOR != 0 {
return Err(SacdError::InvalidImageLength(image.bytes));
}
image.validate_length()?;
let master = select_master_toc(&mut image)?.ok_or(SacdError::MissingMasterToc)?;
let mut stereo = None;
@@ -1017,6 +1081,7 @@ pub struct SacdFrameReader {
impl SacdFrameReader {
pub fn open(path: &Path, track: &SacdTrack) -> Result<Self, SacdError> {
let image = SectorImage::open(path)?;
image.validate_length()?;
let start_lsn = u64::from(track.start_lsn);
let end_lsn = start_lsn
.checked_add(u64::from(track.length_lsn))
@@ -1311,6 +1376,7 @@ impl SacdTrackReader {
pub fn open_with(path: &Path, track: &SacdTrack, sync: FrameSync) -> Result<Self, SacdError> {
let start_lsn = track.start_lsn as u64;
let image = SectorImage::open(path)?;
image.validate_length()?;
let end_lsn = start_lsn
.checked_add(u64::from(track.length_lsn))
.ok_or(SacdError::MalformedToc("track sector range overflows"))?;
@@ -1406,6 +1472,10 @@ impl SacdTrackReader {
}
}
#[cfg(test)]
#[path = "sacd_raw_tests.rs"]
mod raw_sector_tests;
#[cfg(test)]
mod tests {
use super::*;
+285
View File
@@ -0,0 +1,285 @@
//! Synthetic logical/physical copies must expose identical TOCs and audio.
use super::*;
use std::io::Write;
use std::sync::atomic::{AtomicU64, Ordering};
const LOGICAL: usize = 2048;
const PHYSICAL: usize = 2064;
const SECTORS: usize = 640; // Also makes the physical file divisible by 2048.
struct TestImage(PathBuf);
impl TestImage {
fn write(logical: &[u8], physical: bool) -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let path = std::env::temp_dir().join(format!(
"qbz-sacd-raw-{}-{}.iso",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
.unwrap();
if physical {
for sector in logical.chunks_exact(LOGICAL) {
file.write_all(&[0xa5; 12]).unwrap();
file.write_all(sector).unwrap();
file.write_all(&[0x5a; 4]).unwrap();
}
} else {
file.write_all(logical).unwrap();
}
Self(path)
}
}
impl Drop for TestImage {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
fn payload(frame: usize, dst: bool) -> Vec<u8> {
(0..if dst { 3015 } else { 9408 })
.map(|i| ((frame * 31 + i) % 251) as u8)
.collect()
}
fn fixture(dst: bool) -> Vec<u8> {
let mut data = vec![0; SECTORS * LOGICAL];
let span = if dst { 2 } else { 5 };
for lsn in [510, 520, 530] {
let master = &mut data[lsn * LOGICAL..(lsn + 1) * LOGICAL];
master[..8].copy_from_slice(b"SACDMTOC");
master[8..10].copy_from_slice(&[1, 20]);
master[0x40..0x44].copy_from_slice(&544u32.to_be_bytes());
master[0x44..0x48].copy_from_slice(&548u32.to_be_bytes());
master[0x54..0x56].copy_from_slice(&3u16.to_be_bytes());
}
let mut toc = vec![0; 3 * LOGICAL];
toc[..8].copy_from_slice(b"TWOCHTOC");
toc[8..12].copy_from_slice(&[1, 20, 0, 3]);
toc[0x14] = 4;
toc[0x15] = if dst { 0 } else { 2 };
toc[0x20] = 2;
toc[0x42] = 4;
toc[0x45] = 2;
toc[0x48..0x4c].copy_from_slice(&600u32.to_be_bytes());
toc[0x4c..0x50].copy_from_slice(&(600u32 + 4 * span as u32 - 1).to_be_bytes());
toc[LOGICAL..LOGICAL + 8].copy_from_slice(b"SACDTRL1");
toc[2 * LOGICAL..2 * LOGICAL + 8].copy_from_slice(b"SACDTRL2");
for track in 0..2 {
let at = LOGICAL + 8 + track * 4;
toc[at..at + 4].copy_from_slice(&(600u32 + (track * 2 * span) as u32).to_be_bytes());
toc[at + 1020..at + 1024].copy_from_slice(&(2 * span as u32).to_be_bytes());
toc[at + LOGICAL + 2] = (track * 2) as u8;
toc[at + LOGICAL + 1022] = 2;
}
for lsn in [544, 548] {
data[lsn * LOGICAL..(lsn + 3) * LOGICAL].copy_from_slice(&toc);
}
for frame in 0..4 {
let audio = payload(frame, dst);
let mut used = 0;
for index in 0..span {
let lsn = 600 + frame * span + index;
let sector = &mut data[lsn * LOGICAL..(lsn + 1) * LOGICAL];
let first = index == 0;
if dst {
sector[0] = if first { 0x25 } else { 0x21 };
let at = if first { 7 } else { 3 };
let len = (LOGICAL - at).min(audio.len() - used);
let descriptor = 0x1000 | if first { 0x8000 } else { 0 } | len as u16;
sector[1..3].copy_from_slice(&descriptor.to_be_bytes());
if first {
sector[5] = frame as u8;
sector[6] = 2 << 2;
}
sector[at..at + len].copy_from_slice(&audio[used..used + len]);
used += len;
} else {
sector[0] = if first { 0x44 } else { 0x40 };
let header = if first { 8 } else { 5 };
let len = 2016.min(audio.len() - used);
let padding = LOGICAL - header - len;
sector[1..3].copy_from_slice(&(0x1800 | padding as u16).to_be_bytes());
sector[3..5].copy_from_slice(
&(0x1000 | if first { 0x8000 } else { 0 } | len as u16).to_be_bytes(),
);
if first {
sector[7] = frame as u8;
}
sector[LOGICAL - len..].copy_from_slice(&audio[used..used + len]);
used += len;
}
}
assert_eq!(used, audio.len());
}
data
}
#[test]
fn raw_and_logical_copies_preserve_geometry_frames_and_seeks() {
for dst in [false, true] {
let bytes = fixture(dst);
let logical = TestImage::write(&bytes, false);
let raw = TestImage::write(&bytes, true);
assert_eq!(std::fs::metadata(&raw.0).unwrap().len() % 2048, 0);
let expected = read_area(&logical.0).unwrap();
let actual = read_area(&raw.0).unwrap();
assert_eq!(actual.fingerprint(), expected.fingerprint());
assert_eq!(actual.tracks, expected.tracks);
assert_eq!(sniff_sacd_image(&raw.0).unwrap(), SacdSniff::Sacd);
for (index, track) in actual.tracks.iter().enumerate() {
let mut reader = SacdFrameReader::open(&raw.0, track).unwrap();
for frame in index * 2..index * 2 + 2 {
let read = reader.next_frame().unwrap().unwrap();
assert_eq!(read.payload, payload(frame, dst));
assert_eq!(read.timecode_frame, frame as u32);
}
assert!(reader.next_frame().unwrap().is_none());
for offset in [1, 0, 2, 1] {
reader.seek_to_fraction(offset, 2).unwrap();
let read = reader.next_frame().unwrap();
if offset == 2 {
assert!(read.is_none());
} else {
assert_eq!(
read.unwrap().payload,
payload(index * 2 + offset as usize, dst)
);
}
}
}
}
}
#[test]
fn raw_batch_reads_strip_every_header_and_trailer_and_keep_bounds() {
let bytes = fixture(false);
let raw = TestImage::write(&bytes, true);
let mut reader = SectorImage::open(&raw.0).unwrap();
for (lsn, count) in [(0, 1), (510, 30), (600, 20), (639, 1), (640, 0)] {
assert_eq!(
reader.read_sectors(lsn as u64, count).unwrap(),
bytes[lsn * LOGICAL..(lsn + count) * LOGICAL]
);
}
assert!(reader.read_sectors(640, 1).is_err());
assert!(reader.read_sectors(u64::MAX, 2).is_err());
let area = read_area(&raw.0).unwrap();
let mut legacy = SacdTrackReader::open(&raw.0, &area.tracks[0]).unwrap();
let mut audio = Vec::new();
legacy.next_chunk(&mut audio, 200).unwrap();
assert_eq!(audio, [payload(0, false), payload(1, false)].concat());
}
#[test]
fn raw_layout_can_be_detected_from_only_the_last_master_copy() {
let mut bytes = fixture(false);
for lsn in [510, 520] {
bytes[lsn * LOGICAL..lsn * LOGICAL + 8].fill(0);
}
let raw = TestImage::write(&bytes, true);
assert_eq!(sniff_sacd_image(&raw.0).unwrap(), SacdSniff::Sacd);
assert_eq!(read_area(&raw.0).unwrap().tracks.len(), 2);
}
#[test]
fn raw_partial_sectors_are_errors_even_when_only_the_trailer_is_missing() {
for removed in [1, 4, 12, PHYSICAL - 1] {
let raw = TestImage::write(&fixture(false), true);
let track = read_area(&raw.0).unwrap().tracks.remove(0);
std::fs::OpenOptions::new()
.write(true)
.open(&raw.0)
.unwrap()
.set_len((SECTORS * PHYSICAL - removed) as u64)
.unwrap();
assert!(matches!(
sniff_sacd_image(&raw.0),
Err(SacdError::InvalidImageLength(_))
));
assert!(matches!(
read_area(&raw.0),
Err(SacdError::InvalidImageLength(_))
));
assert!(matches!(
SacdFrameReader::open(&raw.0, &track),
Err(SacdError::InvalidImageLength(_))
));
}
let raw = TestImage::write(&fixture(false), true);
std::fs::OpenOptions::new()
.write(true)
.open(&raw.0)
.unwrap()
.set_len((510 * PHYSICAL + 12 + 8) as u64)
.unwrap();
assert!(matches!(
sniff_sacd_image(&raw.0),
Err(SacdError::InvalidImageLength(_))
));
}
#[test]
fn raw_geometry_cannot_point_into_a_missing_whole_sector() {
let raw = TestImage::write(&fixture(false), true);
std::fs::OpenOptions::new()
.write(true)
.open(&raw.0)
.unwrap()
.set_len((610 * PHYSICAL) as u64)
.unwrap();
assert!(matches!(read_area(&raw.0), Err(SacdError::MalformedToc(_))));
}
#[test]
fn raw_conflicting_area_copies_are_still_rejected() {
let mut bytes = fixture(false);
bytes[550 * LOGICAL + 8 + 1020 + 2] = 3;
let raw = TestImage::write(&bytes, true);
assert!(matches!(
read_area(&raw.0),
Err(SacdError::ConflictingAreaTocs)
));
}
#[test]
fn raw_images_cannot_choose_between_two_signed_layouts() {
let raw = TestImage::write(&fixture(false), true);
let mut file = std::fs::OpenOptions::new()
.write(true)
.open(&raw.0)
.unwrap();
file.seek(SeekFrom::Start(510 * 2048)).unwrap();
file.write_all(b"SACDMTOC").unwrap();
assert!(matches!(
sniff_sacd_image(&raw.0),
Err(SacdError::AmbiguousSectorLayout)
));
}
#[test]
fn raw_reads_keep_the_changed_file_guard() {
let raw = TestImage::write(&fixture(false), true);
let mut reader = SectorImage::open(&raw.0).unwrap();
std::fs::OpenOptions::new()
.append(true)
.open(&raw.0)
.unwrap()
.write_all(&[0])
.unwrap();
assert!(matches!(
reader.read_sectors(0, 350),
Err(SacdError::ImageChangedDuringRead(_))
));
}
#[test]
fn raw_sized_unsigned_files_are_not_sacd_images() {
let raw = TestImage::write(&vec![0; SECTORS * LOGICAL], true);
assert_eq!(sniff_sacd_image(&raw.0).unwrap(), SacdSniff::NotSacd);
}
+82
View File
@@ -477,6 +477,88 @@ mod tests {
.unwrap());
}
#[test]
fn raw_sacd_scan_imports_once_and_keeps_tracks_when_the_image_is_truncated() {
let temp = TempDir::new().unwrap();
let root = temp.path().join("music");
std::fs::create_dir(&root).unwrap();
let image_path = root.join("physical.ISO");
let mut logical = vec![0u8; 640 * 2048];
let master = &mut logical[510 * 2048..511 * 2048];
master[..8].copy_from_slice(b"SACDMTOC");
master[8..10].copy_from_slice(&[1, 20]);
master[0x40..0x44].copy_from_slice(&544u32.to_be_bytes());
master[0x54..0x56].copy_from_slice(&3u16.to_be_bytes());
let toc = &mut logical[544 * 2048..547 * 2048];
toc[..8].copy_from_slice(b"TWOCHTOC");
toc[8..12].copy_from_slice(&[1, 20, 0, 3]);
toc[0x14] = 4;
toc[0x15] = 2;
toc[0x20] = 2;
toc[0x42] = 4;
toc[0x45] = 1;
toc[0x48..0x4c].copy_from_slice(&600u32.to_be_bytes());
toc[0x4c..0x50].copy_from_slice(&619u32.to_be_bytes());
toc[2048..2056].copy_from_slice(b"SACDTRL1");
toc[2056..2060].copy_from_slice(&600u32.to_be_bytes());
toc[3076..3080].copy_from_slice(&20u32.to_be_bytes());
toc[4096..4104].copy_from_slice(b"SACDTRL2");
toc[5126] = 4;
let mut file = std::fs::File::create(&image_path).unwrap();
for sector in logical.chunks_exact(2048) {
file.write_all(&[0xa5; 12]).unwrap();
file.write_all(sector).unwrap();
file.write_all(&[0x5a; 4]).unwrap();
}
drop(file);
// Manual open builds the same rows without requiring catalogue import.
let rows = super::build_image_rows(&image_path, &SacdLabels::default()).unwrap();
assert_eq!(rows.album, "physical");
assert_eq!(rows.tracks.len(), 1);
assert_eq!(
rows.tracks[0].file_path,
format!("sacd:{}#1", image_path.display())
);
let db = LibraryDatabase::open(&temp.path().join("library.db")).unwrap();
let root_id = db
.add_folder_with_network_info(&root.to_string_lossy(), false, None)
.unwrap();
let scan = |generation| {
scan_root_for_sacd(
&db,
root_id,
generation,
&root,
&SacdLabels::default(),
&AtomicBool::new(false),
)
};
let first = scan(1);
assert_eq!(first.imported, 1);
assert!(first.failed.is_empty());
let tracks = db.get_all_track_paths().unwrap();
assert_eq!(tracks.len(), 1);
let second = scan(2);
assert_eq!(second.unchanged, 1);
assert_eq!(second.imported, 0);
assert_eq!(db.get_all_track_paths().unwrap(), tracks);
// Even a missing physical trailer is a failed SACD read, not a file
// that may be silently ignored and have its known tracks pruned.
std::fs::OpenOptions::new()
.write(true)
.open(&image_path)
.unwrap()
.set_len(640 * 2064 - 4)
.unwrap();
let third = scan(3);
assert_eq!(third.failed.len(), 1);
assert_eq!(third.ignored, 0);
assert_eq!(third.removed, 0);
assert_eq!(db.get_all_track_paths().unwrap(), tracks);
}
#[test]
fn cancel_stops_before_the_first_candidate() {
let temp = TempDir::new().unwrap();
+10
View File
@@ -66,6 +66,16 @@ cargo test \
--no-fail-fast \
"$@"
say "gate: SACD physical-sector and scanner regressions present"
# Already executed by the workspace run: keep the container/seek equivalence
# and failed-scan preservation checks from silently disappearing.
n=$(cargo test --manifest-path crates/Cargo.toml -p qbz-disc --lib -- --list raw_sector_tests:: 2>/dev/null \
| grep -c ': test$' || true)
(( n >= 9 )) || { echo "SACD physical-sector suite has $n tests (expected >= 9)"; exit 1; }
n=$(cargo test --manifest-path crates/Cargo.toml -p qbz-library --lib -- --list raw_sacd_scan_ 2>/dev/null \
| grep -c ': test$' || true)
(( n >= 1 )) || { echo "SACD raw scanner suite has $n tests (expected >= 1)"; exit 1; }
say "gate: listen log suite present and green (qbz-app::listen_log)"
# The workspace run above already executes these; this step exists so a
# refactor that silently drops the module's tests (a renamed mod, a cfg gate)