pcenginecd_rust/
disc.rs

1//! The disc: a track table and sectors (`disc.py`).
2//!
3//! Addresses. A sector's **LBA** is its index in the disc image: LBA 0 is the first stored
4//! sector, which is absolute time 00:02:00 (the two-second lead-in gap is not stored). So `msf =
5//! lba + 150` frames. The SCSI READ command and every track start in this module are in this LBA,
6//! and the `READ TOC` answers are MSF = LBA + 150 [doc: pcetech 8; emu: Mesen2 `PceScsiBus.cpp`,
7//! Geargrafx `cdrom_physical_image.cpp` read absolute image sectors]. A raw sector is 2352 bytes;
8//! a Mode 1 data sector keeps its 2048 payload bytes at +16 (12 sync, 4 header).
9//!
10//! **This is the one module designed for the browser and not only transcribed.** The table of
11//! contents and the LBA/MSF logic are the reference's; where the reference opens files (and
12//! expands a CHD with `chdman`), this crate has three separate pieces:
13//!
14//! - [`SectorSource`]: the sector store as a trait, "raw sector `lba` into this buffer".
15//!   [`MemorySource`] holds a whole image (the tests' synthetic discs); [`CueSource`] maps an
16//!   LBA to a byte range of one of a cue sheet's files and asks an [`ImageReader`] for it, which
17//!   a web page implements over slices of the user's file (a closure `(file, offset, buffer) ->
18//!   bytes read` is one), [`MemoryImages`] over whole files in memory and, natively only,
19//!   [`FileImages`] over open files.
20//! - [`parse_cue`]: the cue sheet from its text plus a way to learn each named file's length, so
21//!   it needs no filesystem. The grammar is the reference's (`FILE`, `TRACK` with `MODE1/2352` or
22//!   `AUDIO`, `INDEX 00/01`; several FILEs laid end to end; `PREGAP` refused).
23//! - [`Disc`]: tracks plus a source. `Disc::from_cue_path` (native) is the reference's
24//!   `Disc.from_cue`.
25//!
26//! **CHD is not read here** (the reference shells out to `chdman`, which a browser has not, and a
27//! CHD reader would be a separately licensed dependency): extract a CHD to bin/cue first, as the
28//! gate does.
29//!
30//! Other differences forced by Rust: LBAs are `i64` and the divisions are Python's (an audio
31//! command may name a position before LBA 0); `Disc` keeps its source behind a `RefCell` so the
32//! drive and the audio player can share one disc (`Rc<Disc>`), as the reference's two objects
33//! share one; `to_bcd` returns the low eight bits (the reference returns an unbounded integer
34//! for a value past 159, which a register read could not hold).
35
36use std::cell::RefCell;
37
38use pcengine_rust::machine::py_floordiv;
39use sha1::{Digest, Sha1};
40
41pub const RAW_SECTOR: usize = 2352;
42pub const DATA_SECTOR: usize = 2048;
43pub const FRAMES_PER_SECOND: i64 = 75;
44/// the two-second gap before LBA 0 [doc: Red Book; emu: all four]
45pub const LEAD_IN_FRAMES: i64 = 150;
46pub const SYNC: [u8; 12] = [
47    0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00,
48];
49
50pub fn to_bcd(value: i64) -> u8 {
51    ((py_floordiv(value, 10) << 4) | value.rem_euclid(10)) as u8
52}
53
54pub fn from_bcd(value: u8) -> i64 {
55    (value >> 4) as i64 * 10 + (value & 15) as i64
56}
57
58/// The absolute MSF of an LBA (the +150 lead-in applied).
59pub fn lba_to_msf(lba: i64) -> (i64, i64, i64) {
60    relative_msf(lba + LEAD_IN_FRAMES)
61}
62
63pub fn msf_to_lba(minutes: i64, seconds: i64, frames: i64) -> i64 {
64    (minutes * 60 + seconds) * FRAMES_PER_SECOND + frames - LEAD_IN_FRAMES
65}
66
67/// A track-relative position (no lead-in).
68pub fn relative_msf(frames: i64) -> (i64, i64, i64) {
69    (
70        py_floordiv(frames, 60 * FRAMES_PER_SECOND),
71        py_floordiv(frames, FRAMES_PER_SECOND).rem_euclid(60),
72        frames.rem_euclid(75),
73    )
74}
75
76pub fn msf_frames(minutes: i64, seconds: i64, frames: i64) -> i64 {
77    (minutes * 60 + seconds) * FRAMES_PER_SECOND + frames
78}
79
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81pub struct Track {
82    pub number: i64,
83    pub is_data: bool,
84    /// LBA of INDEX 01
85    pub start: i64,
86    /// LBA one past the track's last sector
87    pub end: i64,
88    /// LBA of INDEX 00 (the pregap), if the cue gives one
89    pub index0: Option<i64>,
90}
91
92// --- the sector store -----------------------------------------------------------------------------
93
94/// Where a disc's sectors come from. `lba` is inside the disc (`0 <= lba < sector_count`: `Disc`
95/// answers zeros outside by itself); the source fills all 2352 bytes, with zeros for whatever
96/// it cannot read.
97pub trait SectorSource {
98    fn read_sector(&mut self, lba: i64, out: &mut [u8; RAW_SECTOR]);
99}
100
101/// A whole disc image in memory, the sectors end to end.
102pub struct MemorySource {
103    pub data: Vec<u8>,
104}
105
106impl SectorSource for MemorySource {
107    fn read_sector(&mut self, lba: i64, out: &mut [u8; RAW_SECTOR]) {
108        let from = lba as usize * RAW_SECTOR;
109        let have = self.data.len().saturating_sub(from).min(RAW_SECTOR);
110        out[..have].copy_from_slice(&self.data[from..from + have]);
111        out[have..].fill(0);
112    }
113}
114
115/// Bytes of the files a cue sheet names: `out.len()` bytes of file `file` (its index in
116/// `CueSheet::files`) from `offset`; returns how many were read (fewer at the end of a file).
117/// A web page implements this over `Blob.slice` of the user's file, or hands in a closure.
118pub trait ImageReader {
119    fn read_at(&mut self, file: usize, offset: u64, out: &mut [u8]) -> usize;
120}
121
122impl<F: FnMut(usize, u64, &mut [u8]) -> usize> ImageReader for F {
123    fn read_at(&mut self, file: usize, offset: u64, out: &mut [u8]) -> usize {
124        self(file, offset, out)
125    }
126}
127
128/// The cue sheet's files, each whole in memory.
129pub struct MemoryImages(pub Vec<Vec<u8>>);
130
131impl ImageReader for MemoryImages {
132    fn read_at(&mut self, file: usize, offset: u64, out: &mut [u8]) -> usize {
133        let Some(data) = self.0.get(file) else {
134            return 0;
135        };
136        let from = (offset as usize).min(data.len());
137        let count = (data.len() - from).min(out.len());
138        out[..count].copy_from_slice(&data[from..from + count]);
139        count
140    }
141}
142
143/// The cue sheet's files on disk (native only: nothing else in the crate touches a file).
144#[cfg(not(target_arch = "wasm32"))]
145pub struct FileImages {
146    files: Vec<std::fs::File>,
147}
148
149#[cfg(not(target_arch = "wasm32"))]
150impl FileImages {
151    /// Open every file of `sheet`, named relative to `directory` (the cue's own).
152    pub fn open(sheet: &CueSheet, directory: &std::path::Path) -> Result<FileImages, String> {
153        let mut files = Vec::new();
154        for file in &sheet.files {
155            let path = directory.join(&file.name);
156            files.push(
157                std::fs::File::open(&path)
158                    .map_err(|error| format!("{}: {error}", path.display()))?,
159            );
160        }
161        Ok(FileImages { files })
162    }
163}
164
165#[cfg(not(target_arch = "wasm32"))]
166impl ImageReader for FileImages {
167    fn read_at(&mut self, file: usize, offset: u64, out: &mut [u8]) -> usize {
168        use std::io::{Read, Seek, SeekFrom};
169        let Some(handle) = self.files.get_mut(file) else {
170            return 0;
171        };
172        if handle.seek(SeekFrom::Start(offset)).is_err() {
173            return 0;
174        }
175        let mut done = 0;
176        while done < out.len() {
177            match handle.read(&mut out[done..]) {
178                Ok(0) | Err(_) => break,
179                Ok(count) => done += count,
180            }
181        }
182        done
183    }
184}
185
186/// The sectors of a cue sheet's files, through an `ImageReader`.
187pub struct CueSource<R: ImageReader> {
188    /// (first LBA, sectors) of each file
189    spans: Vec<(i64, i64)>,
190    pub reader: R,
191}
192
193impl<R: ImageReader> CueSource<R> {
194    pub fn new(sheet: &CueSheet, reader: R) -> CueSource<R> {
195        CueSource {
196            spans: sheet
197                .files
198                .iter()
199                .map(|file| (file.first_lba, file.sectors))
200                .collect(),
201            reader,
202        }
203    }
204}
205
206impl<R: ImageReader> SectorSource for CueSource<R> {
207    fn read_sector(&mut self, lba: i64, out: &mut [u8; RAW_SECTOR]) {
208        let mut done = 0;
209        for (file, &(first, sectors)) in self.spans.iter().enumerate() {
210            if first <= lba && lba < first + sectors {
211                let offset = (lba - first) as u64 * RAW_SECTOR as u64;
212                done = self.reader.read_at(file, offset, out).min(RAW_SECTOR);
213                break;
214            }
215        }
216        out[done..].fill(0);
217    }
218}
219
220// --- the cue sheet ----------------------------------------------------------------------------------
221
222#[derive(Clone, Debug, PartialEq, Eq)]
223pub struct CueFile {
224    /// as the cue names it (relative to the cue)
225    pub name: String,
226    /// whole raw sectors in the file
227    pub sectors: i64,
228    /// the LBA of the file's first sector: the files lie end to end, as one disc
229    pub first_lba: i64,
230}
231
232/// A parsed cue sheet: where each file lies on the disc, and the track table.
233#[derive(Clone, Debug, PartialEq, Eq)]
234pub struct CueSheet {
235    pub files: Vec<CueFile>,
236    pub tracks: Vec<Track>,
237    pub sector_count: i64,
238}
239
240impl CueSheet {
241    /// The file and the byte offset in it that hold sector `lba`.
242    pub fn locate(&self, lba: i64) -> Option<(usize, u64)> {
243        self.files.iter().enumerate().find_map(|(index, file)| {
244            (file.first_lba <= lba && lba < file.first_lba + file.sectors)
245                .then(|| (index, (lba - file.first_lba) as u64 * RAW_SECTOR as u64))
246        })
247    }
248}
249
250struct Entry {
251    number: i64,
252    is_data: bool,
253    file: usize,
254    idx0: Option<i64>,
255    idx1: Option<i64>,
256}
257
258fn is_word(c: char) -> bool {
259    c.is_alphanumeric() || c == '_'
260}
261
262/// `KEYWORD\s+rest` at the start of `line`, case-insensitive: the rest, its leading whitespace
263/// removed.
264fn after_keyword<'a>(line: &'a str, keyword: &str) -> Option<&'a str> {
265    let head = line.get(..keyword.len())?;
266    if !head.eq_ignore_ascii_case(keyword) {
267        return None;
268    }
269    let rest = &line[keyword.len()..];
270    let trimmed = rest.trim_start();
271    (trimmed.len() < rest.len()).then_some(trimmed)
272}
273
274/// The reference's `FILE\s+"?(.*?)"?\s+\w+$`: the name between optional quotes, before the
275/// last word of the line.
276fn file_name(line: &str) -> Option<&str> {
277    let rest = after_keyword(line, "FILE")?;
278    let before = rest.trim_end_matches(is_word);
279    if before.len() == rest.len() {
280        return None; // no closing word (BINARY, WAVE, ...)
281    }
282    let name = before.trim_end();
283    if name.len() == before.len() {
284        return None; // the word is not set off by whitespace
285    }
286    let name = name.strip_prefix('"').unwrap_or(name);
287    Some(name.strip_suffix('"').unwrap_or(name))
288}
289
290/// A leading run of ASCII digits as a number, and what follows it.
291fn number(text: &str) -> Option<(i64, &str)> {
292    let end = text
293        .find(|c: char| !c.is_ascii_digit())
294        .unwrap_or(text.len());
295    let value = text[..end].parse().ok()?;
296    Some((value, &text[end..]))
297}
298
299/// The reference's `TRACK\s+(\d+)\s+(\S+)`.
300fn track_line(line: &str) -> Option<(i64, &str)> {
301    let rest = after_keyword(line, "TRACK")?;
302    let (value, rest) = number(rest)?;
303    let mode = rest.trim_start();
304    if mode.len() == rest.len() || mode.is_empty() {
305        return None;
306    }
307    Some((value, mode.split_whitespace().next()?))
308}
309
310/// The reference's `INDEX\s+(\d+)\s+(\d+):(\d+):(\d+)`.
311fn index_line(line: &str) -> Option<(i64, i64)> {
312    let rest = after_keyword(line, "INDEX")?;
313    let (index, rest) = number(rest)?;
314    let time = rest.trim_start();
315    if time.len() == rest.len() {
316        return None;
317    }
318    let (minutes, rest) = number(time)?;
319    let (seconds, rest) = number(rest.strip_prefix(':')?)?;
320    let (frames, _) = number(rest.strip_prefix(':')?)?;
321    Some((index, msf_frames(minutes, seconds, frames)))
322}
323
324/// A cue sheet from its text. `file_bytes` answers the length in bytes of a file the sheet
325/// names (a page asks the `File` the user chose; `Disc::from_cue_path` asks the filesystem).
326///
327/// Handles `FILE`, `TRACK` (MODE1/2352, AUDIO) and `INDEX 00/01`; several FILEs are laid end to
328/// end, as one disc. Cue times are positions in their file (chdman writes them so, with the
329/// pregap stored). `PREGAP` (an unstored gap) is not supported.
330pub fn parse_cue(
331    text: &str,
332    file_bytes: &mut dyn FnMut(&str) -> Result<u64, String>,
333) -> Result<CueSheet, String> {
334    let mut files: Vec<(String, i64)> = Vec::new();
335    let mut entries: Vec<Entry> = Vec::new();
336    for raw in text.split(['\n', '\r']) {
337        let line = raw.trim();
338        if let Some(name) = file_name(line) {
339            let sectors = (file_bytes(name)? / RAW_SECTOR as u64) as i64;
340            files.push((name.to_string(), sectors));
341        } else if let Some((number, mode)) = track_line(line) {
342            let mode = mode.to_uppercase();
343            if mode != "AUDIO" && mode != "MODE1/2352" {
344                return Err(format!("cue: unsupported track mode {mode}"));
345            }
346            if files.is_empty() {
347                return Err("cue: a TRACK before any FILE".to_string());
348            }
349            entries.push(Entry {
350                number,
351                is_data: mode != "AUDIO",
352                file: files.len() - 1,
353                idx0: None,
354                idx1: None,
355            });
356        } else if let Some((index, frames)) = index_line(line) {
357            let entry = entries.last_mut().ok_or("cue: an INDEX before any TRACK")?;
358            match index {
359                0 => entry.idx0 = Some(frames),
360                1 => entry.idx1 = Some(frames),
361                _ => {} // the reference keeps them and never reads them
362            }
363        } else if line.to_uppercase().starts_with("PREGAP") {
364            return Err("cue: PREGAP (an unstored gap) is not supported".to_string());
365        }
366    }
367    if files.is_empty() || entries.is_empty() {
368        return Err("cue: no FILE or TRACK".to_string());
369    }
370    let mut lba = 0;
371    let mut placed = Vec::new();
372    for (name, sectors) in files {
373        placed.push(CueFile {
374            name,
375            sectors,
376            first_lba: lba,
377        });
378        lba += sectors;
379    }
380    let mut tracks = Vec::new();
381    for (i, e) in entries.iter().enumerate() {
382        let missing = || format!("cue: track {} has no INDEX 01", e.number);
383        let base = placed[e.file].first_lba;
384        let start = base + e.idx1.ok_or_else(missing)?;
385        let index0 = e.idx0.map(|frames| base + frames);
386        let end = match entries.get(i + 1) {
387            Some(n) => {
388                let nbase = placed[n.file].first_lba;
389                match n.idx0 {
390                    Some(frames) => nbase + frames,
391                    None => {
392                        nbase
393                            + n.idx1
394                                .ok_or_else(|| format!("cue: track {} has no INDEX 01", n.number))?
395                    }
396                }
397            }
398            None => lba,
399        };
400        tracks.push(Track {
401            number: e.number,
402            is_data: e.is_data,
403            start,
404            end,
405            index0,
406        });
407    }
408    Ok(CueSheet {
409        files: placed,
410        tracks,
411        sector_count: lba,
412    })
413}
414
415// --- the disc ---------------------------------------------------------------------------------------
416
417/// A sector store plus a TOC. `sector_count` is the number of LBAs.
418///
419/// Media, not state: a save state names the disc (`state_identity`), it does not hold it.
420pub struct Disc {
421    pub tracks: Vec<Track>,
422    pub sector_count: i64,
423    source: RefCell<Box<dyn SectorSource>>,
424}
425
426impl Disc {
427    pub fn new(tracks: Vec<Track>, sector_count: i64, source: Box<dyn SectorSource>) -> Disc {
428        Disc {
429            tracks,
430            sector_count,
431            source: RefCell::new(source),
432        }
433    }
434
435    /// What a save state records of the disc: its table of contents (not its sectors, so two
436    /// discs with one layout are not told apart). The same digest as the reference's: the SHA-1
437    /// of Python's `repr(([(number, is_data, start, end), ...], sector_count))`.
438    pub fn state_identity(&self) -> String {
439        let toc: Vec<String> = self
440            .tracks
441            .iter()
442            .map(|t| {
443                let data = if t.is_data { "True" } else { "False" };
444                format!("({}, {}, {}, {})", t.number, data, t.start, t.end)
445            })
446            .collect();
447        let text = format!("([{}], {})", toc.join(", "), self.sector_count);
448        Sha1::digest(text.as_bytes())
449            .iter()
450            .map(|byte| format!("{byte:02x}"))
451            .collect()
452    }
453
454    // -- construction -------------------------------------------------------------------------
455
456    /// The disc of a parsed cue sheet, its sectors from `source` (a `CueSource` over the
457    /// sheet's files, or anything else that answers the sheet's LBAs).
458    pub fn from_cue(sheet: &CueSheet, source: Box<dyn SectorSource>) -> Disc {
459        Disc::new(sheet.tracks.clone(), sheet.sector_count, source)
460    }
461
462    /// A bin/cue pair on disk, read in place (the reference's `Disc.from_cue`).
463    #[cfg(not(target_arch = "wasm32"))]
464    pub fn from_cue_path(cue_path: impl AsRef<std::path::Path>) -> Result<Disc, String> {
465        let cue_path = cue_path.as_ref();
466        let named = |error: String| format!("{}: {error}", cue_path.display());
467        let bytes = std::fs::read(cue_path).map_err(|error| named(error.to_string()))?;
468        let text = String::from_utf8_lossy(&bytes);
469        let directory = cue_path.parent().unwrap_or(std::path::Path::new("."));
470        let sheet = parse_cue(&text, &mut |name| {
471            let path = directory.join(name);
472            std::fs::metadata(&path)
473                .map(|meta| meta.len())
474                .map_err(|error| format!("{}: {error}", path.display()))
475        })
476        .map_err(named)?;
477        let images = FileImages::open(&sheet, directory)?;
478        Ok(Disc::from_cue(
479            &sheet,
480            Box::new(CueSource::new(&sheet, images)),
481        ))
482    }
483
484    /// A disc whose tracks are raw 2352-byte sectors in memory: `(is_data, bytes)` each.
485    /// Used by the tests (`tests/discs.rs` builds the bytes).
486    pub fn from_memory(tracks: Vec<(bool, Vec<u8>)>) -> Result<Disc, String> {
487        let mut out = Vec::new();
488        let mut data = Vec::new();
489        let mut lba = 0;
490        for (index, (is_data, payload)) in tracks.into_iter().enumerate() {
491            if payload.len() % RAW_SECTOR != 0 {
492                return Err("a memory track is whole raw sectors".to_string());
493            }
494            let count = (payload.len() / RAW_SECTOR) as i64;
495            out.push(Track {
496                number: index as i64 + 1,
497                is_data,
498                start: lba,
499                end: lba + count,
500                index0: None,
501            });
502            data.extend_from_slice(&payload);
503            lba += count;
504        }
505        Ok(Disc::new(out, lba, Box::new(MemorySource { data })))
506    }
507
508    // -- reading ------------------------------------------------------------------------------
509
510    /// 2352 bytes of sector `lba`; zeros outside the disc.
511    pub fn read_raw(&self, lba: i64) -> [u8; RAW_SECTOR] {
512        let mut out = [0u8; RAW_SECTOR];
513        if 0 <= lba && lba < self.sector_count {
514            self.source.borrow_mut().read_sector(lba, &mut out);
515        }
516        out
517    }
518
519    /// The 2048-byte user data of a Mode 1 sector (zeros if it is not a data sector).
520    pub fn read_data(&self, lba: i64) -> [u8; DATA_SECTOR] {
521        let mut out = [0u8; DATA_SECTOR];
522        if self.track_at(lba).is_some_and(|track| track.is_data) {
523            out.copy_from_slice(&self.read_raw(lba)[16..16 + DATA_SECTOR]);
524        }
525        out
526    }
527
528    // -- the table of contents ----------------------------------------------------------------
529
530    /// The track whose range (INDEX 00 .. end) holds `lba`.
531    pub fn track_at(&self, lba: i64) -> Option<&Track> {
532        self.tracks.iter().find(|t| {
533            let first = t.index0.unwrap_or(t.start);
534            first <= lba && lba < t.end
535        })
536    }
537
538    pub fn track(&self, number: i64) -> Option<&Track> {
539        self.tracks.iter().find(|t| t.number == number)
540    }
541
542    /// The first track's number (0 for a disc without tracks, which the reference cannot
543    /// answer).
544    pub fn first_track(&self) -> i64 {
545        self.tracks.first().map_or(0, |t| t.number)
546    }
547
548    pub fn last_track(&self) -> i64 {
549        self.tracks.last().map_or(0, |t| t.number)
550    }
551
552    pub fn end_lba(&self) -> i64 {
553        self.sector_count
554    }
555}