opticaldiscs 0.10.0

Format-agnostic optical disc image reading and filesystem browsing (ISO, BIN/CUE, CHD)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
//! `SectorReader` trait and format-specific implementations.
//!
//! All implementations present a uniform view of 2048-byte cooked sectors,
//! stripping container-specific headers transparently. Callers never need to
//! know whether the underlying file is a plain ISO, a raw BIN, or a CHD.

use std::fs::File;
use std::io::{BufReader, Read, Seek, SeekFrom};
use std::path::Path;

use crate::error::{OpticaldiscsError, Result};

/// Cooked sector size in bytes (ISO 9660 logical sector).
pub const SECTOR_SIZE: u64 = 2048;

/// Raw CD sector size in bytes (including sync, header, ECC/EDC).
pub const RAW_SECTOR_SIZE: u64 = 2352;

/// Byte offset to user data within a raw Mode 1 sector.
pub const MODE1_DATA_OFFSET: u64 = 16;

/// Byte offset to user data within a raw Mode 2 (Form 1, XA) sector.
///
/// Mode 2 sectors carry an 8-byte subheader after the 16-byte sync+header,
/// so the 2048-byte user area starts at offset 24.
pub const MODE2_DATA_OFFSET: u64 = 24;

/// 12-byte sync pattern that begins every raw (2352-byte) CD sector.
const RAW_SYNC: [u8; 12] = [
    0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00,
];

/// Abstraction over different disc image containers.
///
/// Implementations always return 2048-byte cooked sectors — the raw sector
/// headers present in BIN/CUE and CHD files are stripped internally.
pub trait SectorReader: Send {
    /// Read a single 2048-byte cooked sector at the given Logical Block Address.
    fn read_sector(&mut self, lba: u64) -> Result<Vec<u8>>;

    /// Read `length` bytes starting at `byte_offset` (cooked address space).
    ///
    /// The default implementation composes calls to `read_sector`; override
    /// for formats (e.g. plain ISO) where a direct seek+read is cheaper.
    fn read_bytes(&mut self, byte_offset: u64, length: usize) -> Result<Vec<u8>> {
        let sector_lba = byte_offset / SECTOR_SIZE;
        let sector_off = (byte_offset % SECTOR_SIZE) as usize;
        let mut out = Vec::with_capacity(length);
        let mut remaining = length;
        let mut lba = sector_lba;
        let mut offset = sector_off;

        while remaining > 0 {
            let sector = self.read_sector(lba)?;
            let available = sector.len().saturating_sub(offset);
            let take = remaining.min(available);
            out.extend_from_slice(&sector[offset..offset + take]);
            remaining -= take;
            lba += 1;
            offset = 0;
        }
        Ok(out)
    }
}

// ── Phase 2: IsoSectorReader ──────────────────────────────────────────────────

/// `SectorReader` for plain `.iso` / `.toast` files, **and** for bare `.iso`
/// files that are actually raw 2352-byte-sector dumps.
///
/// Most `.iso` files store sectors consecutively as 2048-byte cooked data with
/// no headers, so `read_bytes` uses a single seek+read. Some dumps (often from
/// CD-burning tools that saved the full raw sector) instead store 2352-byte raw
/// sectors — recognisable by the 12-byte sync pattern `00 FF×10 00` at offset 0.
/// [`IsoSectorReader::new`] auto-detects this and transparently strips the raw
/// sync+header (+ Mode 2 subheader) so callers still see a 2048-byte cooked view.
pub struct IsoSectorReader {
    file: BufReader<File>,
    /// Physical bytes per sector in the file: 2048 (cooked) or 2352 (raw).
    physical_sector_size: u64,
    /// Byte offset within each physical sector to the start of user data:
    /// 0 (cooked), 16 (raw Mode 1), or 24 (raw Mode 2 Form 1).
    data_offset: u64,
}

