pcenginecd_rust/
cdda.rs

1//! CD-DA: the audio player behind `AUDIO START/END/PAUSE`, `READ SUBQ`, `$1805-$1806` and the
2//! audio source the board mixes (`cdda.py`).
3//!
4//! Time is exact and lazy: the player keeps an anchor (the master clock at which a given sample
5//! of a given sector played) and computes the position for any `mclk`, so playback does not
6//! depend on how often the host asks for samples. 44,100 stereo samples a second, 588 per
7//! 2352-byte sector, 75 sectors a second [hw: Red Book]. Samples are signed 16-bit little-endian
8//! pairs.
9//!
10//! What is not modelled (U9): the drive's subchannel Q stream (the BIOS's `$1807` read and its
11//! IRQ bit 0x10), the DAC's filtering (Mednafen filters, Mesen2 resamples with a Hermite kernel),
12//! and the real fader curve: the times are the Hudson BIOS manual's 6 s / 2.5 s (tier 3;
13//! pcetech's tier-2 "about 8 seconds" / "about 2 seconds" is the `pcetech_fade` switch) and the
14//! shape between is linear here (Mesen2 fades 1% per 60 ms / 25 ms, i.e. 6 s / 2.5 s; MAME calls
15//! its own fader "sketchy and unchecked against real HW").
16//!
17//! Differences forced by Rust:
18//!
19//! - **The fader is its own value** (`Fader`), shared by the player and the ADPCM unit through
20//!   an `Rc<Cell<_>>`: both are audio sources the mixer borrows at once, and the reference's
21//!   ADPCM source calls `unit.cdda.fade_gain`. The reference's class attributes (`FADE_*`,
22//!   `PCETECH_*`) are the fader's fields; `SUBQ_STATUS` is the player's `subq_status`.
23//! - **`on_good_status`** (the reference's callback into the SCSI bus) is a count,
24//!   `good_status_due`, that the bus takes after each `run_to` and answers in the same place.
25//!   `take_samples` (the mixer's call) also runs the player's events, as the reference's does;
26//!   the board has always run the unit up to its clock before it mixes, so nothing fires there.
27//! - The decoded sector kept between samples (`_cache`) is not part of a save state.
28
29use std::cell::Cell;
30use std::rc::Rc;
31
32use pcengine_rust::machine::{py_floordiv, MASTER_HZ};
33use pcengine_rust::sockets::{AudioSource, DeviceState};
34use serde::{Deserialize, Serialize};
35
36use crate::disc::Disc;
37
38pub const SAMPLE_HZ: i64 = 44_100;
39pub const SAMPLES_PER_SECTOR: i64 = 588;
40
41/// Python's `-(-a // b)`: the quotient rounded toward plus infinity.
42#[inline]
43pub(crate) fn ceil_div(a: i64, b: i64) -> i64 {
44    -py_floordiv(-a, b)
45}
46
47#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
48pub enum Status {
49    Playing,
50    Paused,
51    /// idle: nothing started, or stopped / a data read took the head
52    Stopped,
53    /// moving to the start; becomes `Playing` or `Paused`
54    Seeking,
55}
56
57#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
58pub enum EndMode {
59    Stop = 3,
60    Loop = 1,
61    /// stop at the end and give the busy command its good status
62    Irq = 2,
63}
64
65/// The `$180F` fader: the register, when its timer started, and the fade times.
66///
67/// Fade times, linear. Default: [mfr: Hudson BIOS manual CD_FADE "6.0 s / 2.5 s", tier 3; Mesen2
68/// and Mednafen agree, tier 5]. The manufacturer's manual outranks pcetech's research text.
69/// Switch: `pcetech_fade = true` selects [hw: pcetech 8] "silence in about 8 seconds" (value
70/// 8-9) and "about 2 seconds" (C-D), tier 2.
71#[derive(Clone, Copy, Debug, PartialEq)]
72pub struct Fader {
73    pub fade_register: u8,
74    pub fade_start: i64,
75    pub fade_slow_seconds: f64,
76    pub fade_fast_seconds: f64,
77    pub pcetech_slow_seconds: f64,
78    pub pcetech_fast_seconds: f64,
79    pub pcetech_fade: bool,
80}
81
82impl Default for Fader {
83    fn default() -> Self {
84        Fader {
85            fade_register: 0,
86            fade_start: 0,
87            fade_slow_seconds: 6.0,
88            fade_fast_seconds: 2.5,
89            pcetech_slow_seconds: 8.0,
90            pcetech_fast_seconds: 2.0,
91            pcetech_fade: false,
92        }
93    }
94}
95
96impl Fader {
97    /// The `$180F` fader's gain for CD-DA, or for ADPCM (`adpcm`: the fade is aimed at it by
98    /// bit 1; pcetech did not test the ADPCM fade, the Hudson BIOS manual's CD_FADE lists $0A
99    /// and $0E for it: U9/M8).
100    pub fn gain(&self, mclk: i64, adpcm: bool) -> f64 {
101        if self.fade_register & 0x08 == 0 || (self.fade_register & 0x02 != 0) != adpcm {
102            return 1.0; // no fade, or it is aimed at the other source
103        }
104        let fast = self.fade_register & 0x04 != 0;
105        let seconds = match (self.pcetech_fade, fast) {
106            (true, true) => self.pcetech_fast_seconds,
107            (true, false) => self.pcetech_slow_seconds,
108            (false, true) => self.fade_fast_seconds,
109            (false, false) => self.fade_slow_seconds,
110        };
111        (1.0 - (mclk - self.fade_start) as f64 / (seconds * MASTER_HZ as f64)).max(0.0)
112    }
113}
114
115#[derive(Serialize, Deserialize)]
116pub struct CddaPlayer {
117    #[serde(skip)]
118    pub disc: Option<Rc<Disc>>,
119    /// The bus owes this many `good_status()` (the reference's `on_good_status` callback).
120    pub good_status_due: u32,
121    pub status: Status,
122    pub start: i64,
123    pub end: i64,
124    pub end_mode: EndMode,
125    pub anchor_clock: i64,
126    /// absolute sample number (sector * 588 + offset) at the anchor
127    pub anchor_sample: i64,
128    /// seek done, or the end of the range
129    pub event_at: Option<i64>,
130    pub now: i64,
131    /// samples handed out so far, in absolute stream time
132    pub taken: i64,
133    pub take_origin: Option<i64>,
134    #[serde(skip)]
135    cache: Option<(i64, Vec<i16>)>,
136    #[serde(skip)]
137    pub fader: Rc<Cell<Fader>>,
138    /// AudioSource socket: the mixer's gain for this source
139    pub gain: f64,
140    pub paused_after_seek: bool,
141    /// [emu: Mednafen `DoNEC_PCE_READSUBQ`, tier 5] the audio-status byte of READ SUBQ, for
142    /// playing, paused, stopped, seeking (the reference's `SUBQ_STATUS`)
143    #[serde(skip, default = "default_subq_status")]
144    pub subq_status: [u8; 4],
145}
146
147fn default_subq_status() -> [u8; 4] {
148    [0, 2, 3, 3]
149}
150
151impl Default for CddaPlayer {
152    fn default() -> Self {
153        CddaPlayer::new()
154    }
155}
156
157impl CddaPlayer {
158    pub fn new() -> CddaPlayer {
159        CddaPlayer {
160            disc: None,
161            good_status_due: 0,
162            status: Status::Stopped,
163            start: 0,
164            end: 0,
165            end_mode: EndMode::Stop,
166            anchor_clock: 0,
167            anchor_sample: 0,
168            event_at: None,
169            now: 0,
170            taken: 0,
171            take_origin: None,
172            cache: None,
173            fader: Rc::new(Cell::new(Fader::default())),
174            gain: 1.0,
175            paused_after_seek: false,
176            subq_status: default_subq_status(),
177        }
178    }
179
180    /// Take a decoded state's place: the wiring (the disc, the shared fader) and the switch
181    /// stay this player's.
182    pub(crate) fn restore(&mut self, mut saved: CddaPlayer) {
183        saved.disc = self.disc.take();
184        saved.fader = Rc::clone(&self.fader);
185        saved.subq_status = self.subq_status;
186        *self = saved;
187    }
188
189    // -- state the bus reads ---------------------------------------------------------------------
190
191    pub fn active(&self) -> bool {
192        self.status != Status::Stopped
193    }
194
195    pub fn status_code(&self) -> u8 {
196        self.subq_status[match self.status {
197            Status::Playing => 0,
198            Status::Paused => 1,
199            Status::Stopped => 2,
200            Status::Seeking => 3,
201        }]
202    }
203
204    /// The sector under the head at the last time the bus ran (`now`).
205    pub fn position(&self) -> i64 {
206        py_floordiv(self.sample_at(self.now), SAMPLES_PER_SECTOR)
207    }
208
209    fn sample_at(&self, mclk: i64) -> i64 {
210        if self.status == Status::Playing {
211            return self.anchor_sample
212                + py_floordiv((mclk - self.anchor_clock).max(0) * SAMPLE_HZ, MASTER_HZ);
213        }
214        self.anchor_sample
215    }
216
217    // -- commands --------------------------------------------------------------------------------
218
219    /// AUDIO START: seek to `start`, then play to the end of its track (or wait for an AUDIO
220    /// END if `paused`). The bus holds BUSY until the seek is done.
221    pub fn play(&mut self, start: i64, paused: bool, seek_clocks: i64) {
222        let Some(disc) = self.disc.as_ref() else {
223            return;
224        };
225        let end = disc.track_at(start).map_or(disc.sector_count, |t| t.end);
226        self.start = start;
227        self.end = end - 1;
228        self.end_mode = EndMode::Stop;
229        self.anchor_sample = start * SAMPLES_PER_SECTOR;
230        self.anchor_clock = self.now + seek_clocks;
231        self.event_at = Some(self.anchor_clock);
232        self.paused_after_seek = paused;
233        self.status = Status::Seeking;
234    }
235
236    /// AUDIO END (modes 1-3): play (or resume) up to sector `end` inclusive.
237    pub fn set_end(&mut self, end: i64, mode: u8) {
238        let Some(disc) = self.disc.as_ref() else {
239            return;
240        };
241        self.end = end.min(disc.sector_count - 1);
242        self.end_mode = match mode {
243            1 => EndMode::Loop,
244            2 => EndMode::Irq,
245            _ => EndMode::Stop,
246        };
247        match self.status {
248            Status::Paused | Status::Stopped => self.resume(),
249            Status::Seeking => self.paused_after_seek = false,
250            Status::Playing => {}
251        }
252        self.schedule_end();
253    }
254
255    fn resume(&mut self) {
256        self.anchor_clock = self.now;
257        self.status = Status::Playing;
258    }
259
260    pub fn pause(&mut self) {
261        if self.status == Status::Playing {
262            self.anchor_sample = self.sample_at(self.now);
263            self.status = Status::Paused;
264            self.event_at = None;
265        } else if self.status == Status::Seeking {
266            self.paused_after_seek = true;
267        }
268    }
269
270    pub fn stop(&mut self) {
271        if self.status == Status::Playing {
272            self.anchor_sample = self.sample_at(self.now);
273        }
274        self.status = Status::Stopped;
275        self.event_at = None;
276    }
277
278    /// A data read took the head: audio stops.
279    pub fn idle(&mut self) {
280        self.stop();
281    }
282
283    fn schedule_end(&mut self) {
284        if self.status != Status::Playing {
285            self.event_at = (self.status == Status::Seeking).then_some(self.anchor_clock);
286            return;
287        }
288        let remaining = (self.end + 1) * SAMPLES_PER_SECTOR - self.anchor_sample;
289        self.event_at = Some(self.anchor_clock + ceil_div(remaining * MASTER_HZ, SAMPLE_HZ));
290    }
291
292    // -- time ------------------------------------------------------------------------------------
293
294    pub fn next_event(&self) -> Option<i64> {
295        self.event_at
296    }
297
298    /// Fire the seek-done and end-of-range events due at or before `mclk`.
299    pub fn run_to(&mut self, mclk: i64) {
300        while let Some(at) = self.event_at.filter(|&at| at <= mclk) {
301            self.event_at = None;
302            self.now = at;
303            if self.status == Status::Seeking {
304                self.status = if self.paused_after_seek {
305                    Status::Paused
306                } else {
307                    Status::Playing
308                };
309                self.anchor_clock = at;
310                self.schedule_end();
311                self.good_status_due += 1;
312            } else if self.status == Status::Playing {
313                if self.end_mode == EndMode::Loop {
314                    self.anchor_sample = self.start * SAMPLES_PER_SECTOR;
315                    self.anchor_clock = at;
316                    self.schedule_end();
317                } else {
318                    self.anchor_sample = (self.end + 1) * SAMPLES_PER_SECTOR;
319                    self.status = Status::Stopped;
320                    if self.end_mode == EndMode::Irq {
321                        self.good_status_due += 1;
322                    }
323                }
324            }
325        }
326        self.now = self.now.max(mclk);
327    }
328
329    // -- samples ---------------------------------------------------------------------------------
330
331    fn frame(&mut self, absolute_sample: i64) -> (i16, i16) {
332        let lba = py_floordiv(absolute_sample, SAMPLES_PER_SECTOR);
333        let offset = absolute_sample.rem_euclid(SAMPLES_PER_SECTOR) as usize;
334        if self.cache.as_ref().is_none_or(|(cached, _)| *cached != lba) {
335            let mut values = vec![0i16; SAMPLES_PER_SECTOR as usize * 2];
336            if let Some(disc) = self.disc.as_ref() {
337                if disc.track_at(lba).is_some_and(|track| !track.is_data) {
338                    let raw = disc.read_raw(lba);
339                    for (value, pair) in values.iter_mut().zip(raw.chunks_exact(2)) {
340                        *value = i16::from_le_bytes([pair[0], pair[1]]);
341                    }
342                }
343            }
344            self.cache = Some((lba, values));
345        }
346        let values = &self.cache.as_ref().expect("just filled").1;
347        (values[2 * offset], values[2 * offset + 1])
348    }
349
350    /// The sample being played at the last time run (`$1805/$1806`): zeros unless playing.
351    pub fn latest_sample(&mut self) -> (i16, i16) {
352        if self.status != Status::Playing || self.disc.is_none() {
353            return (0, 0);
354        }
355        self.frame(self.sample_at(self.now))
356    }
357
358    /// The fader's gain (the reference's `fade_gain`).
359    pub fn fade_gain(&self, mclk: i64, adpcm: bool) -> f64 {
360        self.fader.get().gain(mclk, adpcm)
361    }
362
363    pub fn fade_register(&self) -> u8 {
364        self.fader.get().fade_register
365    }
366
367    /// `$180F` [hw: pcetech 8]: bit 3 fades, bit 2 chooses the fast fade, bit 1 aims it at
368    /// ADPCM. Rewriting the same value changes nothing; a new value restarts the timer (the
369    /// finer cases in pcetech, a cancelled fade whose timer still runs, are U9).
370    pub fn write_fade(&mut self, value: u8, mclk: i64) {
371        let mut fader = self.fader.get();
372        if value & 0x0F != fader.fade_register & 0x0F {
373            fader.fade_start = mclk;
374        }
375        fader.fade_register = value;
376        self.fader.set(fader);
377    }
378
379    /// Was audio playing at `mclk`? (Past events have already moved the state, so a sample
380    /// before the current anchor or after the end is silence.)
381    fn plays_at(&self, mclk: i64) -> bool {
382        self.status == Status::Playing && mclk >= self.anchor_clock
383    }
384}
385
386impl DeviceState for CddaPlayer {} // saved with the unit
387
388impl AudioSource for CddaPlayer {
389    /// AudioSource attributes (socket 9): a fixed rate; the mixer applies `gain`
390    fn rate_hz(&self) -> f64 {
391        SAMPLE_HZ as f64
392    }
393
394    fn gain(&self) -> f64 {
395        self.gain
396    }
397
398    /// Stereo samples since the last call, one per 1/44100 s of master-clock time (zeros when
399    /// not playing, so a mixer keeps its place). The fader's gain is applied.
400    fn take_samples(&mut self, mclk: i64) -> Vec<(i32, i32)> {
401        self.run_to(mclk);
402        let origin = *self.take_origin.get_or_insert(mclk);
403        let total = py_floordiv((mclk - origin) * SAMPLE_HZ, MASTER_HZ);
404        let mut out = Vec::with_capacity((total - self.taken).max(0) as usize);
405        for n in self.taken..total {
406            let at = origin + ceil_div(n * MASTER_HZ, SAMPLE_HZ);
407            if self.disc.is_some() && self.plays_at(at) {
408                let (left, right) = self.frame(self.sample_at(at));
409                let g = self.fade_gain(at, false);
410                // Python's int(): toward zero
411                out.push(((left as f64 * g) as i32, (right as f64 * g) as i32));
412            } else {
413                out.push((0, 0));
414            }
415        }
416        self.taken = total;
417        out
418    }
419}