pcenginecd_rust/
scsi.rs

1//! The drive's SCSI-class controller: bus signals, phases, the REQ/ACK handshake, the commands
2//! (`scsi.py`).
3//!
4//! The CD unit's controller is not emulated as a microcontroller (there is no second CPU on this
5//! machine); it is a bus state machine that the System Card drives through `$1800-$1802` and
6//! `$1808` [hw: pcetech 8; emu: Mesen2 `PceScsiBus.cpp`, Geargrafx `scsi_controller.cpp`,
7//! Mednafen `scsicd.cpp`, ares `pcd/scsi.cpp`, MAME `pce_cd.cpp` all do the same]. Everything
8//! here is time in **master clocks** (21.477272 MHz); the unit calls `run_to(mclk)` before
9//! register accesses and the bus then runs its own timers up to that instant.
10//!
11//! Signals (`$1800` read): D3 I/O, D4 C/D, D5 MSG, D6 REQ, D7 BSY. Phases and the signals they
12//! hold:
13//!
14//! | phase       | BSY | C/D | I/O | MSG | REQ | what the CPU does                      |
15//! | ----------- | --- | --- | --- | --- | --- | -------------------------------------- |
16//! | bus free    |     |     |     |     |     | writes `$1800` (selects the drive)     |
17//! | command     |  1  |  1  |     |     |  1  | writes command bytes to `$1801`        |
18//! | data in     |  1  |     |  1  |     | (1) | reads bytes from `$1801`/`$1808`       |
19//! | status      |  1  |  1  |  1  |     | (1) | reads the status byte                  |
20//! | message in  |  1  |  1  |  1  |  1  | (1) | reads the message byte                 |
21//! | busy        |  1  |     |     |     |     | waits (an audio command in progress)   |
22//!
23//! Every byte is a REQ/ACK handshake: the drive raises REQ, the CPU sets ACK (`$1802` bit 7),
24//! the drive drops REQ, the CPU drops ACK. IRQ2 sources (`$1803` bits): data-in 0x40 and
25//! status/message 0x20 are REQ held in those phases (`CdUnit` turns the levels into IRQ2).
26//!
27//! The timings are `ScsiSwitches` (the reference's class attributes), all provisional (U8): the
28//! only measurements of this hardware are Shadoff's seek table (tier 3) and the test ROMs
29//! Mesen2's author ran on a real console (tier 5, claimed in his source comments).
30//!
31//! Differences forced by Rust:
32//!
33//! - **The bus owns the audio player** (`bus.cdda`), where the reference's bus and unit hold
34//!   the same object; the player's `on_good_status` callback is `cdda.good_status_due`, answered
35//!   here right after the player ran (`run_cdda`).
36//! - **The `irq` callback** into the unit is a list, `irq_changes`, of `(mask, level)` in the
37//!   order the reference would have called; the unit applies it after each call into the bus
38//!   (nothing the callback reads can change in between).
39//! - The command list `cmd`, the buffer `out` and the ports are bytes; a sector with no disc
40//!   in the drive (the reference asserts) reads as zeros.
41
42use std::collections::VecDeque;
43use std::rc::Rc;
44
45use pcengine_rust::machine::MASTER_HZ;
46use serde::{Deserialize, Serialize};
47
48use crate::cdda::CddaPlayer;
49use crate::disc::{from_bcd, lba_to_msf, msf_to_lba, relative_msf, to_bcd, Disc, DATA_SECTOR};
50use crate::seek::seek_time_ms;
51
52#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
53pub enum Phase {
54    BusFree,
55    Command,
56    DataIn,
57    MessageIn,
58    Status,
59    Busy,
60}
61
62impl Phase {
63    /// The reference's `Phase.value`.
64    pub fn value(self) -> &'static str {
65        match self {
66            Phase::BusFree => "bus free",
67            Phase::Command => "command",
68            Phase::DataIn => "data in",
69            Phase::MessageIn => "message in",
70            Phase::Status => "status",
71            Phase::Busy => "busy",
72        }
73    }
74}
75
76/// What a queued drive timer does when it fires.
77#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
78pub enum Update {
79    None,
80    CommandPhase,
81    Req,
82    DataInPhase,
83    GoodStatus,
84}
85
86// SCSI status byte
87pub const GOOD: u8 = 0x00;
88pub const CHECK_CONDITION: u8 = 0x02;
89
90// Commands the System Card issues [hw: pcetech 8]. REQUEST SENSE (0x03) is a standard SCSI-2
91// command the BIOS sends after commands; Mesen2 does not implement it (it answers Good with no
92// data), Mednafen sends an 18-byte fixed-format block (C14).
93pub const CMD_TEST_UNIT_READY: u8 = 0x00;
94pub const CMD_REQUEST_SENSE: u8 = 0x03;
95pub const CMD_READ: u8 = 0x08;
96pub const CMD_AUDIO_START: u8 = 0xD8;
97pub const CMD_AUDIO_END: u8 = 0xD9;
98pub const CMD_PAUSE: u8 = 0xDA;
99pub const CMD_READ_SUBQ: u8 = 0xDD;
100pub const CMD_READ_TOC: u8 = 0xDE;
101
102pub fn command_length(op: u8) -> Option<usize> {
103    match op {
104        CMD_TEST_UNIT_READY | CMD_REQUEST_SENSE | CMD_READ => Some(6),
105        CMD_AUDIO_START | CMD_AUDIO_END | CMD_PAUSE | CMD_READ_SUBQ | CMD_READ_TOC => Some(10),
106        _ => None,
107    }
108}
109
110// Sense keys / additional codes used (SCSI-2)
111pub const SENSE_NOT_READY: u8 = 0x02;
112pub const SENSE_ILLEGAL_REQUEST: u8 = 0x05;
113pub const ASC_MEDIUM_NOT_PRESENT: u8 = 0x3A;
114pub const ASC_INVALID_COMMAND: u8 = 0x20;
115pub const ASC_LBA_OUT_OF_RANGE: u8 = 0x21;
116
117/// Timing (master clocks), provisional; tier in the comment. The reference's `ScsiBus` class
118/// attributes, with its defaults.
119///
120/// [emu: Mesen2, "approximations ... haven't been validated beyond what validator.pce checks"]
121/// Mesen2 counts these in units of 3 master clocks (one fast CPU cycle); converted here.
122#[derive(Clone, Copy, Debug, PartialEq)]
123pub struct ScsiSwitches {
124    /// tier 5: SEL to the drive entering the command phase
125    pub sel_to_command_phase: i64,
126    /// tier 5: REQ for the next command byte
127    pub next_command_byte_req: i64,
128    /// tier 5, deliberately ~100x shorter than the real spin-up
129    pub test_unit_ready: i64,
130    /// tier 5
131    pub toc_answer: i64,
132    /// tier 5
133    pub subq_answer: i64,
134    /// tier 5: last data byte taken to the good status
135    pub done_status: i64,
136    /// tier 5: SEL during data in ("verificator.pce")
137    pub abort_to_command: i64,
138    /// tier 5: an auto-ack pulse ("hardware measurements show ~1 us")
139    pub ack_clear: i64,
140    /// [hw: Red Book] single speed: 75 sectors a second; one sector's bytes are delivered this
141    /// often (tier 2 for the rate, the delivery phase is U8).
142    pub sector_clocks: i64,
143    /// [emu: Mesen2 comment, Sherlock Holmes] software that misses a sector waits for a
144    /// re-read; tier 5
145    pub reread_penalty_ms: i64,
146    /// The seek model is `seek.rs` (Shadoff's measurements, tier 3 for the shape).
147    pub seek_scale: f64,
148    /// Bytes in the READ TOC answers for kinds 0 (first/last track), 1 (lead-out), 2 (a
149    /// track). Mednafen sends 2, 3, 4 ("returned data lengths on real PCE are not confirmed",
150    /// its own comment); Mesen2 sends 4, 4, 4 (C15). Tier 5 both; the BIOS must read the same
151    /// number.
152    pub toc_answer_bytes: [usize; 3],
153}
154
155impl Default for ScsiSwitches {
156    fn default() -> Self {
157        ScsiSwitches {
158            sel_to_command_phase: 25_000 * 3,
159            next_command_byte_req: 1_000 * 3,
160            test_unit_ready: 150_000 * 3,
161            toc_answer: 3_000 * 3,
162            subq_answer: 1_000 * 3,
163            done_status: 1_000 * 3,
164            abort_to_command: 300_000 * 3,
165            ack_clear: 21,
166            sector_clocks: MASTER_HZ * DATA_SECTOR as i64 / 153_600,
167            reread_penalty_ms: 290,
168            seek_scale: 1.0,
169            toc_answer_bytes: [2, 3, 4],
170        }
171    }
172}
173
174/// Signals, phase, timers and the command set. `irq_changes` collects (mask, level) when the
175/// REQ-held-in-a-phase conditions change (mask 0x40 data in, 0x20 status/message).
176#[derive(Serialize, Deserialize)]
177pub struct ScsiBus {
178    #[serde(skip)]
179    pub disc: Option<Rc<Disc>>,
180    pub cdda: CddaPlayer,
181    #[serde(skip)]
182    pub switches: ScsiSwitches,
183    pub now: i64,
184    /// (mclk, text) of commands, for the tests and runs
185    #[serde(skip)]
186    pub log: Vec<(i64, String)>,
187    #[serde(skip)]
188    pub record_log: bool,
189    #[serde(skip)]
190    pub irq_changes: Vec<(u8, bool)>,
191    pub bsy: bool,
192    pub sel: bool,
193    pub cd: bool,
194    pub io: bool,
195    pub msg: bool,
196    pub req: bool,
197    pub ack: bool,
198    pub atn: bool,
199    pub rst: bool,
200    pub phase: Phase,
201    /// what the CPU wrote
202    pub data_port: u8,
203    /// what the drive presents
204    pub read_port: u8,
205    pub message_done: bool,
206    /// next LBA to deliver
207    pub sector: i64,
208    pub sectors_left: i64,
209    /// where the head is (for seek times)
210    pub last_lba: i64,
211    pub cmd: Vec<u8>,
212    pub out: VecDeque<u8>,
213    changed: bool,
214    update: Update,
215    update_at: Option<i64>,
216    read_at: Option<i64>,
217    ack_at: Option<i64>,
218    pub sense_key: u8,
219    pub sense_asc: u8,
220    irq_levels: (bool, bool),
221}
222
223fn soonest(times: [Option<i64>; 4]) -> Option<i64> {
224    times.into_iter().flatten().min()
225}
226
227impl ScsiBus {
228    pub fn new(disc: Option<Rc<Disc>>, mut cdda: CddaPlayer) -> ScsiBus {
229        cdda.disc = disc.clone();
230        let mut bus = ScsiBus {
231            disc,
232            cdda,
233            switches: ScsiSwitches::default(),
234            now: 0,
235            log: Vec::new(),
236            record_log: false,
237            irq_changes: Vec::new(),
238            bsy: false,
239            sel: false,
240            cd: false,
241            io: false,
242            msg: false,
243            req: false,
244            ack: false,
245            atn: false,
246            rst: false,
247            phase: Phase::BusFree,
248            data_port: 0,
249            read_port: 0,
250            message_done: false,
251            sector: 0,
252            sectors_left: 0,
253            last_lba: 0,
254            cmd: Vec::new(),
255            out: VecDeque::new(),
256            changed: false,
257            update: Update::None,
258            update_at: None,
259            read_at: None,
260            ack_at: None,
261            sense_key: 0,
262            sense_asc: 0,
263            irq_levels: (false, false),
264        };
265        bus.reset();
266        bus
267    }
268
269    /// Take a decoded state's place: the disc, the switches and the tooling stay this bus's.
270    pub(crate) fn restore(&mut self, mut saved: ScsiBus) {
271        saved.disc = self.disc.take();
272        saved.switches = self.switches;
273        saved.log = std::mem::take(&mut self.log);
274        saved.record_log = self.record_log;
275        saved.irq_changes = std::mem::take(&mut self.irq_changes);
276        let mut cdda = std::mem::take(&mut self.cdda);
277        cdda.restore(std::mem::take(&mut saved.cdda));
278        saved.cdda = cdda;
279        *self = saved;
280    }
281
282    // -- state ---------------------------------------------------------------------------------
283
284    pub fn reset(&mut self) {
285        self.bsy = false;
286        self.sel = false;
287        self.cd = false;
288        self.io = false;
289        self.msg = false;
290        self.req = false;
291        self.ack = false;
292        self.atn = false;
293        self.rst = false;
294        self.phase = Phase::BusFree;
295        self.data_port = 0;
296        self.read_port = 0;
297        self.message_done = false;
298        self.sector = 0;
299        self.sectors_left = 0;
300        self.last_lba = 0;
301        self.cmd = Vec::new();
302        self.out = VecDeque::new();
303        self.changed = false;
304        self.update = Update::None;
305        self.update_at = None;
306        self.read_at = None;
307        self.ack_at = None;
308        self.sense_key = 0;
309        self.sense_asc = 0;
310        self.cdda.stop();
311        self.irq_levels = (false, false);
312        self.update_irq();
313    }
314
315    /// `$1800` read: I/O D3, C/D D4, MSG D5, REQ D6, BSY D7 [emu: all].
316    pub fn status_bits(&self) -> u8 {
317        (if self.io { 0x08 } else { 0 })
318            | (if self.cd { 0x10 } else { 0 })
319            | (if self.msg { 0x20 } else { 0 })
320            | (if self.req { 0x40 } else { 0 })
321            | (if self.bsy { 0x80 } else { 0 })
322    }
323
324    pub fn current_lba(&self) -> i64 {
325        if self.cdda.active() {
326            self.cdda.position()
327        } else {
328            self.last_lba
329        }
330    }
331
332    // -- time ----------------------------------------------------------------------------------
333
334    pub fn next_event(&self) -> Option<i64> {
335        soonest([
336            self.update_at,
337            self.read_at,
338            self.ack_at,
339            self.cdda.next_event(),
340        ])
341    }
342
343    /// Run the player and answer the good statuses it asked for (the reference's player calls
344    /// `good_status` from inside its `run_to`).
345    fn run_cdda(&mut self, mclk: i64) {
346        self.cdda.run_to(mclk);
347        for _ in 0..std::mem::take(&mut self.cdda.good_status_due) {
348            self.good_status();
349        }
350    }
351
352    /// Fire every timer due at or before `mclk`, in time order.
353    pub fn run_to(&mut self, mclk: i64) {
354        while let Some(at) = self.next_event().filter(|&at| at <= mclk) {
355            self.now = self.now.max(at);
356            if self.cdda.next_event() == Some(at) {
357                self.run_cdda(at);
358            } else if self.ack_at == Some(at) {
359                self.ack_at = None;
360                self.set_ack_signal(false);
361            } else if self.update_at == Some(at) {
362                let kind = self.update;
363                self.update_at = None;
364                self.fire(kind);
365            } else if self.read_at == Some(at) {
366                self.read_at = None;
367                self.sector_ready();
368            }
369            self.settle();
370        }
371        self.now = self.now.max(mclk);
372        self.run_cdda(self.now);
373    }
374
375    fn queue(&mut self, kind: Update, delay: i64) {
376        if kind != self.update || self.update_at.is_none() {
377            self.update = kind;
378            self.update_at = Some(self.now + delay);
379        }
380    }
381
382    fn fire(&mut self, kind: Update) {
383        match kind {
384            Update::CommandPhase => self.set_phase(Phase::Command),
385            Update::Req => self.set_req_signal(true),
386            Update::DataInPhase => self.set_phase(Phase::DataIn),
387            Update::GoodStatus => self.good_status(),
388            Update::None => {}
389        }
390    }
391
392    // -- signals and phases ----------------------------------------------------------------------
393
394    /// The reference's `_set(req=...)`.
395    fn set_req_signal(&mut self, value: bool) {
396        if self.req != value {
397            self.req = value;
398            self.changed = true;
399        }
400        self.update_irq();
401    }
402
403    /// The reference's `_set(ack=...)`.
404    fn set_ack_signal(&mut self, value: bool) {
405        if self.ack != value {
406            self.ack = value;
407            self.changed = true;
408        }
409        self.update_irq();
410    }
411
412    fn update_irq(&mut self) {
413        let held = self.req && self.io && self.bsy;
414        // (data in 0x40, status/message 0x20)
415        let levels = (held && !self.cd, held && self.cd);
416        if levels != self.irq_levels {
417            if levels.0 != self.irq_levels.0 {
418                self.irq_changes.push((0x40, levels.0));
419            }
420            if levels.1 != self.irq_levels.1 {
421                self.irq_changes.push((0x20, levels.1));
422            }
423            self.irq_levels = levels;
424        }
425    }
426
427    fn set_phase(&mut self, phase: Phase) {
428        if self.phase == phase {
429            return;
430        }
431        self.update_at = None; // a phase change cancels a queued drive timer
432        self.changed = true;
433        self.phase = phase;
434        self.bsy = false;
435        self.cd = false;
436        self.io = false;
437        self.msg = false;
438        self.req = false;
439        match phase {
440            Phase::Command => {
441                self.read_at = None; // leaving data in stops any pending sector
442                self.sectors_left = 0;
443                self.bsy = true;
444                self.cd = true;
445                self.req = true;
446            }
447            Phase::DataIn => {
448                self.bsy = true;
449                self.io = true;
450            }
451            Phase::MessageIn => {
452                self.bsy = true;
453                self.cd = true;
454                self.io = true;
455                self.msg = true;
456                self.req = true;
457            }
458            Phase::Status => {
459                self.bsy = true;
460                self.cd = true;
461                self.io = true;
462                self.req = true;
463            }
464            Phase::Busy => self.bsy = true,
465            Phase::BusFree => {}
466        }
467        self.update_irq();
468    }
469
470    /// Enter the status phase with `status`; `length` message bytes follow.
471    pub fn status_message(&mut self, status: u8, message: u8, length: usize) {
472        self.out = std::iter::repeat_n(message, length).collect();
473        self.message_done = false;
474        self.read_port = status;
475        self.set_phase(Phase::Status);
476    }
477
478    pub fn good_status(&mut self) {
479        self.status_message(GOOD, 0, 1);
480        self.settle();
481    }
482
483    // -- CPU side ------------------------------------------------------------------------------
484
485    /// A write to `$1800`: SEL pulses. From any phase but data in this starts a command.
486    pub fn select(&mut self) {
487        self.sel = true;
488        self.changed = true;
489        self.settle();
490        self.sel = false;
491        self.changed = true;
492        self.settle();
493    }
494
495    pub fn write_data(&mut self, value: u8) {
496        self.data_port = value;
497    }
498
499    pub fn read_data(&self) -> u8 {
500        if matches!(self.phase, Phase::Status | Phase::DataIn | Phase::MessageIn) {
501            return self.read_port;
502        }
503        self.data_port
504    }
505
506    pub fn set_ack(&mut self, level: bool) {
507        self.set_ack_signal(level);
508        self.settle();
509    }
510
511    /// A `$1808` data read: ACK for a moment, so the next byte is presented without the CPU's
512    /// own handshake [emu: Mesen2; the pulse width is its measurement].
513    pub fn pulse_ack(&mut self) {
514        self.set_ack_signal(true);
515        self.ack_at = Some(self.now + self.switches.ack_clear);
516        self.settle();
517    }
518
519    /// `$1804` bit 1: the SCSI RST line.
520    pub fn set_reset(&mut self, level: bool) {
521        self.rst = level;
522        self.changed = true;
523        self.settle();
524    }
525
526    // -- the state machine ---------------------------------------------------------------------
527
528    /// Run the phase logic until the signals stop changing (Mesen2's `UpdateState`).
529    fn settle(&mut self) {
530        while self.changed {
531            self.changed = false;
532            if self.rst {
533                self.reset();
534                return;
535            }
536            if self.sel {
537                self.update_at = None;
538                if self.phase != Phase::DataIn {
539                    self.queue(Update::CommandPhase, self.switches.sel_to_command_phase);
540                } else {
541                    // Aborting a transfer yields an 8-byte message, then the command phase
542                    // comes back on its own [emu: Mesen2 from scsitest.pce, verificator.pce]
543                    self.status_message(GOOD, 0, 8);
544                    self.queue(Update::CommandPhase, self.switches.abort_to_command);
545                    break;
546                }
547            } else {
548                match self.phase {
549                    Phase::Command => self.command_phase(),
550                    Phase::DataIn => self.data_in_phase(),
551                    Phase::Status => self.status_phase(),
552                    Phase::MessageIn => self.message_phase(),
553                    Phase::BusFree | Phase::Busy => {}
554                }
555            }
556        }
557    }
558
559    fn handshake_done(&self) -> bool {
560        !self.req && !self.ack
561    }
562
563    fn command_phase(&mut self) {
564        if self.req && self.ack {
565            self.set_req_signal(false);
566            self.cmd.push(self.data_port);
567        } else if self.handshake_done() && !self.cmd.is_empty() {
568            match command_length(self.cmd[0]) {
569                None => {
570                    // An unknown command: Good, no data [emu: Mesen2]
571                    self.cmd.clear();
572                    self.status_message(GOOD, 0, 1);
573                }
574                Some(length) if self.cmd.len() >= length => {
575                    let cmd = std::mem::take(&mut self.cmd);
576                    self.execute(&cmd);
577                }
578                Some(_) => self.queue(Update::Req, self.switches.next_command_byte_req),
579            }
580        }
581    }
582
583    fn data_in_phase(&mut self) {
584        if self.req && self.ack {
585            self.set_req_signal(false);
586        } else if self.handshake_done() {
587            if let Some(byte) = self.out.pop_front() {
588                self.read_port = byte;
589                self.set_req_signal(true);
590            } else if self.sectors_left == 0 && self.read_at.is_none() {
591                self.queue(Update::GoodStatus, self.switches.done_status);
592            }
593        }
594    }
595
596    fn status_phase(&mut self) {
597        if self.req && self.ack {
598            self.set_req_signal(false);
599        } else if self.handshake_done() {
600            if let Some(byte) = self.out.pop_front() {
601                self.read_port = byte;
602                if self.out.is_empty() {
603                    self.set_phase(Phase::MessageIn);
604                } else {
605                    self.set_req_signal(true);
606                }
607            }
608        }
609    }
610
611    fn message_phase(&mut self) {
612        if self.req && self.ack {
613            self.set_req_signal(false);
614            self.message_done = true;
615        } else if self.handshake_done() && self.message_done {
616            self.message_done = false;
617            self.set_phase(Phase::BusFree);
618        }
619    }
620
621    // -- sector delivery -----------------------------------------------------------------------
622
623    fn sector_ready(&mut self) {
624        if !self.out.is_empty() {
625            // The program has not taken the last sector: the drive has to find it again.
626            let penalty = (MASTER_HZ * self.switches.reread_penalty_ms) as f64 / 1000.0;
627            self.read_at = Some(self.now + penalty as i64);
628            return;
629        }
630        self.out = match self.disc.as_ref() {
631            Some(disc) => disc.read_data(self.sector).into_iter().collect(),
632            None => std::iter::repeat_n(0, DATA_SECTOR).collect(),
633        };
634        self.last_lba = self.sector;
635        self.sector = (self.sector + 1) & 0x1FFFFF;
636        self.sectors_left -= 1;
637        self.read_at = (self.sectors_left != 0).then_some(self.now + self.switches.sector_clocks);
638        self.changed = true; // the data-in logic presents the first byte
639        self.set_phase(Phase::DataIn);
640    }
641
642    // -- the commands --------------------------------------------------------------------------
643
644    fn note(&mut self, cmd: &[u8]) {
645        if self.record_log {
646            let bytes: Vec<String> = cmd.iter().map(|b| format!("{b:02X}")).collect();
647            self.log
648                .push((self.now, format!("cmd {}", bytes.join(" "))));
649        }
650    }
651
652    fn fail(&mut self, key: u8, asc: u8) {
653        self.sense_key = key;
654        self.sense_asc = asc;
655        self.status_message(CHECK_CONDITION, 0, 1);
656    }
657
658    fn execute(&mut self, cmd: &[u8]) {
659        let op = cmd[0];
660        self.note(cmd);
661        let Some(disc) = self.disc.clone() else {
662            // no disc: TEST UNIT READY and every other command but REQUEST SENSE fail alike
663            if op == CMD_REQUEST_SENSE {
664                self.request_sense(cmd);
665            } else {
666                self.fail(SENSE_NOT_READY, ASC_MEDIUM_NOT_PRESENT);
667            }
668            return;
669        };
670        match op {
671            CMD_TEST_UNIT_READY => self.queue(Update::GoodStatus, self.switches.test_unit_ready),
672            CMD_REQUEST_SENSE => self.request_sense(cmd),
673            CMD_READ => self.read(cmd, &disc),
674            CMD_AUDIO_START => self.audio_start(cmd, &disc),
675            CMD_AUDIO_END => self.audio_end(cmd, &disc),
676            CMD_PAUSE => {
677                self.cdda.pause();
678                self.status_message(GOOD, 0, 1);
679            }
680            CMD_READ_SUBQ => self.read_subq(&disc),
681            CMD_READ_TOC => self.read_toc(cmd, &disc),
682            _ => {}
683        }
684    }
685
686    fn data_answer(&mut self, data: &[u8], delay: i64) {
687        self.out = data.iter().copied().collect();
688        self.queue(Update::DataInPhase, delay);
689    }
690
691    fn request_sense(&mut self, cmd: &[u8]) {
692        // Fixed-format sense data, SCSI-2: 0x70, segment, key, information[4], additional
693        // length, command-specific[4], ASC, ASCQ, FRU, sense-key specific[3]. The allocation
694        // length is cmd[4]; 0 means 4 bytes in SCSI-1 (C14: whether the drive honours it is
695        // unknown).
696        let mut block = [0u8; 18];
697        block[0] = 0x70;
698        block[2] = self.sense_key;
699        block[7] = 10;
700        block[12] = self.sense_asc;
701        let length = if cmd[4] != 0 { cmd[4] as usize } else { 4 };
702        self.sense_key = 0;
703        self.sense_asc = 0;
704        self.data_answer(&block[..length.min(block.len())], self.switches.subq_answer);
705    }
706
707    fn read(&mut self, cmd: &[u8], disc: &Disc) {
708        let lba = cmd[3] as i64 | (cmd[2] as i64) << 8 | ((cmd[1] & 0x1F) as i64) << 16;
709        let count = cmd[4] as i64;
710        if count == 0 {
711            self.status_message(GOOD, 0, 1);
712            return;
713        }
714        if lba >= disc.sector_count {
715            self.fail(SENSE_ILLEGAL_REQUEST, ASC_LBA_OUT_OF_RANGE);
716            return;
717        }
718        self.sector = lba;
719        self.sectors_left = count;
720        let seek = self.clocks(seek_time_ms(self.current_lba(), lba) * self.switches.seek_scale);
721        self.cdda.idle();
722        self.out.clear();
723        self.read_at = Some(self.now + seek + self.switches.sector_clocks);
724        // The phase goes to data in at once: Ys IV expects it soon after the command
725        // [emu: Mesen2 comment]. No REQ until the first sector is in the buffer.
726        self.set_phase(Phase::DataIn);
727    }
728
729    fn clocks(&self, ms: f64) -> i64 {
730        (MASTER_HZ as f64 * ms / 1000.0) as i64
731    }
732
733    /// The audio command's address; the mode is cmd[9] bits 7-6 [hw: pcetech 8; emu].
734    fn position(&self, cmd: &[u8], disc: &Disc) -> i64 {
735        match cmd[9] & 0xC0 {
736            // LBA
737            0x00 => (cmd[3] as i64) << 16 | (cmd[4] as i64) << 8 | cmd[5] as i64,
738            // MSF in BCD (absolute)
739            0x40 => msf_to_lba(from_bcd(cmd[2]), from_bcd(cmd[3]), from_bcd(cmd[4])),
740            // track number in BCD
741            0x80 => disc.track(from_bcd(cmd[2])).map_or(0, |track| track.start),
742            _ => 0,
743        }
744    }
745
746    fn audio_start(&mut self, cmd: &[u8], disc: &Disc) {
747        let start = self.position(cmd, disc);
748        if start >= disc.sector_count {
749            self.status_message(GOOD, 0, 1);
750            return;
751        }
752        let delay = self.clocks(seek_time_ms(self.current_lba(), start) * self.switches.seek_scale);
753        self.cdda.play(start, cmd[1] == 0, delay);
754        // Busy until playback starts; the player ends it with good status
755        self.set_phase(Phase::Busy);
756    }
757
758    fn audio_end(&mut self, cmd: &[u8], disc: &Disc) {
759        let end = self.position(cmd, disc);
760        let mode = cmd[1];
761        if mode == 0 {
762            self.cdda.stop();
763        } else if matches!(mode, 1..=3) {
764            self.cdda.set_end(end, mode);
765        }
766        if matches!(mode, 1 | 2) {
767            self.set_phase(Phase::Busy); // in mode 2 until playback ends
768        } else {
769            self.status_message(GOOD, 0, 1);
770        }
771    }
772
773    fn read_subq(&mut self, disc: &Disc) {
774        let lba = self.current_lba();
775        let track = disc.track_at(lba);
776        let number = track.map_or(0, |t| t.number);
777        let is_data = track.is_some_and(|t| t.is_data);
778        let rel = match track {
779            Some(t) if lba >= t.start => relative_msf(lba - t.start),
780            _ => (0, 0, 0),
781        };
782        let absolute = lba_to_msf(lba);
783        let data = [
784            self.cdda.status_code(),
785            0x01 | if is_data { 0x40 } else { 0 }, // ADR 1 (position), control bit 6 = data track
786            to_bcd(number),
787            1, // index
788            to_bcd(rel.0),
789            to_bcd(rel.1),
790            to_bcd(rel.2),
791            to_bcd(absolute.0),
792            to_bcd(absolute.1),
793            to_bcd(absolute.2),
794        ];
795        self.data_answer(&data, self.switches.subq_answer);
796    }
797
798    fn read_toc(&mut self, cmd: &[u8], disc: &Disc) {
799        let kind = cmd[1];
800        let msf = |lba: i64, last: u8| {
801            let (m, s, f) = lba_to_msf(lba);
802            [to_bcd(m), to_bcd(s), to_bcd(f), last]
803        };
804        let data: [u8; 4] = match kind {
805            // first and last track numbers
806            0 => [to_bcd(disc.first_track()), to_bcd(disc.last_track()), 0, 0],
807            // lead-out
808            1 => msf(disc.end_lba(), 0),
809            // a track's start and type
810            2 => {
811                let number = match from_bcd(cmd[2]) {
812                    0 => 1,
813                    number => number,
814                };
815                match disc.track(number) {
816                    None => msf(disc.end_lba(), 0),
817                    Some(track) => msf(track.start, if track.is_data { 4 } else { 0 }),
818                }
819            }
820            _ => {
821                self.status_message(GOOD, 0, 1);
822                return;
823            }
824        };
825        let want = self.switches.toc_answer_bytes[kind as usize].min(8);
826        let mut padded = [0u8; 8];
827        padded[..4].copy_from_slice(&data);
828        self.data_answer(&padded[..want], self.switches.toc_answer);
829    }
830}