impl IsoSectorReader {
    /// Open an ISO image file for reading, auto-detecting raw 2352-byte layout.
    pub fn new(path: impl AsRef<Path>) -> Result<Self> {
        let mut file = BufReader::new(File::open(path.as_ref()).map_err(OpticaldiscsError::Io)?);

        // Sniff the first 16 bytes for the raw-sector sync pattern.
        let mut head = [0u8; 16];
        let (physical_sector_size, data_offset) = match file.read_exact(&mut head) {
            Ok(()) if head[..12] == RAW_SYNC => {
                // Byte 15 is the mode byte (after the 3-byte MSF address).
                let data_offset = match head[15] {
                    2 => MODE2_DATA_OFFSET,
                    _ => MODE1_DATA_OFFSET, // Mode 1 (and unknown → treat as Mode 1)
                };
                (RAW_SECTOR_SIZE, data_offset)
            }
            _ => (SECTOR_SIZE, 0),
        };
        file.seek(SeekFrom::Start(0))
            .map_err(OpticaldiscsError::Io)?;

        Ok(Self {
            file,
            physical_sector_size,
            data_offset,
        })
    }

    /// True if this image is stored as raw 2352-byte sectors.
    fn is_raw(&self) -> bool {
        self.physical_sector_size != SECTOR_SIZE
    }
}

impl SectorReader for IsoSectorReader {
    fn read_sector(&mut self, lba: u64) -> Result<Vec<u8>> {
        let offset = lba * self.physical_sector_size + self.data_offset;
        self.file
            .seek(SeekFrom::Start(offset))
            .map_err(OpticaldiscsError::Io)?;
        let mut buf = vec![0u8; SECTOR_SIZE as usize];
        self.file
            .read_exact(&mut buf)
            .map_err(OpticaldiscsError::Io)?;
        Ok(buf)
    }

    /// Cooked images use an optimised direct seek+read; raw images fall back to
    /// sector-at-a-time composition (the default impl) so the per-sector
    /// sync+header gaps are stripped correctly.
    fn read_bytes(&mut self, byte_offset: u64, length: usize) -> Result<Vec<u8>> {
        if self.is_raw() {
            // Sector-composed read (mirrors the trait default) to skip gaps.
            let sector_lba = byte_offset / SECTOR_SIZE;
            let sector_off = (byte_offset % SECTOR_SIZE) as usize;
            let mut out = Vec::with_capacity(length);
            let mut remaining = length;
            let mut lba = sector_lba;
            let mut offset = sector_off;
            while remaining > 0 {
                let sector = self.read_sector(lba)?;
                let available = sector.len().saturating_sub(offset);
                let take = remaining.min(available);
                out.extend_from_slice(&sector[offset..offset + take]);
                remaining -= take;
                lba += 1;
                offset = 0;
            }
            return Ok(out);
        }
        self.file
            .seek(SeekFrom::Start(byte_offset))
            .map_err(OpticaldiscsError::Io)?;
        let mut buf = vec![0u8; length];
        self.file
            .read_exact(&mut buf)
            .map_err(OpticaldiscsError::Io)?;
        Ok(buf)
    }
}

// ── Phase 3: BinCueSectorReader ──────────────────────────────────────────────

/// `SectorReader` for BIN/CUE disc images.
///
/// Reads a single data track from a raw `.bin` file, translating logical
/// 2048-byte sector addresses to physical byte offsets in the file, stripping
/// raw sector headers (sync + header bytes) transparently.
///
/// Create one via [`BinCueSectorReader::open`] by passing the data track from
/// [`crate::bincue::parse_cue_tracks`].
pub struct BinCueSectorReader {
    file: BufReader<File>,
    /// Byte offset in the BIN file where this track's sectors start.
    file_byte_offset: u64,
    /// Physical bytes per sector in the BIN file (2352, 2048, or 2336).
    physical_sector_size: u64,
    /// Byte offset within each physical sector to the start of user data.
    data_offset: u64,
}

impl BinCueSectorReader {
    /// Open a BIN/CUE data track for reading.
    ///
    /// `track` should be a data track. Use
    /// `parse_cue_tracks(cue_path)?.into_iter().find(|t| t.is_data())`
    /// to obtain one.
    pub fn open(track: &crate::bincue::BinTrack) -> Result<Self> {
        let file = File::open(&track.bin_path).map_err(OpticaldiscsError::Io)?;
        Ok(Self {
            file: BufReader::new(file),
            file_byte_offset: track.file_byte_offset,
            physical_sector_size: track.sector_size(),
            data_offset: track.data_offset(),
        })
    }

