//! The drive's SCSI-class controller: bus signals, phases, the REQ/ACK handshake, the commands //! (`scsi.py`). //! //! The CD unit's controller is not emulated as a microcontroller (there is no second CPU on this //! machine); it is a bus state machine that the System Card drives through `$1800-$1802` and //! `$1808` [hw: pcetech 8; emu: Mesen2 `PceScsiBus.cpp`, Geargrafx `scsi_controller.cpp`, //! Mednafen `scsicd.cpp`, ares `pcd/scsi.cpp`, MAME `pce_cd.cpp` all do the same]. Everything //! here is time in **master clocks** (21.477272 MHz); the unit calls `run_to(mclk)` before //! register accesses and the bus then runs its own timers up to that instant. //! //! Signals (`$1800` read): D3 I/O, D4 C/D, D5 MSG, D6 REQ, D7 BSY. Phases and the signals they //! hold: //! //! | phase | BSY | C/D | I/O | MSG | REQ | what the CPU does | //! | ----------- | --- | --- | --- | --- | --- | -------------------------------------- | //! | bus free | | | | | | writes `$1800` (selects the drive) | //! | command | 1 | 1 | | | 1 | writes command bytes to `$1801` | //! | data in | 1 | | 1 | | (1) | reads bytes from `$1801`/`$1808` | //! | status | 1 | 1 | 1 | | (1) | reads the status byte | //! | message in | 1 | 1 | 1 | 1 | (1) | reads the message byte | //! | busy | 1 | | | | | waits (an audio command in progress) | //! //! Every byte is a REQ/ACK handshake: the drive raises REQ, the CPU sets ACK (`$1802` bit 7), //! the drive drops REQ, the CPU drops ACK. IRQ2 sources (`$1803` bits): data-in 0x40 and //! status/message 0x20 are REQ held in those phases (`CdUnit` turns the levels into IRQ2). //! //! The timings are `ScsiSwitches` (the reference's class attributes), all provisional (U8): the //! only measurements of this hardware are Shadoff's seek table (tier 3) and the test ROMs //! Mesen2's author ran on a real console (tier 5, claimed in his source comments). //! //! Differences forced by Rust: //! //! - **The bus owns the audio player** (`bus.cdda`), where the reference's bus and unit hold //! the same object; the player's `on_good_status` callback is `cdda.good_status_due`, answered //! here right after the player ran (`run_cdda`). //! - **The `irq` callback** into the unit is a list, `irq_changes`, of `(mask, level)` in the //! order the reference would have called; the unit applies it after each call into the bus //! (nothing the callback reads can change in between). //! - The command list `cmd`, the buffer `out` and the ports are bytes; a sector with no disc //! in the drive (the reference asserts) reads as zeros. use std::collections::VecDeque; use std::rc::Rc; use pcengine_rust::machine::MASTER_HZ; use serde::{Deserialize, Serialize}; use crate::cdda::CddaPlayer; use crate::disc::{from_bcd, lba_to_msf, msf_to_lba, relative_msf, to_bcd, Disc, DATA_SECTOR}; use crate::seek::seek_time_ms; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum Phase { BusFree, Command, DataIn, MessageIn, Status, Busy, } impl Phase { /// The reference's `Phase.value`. pub fn value(self) -> &'static str { match self { Phase::BusFree => "bus free", Phase::Command => "command", Phase::DataIn => "data in", Phase::MessageIn => "message in", Phase::Status => "status", Phase::Busy => "busy", } } } /// What a queued drive timer does when it fires. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum Update { None, CommandPhase, Req, DataInPhase, GoodStatus, } // SCSI status byte pub const GOOD: u8 = 0x00; pub const CHECK_CONDITION: u8 = 0x02; // Commands the System Card issues [hw: pcetech 8]. REQUEST SENSE (0x03) is a standard SCSI-2 // command the BIOS sends after commands; Mesen2 does not implement it (it answers Good with no // data), Mednafen sends an 18-byte fixed-format block (C14). pub const CMD_TEST_UNIT_READY: u8 = 0x00; pub const CMD_REQUEST_SENSE: u8 = 0x03; pub const CMD_READ: u8 = 0x08; pub const CMD_AUDIO_START: u8 = 0xD8; pub const CMD_AUDIO_END: u8 = 0xD9; pub const CMD_PAUSE: u8 = 0xDA; pub const CMD_READ_SUBQ: u8 = 0xDD; pub const CMD_READ_TOC: u8 = 0xDE; pub fn command_length(op: u8) -> Option { match op { CMD_TEST_UNIT_READY | CMD_REQUEST_SENSE | CMD_READ => Some(6), CMD_AUDIO_START | CMD_AUDIO_END | CMD_PAUSE | CMD_READ_SUBQ | CMD_READ_TOC => Some(10), _ => None, } } // Sense keys / additional codes used (SCSI-2) pub const SENSE_NOT_READY: u8 = 0x02; pub const SENSE_ILLEGAL_REQUEST: u8 = 0x05; pub const ASC_MEDIUM_NOT_PRESENT: u8 = 0x3A; pub const ASC_INVALID_COMMAND: u8 = 0x20; pub const ASC_LBA_OUT_OF_RANGE: u8 = 0x21; /// Timing (master clocks), provisional; tier in the comment. The reference's `ScsiBus` class /// attributes, with its defaults. /// /// [emu: Mesen2, "approximations ... haven't been validated beyond what validator.pce checks"] /// Mesen2 counts these in units of 3 master clocks (one fast CPU cycle); converted here. #[derive(Clone, Copy, Debug, PartialEq)] pub struct ScsiSwitches { /// tier 5: SEL to the drive entering the command phase pub sel_to_command_phase: i64, /// tier 5: REQ for the next command byte pub next_command_byte_req: i64, /// tier 5, deliberately ~100x shorter than the real spin-up pub test_unit_ready: i64, /// tier 5 pub toc_answer: i64, /// tier 5 pub subq_answer: i64, /// tier 5: last data byte taken to the good status pub done_status: i64, /// tier 5: SEL during data in ("verificator.pce") pub abort_to_command: i64, /// tier 5: an auto-ack pulse ("hardware measurements show ~1 us") pub ack_clear: i64, /// [hw: Red Book] single speed: 75 sectors a second; one sector's bytes are delivered this /// often (tier 2 for the rate, the delivery phase is U8). pub sector_clocks: i64, /// [emu: Mesen2 comment, Sherlock Holmes] software that misses a sector waits for a /// re-read; tier 5 pub reread_penalty_ms: i64, /// The seek model is `seek.rs` (Shadoff's measurements, tier 3 for the shape). pub seek_scale: f64, /// Bytes in the READ TOC answers for kinds 0 (first/last track), 1 (lead-out), 2 (a /// track). Mednafen sends 2, 3, 4 ("returned data lengths on real PCE are not confirmed", /// its own comment); Mesen2 sends 4, 4, 4 (C15). Tier 5 both; the BIOS must read the same /// number. pub toc_answer_bytes: [usize; 3], /// An opcode the drive does not know (C22): Good status with no data [emu: Mesen2, /// Geargrafx], or CHECK CONDITION with ILLEGAL REQUEST / INVALID COMMAND for REQUEST SENSE /// to report [emu: Mednafen `scsicd.cpp`; the SCSI-2 rule for an unsupported opcode, which /// this drive is not known to follow]. True selects the second. Either way the answer comes /// at the first byte (Mednafen first waits for its opcode group's CDB length). pub unknown_command_check_condition: bool, } impl Default for ScsiSwitches { fn default() -> Self { ScsiSwitches { sel_to_command_phase: 25_000 * 3, next_command_byte_req: 1_000 * 3, test_unit_ready: 150_000 * 3, toc_answer: 3_000 * 3, subq_answer: 1_000 * 3, done_status: 1_000 * 3, abort_to_command: 300_000 * 3, ack_clear: 21, sector_clocks: MASTER_HZ * DATA_SECTOR as i64 / 153_600, reread_penalty_ms: 290, seek_scale: 1.0, toc_answer_bytes: [2, 3, 4], unknown_command_check_condition: false, } } } /// Signals, phase, timers and the command set. `irq_changes` collects (mask, level) when the /// REQ-held-in-a-phase conditions change (mask 0x40 data in, 0x20 status/message). #[derive(Serialize, Deserialize)] pub struct ScsiBus { #[serde(skip)] pub disc: Option>, pub cdda: CddaPlayer, #[serde(skip)] pub switches: ScsiSwitches, pub now: i64, /// (mclk, text) of commands, for the tests and runs #[serde(skip)] pub log: Vec<(i64, String)>, #[serde(skip)] pub record_log: bool, #[serde(skip)] pub irq_changes: Vec<(u8, bool)>, pub bsy: bool, pub sel: bool, pub cd: bool, pub io: bool, pub msg: bool, pub req: bool, pub ack: bool, pub atn: bool, pub rst: bool, pub phase: Phase, /// what the CPU wrote pub data_port: u8, /// what the drive presents pub read_port: u8, pub message_done: bool, /// next LBA to deliver pub sector: i64, pub sectors_left: i64, /// where the head is (for seek times) pub last_lba: i64, pub cmd: Vec, pub out: VecDeque, changed: bool, update: Update, update_at: Option, read_at: Option, ack_at: Option, pub sense_key: u8, pub sense_asc: u8, irq_levels: (bool, bool), } fn soonest(times: [Option; 4]) -> Option { times.into_iter().flatten().min() } impl ScsiBus { pub fn new(disc: Option>, mut cdda: CddaPlayer) -> ScsiBus { cdda.disc = disc.clone(); let mut bus = ScsiBus { disc, cdda, switches: ScsiSwitches::default(), now: 0, log: Vec::new(), record_log: false, irq_changes: Vec::new(), bsy: false, sel: false, cd: false, io: false, msg: false, req: false, ack: false, atn: false, rst: false, phase: Phase::BusFree, data_port: 0, read_port: 0, message_done: false, sector: 0, sectors_left: 0, last_lba: 0, cmd: Vec::new(), out: VecDeque::new(), changed: false, update: Update::None, update_at: None, read_at: None, ack_at: None, sense_key: 0, sense_asc: 0, irq_levels: (false, false), }; // `irq_levels` and `rst` are set here, not by `reset` (the reference's issue 0001): the // RST line is the CPU's (`$1804` bit 1), and a reset does not let go of it, so the drive // stays in reset while the bit is held (Mesen2 the same). bus.reset(); bus } /// Take a decoded state's place: the disc, the switches and the tooling stay this bus's. pub(crate) fn restore(&mut self, mut saved: ScsiBus) { saved.disc = self.disc.take(); saved.switches = self.switches; saved.log = std::mem::take(&mut self.log); saved.record_log = self.record_log; saved.irq_changes = std::mem::take(&mut self.irq_changes); let mut cdda = std::mem::take(&mut self.cdda); cdda.restore(std::mem::take(&mut saved.cdda)); saved.cdda = cdda; *self = saved; } // -- state --------------------------------------------------------------------------------- pub fn reset(&mut self) { self.bsy = false; self.sel = false; self.cd = false; self.io = false; self.msg = false; self.req = false; self.ack = false; self.atn = false; self.phase = Phase::BusFree; self.data_port = 0; self.read_port = 0; self.message_done = false; self.sector = 0; self.sectors_left = 0; self.last_lba = 0; self.cmd = Vec::new(); self.out = VecDeque::new(); self.changed = false; self.update = Update::None; self.update_at = None; self.read_at = None; self.ack_at = None; self.sense_key = 0; self.sense_asc = 0; self.cdda.stop(); self.update_irq(); // REQ is down: a level that was up is reported dropped (issue 0001) } /// `$1800` read: I/O D3, C/D D4, MSG D5, REQ D6, BSY D7 [emu: all]. pub fn status_bits(&self) -> u8 { (if self.io { 0x08 } else { 0 }) | (if self.cd { 0x10 } else { 0 }) | (if self.msg { 0x20 } else { 0 }) | (if self.req { 0x40 } else { 0 }) | (if self.bsy { 0x80 } else { 0 }) } pub fn current_lba(&self) -> i64 { if self.cdda.active() { self.cdda.position() } else { self.last_lba } } // -- time ---------------------------------------------------------------------------------- pub fn next_event(&self) -> Option { soonest([ self.update_at, self.read_at, self.ack_at, self.cdda.next_event(), ]) } /// Run the player and answer the good statuses it asked for (the reference's player calls /// `good_status` from inside its `run_to`). fn run_cdda(&mut self, mclk: i64) { self.cdda.run_to(mclk); for _ in 0..std::mem::take(&mut self.cdda.good_status_due) { self.good_status(); } } /// Fire every timer due at or before `mclk`, in time order. pub fn run_to(&mut self, mclk: i64) { while let Some(at) = self.next_event().filter(|&at| at <= mclk) { self.now = self.now.max(at); if self.cdda.next_event() == Some(at) { self.run_cdda(at); } else if self.ack_at == Some(at) { self.ack_at = None; self.set_ack_signal(false); } else if self.update_at == Some(at) { let kind = self.update; self.update_at = None; self.fire(kind); } else if self.read_at == Some(at) { self.read_at = None; self.sector_ready(); } self.settle(); } self.now = self.now.max(mclk); self.run_cdda(self.now); } fn queue(&mut self, kind: Update, delay: i64) { if kind != self.update || self.update_at.is_none() { self.update = kind; self.update_at = Some(self.now + delay); } } fn fire(&mut self, kind: Update) { match kind { Update::CommandPhase => self.set_phase(Phase::Command), Update::Req => self.set_req_signal(true), Update::DataInPhase => self.set_phase(Phase::DataIn), Update::GoodStatus => self.good_status(), Update::None => {} } } // -- signals and phases ---------------------------------------------------------------------- /// The reference's `_set(req=...)`. fn set_req_signal(&mut self, value: bool) { if self.req != value { self.req = value; self.changed = true; } self.update_irq(); } /// The reference's `_set(ack=...)`. fn set_ack_signal(&mut self, value: bool) { if self.ack != value { self.ack = value; self.changed = true; } self.update_irq(); } fn update_irq(&mut self) { let held = self.req && self.io && self.bsy; // (data in 0x40, status/message 0x20) let levels = (held && !self.cd, held && self.cd); if levels != self.irq_levels { if levels.0 != self.irq_levels.0 { self.irq_changes.push((0x40, levels.0)); } if levels.1 != self.irq_levels.1 { self.irq_changes.push((0x20, levels.1)); } self.irq_levels = levels; } } fn set_phase(&mut self, phase: Phase) { if self.phase == phase { return; } self.update_at = None; // a phase change cancels a queued drive timer self.changed = true; self.phase = phase; self.bsy = false; self.cd = false; self.io = false; self.msg = false; self.req = false; match phase { Phase::Command => { self.read_at = None; // leaving data in stops any pending sector self.sectors_left = 0; self.bsy = true; self.cd = true; self.req = true; } Phase::DataIn => { self.bsy = true; self.io = true; } Phase::MessageIn => { self.bsy = true; self.cd = true; self.io = true; self.msg = true; self.req = true; } Phase::Status => { self.bsy = true; self.cd = true; self.io = true; self.req = true; } Phase::Busy => self.bsy = true, Phase::BusFree => {} } self.update_irq(); } /// Enter the status phase with `status`; `length` message bytes follow. pub fn status_message(&mut self, status: u8, message: u8, length: usize) { self.out = std::iter::repeat_n(message, length).collect(); self.message_done = false; self.read_port = status; self.set_phase(Phase::Status); } pub fn good_status(&mut self) { self.status_message(GOOD, 0, 1); self.settle(); } // -- CPU side ------------------------------------------------------------------------------ /// A write to `$1800`: SEL pulses. From any phase but data in this starts a command. pub fn select(&mut self) { self.sel = true; self.changed = true; self.settle(); self.sel = false; self.changed = true; self.settle(); } pub fn write_data(&mut self, value: u8) { self.data_port = value; } pub fn read_data(&self) -> u8 { if matches!(self.phase, Phase::Status | Phase::DataIn | Phase::MessageIn) { return self.read_port; } self.data_port } pub fn set_ack(&mut self, level: bool) { self.set_ack_signal(level); self.settle(); } /// A `$1808` data read: ACK for a moment, so the next byte is presented without the CPU's /// own handshake [emu: Mesen2; the pulse width is its measurement]. pub fn pulse_ack(&mut self) { self.set_ack_signal(true); self.ack_at = Some(self.now + self.switches.ack_clear); self.settle(); } /// `$1804` bit 1: the SCSI RST line. pub fn set_reset(&mut self, level: bool) { self.rst = level; self.changed = true; self.settle(); } // -- the state machine --------------------------------------------------------------------- /// Run the phase logic until the signals stop changing (Mesen2's `UpdateState`). fn settle(&mut self) { while self.changed { self.changed = false; if self.rst { self.reset(); return; } if self.sel { self.update_at = None; if self.phase != Phase::DataIn { self.queue(Update::CommandPhase, self.switches.sel_to_command_phase); } else { // Aborting a transfer yields an 8-byte message, then the command phase // comes back on its own [emu: Mesen2 from scsitest.pce, verificator.pce] self.status_message(GOOD, 0, 8); self.queue(Update::CommandPhase, self.switches.abort_to_command); break; } } else { match self.phase { Phase::Command => self.command_phase(), Phase::DataIn => self.data_in_phase(), Phase::Status => self.status_phase(), Phase::MessageIn => self.message_phase(), Phase::BusFree | Phase::Busy => {} } } } } fn handshake_done(&self) -> bool { !self.req && !self.ack } fn command_phase(&mut self) { if self.req && self.ack { self.set_req_signal(false); self.cmd.push(self.data_port); } else if self.handshake_done() && !self.cmd.is_empty() { match command_length(self.cmd[0]) { None => { // An unknown command (C22, `unknown_command_check_condition`) self.cmd.clear(); if self.switches.unknown_command_check_condition { self.fail(SENSE_ILLEGAL_REQUEST, ASC_INVALID_COMMAND); } else { self.status_message(GOOD, 0, 1); } } Some(length) if self.cmd.len() >= length => { let cmd = std::mem::take(&mut self.cmd); self.execute(&cmd); } Some(_) => self.queue(Update::Req, self.switches.next_command_byte_req), } } } fn data_in_phase(&mut self) { if self.req && self.ack { self.set_req_signal(false); } else if self.handshake_done() { if let Some(byte) = self.out.pop_front() { self.read_port = byte; self.set_req_signal(true); } else if self.sectors_left == 0 && self.read_at.is_none() { self.queue(Update::GoodStatus, self.switches.done_status); } } } fn status_phase(&mut self) { if self.req && self.ack { self.set_req_signal(false); } else if self.handshake_done() { if let Some(byte) = self.out.pop_front() { self.read_port = byte; if self.out.is_empty() { self.set_phase(Phase::MessageIn); } else { self.set_req_signal(true); } } } } fn message_phase(&mut self) { if self.req && self.ack { self.set_req_signal(false); self.message_done = true; } else if self.handshake_done() && self.message_done { self.message_done = false; self.set_phase(Phase::BusFree); } } // -- sector delivery ----------------------------------------------------------------------- fn sector_ready(&mut self) { if !self.out.is_empty() { // The program has not taken the last sector: the drive has to find it again. let penalty = (MASTER_HZ * self.switches.reread_penalty_ms) as f64 / 1000.0; self.read_at = Some(self.now + penalty as i64); return; } self.out = match self.disc.as_ref() { Some(disc) => disc.read_data(self.sector).into_iter().collect(), None => std::iter::repeat_n(0, DATA_SECTOR).collect(), }; self.last_lba = self.sector; self.sector = (self.sector + 1) & 0x1FFFFF; self.sectors_left -= 1; self.read_at = (self.sectors_left != 0).then_some(self.now + self.switches.sector_clocks); self.changed = true; // the data-in logic presents the first byte self.set_phase(Phase::DataIn); } // -- the commands -------------------------------------------------------------------------- fn note(&mut self, cmd: &[u8]) { if self.record_log { let bytes: Vec = cmd.iter().map(|b| format!("{b:02X}")).collect(); self.log .push((self.now, format!("cmd {}", bytes.join(" ")))); } } fn fail(&mut self, key: u8, asc: u8) { self.sense_key = key; self.sense_asc = asc; self.status_message(CHECK_CONDITION, 0, 1); } fn execute(&mut self, cmd: &[u8]) { let op = cmd[0]; self.note(cmd); let Some(disc) = self.disc.clone() else { // no disc: TEST UNIT READY and every other command but REQUEST SENSE fail alike if op == CMD_REQUEST_SENSE { self.request_sense(cmd); } else { self.fail(SENSE_NOT_READY, ASC_MEDIUM_NOT_PRESENT); } return; }; match op { CMD_TEST_UNIT_READY => self.queue(Update::GoodStatus, self.switches.test_unit_ready), CMD_REQUEST_SENSE => self.request_sense(cmd), CMD_READ => self.read(cmd, &disc), CMD_AUDIO_START => self.audio_start(cmd, &disc), CMD_AUDIO_END => self.audio_end(cmd, &disc), CMD_PAUSE => { self.cdda.pause(); self.status_message(GOOD, 0, 1); } CMD_READ_SUBQ => self.read_subq(&disc), CMD_READ_TOC => self.read_toc(cmd, &disc), _ => {} } } fn data_answer(&mut self, data: &[u8], delay: i64) { self.out = data.iter().copied().collect(); self.queue(Update::DataInPhase, delay); } fn request_sense(&mut self, cmd: &[u8]) { // Fixed-format sense data, SCSI-2: 0x70, segment, key, information[4], additional // length, command-specific[4], ASC, ASCQ, FRU, sense-key specific[3]. The allocation // length is cmd[4]; 0 means 4 bytes in SCSI-1 (C14: whether the drive honours it is // unknown). let mut block = [0u8; 18]; block[0] = 0x70; block[2] = self.sense_key; block[7] = 10; block[12] = self.sense_asc; let length = if cmd[4] != 0 { cmd[4] as usize } else { 4 }; self.sense_key = 0; self.sense_asc = 0; self.data_answer(&block[..length.min(block.len())], self.switches.subq_answer); } fn read(&mut self, cmd: &[u8], disc: &Disc) { let lba = cmd[3] as i64 | (cmd[2] as i64) << 8 | ((cmd[1] & 0x1F) as i64) << 16; let count = cmd[4] as i64; if count == 0 { self.status_message(GOOD, 0, 1); return; } if lba >= disc.sector_count { self.fail(SENSE_ILLEGAL_REQUEST, ASC_LBA_OUT_OF_RANGE); return; } self.sector = lba; self.sectors_left = count; let seek = self.clocks(seek_time_ms(self.current_lba(), lba) * self.switches.seek_scale); self.cdda.idle(); self.out.clear(); self.read_at = Some(self.now + seek + self.switches.sector_clocks); // The phase goes to data in at once: Ys IV expects it soon after the command // [emu: Mesen2 comment]. No REQ until the first sector is in the buffer. self.set_phase(Phase::DataIn); } fn clocks(&self, ms: f64) -> i64 { (MASTER_HZ as f64 * ms / 1000.0) as i64 } /// The audio command's address; the mode is cmd[9] bits 7-6 [hw: pcetech 8; emu]. fn position(&self, cmd: &[u8], disc: &Disc) -> i64 { match cmd[9] & 0xC0 { // LBA 0x00 => (cmd[3] as i64) << 16 | (cmd[4] as i64) << 8 | cmd[5] as i64, // MSF in BCD (absolute) 0x40 => msf_to_lba(from_bcd(cmd[2]), from_bcd(cmd[3]), from_bcd(cmd[4])), // track number in BCD 0x80 => disc.track(from_bcd(cmd[2])).map_or(0, |track| track.start), _ => 0, } } fn audio_start(&mut self, cmd: &[u8], disc: &Disc) { let start = self.position(cmd, disc); if start >= disc.sector_count { self.status_message(GOOD, 0, 1); return; } let delay = self.clocks(seek_time_ms(self.current_lba(), start) * self.switches.seek_scale); self.cdda.play(start, cmd[1] == 0, delay); // Busy until playback starts; the player ends it with good status self.set_phase(Phase::Busy); } fn audio_end(&mut self, cmd: &[u8], disc: &Disc) { let end = self.position(cmd, disc); let mode = cmd[1]; if mode == 0 { self.cdda.stop(); } else if matches!(mode, 1..=3) { self.cdda.set_end(end, mode); } if matches!(mode, 1 | 2) { self.set_phase(Phase::Busy); // in mode 2 until playback ends } else { self.status_message(GOOD, 0, 1); } } fn read_subq(&mut self, disc: &Disc) { let lba = self.current_lba(); let track = disc.track_at(lba); let number = track.map_or(0, |t| t.number); let is_data = track.is_some_and(|t| t.is_data); let rel = match track { Some(t) if lba >= t.start => relative_msf(lba - t.start), _ => (0, 0, 0), }; let absolute = lba_to_msf(lba); let data = [ self.cdda.status_code(), 0x01 | if is_data { 0x40 } else { 0 }, // ADR 1 (position), control bit 6 = data track to_bcd(number), 1, // index to_bcd(rel.0), to_bcd(rel.1), to_bcd(rel.2), to_bcd(absolute.0), to_bcd(absolute.1), to_bcd(absolute.2), ]; self.data_answer(&data, self.switches.subq_answer); } fn read_toc(&mut self, cmd: &[u8], disc: &Disc) { let kind = cmd[1]; let msf = |lba: i64, last: u8| { let (m, s, f) = lba_to_msf(lba); [to_bcd(m), to_bcd(s), to_bcd(f), last] }; let data: [u8; 4] = match kind { // first and last track numbers 0 => [to_bcd(disc.first_track()), to_bcd(disc.last_track()), 0, 0], // lead-out 1 => msf(disc.end_lba(), 0), // a track's start and type 2 => { let number = match from_bcd(cmd[2]) { 0 => 1, number => number, }; match disc.track(number) { None => msf(disc.end_lba(), 0), Some(track) => msf(track.start, if track.is_data { 4 } else { 0 }), } } _ => { self.status_message(GOOD, 0, 1); return; } }; let want = self.switches.toc_answer_bytes[kind as usize].min(8); let mut padded = [0u8; 8]; padded[..4].copy_from_slice(&data); self.data_answer(&padded[..want], self.switches.toc_answer); } }