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