    /// Open a raw data track with an **explicit** sector geometry.
    ///
    /// Some containers (MDS/MDF, NRG, DiscJuggler) specify a physical sector size
    /// and in-sector data offset directly, including cases the fixed
    /// [`crate::bincue::TrackType`] table cannot express — e.g. 2448-byte sectors
    /// (2352 data + 96 bytes of appended subchannel). `data` need not be the same
    /// file as any `.cue`/`.bin`; it is the container/data file to read from.
    ///
    /// - `file_byte_offset`: byte position in `data` of the track's first sector
    /// - `physical_sector_size`: stride between sectors (e.g. 2352, 2448, 2048)
    /// - `data_offset`: bytes from each sector's start to its 2048-byte user data
    pub fn with_layout(
        data: &Path,
        file_byte_offset: u64,
        physical_sector_size: u64,
        data_offset: u64,
    ) -> Result<Self> {
        let file = File::open(data).map_err(OpticaldiscsError::Io)?;
        Ok(Self {
            file: BufReader::new(file),
            file_byte_offset,
            physical_sector_size,
            data_offset,
        })
    }
}

impl SectorReader for BinCueSectorReader {
    /// Read a 2048-byte cooked sector at `lba`.
    ///
    /// Physical layout per sector:
    /// `file_byte_offset + lba * physical_sector_size + data_offset`
    fn read_sector(&mut self, lba: u64) -> Result<Vec<u8>> {
        let physical_offset =
            self.file_byte_offset + lba * self.physical_sector_size + self.data_offset;
        self.file
            .seek(SeekFrom::Start(physical_offset))
            .map_err(OpticaldiscsError::Io)?;
        let mut buf = vec![0u8; SECTOR_SIZE as usize];
        self.file
            .read_exact(&mut buf)
            .map_err(OpticaldiscsError::Io)?;
        Ok(buf)
    }
}

// ── Phase 4: ChdSectorReader ─────────────────────────────────────────────────

/// `SectorReader` for CHD optical disc images.
///
/// Backed by [`libchdman_rs::cd::CdCookedReader`], which wraps MAME's
/// `chd_file` core and yields a 2048-byte cooked stream for the selected
/// track. Multi-track CHDs are supported: the 1-based track number from
/// [`crate::chd::ChdTrack`] is translated to libchdman-rs's 0-based index.
///
/// Create one via [`ChdSectorReader::open`] by passing the path to the `.chd`
/// file and the data track obtained from [`crate::chd::open_chd`].
pub struct ChdSectorReader {
    inner: libchdman_rs::cd::CdCookedReader,
}

impl ChdSectorReader {
    /// Open a CHD file and prepare to read sectors from `track`.
    ///
    /// Opens a fresh CHD handle and selects the requested track. Audio tracks
    /// are rejected by libchdman-rs — pass a data track (use
    /// [`crate::chd::ChdInfo::find_first_data_track`]).
    pub fn open(path: impl AsRef<Path>, track: &crate::chd::ChdTrack) -> Result<Self> {
        let path = path.as_ref();

        // Surface missing/unreadable files as Io rather than Chd.
        std::fs::metadata(path).map_err(OpticaldiscsError::Io)?;

        let path_str = path.to_str().ok_or_else(|| {
            OpticaldiscsError::Chd(format!("non-UTF-8 CHD path: {}", path.display()))
        })?;

        let chd = libchdman_rs::Chd::open(path_str, false, None)
            .map_err(|e| OpticaldiscsError::Chd(format!("failed to open CHD: {e:?}")))?;

        let track_index = track.track_no.checked_sub(1).ok_or_else(|| {
            OpticaldiscsError::Chd(format!(
                "invalid track_no {} (must be >= 1)",
                track.track_no
            ))
        })?;

        let inner =
            libchdman_rs::cd::CdCookedReader::open_track(chd, track_index).map_err(|e| {
                OpticaldiscsError::Chd(format!("open CHD track {}: {e:?}", track.track_no))
            })?;

        Ok(Self { inner })
    }
}

impl SectorReader for ChdSectorReader {
    /// Read a 2048-byte cooked sector at `lba` (track-relative).
    fn read_sector(&mut self, lba: u64) -> Result<Vec<u8>> {
        self.inner
            .seek(SeekFrom::Start(lba * SECTOR_SIZE))
            .map_err(OpticaldiscsError::Io)?;
        let mut buf = vec![0u8; SECTOR_SIZE as usize];
        self.inner
            .read_exact(&mut buf)
            .map_err(OpticaldiscsError::Io)?;
        Ok(buf)
    }
}

// ── GD-ROM high-density area reader ──────────────────────────────────────────

