pcenginecd_rust/
unit.rs

1//! The CD unit: the expansion-port device that owns `$1800-$18FF`, CD RAM and the backup RAM
2//! (`unit.py`).
3//!
4//! It plugs into the base board's socket 2 (`PortDevice`): `claims()` lists the pages, every
5//! access carries its master-clock time, `catch_up(mclk)` runs the drive up to it (the board
6//! calls it at every advance, base issue 0002; a register access also brings the drive's clock
7//! to its own time), `present` pulls the I/O port's bit 7 low, and IRQ2 is the board's wired-OR
8//! line with this unit's own bit, "cd".
9//!
10//! Registers [hw: pcetech 8 for the names; the bit-level behaviour is emulator-derived, tier 5,
11//! and each is marked]:
12//!
13//! | addr | read | write |
14//! | --- | --- | --- |
15//! | `$1800` | SCSI status: D3 I/O, D4 C/D, D5 MSG, D6 REQ, D7 BSY | select the drive (SEL pulse) |
16//! | `$1801` | the SCSI data bus | the data bus (command bytes) |
17//! | `$1802` | IRQ enable mask (D6-D0) and ACK (D7) | the same: D7 sets ACK, D6-D0 the mask |
18//! | `$1803` | active IRQ bits, D1 = left/right flag; **locks BRAM** | -- |
19//! | `$1804` | the reset register | D1 = SCSI reset (the BIOS's CD_RESET sets then clears it) |
20//! | `$1805` | CD-DA sample, low byte | toggles left/right and latches that channel's sample |
21//! | `$1806` | CD-DA sample, high byte | -- |
22//! | `$1807` | subchannel byte (not modelled: 0) | D7 set **unlocks BRAM** |
23//! | `$1808` | the SCSI data bus; a read of data in pulses ACK | ADPCM address low |
24//! | `$1809` | -- | ADPCM address high |
25//! | `$1808/9`, `$180A-$180E` | the ADPCM unit (adpcm.rs); `$180B` bit 1 = CD-to-ADPCM DMA | the same |
26//! | `$180F` | the fader register | fade control |
27//! | `$1A00-$1AFF`, banks `$40-$43` | the Arcade Card, when fitted (arcade.rs) | the same |
28//! | `$18C0-$18C7` | the Super System Card id registers (answered by the card) | -- |
29//!
30//! IRQ2 = (enable mask & active bits) != 0. Active bits: 0x04 ADPCM half, 0x08 ADPCM end, 0x10
31//! subchannel, 0x20 status/message-in (REQ in those phases), 0x40 data-in (REQ in data in). The
32//! status/message and data-in bits are derived from the bus levels, the ADPCM bits are the
33//! unit's half and end flags (adpcm.rs), the subchannel bit is U9.
34//!
35//! Differences forced by Rust:
36//!
37//! - **`BoardPins` arrives with each call** (the base board's sockets.rs), so there is no
38//!   `bind`; `sync_irq` is the reference's `_bus_irq`, `_adpcm_irq` and `_update_irq`: after
39//!   each call into the bus or the ADPCM unit it applies the level changes they listed, in
40//!   order, and sets the unit's bit on IRQ2. A unit driven with no board behind it takes a
41//!   `DetachedPins` (the reference's unbound unit).
42//! - **The audio player is the bus's** (`unit.bus.cdda`; `unit.cdda()`), **the ADPCM unit is
43//!   its own audio source**, and the two are what `audio_sources` hands the mixer (the
44//!   reference appends them to the board's list).
45//! - **The disc is shared** by the bus and the player as an `Rc<Disc>`.
46//! - **The id registers** `$18C0-$18C7` are asked of `pins.card` when it is a `SystemCard`
47//!   (the reference's unit keeps the card `PcEngineCd` built it with).
48//! - **Save states** (`DeviceState`): everything that changes as the console runs, in one
49//!   bincode value; the switches, the wiring and the drive's command log stay the unit's own.
50//!   The identity names the disc by its table of contents and says whether an Arcade Card is
51//!   fitted, so a machine with another disc, or without the card, refuses the state.
52//! - A `bram` image longer than 2 KiB is an error (the reference's `ValueError`): `with`
53//!   returns a `Result`.
54
55use std::any::Any;
56use std::rc::Rc;
57
58use pcengine_rust::sockets::{
59    AudioSource, BoardPins, DeviceState, PageHandler, PortDevice, ResetKind,
60};
61use serde::{Deserialize, Serialize};
62
63use crate::adpcm::Adpcm;
64use crate::arcade::{ArcadeCard, REGISTER_PAGE as ARCADE_REGISTER_PAGE};
65use crate::cdda::CddaPlayer;
66use crate::disc::Disc;
67use crate::scsi::ScsiBus;
68use crate::syscard::SystemCard;
69
70pub const CD_RAM_BYTES: usize = 64 * 1024;
71pub const BRAM_BYTES: usize = 2 * 1024;
72
73// The pages of the 256-byte-granular decode (docs/sockets.md of the base board).
74/// banks $80-$87, physical $100000-$10FFFF [hw: pcetech 8]
75pub const CD_RAM_PAGES: (usize, usize) = (0x1000, 0x10FF);
76/// $1EE000-$1EE7FF, the first 2 KiB of bank $F7 [hw: pcetech 8]
77pub const BRAM_PAGES: (usize, usize) = (0x1EE0, 0x1EE7);
78/// $1800-$18FF
79pub const REGISTER_PAGE: usize = 0x1FF8;
80
81pub const IRQ_ADPCM_HALF: u8 = 0x04;
82pub const IRQ_ADPCM_END: u8 = 0x08;
83pub const IRQ_SUBCODE: u8 = 0x10;
84pub const IRQ_STATUS_MESSAGE: u8 = 0x20;
85pub const IRQ_DATA_IN: u8 = 0x40;
86
87/// [emu: Mesen2 `PceCdRom.cpp`] the BRAM the BIOS leaves after "initialise": a header, rest
88/// zero. The real RAM is battery-backed and its content at an owner's first power-up is unknown
89/// (U36); unformatted RAM makes some games (Far East of Eden) misbehave [emu: Mesen2 comment].
90pub const BRAM_FORMATTED: [u8; 8] = [0x48, 0x55, 0x42, 0x4D, 0x00, 0xA0, 0x10, 0x80];
91
92/// The reference's `CdUnit` class attributes, with its defaults.
93#[derive(Clone, Copy, Debug, PartialEq, Eq)]
94pub struct UnitSwitches {
95    /// [emu: Mesen2 `PceCdRom.cpp`, from its test ROMs] a second write to $1805 within this
96    /// many master clocks of the first is ignored (tier 5)
97    pub channel_latch_guard: i64,
98    /// [emu: Mesen2 `PceAdpcm.cpp`, "verificator" test ROM: values 18 to 22 CPU-ticks pass,
99    /// higher or lower fail; one tick = 3 master clocks] master clocks from REQ to the DMA
100    /// taking the byte
101    pub dma_byte_clocks: i64,
102}
103
104impl Default for UnitSwitches {
105    fn default() -> Self {
106        UnitSwitches {
107            channel_latch_guard: 700,
108            dma_byte_clocks: 20 * 3,
109        }
110    }
111}
112
113/// CD RAM, backup RAM, the registers, the SCSI bus and the CD-DA player.
114#[derive(Serialize, Deserialize)]
115pub struct CdUnit {
116    #[serde(skip)]
117    pub switches: UnitSwitches,
118    pub bus: ScsiBus,
119    pub adpcm: Adpcm,
120    pub ram: Vec<u8>,
121    pub bram: Vec<u8>,
122    /// [hw: pcetech 8] locked at power-up
123    pub bram_locked: bool,
124    /// the Arcade Card, if fitted: banks $40-$43 and $1A00-$1AFF (arcade.rs)
125    pub arcade: Option<ArcadeCard>,
126    pub enable: u8,
127    pub active: u8,
128    pub reset_register: u8,
129    pub right_channel: bool,
130    pub sample_latch: u16,
131    latch_guard_until: i64,
132    next_event: Option<i64>,
133    dma_at: Option<i64>,
134    pub mclk: i64,
135}
136
137impl CdUnit {
138    pub fn new(disc: Option<Disc>) -> CdUnit {
139        CdUnit::with(disc, None, None).expect("the formatted header fits")
140    }
141
142    /// `bram`: the backup RAM's first bytes (`None`: the formatted-empty header, U36); more than
143    /// 2 KiB is an error (the RAM is 2 KiB, pcetech 8; the reference's issue 0001).
144    pub fn with(
145        disc: Option<Disc>,
146        bram: Option<&[u8]>,
147        arcade: Option<ArcadeCard>,
148    ) -> Result<CdUnit, String> {
149        let header = bram.unwrap_or(&BRAM_FORMATTED);
150        if header.len() > BRAM_BYTES {
151            return Err(format!(
152                "bram holds {} bytes; the backup RAM is {BRAM_BYTES}",
153                header.len()
154            ));
155        }
156        let cdda = CddaPlayer::new();
157        let adpcm = Adpcm::new(Rc::clone(&cdda.fader));
158        let bus = ScsiBus::new(disc.map(Rc::new), cdda);
159        let mut image = vec![0; BRAM_BYTES];
160        image[..header.len()].copy_from_slice(header);
161        Ok(CdUnit {
162            switches: UnitSwitches::default(),
163            bus,
164            adpcm,
165            ram: vec![0; CD_RAM_BYTES],
166            bram: image,
167            bram_locked: true,
168            arcade,
169            enable: 0,
170            active: 0,
171            reset_register: 0,
172            right_channel: false,
173            sample_latch: 0,
174            latch_guard_until: 0,
175            next_event: None,
176            dma_at: None,
177            mclk: 0,
178        })
179    }
180
181    pub fn disc(&self) -> Option<&Rc<Disc>> {
182        self.bus.disc.as_ref()
183    }
184
185    pub fn insert(&mut self, disc: Option<Disc>) {
186        let disc = disc.map(Rc::new);
187        self.bus.cdda.disc = disc.clone();
188        self.bus.disc = disc;
189    }
190
191    /// The CD-DA player (the reference's `unit.cdda`).
192    pub fn cdda(&mut self) -> &mut CddaPlayer {
193        &mut self.bus.cdda
194    }
195
196    /// The 2 KiB of backup RAM, for the host to keep between sessions.
197    pub fn bram(&self) -> &[u8] {
198        &self.bram
199    }
200
201    /// Put kept backup RAM back (up to 2 KiB; the rest is left as it is).
202    pub fn set_bram(&mut self, data: &[u8]) {
203        let count = data.len().min(BRAM_BYTES);
204        self.bram[..count].copy_from_slice(&data[..count]);
205    }
206
207    /// The unit's own timers: (the CD-to-ADPCM DMA's next byte, the next event of any kind).
208    /// For tests and debuggers (the reference's tests read `_dma_at` and `_next_event`).
209    pub fn pending_timers(&self) -> (Option<i64>, Option<i64>) {
210        (self.dma_at, self.next_event)
211    }
212
213    // -- the PortDevice socket: time -------------------------------------------------------------
214
215    /// Run the drive, the ADPCM unit and the ADPCM DMA, event by event, up to `mclk`.
216    fn run(&mut self, mclk: i64) {
217        while let Some(at) = self.soonest().filter(|&at| at <= mclk) {
218            self.bus.run_to(at);
219            self.adpcm.run(at);
220            if self.dma_at == Some(at) {
221                self.dma_at = None;
222                self.dma_step(at);
223            }
224            self.dma_arm();
225        }
226        self.bus.run_to(mclk);
227        self.adpcm.run(mclk);
228        self.dma_arm();
229        self.next_event = self.soonest();
230    }
231
232    fn soonest(&self) -> Option<i64> {
233        [self.bus.next_event(), self.dma_at, self.adpcm.next_event()]
234            .into_iter()
235            .flatten()
236            .min()
237    }
238
239    /// The reference's `catch_up`: the board's call, at every advance: do whatever falls due.
240    /// While nothing is due the drive's clock is left where it is (a cheap early-out);
241    /// `run_now` brings it to the present before a register access.
242    fn run_if_due(&mut self, mclk: i64, pins: &mut BoardPins) {
243        if self.next_event.is_none_or(|at| mclk >= at) {
244            self.run(mclk);
245            self.sync_irq(pins);
246        }
247        self.mclk = mclk;
248    }
249
250    /// The reference's `_run_now`: bring the drive, the ADPCM unit and the DMA to `mclk` even
251    /// when no event is due, so a timer that a register access starts counts from that access
252    /// (issue 0001 item 1: before, the bus's clock stood at the last event while another one
253    /// waited in the future, and a SEL written a second after CD audio started got its command
254    /// phase at once).
255    fn run_now(&mut self, mclk: i64, pins: &mut BoardPins) {
256        self.run(mclk);
257        self.sync_irq(pins);
258        self.mclk = mclk;
259    }
260
261    // -- CD to ADPCM DMA (AD_TRANS): `$180B` bits 1/0 [hw: pcetech 8, "no DMA to RAM ... only
262    // one sector at a time into ADPCM RAM"; the BIOS sets bit 1, polls `$180C` bit 2 and `$1803`
263    // bit 5]. One byte at a time: the drive's data is taken while REQ is up in data in, then ACK
264    // pulses.
265
266    fn dma_wanted(&self) -> bool {
267        let bus = &self.bus;
268        self.adpcm.dma & 0x03 != 0 && bus.req && bus.io && !bus.cd && !bus.ack
269    }
270
271    fn dma_arm(&mut self) {
272        if self.dma_at.is_none() && self.dma_wanted() {
273            self.dma_at = Some(self.bus.now + self.switches.dma_byte_clocks);
274        }
275    }
276
277    fn dma_step(&mut self, at: i64) {
278        if !self.dma_wanted() {
279            return;
280        }
281        if !self.adpcm.dma_write(self.bus.read_data(), at) {
282            self.dma_at = Some(at + 3); // the RAM is still taking the last byte: ask again
283            return;
284        }
285        self.bus.pulse_ack();
286        if self.bus.out.is_empty() {
287            // the sector is through (bit 1, the request, stays until cleared)
288            self.adpcm.dma &= !0x01;
289        }
290    }
291
292    // -- IRQ2 ------------------------------------------------------------------------------------
293
294    /// The reference's `_bus_irq`, `_adpcm_irq` and `_update_irq`: apply the level changes the
295    /// bus and the ADPCM unit listed, then set this unit's bit on the board's IRQ2 line.
296    fn sync_irq(&mut self, pins: &mut BoardPins) {
297        for (mask, level) in self.bus.irq_changes.drain(..) {
298            if level {
299                if self.reset_register & 0x02 == 0 {
300                    // no IRQ while the drive is held in reset
301                    self.active |= mask;
302                }
303            } else {
304                self.active &= !mask;
305            }
306        }
307        // The ADPCM half and end flags: IRQ2 sources `$04` and `$08` (the drive's reset does
308        // not hold them off).
309        for (mask, level) in self.adpcm.irq_changes.drain(..) {
310            if level {
311                self.active |= mask;
312            } else {
313                self.active &= !mask;
314            }
315        }
316        pins.irq2.set("cd", self.enable & self.active != 0);
317    }
318
319    // -- the registers ---------------------------------------------------------------------------
320
321    fn read_register(&mut self, reg: u8, mclk: i64, pins: &mut BoardPins) -> u8 {
322        match reg {
323            0x00 => self.bus.status_bits(),
324            0x01 => self.bus.read_data(),
325            0x02 => self.enable | if self.bus.ack { 0x80 } else { 0 },
326            0x03 => {
327                self.bram_locked = true; // [hw: pcetech 8] a read of $1803 locks BRAM
328                self.active | if self.right_channel { 0 } else { 0x02 }
329            }
330            0x04 => self.reset_register,
331            0x05 => self.sample_latch as u8,
332            0x06 => (self.sample_latch >> 8) as u8,
333            0x07 => 0, // the subchannel byte (U9)
334            0x08 => {
335                let value = self.bus.read_data();
336                if self.bus.req && self.bus.io && !self.bus.cd {
337                    self.bus.pulse_ack();
338                    self.dma_arm();
339                    self.next_event = self.soonest();
340                }
341                value
342            }
343            0x09..=0x0E => {
344                let value = self.adpcm.read(reg, mclk);
345                self.next_event = self.soonest();
346                value
347            }
348            0x0F => self.bus.cdda.fade_register(),
349            0xC0..=0xC7 => {
350                let card = pins
351                    .card
352                    .as_mut()
353                    .and_then(|card| card.as_any_mut().downcast_mut::<SystemCard>());
354                card.map_or(0xFF, |card| card.register_read(reg & 7))
355            }
356            _ => 0xFF,
357        }
358    }
359
360    fn write_register(&mut self, reg: u8, mut value: u8, mclk: i64, pins: &mut BoardPins) {
361        match reg {
362            0x00 => self.bus.select(),
363            0x01 => self.bus.write_data(value),
364            0x02 => {
365                self.bus.set_ack(value & 0x80 != 0);
366                self.enable = value & 0x7F;
367            }
368            0x04 => {
369                self.reset_register = value & 0x0F;
370                let reset = value & 0x02 != 0;
371                self.bus.set_reset(reset);
372                self.sync_irq(pins);
373                if reset {
374                    self.enable &= 0x8F; // the drive's three IRQ enables drop
375                    self.active &= 0x8F;
376                }
377            }
378            0x05 => {
379                if mclk >= self.latch_guard_until {
380                    self.right_channel = !self.right_channel;
381                    let (left, right) = self.bus.cdda.latest_sample();
382                    self.sample_latch = if self.right_channel { right } else { left } as u16;
383                    self.latch_guard_until = mclk + self.switches.channel_latch_guard;
384                }
385            }
386            0x07 => self.bram_locked = value & 0x80 == 0,
387            0x08..=0x0E => {
388                if reg == 0x0B && self.bus.out.is_empty() {
389                    // bit 0 cannot be set when no data block is waiting [emu: Mesen2]
390                    value &= !0x01;
391                }
392                self.adpcm.write(reg, value, mclk);
393            }
394            0x0F => self.bus.cdda.write_fade(value, mclk),
395            _ => {}
396        }
397    }
398
399    // -- save states -----------------------------------------------------------------------------
400
401    fn disc_identity(&self) -> String {
402        self.disc()
403            .map_or("none".to_string(), |disc| disc.state_identity())
404    }
405}
406
407impl PageHandler for CdUnit {
408    fn read(&mut self, address: u32, mclk: i64, pins: &mut BoardPins) -> u8 {
409        let page = (address >> 8) as usize;
410        if let Some(arcade) = self.arcade.as_mut() {
411            if page < 0x1000 || page == ARCADE_REGISTER_PAGE {
412                return arcade.read(address); // the card has no clock
413            }
414        }
415        if (CD_RAM_PAGES.0..=CD_RAM_PAGES.1).contains(&page) {
416            return self.ram[(address & 0xFFFF) as usize]; // memory: no clock either
417        }
418        if (BRAM_PAGES.0..=BRAM_PAGES.1).contains(&page) {
419            return if self.bram_locked {
420                0xFF
421            } else {
422                self.bram[(address & 0x7FF) as usize]
423            };
424        }
425        self.run_now(mclk, pins);
426        let value = self.read_register((address & 0xFF) as u8, mclk, pins);
427        self.sync_irq(pins);
428        value
429    }
430
431    fn write(&mut self, address: u32, value: u8, mclk: i64, pins: &mut BoardPins) {
432        let page = (address >> 8) as usize;
433        if let Some(arcade) = self.arcade.as_mut() {
434            if page < 0x1000 || page == ARCADE_REGISTER_PAGE {
435                arcade.write(address, value);
436                return;
437            }
438        }
439        if (CD_RAM_PAGES.0..=CD_RAM_PAGES.1).contains(&page) {
440            self.ram[(address & 0xFFFF) as usize] = value;
441            return;
442        }
443        if (BRAM_PAGES.0..=BRAM_PAGES.1).contains(&page) {
444            if !self.bram_locked {
445                self.bram[(address & 0x7FF) as usize] = value;
446            }
447            return;
448        }
449        self.run_now(mclk, pins);
450        self.write_register((address & 0xFF) as u8, value, mclk, pins);
451        self.dma_arm();
452        self.next_event = self.soonest();
453        self.sync_irq(pins);
454    }
455}
456
457impl PortDevice for CdUnit {
458    /// K7 low: the I/O port reports "CD unit attached" (C6 polarity)
459    fn present(&self) -> bool {
460        true
461    }
462
463    fn claims(&self) -> Vec<(usize, usize)> {
464        let mut pages = vec![CD_RAM_PAGES, BRAM_PAGES, (REGISTER_PAGE, REGISTER_PAGE)];
465        if let Some(arcade) = self.arcade.as_ref() {
466            pages.extend(arcade.claims());
467        }
468        pages
469    }
470
471    fn catch_up(&mut self, mclk: i64, pins: &mut BoardPins) {
472        self.run_if_due(mclk, pins);
473    }
474
475    fn reset(&mut self, kind: ResetKind, pins: &mut BoardPins) {
476        if let Some(arcade) = self.arcade.as_mut() {
477            arcade.reset(kind);
478        }
479        if kind == ResetKind::PowerOn {
480            self.bram_locked = true;
481            self.bus.rst = false; // the reset register is cleared below: RST lets go
482            self.bus.reset();
483            self.adpcm.power_on(self.mclk);
484            self.sync_irq(pins);
485            self.enable = 0;
486            self.active = 0;
487            self.reset_register = 0;
488            self.right_channel = false;
489            self.sample_latch = 0;
490            // issue 0001 item 3: the unit's own timers go too
491            self.latch_guard_until = 0;
492            self.dma_at = None;
493            self.next_event = self.soonest();
494            self.sync_irq(pins);
495        }
496    }
497
498    /// Socket 9: CD-DA, then ADPCM (the order the reference appends them to the board's list).
499    fn audio_sources(&mut self) -> Vec<&mut dyn AudioSource> {
500        vec![&mut self.bus.cdda, &mut self.adpcm]
501    }
502
503    fn as_any_mut(&mut self) -> &mut dyn Any {
504        self
505    }
506}
507
508impl DeviceState for CdUnit {
509    fn save_state(&self) -> Vec<u8> {
510        let fader = self.bus.cdda.fader.get();
511        let mut out = bincode::serialize(&(fader.fade_register, fader.fade_start))
512            .expect("a fader serialises");
513        out.extend(bincode::serialize(self).expect("a unit serialises"));
514        out
515    }
516
517    fn load_state(&mut self, data: &[u8]) -> Result<(), String> {
518        let bad = |error: bincode::Error| format!("a CD unit's state: {error}");
519        let fade: (u8, i64) = bincode::deserialize(data).map_err(bad)?;
520        let head = bincode::serialized_size(&fade).map_err(bad)? as usize;
521        let saved: CdUnit = bincode::deserialize(&data[head..]).map_err(bad)?;
522        if saved.arcade.is_some() != self.arcade.is_some() {
523            return Err("a state of a machine with another Arcade Card option".to_string());
524        }
525        // the bus, the player and the ADPCM unit keep their wiring (the disc, the shared fader)
526        // and every device its switches
527        let CdUnit {
528            switches: _,
529            bus,
530            adpcm,
531            ram,
532            bram,
533            bram_locked,
534            arcade,
535            enable,
536            active,
537            reset_register,
538            right_channel,
539            sample_latch,
540            latch_guard_until,
541            next_event,
542            dma_at,
543            mclk,
544        } = saved;
545        self.bus.restore(bus);
546        self.adpcm.restore(adpcm);
547        if let (Some(ours), Some(mut theirs)) = (self.arcade.as_mut(), arcade) {
548            theirs.switches = ours.switches;
549            *ours = theirs;
550        }
551        self.ram = ram;
552        self.bram = bram;
553        self.bram_locked = bram_locked;
554        self.enable = enable;
555        self.active = active;
556        self.reset_register = reset_register;
557        self.right_channel = right_channel;
558        self.sample_latch = sample_latch;
559        self.latch_guard_until = latch_guard_until;
560        self.next_event = next_event;
561        self.dma_at = dma_at;
562        self.mclk = mclk;
563        let mut fader = self.bus.cdda.fader.get();
564        (fader.fade_register, fader.fade_start) = fade;
565        self.bus.cdda.fader.set(fader);
566        Ok(())
567    }
568
569    /// What the unit is and which media it holds: the disc by its table of contents (never its
570    /// sectors), and whether the Arcade Card is fitted.
571    fn state_identity(&self) -> String {
572        format!(
573            "CdUnit disc {} arcade {}",
574            self.disc_identity(),
575            self.arcade.is_some()
576        )
577    }
578}