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    pub fn power_on(&mut self) {
268        self.reset();
269        self.control = 0;
270        self.dma = 0;
271        self.rate = 0;
272        self.read_buffer = 0;
273        self.playing = false;
274        self.read_due = None;
275        self.write_due = None;
276        self.output(0, 0);
277    }
278
279    // -- flags --------------------------------------------------------------------------------
280
281    fn set_half(&mut self, value: bool) {
282        if self.half != value {
283            self.half = value;
284            self.irq_changes.push((IRQ_HALF, value));
285        }
286    }
287
288    fn set_end(&mut self, value: bool) {
289        if self.end != value {
290            self.end = value;
291            self.end_count += value as u64;
292            self.irq_changes.push((IRQ_END, value));
293        }
294    }
295
296    // -- registers ----------------------------------------------------------------------------
297
298    pub fn write(&mut self, reg: u8, value: u8, now: i64) {
299        match reg {
300            0x08 | 0x09 => {
301                if reg == 0x08 {
302                    self.latch = (self.latch & 0xFF00) | value as u16;
303                } else {
304                    self.latch = (self.latch & 0x00FF) | (value as u16) << 8;
305                }
306                if self.control & 0x10 != 0 {
307                    // the length latch follows the address while bit 4 is held
308                    self.length = self.latch as u32;
309                }
310            }
311            0x0A => {
312                self.write_value = value;
313                self.write_due = Some(now + self.switches.write_clocks);
314                if self.switches.write_clocks == 0 {
315                    self.finish_write();
316                }
317            }
318            0x0B => self.dma = value,
319            0x0D => self.write_control(value, now),
320            0x0E => self.rate = value,
321            _ => {}
322        }
323    }
324
325    pub fn read(&mut self, reg: u8, now: i64) -> u8 {
326        match reg {
327            0x0A => {
328                let value = self.read_buffer;
329                self.read_due = Some(now + self.switches.read_clocks);
330                if self.switches.read_clocks == 0 {
331                    self.finish_read();
332                }
333                value
334            }
335            0x0B => self.dma,
336            0x0C => {
337                (if self.end { 0x01 } else { 0 })
338                    | (if self.write_busy() { 0x04 } else { 0 })
339                    | (if self.playing { 0x08 } else { 0 })
340                    | (if self.read_busy() { 0x80 } else { 0 })
341            }
342            0x0D => self.control,
343            0x0E => self.rate,
344            _ => 0,
345        }
346    }
347
348    fn write_control(&mut self, value: u8, now: i64) {
349        let old = self.control;
350        self.control = value;
351        if value & 0x02 != 0 && old & 0x02 == 0 {
352            self.write_ptr = self
353                .latch
354                .wrapping_sub(if value & 0x01 != 0 { 0 } else { 1 });
355        }
356        if value & 0x08 != 0 && old & 0x08 == 0 {
357            self.read_ptr = self
358                .latch
359                .wrapping_sub(if value & 0x04 != 0 { 0 } else { 1 });
360        }
361        if value & 0x20 != 0 && !self.playing {
362            if !self.play_request {
363                self.sample_at = (now << 16) + self.period_fixed();
364            }
365            self.play_request = true;
366        }
367        if value & 0x10 != 0 {
368            self.length = self.latch as u32;
369            self.set_end(false);
370        }
371        if value & 0x80 != 0 {
372            self.reset();
373            if value & 0x20 == 0 {
374                self.stop(now);
375            }
376        }
377    }
378
379    // -- RAM port operations --------------------------------------------------------------------
380
381    fn finish_read(&mut self) {
382        self.read_due = None;
383        self.read_buffer = self.ram[self.read_ptr as usize];
384        self.read_ptr = self.read_ptr.wrapping_add(1);
385        if self.control & 0x10 == 0 {
386            if self.length > 0 {
387                self.length -= 1;
388                self.set_half(self.length < 0x8000);
389            } else {
390                self.set_end(true);
391                self.set_half(false);
392            }
393        }
394    }
395
396    fn finish_write(&mut self) {
397        self.write_due = None;
398        self.ram[self.write_ptr as usize] = self.write_value;
399        self.write_ptr = self.write_ptr.wrapping_add(1);
400        if self.length == 0 && self.switches.end_on_write_at_zero {
401            self.set_end(true);
402        }
403        self.set_half(self.length < 0x8000);
404        if self.control & 0x10 == 0 {
405            self.length = (self.length + 1) & LENGTH_MASK;
406        }
407    }
408
409    /// One byte from the CD-to-ADPCM DMA, through the same write path as `$180A`. False if
410    /// the previous write is still in progress (the DMA retries).
411    pub fn dma_write(&mut self, value: u8, now: i64) -> bool {
412        if self.write_busy() {
413            return false;
414        }
415        self.write(0x0A, value, now);
416        true
417    }
418
419    // -- time ---------------------------------------------------------------------------------
420
421    fn sample_due(&self) -> i64 {
422        ceil_div(self.sample_at, 65536)
423    }
424
425    pub fn next_event(&self) -> Option<i64> {
426        let mut due = match (self.read_due, self.write_due) {
427            (Some(read), Some(write)) => Some(read.min(write)),
428            (read, write) => read.or(write),
429        };
430        if self.playing || self.play_request {
431            let sample = self.sample_due();
432            due = Some(due.map_or(sample, |at| at.min(sample)));
433        }
434        due
435    }
436
437    /// Do every event due at or before `mclk`, in time order.
438    pub fn run(&mut self, mclk: i64) {
439        while let Some(at) = self.next_event().filter(|&at| at <= mclk) {
440            if self.read_due.is_some_and(|due| due <= at) {
441                self.finish_read();
442            }
443            if self.write_due.is_some_and(|due| due <= at) {
444                self.finish_write();
445            }
446            if (self.playing || self.play_request) && self.sample_due() <= at {
447                self.play_sample(at);
448            }
449        }
450    }
451
452    fn stop(&mut self, at: i64) {
453        self.playing = false;
454        self.play_request = false;
455        self.output(at, 0);
456    }
457
458    /// The decoder output changed at `at` (0 = the DAC is idle).
459    fn output(&mut self, at: i64, value: i32) {
460        if value != self.last_output {
461            self.last_output = value;
462            if self.record {
463                self.events.push((at, value));
464            }
465        }
466    }
467
468    fn play_sample(&mut self, at: i64) {
469        let control = self.control;
470        self.sample_at += self.period_fixed();
471        if control & 0x80 != 0 {
472            // reset held: play follows bit 5 but nothing is fetched
473            self.playing = control & 0x20 != 0;
474            self.play_request = false;
475            if !self.playing {
476                self.output(at, 0);
477            }
478            return;
479        }
480        if (control & 0x40 != 0 && self.length == 0) || control & 0x20 == 0 {
481            self.stop(at);
482            return;
483        }
484        if self.play_request {
485            self.play_request = false;
486            self.playing = true;
487            self.signal = 0;
488            self.index = 0;
489        }
490        let byte = self.ram[self.read_ptr as usize];
491        let nibble = if self.high_nibble_next {
492            self.high_nibble_next = false;
493            byte >> 4
494        } else {
495            self.high_nibble_next = true;
496            self.read_ptr = self.read_ptr.wrapping_add(1);
497            self.length = self.length.wrapping_sub(1) & LENGTH_MASK;
498            byte & 0x0F
499        };
500        let delta = DELTA[self.index as usize * 8 + (nibble & 7) as usize];
501        let signal = self.signal + if nibble & 8 != 0 { -delta } else { delta };
502        self.signal = if self.switches.saturate {
503            signal.clamp(-2048, 2047)
504        } else {
505            ((signal + 2048) & 0xFFF) - 2048
506        };
507        self.index = (self.index + INDEX_STEP[(nibble & 7) as usize]).clamp(0, 48);
508        self.sample_count += 1;
509        self.set_half(self.length < 0x8000);
510        if self.length == 0 {
511            self.set_end(true);
512        }
513        self.output(at, self.signal * self.switches.output_scale);
514    }
515}
516
517impl DeviceState for Adpcm {} // saved with the unit
518
519/// The ADPCM audio for the board's mixer (socket 9): the decoder output held, sampled at 44.1
520/// kHz at exact master-clock times, with the `$180F` fader when it is aimed at ADPCM.
521impl AudioSource for Adpcm {
522    fn rate_hz(&self) -> f64 {
523        OUTPUT_HZ as f64
524    }
525
526    fn gain(&self) -> f64 {
527        self.gain
528    }
529
530    fn take_samples(&mut self, mclk: i64) -> Vec<(i32, i32)> {
531        let Some(origin) = self.origin else {
532            self.origin = Some(mclk);
533            self.record = true;
534            self.events.clear();
535            self.held = self.last_output;
536            return Vec::new();
537        };
538        let total = py_floordiv((mclk - origin) * OUTPUT_HZ, MASTER_HZ);
539        let fader = self.fader.get();
540        let mut used = 0;
541        let mut out = Vec::with_capacity((total - self.taken).max(0) as usize);
542        for n in self.taken..total {
543            let at = origin + ceil_div(n * MASTER_HZ, OUTPUT_HZ);
544            while used < self.events.len() && self.events[used].0 <= at {
545                self.held = self.events[used].1;
546                used += 1;
547            }
548            let value = round_ties_even(self.held as f64 * fader.gain(at, true)) as i32;
549            out.push((value, value));
550        }
551        self.events.drain(..used);
552        self.taken = total;
553        out
554    }
555}