/// The Logical Block Address at which a Dreamcast GD-ROM's high-density area
/// (the game data) begins. Track 3 of a GD-ROM always starts here.
pub const GDROM_HD_START_LBA: u64 = 45000;

/// One high-density data track, tagged with the absolute LBA range it covers.
///
/// `reader` is scoped to the track and addressed **track-relative** (sector 0 is
/// the first sector of the track); [`GdromSectorReader`] converts absolute disc
/// LBAs into track-relative offsets before delegating to it.
pub struct GdromHdTrack {
    /// Absolute LBA where this track begins on the disc.
    pub start_lba: u64,
    /// Number of sectors the track covers (its coverage is
    /// `[start_lba, start_lba + frame_count)`).
    pub frame_count: u64,
    /// Track-relative reader (sector 0 = first sector of the track).
    pub reader: Box<dyn SectorReader>,
}

/// A `SectorReader` that presents a Dreamcast GD-ROM high-density area using the
/// disc's *absolute* LBAs, routing each read to the physical track that holds it.
///
/// The HD-area ISO 9660 volume's directory records reference **absolute** disc
/// LBAs (e.g. the root directory at 45020), while its Primary Volume Descriptor
/// is still addressed volume-relative at LBA 16. Crucially, the HD area can span
/// **several data tracks** separated by audio tracks — a file's data may live in
/// track 3, track 5, track 11, etc. — so a single fixed rebase (`lba - 45000`)
/// only reaches the first track and leaves the rest unreadable.
///
/// This reader holds every HD data track (sorted by `start_lba`) and, for a
/// requested absolute LBA, finds the track whose `[start_lba, start_lba +
/// frame_count)` range contains it and reads it track-relative. Volume-relative
/// low LBAs (the PVD at 16, path tables) live at the start of the first HD track
/// and pass through to it directly. The net effect is that the standard
/// [`crate::browse::iso9660`] browser reads the whole HD-area filesystem
/// correctly with no Dreamcast-specific knowledge.
pub struct GdromSectorReader {
    /// HD data tracks, sorted ascending by `start_lba`. Always non-empty.
    tracks: Vec<GdromHdTrack>,
}

impl GdromSectorReader {
    /// Wrap a single reader scoped to the GD-ROM high-density track (track 3),
    /// assumed to cover the entire HD area.
    ///
    /// Prefer [`GdromSectorReader::from_tracks`] when the HD area spans multiple
    /// data tracks; this single-track form cannot reach data stored past track 3.
    pub fn new(inner: Box<dyn SectorReader>) -> Self {
        Self::from_tracks(vec![GdromHdTrack {
            start_lba: GDROM_HD_START_LBA,
            frame_count: u64::MAX - GDROM_HD_START_LBA,
            reader: inner,
        }])
    }

    /// Build a reader over all high-density data tracks.
    ///
    /// `tracks` need not be pre-sorted; it is sorted by `start_lba` here. Must be
    /// non-empty — the first track (lowest `start_lba`) also serves the
    /// volume-relative low LBAs such as the PVD at sector 16.
    pub fn from_tracks(mut tracks: Vec<GdromHdTrack>) -> Self {
        tracks.sort_by_key(|t| t.start_lba);
        debug_assert!(!tracks.is_empty(), "GD-ROM reader needs at least one track");
        Self { tracks }
    }
}

impl SectorReader for GdromSectorReader {
    fn read_sector(&mut self, lba: u64) -> Result<Vec<u8>> {
        // Volume-relative low sectors (the PVD at 16, path tables) live at the
        // start of the first HD track — read them there directly.
        if lba < GDROM_HD_START_LBA {
            return self.tracks[0].reader.read_sector(lba);
        }
        // Otherwise route the absolute LBA to the track that physically holds it.
        for t in &mut self.tracks {
            if lba >= t.start_lba && lba < t.start_lba.saturating_add(t.frame_count) {
                return t.reader.read_sector(lba - t.start_lba);
            }
        }
        Err(OpticaldiscsError::Io(std::io::Error::new(
            std::io::ErrorKind::UnexpectedEof,
            format!("GD-ROM LBA {lba} is not within any high-density data track"),
        )))
    }
}

// ── Absolute-LBA rebasing reader ─────────────────────────────────────────────

