pcenginecd_rust/
adpcm.rs

1//! The ADPCM unit: 64 KiB of RAM, its pointers, the MSM5205 decoder and the audio source
2//! (`adpcm.py`).
3//!
4//! Tiers (the base board's docs/validation.md): [hw: pcetech 8] MacDonald, tier 2, names the
5//! registers and a few bit meanings and says the rest is "currently trying to document"; [mfr:
6//! Hudson BIOS manual and System Card ROM] tier 3, the BIOS source (`AD_STAT`, `AD_PLAY`,
7//! `ad_*_addr_set` in `Super CD-ROM2 System V3.00 (J).ASM`) shows how the registers are driven;
8//! \[emu\] Mesen2 `PceAdpcm.cpp`, Geargrafx `adpcm*.cpp`, Mednafen `pcecd.cpp` and MAME
9//! `pce_cd.cpp` are tier 5 detectors: where a behaviour comes only from them it is a field of
10//! `AdpcmSwitches` (a named switch) with a U/C entry in the reference's docs/m8-record.md.
11//!
12//! Registers (offsets from `$1800`):
13//!
14//! | reg | write | read |
15//! | --- | --- | --- |
16//! | `$08/$09` | the 16-bit address latch (low / high) | (`$08` reads the CD data bus: the unit) |
17//! | `$0A` | the byte for the write pointer, which then steps | the read buffer; next fetch starts |
18//! | `$0B` | DMA control (bit 1 requests CD-to-ADPCM DMA; bit 0 follows a waiting block) | the same |
19//! | `$0C` | -- | bit 7 read busy, bit 3 playing, bit 2 write busy, bit 0 end reached |
20//! | `$0D` | control (below) | the last value written |
21//! | `$0E` | rate: playback at 32 / (16 - n) kHz, n = value & $0F | the same |
22//!
23//! Control `$0D`: bit 7 reset (pointers and length to zero, flags cleared, the read buffer is
24//! kept), bit 6 stop at length zero (clear: keep playing), bit 5 play, bit 4 latch the length
25//! from the address latch (a length of zero then means 64 KiB), bit 3 copy the latch to the read
26//! pointer on a rising edge (bit 2 set: as it is; clear: one less, so the first read fetch lands
27//! on it), bit 1 the same for the write pointer (bit 0). [hw: pcetech 8; mfr: the BIOS routines
28//! `ad_read_addr_set`, `ad_write_addr_set`, `ad_length_set`]
29//!
30//! Flags: the half flag (IRQ2 source `$04`, `$1803` bit 2) is set while less than half of the
31//! length is left and the end flag (source `$08`, `$180C` bit 0) when the length has run out.
32//! [hw: pcetech 8 `$1803` bit 2; mfr: `AD_STAT` reads `$180C` bit 0 then `$1803` bit 2, and
33//! `$180C` bit 3 for busy]
34//!
35//! Decoder (MSM5205, 4-bit): a 12-bit signal and a step index 0-48. A nibble is a sign bit and
36//! three magnitude bits; the signal moves by `step/8 + step/4*b0 + step/2*b1 + step*b2` (integer
37//! divisions of `step = floor(16 * 1.1 ** index)`), the index by -1 -1 -1 -1 +2 +4 +6 +8 clamped
38//! to 0..48. Each byte holds two samples, the high nibble first. The audio is the signal held
39//! between samples (the `AudioSource` below).
40//!
41//! Differences forced by Rust:
42//!
43//! - **`Adpcm` is its own audio source**: the reference's `AdpcmSource` (an object that holds
44//!   the unit) is the `origin`, `taken` and `held` fields and the `AudioSource` impl here; the
45//!   fader it asks the audio player for is the shared `Fader` (cdda.rs). The reference's source
46//!   first catches the unit up to the mixer's clock; the board has always done that already
47//!   (it runs the port device at every advance), and this source cannot reach the unit.
48//! - **`on_irq`** (the reference's callback into the unit) is the list `irq_changes`, applied
49//!   by the unit after each call.
50//! - **The step table** is the 49 integers `floor(16 * 1.1 ** index)` written out, so that it
51//!   does not depend on a platform's `pow` (wasm).
52
53use std::cell::Cell;
54use std::rc::Rc;
55
56use pcengine_rust::machine::{py_floordiv, round_ties_even, MASTER_HZ};
57use pcengine_rust::sockets::{AudioSource, DeviceState};
58use serde::{Deserialize, Serialize};
59
60use crate::cdda::{ceil_div, Fader};
61
62pub const ADPCM_RAM_BYTES: usize = 64 * 1024;
63pub const OUTPUT_HZ: i64 = 44_100;
64
65pub const IRQ_HALF: u8 = 0x04;
66pub const IRQ_END: u8 = 0x08;
67
68/// [emu: Mesen2, Geargrafx] 17 bits: a length of 64 KiB needs the 17th
69pub const LENGTH_MASK: u32 = 0x1FFFF;
70
71pub const INDEX_STEP: [i32; 8] = [-1, -1, -1, -1, 2, 4, 6, 8];
72
73/// `floor(16 * 1.1 ** index)` for index 0..48.
74pub const STEPS: [i32; 49] = [
75    16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130,
76    143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
77    876, 963, 1060, 1166, 1282, 1411, 1552,
78];
79
80/// `DELTA[index * 8 + magnitude]`, the signal change for a 3-bit magnitude [MSM5205 data sheet
81/// as modelled by MAME `msm5205.cpp`, Mednafen `okiadpcm.cpp`, Geargrafx: tier 3/5].
82pub const DELTA: [i32; 49 * 8] = step_table();
83
84const fn step_table() -> [i32; 49 * 8] {
85    let mut table = [0; 49 * 8];
86    let mut index = 0;
87    while index < 49 {
88        let step = STEPS[index];
89        let mut magnitude = 0;
90        while magnitude < 8 {
91            table[index * 8 + magnitude] = step / 8
92                + (if magnitude & 1 != 0 { step / 4 } else { 0 })
93                + (if magnitude & 2 != 0 { step / 2 } else { 0 })
94                + (if magnitude & 4 != 0 { step } else { 0 });
95            magnitude += 1;
96        }
97        index += 1;
98    }
99    table
100}
101
102/// Switches: behaviours only tier 5 gives, or undecidable between sources (the reference's
103/// docs/m8-record.md; its `Adpcm` class attributes, with its defaults).
104#[derive(Clone, Copy, Debug, PartialEq)]
105pub struct AdpcmSwitches {
106    /// Playback rate base: f = base_hz / (16 - n). [hw: pcetech 8; mfr: BIOS manual AD_PLAY
107    /// "fKHz=32/(16-n)"] 32 kHz; Mednafen uses 32087.5 (a crystal-derived guess, tier 5).
108    pub base_hz: f64,
109    /// Master clocks until `$180C` bit 7 clears after a `$180A` read. [hw: pcetech 8: "about
110    /// 24 cycles in high-speed mode"] 24 CPU cycles x 3. Mednafen: 57 clocks; Mesen2: a RAM slot
111    /// model (30 cycles minimum, 32 safe); 0 = immediate.
112    pub read_clocks: i64,
113    /// The same for a `$180A` write (bit 2). [emu: Mesen2: 22 cycles minimum, 24 safe; Mednafen
114    /// 33 clocks] pcetech: the BIOS polls bit 2 after each write, no time given.
115    pub write_clocks: i64,
116    /// The 12-bit signal saturates at -2048..2047 (MAME's MSM5205 model) or wraps (Mesen2,
117    /// Geargrafx).
118    pub saturate: bool,
119    /// 16-bit output per signal unit. 16 would be full scale; Mesen2 and Geargrafx use 10
120    /// (headroom for the PSG and CD-DA). Tier 5.
121    pub output_scale: i32,
122    /// A write to RAM while the length is zero raises the end flag [emu: Mesen2, Geargrafx];
123    /// the BIOS clears it with the length latch afterwards. Mednafen has no such rule.
124    pub end_on_write_at_zero: bool,
125}
126
127impl Default for AdpcmSwitches {
128    fn default() -> Self {
129        AdpcmSwitches {
130            base_hz: 32_000.0,
131            read_clocks: 24 * 3,
132            write_clocks: 24 * 3,
133            saturate: true,
134            output_scale: 10,
135            end_on_write_at_zero: true,
136        }
137    }
138}
139
140fn zeroed_ram() -> Vec<u8> {
141    vec![0; ADPCM_RAM_BYTES]
142}
143
144/// RAM, pointers, flags and the decoder. Time comes from the unit (`run(mclk)` and the `now`
145/// of each register access); the unit calls `run` for every event from `next_event`.
146#[derive(Serialize, Deserialize)]
147pub struct Adpcm {
148    #[serde(skip)]
149    pub switches: AdpcmSwitches,
150    #[serde(skip)]
151    pub irq_changes: Vec<(u8, bool)>,
152    #[serde(skip)]
153    pub fader: Rc<Cell<Fader>>,
154    pub ram: Vec<u8>,
155    pub latch: u16,
156    pub read_ptr: u16,
157    pub write_ptr: u16,
158    pub read_buffer: u8,
159    pub control: u8,
160    pub dma: u8,
161    pub rate: u8,
162    pub length: u32,
163    pub half: bool,
164    pub end: bool,
165    pub playing: bool,
166    pub play_request: bool,
167    /// the next sample is the high nibble of the byte at read_ptr
168    pub high_nibble_next: bool,
169    pub signal: i32,
170    pub index: i32,
171    pub read_due: Option<i64>,
172    pub write_due: Option<i64>,
173    pub write_value: u8,
174    /// 16.16 fixed-point master clocks
175    pub sample_at: i64,
176    /// the audio source wants (time, output) events
177    pub record: bool,
178    pub events: Vec<(i64, i32)>,
179    pub last_output: i32,
180    /// decoded samples (statistics)
181    pub sample_count: u64,
182    /// times the end flag was raised (statistics)
183    pub end_count: u64,
184    // the audio source (the reference's `AdpcmSource`)
185    pub origin: Option<i64>,
186    pub taken: i64,
187    pub held: i32,
188    /// AudioSource socket: the mixer's gain for this source
189    pub gain: f64,
190}
191
192impl Adpcm {
193    pub fn new(fader: Rc<Cell<Fader>>) -> Adpcm {
194        Adpcm {
195            switches: AdpcmSwitches::default(),
196            irq_changes: Vec::new(),
197            fader,
198            ram: zeroed_ram(),
199            latch: 0,
200            read_ptr: 0,
201            write_ptr: 0,
202            read_buffer: 0,
203            control: 0,
204            dma: 0,
205            rate: 0,
206            length: 0,
207            half: false,
208            end: false,
209            playing: false,
210            play_request: false,
211            high_nibble_next: true,
212            signal: 0,
213            index: 0,
214            read_due: None,
215            write_due: None,
216            write_value: 0,
217            sample_at: 0,
218            record: false,
219            events: Vec::new(),
220            last_output: 0,
221            sample_count: 0,
222            end_count: 0,
223            origin: None,
224            taken: 0,
225            held: 0,
226            gain: 1.0,
227        }
228    }
229
230    /// Take a decoded state's place: the switches and the shared fader stay this unit's.
231    pub(crate) fn restore(&mut self, mut saved: Adpcm) {
232        saved.switches = self.switches;
233        saved.fader = Rc::clone(&self.fader);
234        *self = saved;
235    }
236
237    // -- state the unit reads -----------------------------------------------------------------
238
239    pub fn write_busy(&self) -> bool {
240        self.write_due.is_some()
241    }
242
243    pub fn read_busy(&self) -> bool {
244        self.read_due.is_some()
245    }
246
247    /// Master clocks per sample, 16.16 fixed point.
248    pub fn period_fixed(&self) -> i64 {
249        let clocks = MASTER_HZ * 65536 * (16 - (self.rate & 0x0F) as i64);
250        (clocks as f64 / self.switches.base_hz) as i64
251    }
252
253    /// Power-on and the `$180D` bit 7 reset (the latter keeps the read buffer).
254    pub fn reset(&mut self) {
255        self.read_ptr = 0;
256        self.write_ptr = 0;
257        self.latch = 0;
258        self.length = 0;
259        self.high_nibble_next = true;
260        self.signal = 0;
261        self.index = 0;
262        self.play_request = false;
263        self.set_half(false);
264        self.set_end(false);
265    }
266
267    /// Power-on at master clock `at` (the output goes idle then, the reference's issue 0001
268    /// item 3).
269    pub fn power_on(&mut self, at: i64) {
270        self.reset();
271        self.control = 0;
272        self.dma = 0;
273        self.rate = 0;
274        self.read_buffer = 0;
275        self.playing = false;
276        self.read_due = None;
277        self.write_due = None;
278        self.output(at, 0);
279    }
280
281    // -- flags --------------------------------------------------------------------------------
282
283    fn set_half(&mut self, value: bool) {
284        if self.half != value {
285            self.half = value;
286            self.irq_changes.push((IRQ_HALF, value));
287        }
288    }
289
290    fn set_end(&mut self, value: bool) {
291        if self.end != value {
292            self.end = value;
293            self.end_count += value as u64;
294            self.irq_changes.push((IRQ_END, value));
295        }
296    }
297
298    // -- registers ----------------------------------------------------------------------------
299
300    pub fn write(&mut self, reg: u8, value: u8, now: i64) {
301        match reg {
302            0x08 | 0x09 => {
303                if reg == 0x08 {
304                    self.latch = (self.latch & 0xFF00) | value as u16;
305                } else {
306                    self.latch = (self.latch & 0x00FF) | (value as u16) << 8;
307                }
308                if self.control & 0x10 != 0 {
309                    // the length latch follows the address while bit 4 is held
310                    self.length = self.latch as u32;
311                }
312            }
313            0x0A => {
314                self.write_value = value;
315                self.write_due = Some(now + self.switches.write_clocks);
316                if self.switches.write_clocks == 0 {
317                    self.finish_write();
318                }
319            }
320            0x0B => self.dma = value,
321            0x0D => self.write_control(value, now),
322            0x0E => self.rate = value,
323            _ => {}
324        }
325    }
326
327    pub fn read(&mut self, reg: u8, now: i64) -> u8 {
328        match reg {
329            0x0A => {
330                let value = self.read_buffer;
331                self.read_due = Some(now + self.switches.read_clocks);
332                if self.switches.read_clocks == 0 {
333                    self.finish_read();
334                }
335                value
336            }
337            0x0B => self.dma,
338            0x0C => {
339                (if self.end { 0x01 } else { 0 })
340                    | (if self.write_busy() { 0x04 } else { 0 })
341                    | (if self.playing { 0x08 } else { 0 })
342                    | (if self.read_busy() { 0x80 } else { 0 })
343            }
344            0x0D => self.control,
345            0x0E => self.rate,
346            _ => 0,
347        }
348    }
349
350    fn write_control(&mut self, value: u8, now: i64) {
351        let old = self.control;
352        self.control = value;
353        if value & 0x02 != 0 && old & 0x02 == 0 {
354            self.write_ptr = self
355                .latch
356                .wrapping_sub(if value & 0x01 != 0 { 0 } else { 1 });
357        }
358        if value & 0x08 != 0 && old & 0x08 == 0 {
359            self.read_ptr = self
360                .latch
361                .wrapping_sub(if value & 0x04 != 0 { 0 } else { 1 });
362        }
363        if value & 0x20 != 0 && !self.playing {
364            if !self.play_request {
365                self.sample_at = (now << 16) + self.period_fixed();
366            }
367            self.play_request = true;
368        }
369        if value & 0x10 != 0 {
370            self.length = self.latch as u32;
371            self.set_end(false);
372        }
373        if value & 0x80 != 0 {
374            self.reset();
375            if value & 0x20 == 0 {
376                self.stop(now);
377            }
378        }
379    }
380
381    // -- RAM port operations --------------------------------------------------------------------
382
383    fn finish_read(&mut self) {
384        self.read_due = None;
385        self.read_buffer = self.ram[self.read_ptr as usize];
386        self.read_ptr = self.read_ptr.wrapping_add(1);
387        if self.control & 0x10 == 0 {
388            if self.length > 0 {
389                self.length -= 1;
390                self.set_half(self.length < 0x8000);
391            } else {
392                self.set_end(true);
393                self.set_half(false);
394            }
395        }
396    }
397
398    fn finish_write(&mut self) {
399        self.write_due = None;
400        self.ram[self.write_ptr as usize] = self.write_value;
401        self.write_ptr = self.write_ptr.wrapping_add(1);
402        if self.length == 0 && self.switches.end_on_write_at_zero {
403            self.set_end(true);
404        }
405        self.set_half(self.length < 0x8000);
406        if self.control & 0x10 == 0 {
407            self.length = (self.length + 1) & LENGTH_MASK;
408        }
409    }
410
411    /// One byte from the CD-to-ADPCM DMA, through the same write path as `$180A`. False if
412    /// the previous write is still in progress (the DMA retries).
413    pub fn dma_write(&mut self, value: u8, now: i64) -> bool {
414        if self.write_busy() {
415            return false;
416        }
417        self.write(0x0A, value, now);
418        true
419    }
420
421    // -- time ---------------------------------------------------------------------------------
422
423    fn sample_due(&self) -> i64 {
424        ceil_div(self.sample_at, 65536)
425    }
426
427    pub fn next_event(&self) -> Option<i64> {
428        let mut due = match (self.read_due, self.write_due) {
429            (Some(read), Some(write)) => Some(read.min(write)),
430            (read, write) => read.or(write),
431        };
432        if self.playing || self.play_request {
433            let sample = self.sample_due();
434            due = Some(due.map_or(sample, |at| at.min(sample)));
435        }
436        due
437    }
438
439    /// Do every event due at or before `mclk`, in time order.
440    pub fn run(&mut self, mclk: i64) {
441        while let Some(at) = self.next_event().filter(|&at| at <= mclk) {
442            if self.read_due.is_some_and(|due| due <= at) {
443                self.finish_read();
444            }
445            if self.write_due.is_some_and(|due| due <= at) {
446                self.finish_write();
447            }
448            if (self.playing || self.play_request) && self.sample_due() <= at {
449                self.play_sample(at);
450            }
451        }
452    }
453
454    fn stop(&mut self, at: i64) {
455        self.playing = false;
456        self.play_request = false;
457        self.output(at, 0);
458    }
459
460    /// The decoder output changed at `at` (0 = the DAC is idle).
461    fn output(&mut self, at: i64, value: i32) {
462        if value != self.last_output {
463            self.last_output = value;
464            if self.record {
465                self.events.push((at, value));
466            }
467        }
468    }
469
470    fn play_sample(&mut self, at: i64) {
471        let control = self.control;
472        self.sample_at += self.period_fixed();
473        if control & 0x80 != 0 {
474            // reset held: play follows bit 5 but nothing is fetched
475            self.playing = control & 0x20 != 0;
476            self.play_request = false;
477            if !self.playing {
478                self.output(at, 0);
479            }
480            return;
481        }
482        if (control & 0x40 != 0 && self.length == 0) || control & 0x20 == 0 {
483            self.stop(at);
484            return;
485        }
486        if self.play_request {
487            self.play_request = false;
488            self.playing = true;
489            self.signal = 0;
490            self.index = 0;
491        }
492        let byte = self.ram[self.read_ptr as usize];
493        let nibble = if self.high_nibble_next {
494            self.high_nibble_next = false;
495            byte >> 4
496        } else {
497            self.high_nibble_next = true;
498            self.read_ptr = self.read_ptr.wrapping_add(1);
499            self.length = self.length.wrapping_sub(1) & LENGTH_MASK;
500            byte & 0x0F
501        };
502        let delta = DELTA[self.index as usize * 8 + (nibble & 7) as usize];
503        let signal = self.signal + if nibble & 8 != 0 { -delta } else { delta };
504        self.signal = if self.switches.saturate {
505            signal.clamp(-2048, 2047)
506        } else {
507            ((signal + 2048) & 0xFFF) - 2048
508        };
509        self.index = (self.index + INDEX_STEP[(nibble & 7) as usize]).clamp(0, 48);
510        self.sample_count += 1;
511        self.set_half(self.length < 0x8000);
512        if self.length == 0 {
513            self.set_end(true);
514        }
515        self.output(at, self.signal * self.switches.output_scale);
516    }
517}
518
519impl DeviceState for Adpcm {} // saved with the unit
520
521/// The ADPCM audio for the board's mixer (socket 9): the decoder output held, sampled at 44.1
522/// kHz at exact master-clock times, with the `$180F` fader when it is aimed at ADPCM.
523impl AudioSource for Adpcm {
524    fn rate_hz(&self) -> f64 {
525        OUTPUT_HZ as f64
526    }
527
528    fn gain(&self) -> f64 {
529        self.gain
530    }
531
532    fn take_samples(&mut self, mclk: i64) -> Vec<(i32, i32)> {
533        let Some(origin) = self.origin else {
534            self.origin = Some(mclk);
535            self.record = true;
536            self.events.clear();
537            self.held = self.last_output;
538            return Vec::new();
539        };
540        let total = py_floordiv((mclk - origin) * OUTPUT_HZ, MASTER_HZ);
541        let fader = self.fader.get();
542        let mut used = 0;
543        let mut out = Vec::with_capacity((total - self.taken).max(0) as usize);
544        for n in self.taken..total {
545            let at = origin + ceil_div(n * MASTER_HZ, OUTPUT_HZ);
546            while used < self.events.len() && self.events[used].0 <= at {
547                self.held = self.events[used].1;
548                used += 1;
549            }
550            let value = round_ties_even(self.held as f64 * fader.gain(at, true)) as i32;
551            out.push((value, value));
552        }
553        self.events.drain(..used);
554        self.taken = total;
555        out
556    }
557}