/// A `SectorReader` that rebases absolute directory LBAs onto a track-relative
/// inner reader.
///
/// Some images author their ISO 9660 volume with an absolute disc base: the
/// Primary Volume Descriptor is still read volume-relative at LBA 16, but every
/// directory extent stores an **absolute** disc LBA (`base_lba + relative`).
/// DiscJuggler (`.cdi`) Dreamcast GD-ROM rips do this — the high-density
/// session's `start_address` is the base (e.g. 45000, or 11702 for a rebuilt
/// rip). This reader passes low LBAs (below `base_lba`: the PVD, path tables)
/// straight through and subtracts `base_lba` from absolute directory LBAs before
/// delegating, so the standard ISO 9660 browser reads the volume with no
/// format-specific knowledge.
///
/// With `base_lba == 0` it is a transparent pass-through.
pub struct RebaseSectorReader {
    base_lba: u64,
    inner: Box<dyn SectorReader>,
}

impl RebaseSectorReader {
    /// Wrap `inner` (a track-relative reader whose sector 0 is the volume's LBA
    /// 0), rebasing absolute LBAs `>= base_lba` by `base_lba`.
    pub fn new(inner: Box<dyn SectorReader>, base_lba: u64) -> Self {
        Self { base_lba, inner }
    }
}

impl SectorReader for RebaseSectorReader {
    fn read_sector(&mut self, lba: u64) -> Result<Vec<u8>> {
        let target = if lba < self.base_lba {
            lba
        } else {
            lba - self.base_lba
        };
        self.inner.read_sector(target)
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;

    /// Build one raw 2352-byte sector carrying `data` as its cooked payload.
    fn raw_sector(mode: u8, data: &[u8]) -> Vec<u8> {
        let mut s = vec![0u8; RAW_SECTOR_SIZE as usize];
        s[..12].copy_from_slice(&RAW_SYNC);
        s[15] = mode;
        let off = if mode == 2 {
            MODE2_DATA_OFFSET
        } else {
            MODE1_DATA_OFFSET
        } as usize;
        let n = data.len().min(SECTOR_SIZE as usize);
        s[off..off + n].copy_from_slice(&data[..n]);
        s
    }

    fn write_tmp_iso(bytes: &[u8]) -> tempfile::NamedTempFile {
        let mut f = tempfile::Builder::new().suffix(".iso").tempfile().unwrap();
        f.write_all(bytes).unwrap();
        f.flush().unwrap();
        f
    }

    /// A cooked `.iso` is read at 2048-byte stride with no offset.
    #[test]
    fn cooked_iso_reads_directly() {
        let mut img = vec![0u8; 18 * SECTOR_SIZE as usize];
        // Marker at start of cooked sector 16.
        let off = 16 * SECTOR_SIZE as usize;
        img[off..off + 5].copy_from_slice(b"CD001");
        let f = write_tmp_iso(&img);
        let mut r = IsoSectorReader::new(f.path()).unwrap();
        assert!(!r.is_raw());
        assert_eq!(&r.read_sector(16).unwrap()[..5], b"CD001");
        assert_eq!(&r.read_bytes(16 * SECTOR_SIZE, 5).unwrap(), b"CD001");
    }

    /// A raw 2352-byte Mode 1 `.iso` is auto-detected and the sync/header
    /// stripped so callers still see cooked 2048-byte sectors.
    #[test]
    fn raw_mode1_iso_is_detected_and_stripped() {
        let mut sectors: Vec<u8> = Vec::new();
        for lba in 0..18u8 {
            let mut data = vec![0u8; SECTOR_SIZE as usize];
            if lba == 16 {
                data[..5].copy_from_slice(b"CD001");
                data[100..105].copy_from_slice(b"HELLO");
            }
            sectors.extend_from_slice(&raw_sector(1, &data));
        }
        let f = write_tmp_iso(&sectors);
        let mut r = IsoSectorReader::new(f.path()).unwrap();
        assert!(r.is_raw());
        assert_eq!(r.physical_sector_size, RAW_SECTOR_SIZE);
        assert_eq!(r.data_offset, MODE1_DATA_OFFSET);
        assert_eq!(&r.read_sector(16).unwrap()[..5], b"CD001");
        // read_bytes must compose across the raw sector gaps correctly.
        assert_eq!(&r.read_bytes(16 * SECTOR_SIZE + 100, 5).unwrap(), b"HELLO");
    }

    /// The GD-ROM reader rebases absolute HD-area LBAs into the track while
    /// passing volume-relative low LBAs (the PVD at 16) straight through.
    #[test]
    fn gdrom_reader_rebases_absolute_lbas() {
        struct Track(Vec<u8>);
        impl SectorReader for Track {
            fn read_sector(&mut self, lba: u64) -> Result<Vec<u8>> {
                let off = (lba * SECTOR_SIZE) as usize;
                Ok(self.0[off..off + SECTOR_SIZE as usize].to_vec())
            }
        }
        // 25-sector track: mark sector 16 (PVD slot) and sector 20 (abs 45020).
        let mut buf = vec![0u8; 25 * SECTOR_SIZE as usize];
        buf[16 * SECTOR_SIZE as usize] = 0xAA;
        buf[20 * SECTOR_SIZE as usize] = 0xBB;
        let mut r = GdromSectorReader::new(Box::new(Track(buf)));

        // LBA 16 < 45000 → track-relative 16.
        assert_eq!(r.read_sector(16).unwrap()[0], 0xAA);
        // Absolute LBA 45020 → track-relative 20.
        assert_eq!(r.read_sector(GDROM_HD_START_LBA + 20).unwrap()[0], 0xBB);
    }

    /// A GD-ROM whose high-density area spans two data tracks separated by an
    /// audio gap: each absolute LBA must route to the track that holds it, read
    /// track-relative — a single fixed `lba - 45000` rebase would misdirect any
    /// read past the first track. Volume-relative low LBAs go to the first track.
    #[test]
    fn gdrom_reader_routes_across_multiple_tracks() {
        use std::sync::atomic::{AtomicU64, Ordering};
        use std::sync::Arc;

        /// Reader whose sectors are all filled with `tag`, so a returned byte
        /// identifies which track served the read; also records the last LBA.
        struct Tagged {
            tag: u8,
            last: Arc<AtomicU64>,
        }
        impl SectorReader for Tagged {
            fn read_sector(&mut self, lba: u64) -> Result<Vec<u8>> {
                self.last.store(lba, Ordering::SeqCst);
                Ok(vec![self.tag; SECTOR_SIZE as usize])
            }
        }

        let last0 = Arc::new(AtomicU64::new(u64::MAX));
        let last1 = Arc::new(AtomicU64::new(u64::MAX));
        // Track A: absolute 45000..45000+1000. Track B: absolute 300000..300000+1000.
        let mut r = GdromSectorReader::from_tracks(vec![
            GdromHdTrack {
                start_lba: GDROM_HD_START_LBA,
                frame_count: 1000,
                reader: Box::new(Tagged {
                    tag: 0xA0,
                    last: last0.clone(),
                }),
            },
            GdromHdTrack {
                start_lba: 300_000,
                frame_count: 1000,
                reader: Box::new(Tagged {
                    tag: 0xB0,
                    last: last1.clone(),
                }),
            },
        ]);

        // Volume-relative PVD sector 16 → first track, relative 16.
        assert_eq!(r.read_sector(16).unwrap()[0], 0xA0);
        assert_eq!(last0.load(Ordering::SeqCst), 16);

        // Absolute 45020 → track A, relative 20.
        assert_eq!(r.read_sector(45_020).unwrap()[0], 0xA0);
        assert_eq!(last0.load(Ordering::SeqCst), 20);

        // Absolute 300_500 → track B, relative 500 (a fixed -45000 rebase would
        // instead ask for 255_500 and hit the wrong track).
        assert_eq!(r.read_sector(300_500).unwrap()[0], 0xB0);
        assert_eq!(last1.load(Ordering::SeqCst), 500);

        // An LBA in the audio gap between the tracks belongs to neither → error.
        assert!(r.read_sector(200_000).is_err());
    }

    /// Mode 2 raw sectors put user data at offset 24.
    #[test]
    fn raw_mode2_iso_uses_offset_24() {
        let mut sectors: Vec<u8> = Vec::new();
        for lba in 0..18u8 {
            let mut data = vec![0u8; SECTOR_SIZE as usize];
            if lba == 16 {
                data[..5].copy_from_slice(b"CD001");
            }
            sectors.extend_from_slice(&raw_sector(2, &data));
        }
        let f = write_tmp_iso(&sectors);
        let mut r = IsoSectorReader::new(f.path()).unwrap();
        assert!(r.is_raw());
        assert_eq!(r.data_offset, MODE2_DATA_OFFSET);
        assert_eq!(&r.read_sector(16).unwrap()[..5], b"CD001");
    }
}