pcengine_rust/psg/
chip.rs

1//! The HuC6280's programmable sound generator: six wavetable channels, noise, LFO, DDA
2//! (`psg/chip.py`).
3//!
4//! Written (in the reference) from Hudson's *HuC6280 PSG Manual* (tier 3: "manual" below) and
5//! MacDonald's pcetech §10 and §2.4 (tier 2); where those are silent the choice is named in a
6//! comment with a U/C number (docs/m4-record.md) and may be changed by a switch. There is no
7//! hardware audio reference anywhere: **every output of this module is provisional, tier 5**.
8//!
9//! Time: one *step* is one PSG clock, master/6 = 3.58 MHz [pcetech 2.4; the manual's "7.16 MHz" and
10//! its formulas' factor 2 agree]. A channel's waveform index advances every F steps (F = the 12-bit
11//! frequency, 0 meaning 4096) [pcetech 10: $000 is the lowest frequency; manual 2.2.1:
12//! f = fmaster / (2 x 32 x F)]. The model is event-driven: output is constant between index changes.
13//!
14//! Within a step every channel's output is taken from the state at the start of the step and the
15//! counters then advance together (the manual says nothing of an order): ch 1's modulation of ch 0
16//! therefore reads ch 2's sample *before* ch 2 advances in the same step.
17//!
18//! Differences forced by Rust: the class attributes are the fields of `PsgSwitches`
19//! (`Psg::switches`), with `variant("mame")` and `variant("mednafen")` for the reference's
20//! `VARIANTS`; `keyon_mode` is an enum. The step-stream listeners (the reference's referee
21//! comparison, Python-side tooling) are not carried over. The host-rate arithmetic is the
22//! reference's, in `f64`, operation for operation.
23
24use serde::{Deserialize, Serialize};
25
26use crate::cpu_io::PsgPins;
27use crate::machine::{py_floordiv, round_ties_even};
28use crate::sockets::{AudioSource, DeviceState};
29
30pub const PSG_CLOCK_DIVIDER: i64 = 6; // master clocks per step [pcetech 2.4]
31pub const NOISE_TAPS: [u32; 5] = [0, 1, 11, 12, 17]; // [emu: MAME and Mednafen agree; MacDonald's research] U6
32pub const SILENT_UNITS: usize = 30; // [mfr 2.3] about 45 dB below the maximum "none is output"; 1 unit = 1.5 dB
33
34#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
35pub struct Channel {
36    pub frequency: i64,
37    /// bit 7 ON, bit 6 DDA, bits 4-0 AL
38    pub control: u8,
39    pub balance: u8,
40    pub wave: [u8; 32],
41    pub index: usize,
42    /// the DAC value held by DDA mode
43    pub latch: u8,
44    pub noise_control: u8,
45    /// steps until the waveform index advances
46    pub counter: i64,
47    pub noise_counter: i64,
48    pub lfsr: u32,
49    /// C16: a sample forced by an R6 write until the next address step
50    pub override_sample: Option<u8>,
51}
52
53impl Default for Channel {
54    fn default() -> Self {
55        Channel {
56            frequency: 0,
57            control: 0,
58            balance: 0,
59            wave: [0; 32],
60            index: 0,
61            latch: 0,
62            noise_control: 0,
63            counter: 1,
64            noise_counter: 1,
65            lfsr: 1,
66            override_sample: None,
67        }
68    }
69}
70
71impl Channel {
72    #[inline]
73    pub fn on(&self) -> bool {
74        self.control & 0x80 != 0
75    }
76
77    #[inline]
78    pub fn dda(&self) -> bool {
79        self.control & 0x40 != 0
80    }
81}
82
83/// C22: what key-on (ON 0 -> 1) does to a waveform channel.
84#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
85pub enum KeyOnMode {
86    /// the counter restarts from F, the address stays (MAME)
87    Reload,
88    /// the counter resumes where it stopped and the address steps once (Mednafen)
89    ResumeStep,
90}
91
92/// The points on which the manual and pcetech are silent or the two readable emulators differ
93/// (docs/m4-record.md, C13-C23). Each default below follows the manual or pcetech where they
94/// speak, else the larger share of the sources; `variant` flips them to one emulator's way.
95#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
96pub struct PsgSwitches {
97    /// C13: data written to R6 while a channel is ON and not DDA. pcetech: ignored, the index does
98    /// not move. MAME and Mednafen store it in the waveform. True follows the two emulators.
99    pub write_wave_while_playing: bool,
100    /// C16: R6 in DDA mode loads the DAC latch: the manual says whenever DDA is set (also with the
101    /// channel off); Mednafen only with the channel on, and it also lets an R6 write while playing
102    /// override the sample until the next address step ("tested on a SuperGrafx").
103    pub dda_latch_needs_on: bool,
104    pub r6_overrides_sample_while_on: bool,
105    /// C22: neither reading is in the manual.
106    pub keyon_mode: KeyOnMode,
107    /// C18: the LFO acts only when channel 2 is on (manual); MAME modulates whatever channel 2 is.
108    pub lfo_requires_ch2_on: bool,
109    /// C19: the LFO frequency register 0: 256 (Mednafen) or 1 (MAME's zero-length counter).
110    pub lfo_zero_multiplier: i64,
111    /// U6: the modulated frequency wraps in 12 bits (Mednafen) or not (MAME).
112    pub lfo_mask12: bool,
113    /// C23: LF TRG (R9 bit 7) halts channel 2 whatever LF CTL holds (Mednafen); MAME only with LF
114    /// CTL non-zero.
115    pub lf_trg_halts_always: bool,
116    /// C15: R1/R5's table: the manual says 3 dB a step; both emulators share a table in which the
117    /// step from 7 to 8 is 1.5 dB and from 8 to 9 4.5 dB (index 8 costs 15 units, not 14). The
118    /// sixteen values in `scale` are that table, as in MAME's c6280.cpp (BSD-3-Clause, Charles
119    /// MacDonald; see the reference's NOTICE.md).
120    pub scale_table_quirk: bool,
121    /// C14: attenuation at which a channel goes silent, in 1.5 dB units. The manual: 45 dB (30).
122    /// Both emulators keep a 31st step (46.5 dB) that is still audible.
123    pub silent_units: usize,
124    /// False skips the host-rate output.
125    pub render_audio: bool,
126    /// C17: noise frequency NF' = 0 ("undefined" in the manual). MAME clocks the shift register
127    /// every step; Mednafen every 32. 32 here.
128    pub noise_zero_period: i64,
129    /// C20: the noise shift register runs whether or not noise is selected (Mednafen); MAME runs it
130    /// only while a channel is playing noise.
131    pub noise_free_running: bool,
132}
133
134impl Default for PsgSwitches {
135    fn default() -> Self {
136        PsgSwitches {
137            write_wave_while_playing: false,
138            dda_latch_needs_on: false,
139            r6_overrides_sample_while_on: false,
140            keyon_mode: KeyOnMode::Reload,
141            lfo_requires_ch2_on: true,
142            lfo_zero_multiplier: 256,
143            lfo_mask12: true,
144            lf_trg_halts_always: true,
145            scale_table_quirk: false,
146            silent_units: SILENT_UNITS,
147            render_audio: true,
148            noise_zero_period: 32,
149            noise_free_running: true,
150        }
151    }
152}
153
154impl PsgSwitches {
155    /// Each readable emulator's way on the disputed points (the reference's `VARIANTS`):
156    /// `"manual"` (the defaults), `"mame"`, `"mednafen"`.
157    pub fn variant(name: &str) -> Option<PsgSwitches> {
158        let manual = PsgSwitches::default();
159        match name {
160            "manual" => Some(manual),
161            "mame" => Some(PsgSwitches {
162                write_wave_while_playing: true,
163                noise_zero_period: 1,
164                noise_free_running: false,
165                keyon_mode: KeyOnMode::Reload,
166                lfo_requires_ch2_on: false,
167                lfo_zero_multiplier: 1,
168                lfo_mask12: false,
169                lf_trg_halts_always: false,
170                scale_table_quirk: true,
171                silent_units: 31,
172                ..manual
173            }),
174            "mednafen" => Some(PsgSwitches {
175                write_wave_while_playing: true,
176                dda_latch_needs_on: true,
177                r6_overrides_sample_while_on: true,
178                noise_zero_period: 32,
179                noise_free_running: true,
180                keyon_mode: KeyOnMode::ResumeStep,
181                lfo_requires_ch2_on: true,
182                lfo_zero_multiplier: 256,
183                lfo_mask12: true,
184                lf_trg_halts_always: true,
185                scale_table_quirk: true,
186                silent_units: 31,
187                ..manual
188            }),
189            _ => None,
190        }
191    }
192}
193
194#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
195pub struct Psg {
196    /// Switches, not state: a loaded state keeps the system's own.
197    pub switches: PsgSwitches,
198    pub channels: [Channel; 6],
199    pub select: u8,
200    /// R1
201    pub balance: u8,
202    /// R8
203    pub lfo_frequency: u8,
204    /// R9
205    pub lfo_control: u8,
206    /// steps run so far
207    pub step: i64,
208    // host-rate output (a box average of the step stream; outside the reference path)
209    pub rate_hz: f64,
210    pub gain: f64,
211    /// up to 30 + 31 + 30
212    levels: Vec<f64>,
213    acc: [f64; 2],
214    acc_steps: f64,
215    phase: f64,
216    out: Vec<(i32, i32)>,
217    noise_period: [i64; 6],
218}
219
220impl Default for Psg {
221    fn default() -> Self {
222        Psg::new(44100.0, PsgSwitches::default())
223    }
224}
225
226impl Psg {
227    pub fn new(rate_hz: f64, switches: PsgSwitches) -> Psg {
228        let levels = (0..128)
229            .map(|u| {
230                if u < switches.silent_units {
231                    10f64.powf(-1.5 * u as f64 / 20.0)
232                } else {
233                    0.0
234                }
235            })
236            .collect();
237        let mut psg = Psg {
238            switches,
239            channels: Default::default(),
240            select: 0,
241            balance: 0,
242            lfo_frequency: 0,
243            lfo_control: 0,
244            step: 0,
245            rate_hz,
246            gain: 1.0,
247            levels,
248            acc: [0.0, 0.0],
249            acc_steps: 0.0,
250            phase: 0.0,
251            out: Vec::new(),
252            noise_period: [0; 6],
253        };
254        for ch in 0..6 {
255            psg.channels[ch].counter = psg.period(ch);
256        }
257        for ch in [4, 5] {
258            psg.set_noise_period(ch);
259            psg.channels[ch].noise_counter = 1;
260        }
261        psg
262    }
263
264    /// A loaded state keeps the system's own switches and the table made from them.
265    pub(crate) fn keep_configuration(&mut self, live: &Psg) {
266        self.switches = live.switches;
267        self.levels = live.levels.clone();
268    }
269
270    // -- derived values -------------------------------------------------------------------------
271
272    /// [mfr 2.1.10 note] the LFO acts only when channel 1 and 2 are both on; LF TRG halts it.
273    fn lfo_modulating(&self) -> bool {
274        if self.lfo_control & 3 == 0 || self.lfo_control & 0x80 != 0 {
275            return false;
276        }
277        self.channels[1].on() || !self.switches.lfo_requires_ch2_on
278    }
279
280    fn mask12(&self, frequency: i64) -> i64 {
281        if self.switches.lfo_mask12 {
282            let masked = frequency & 0xFFF;
283            if masked != 0 {
284                masked
285            } else {
286                4096
287            }
288        } else {
289            frequency.max(1)
290        }
291    }
292
293    fn period(&self, ch: usize) -> i64 {
294        let channel = &self.channels[ch];
295        let mut frequency = if channel.frequency != 0 {
296            channel.frequency
297        } else {
298            4096
299        };
300        if ch == 0 && self.lfo_modulating() {
301            let shift = ((self.lfo_control & 3) as u32 - 1) * 2; // 0, 2, 4 [mfr 2.1.10]
302            let modulation = self.channels[1].wave[self.channels[1].index] as i64 - 16; // [mfr table]
303            frequency = self.mask12(channel.frequency + (modulation << shift));
304        } else if ch == 1 && self.lfo_control & 3 != 0 {
305            // [mfr 2.2.2] f_LFO = fmaster / (2x32xF2xFLF)
306            frequency *= if self.lfo_frequency != 0 {
307                self.lfo_frequency as i64
308            } else {
309                self.switches.lfo_zero_multiplier
310            };
311        }
312        frequency
313    }
314
315    fn set_noise_period(&mut self, ch: usize) {
316        let nf = 0x1F - (self.channels[ch].noise_control & 0x1F) as i64; // [mfr 2.3.3] NF is the complement
317        self.noise_period[ch] = if nf != 0 {
318            nf * 64
319        } else {
320            self.switches.noise_zero_period
321        }; // 2 x 32 x 2 / 2 steps
322    }
323
324    /// Units of 1.5 dB below the maximum for a channel on one side (0 left, 1 right):
325    /// R1 and R5 step 3 dB, R4 1.5 dB [mfr 2.1.2, 2.1.5, 2.1.6, 2.3]. 30 or more is silent.
326    pub fn attenuation(&self, ch: usize, side: usize) -> usize {
327        let channel = &self.channels[ch];
328        let shift = if side == 0 { 4 } else { 0 };
329        let main = (self.balance >> shift) & 0xF;
330        let pan = (channel.balance >> shift) & 0xF;
331        self.scale(main) + (31 - (channel.control & 0x1F) as usize) + self.scale(pan)
332    }
333
334    /// Units below the maximum for an R1/R5 nibble: 2 a step, 30 for 0 [mfr 2.1.2, 2.1.6].
335    fn scale(&self, nibble: u8) -> usize {
336        if self.switches.scale_table_quirk {
337            const TABLE: [usize; 16] = [0, 3, 5, 7, 9, 11, 13, 15, 16, 19, 21, 23, 25, 27, 29, 31];
338            return 31 - TABLE[nibble as usize];
339        }
340        2 * (15 - nibble as usize)
341    }
342
343    // -- the CPU's port --------------------------------------------------------------------------
344
345    pub fn write(&mut self, offset: u32, value: u8, mclk: i64) {
346        self.advance_to(py_floordiv(mclk, PSG_CLOCK_DIVIDER));
347        self.write_register((offset & 0x0F) as u8, value);
348    }
349
350    fn write_register(&mut self, reg: u8, value: u8) {
351        if reg == 0 {
352            self.select = value & 7;
353            return;
354        }
355        if reg == 1 {
356            self.balance = value;
357            return;
358        }
359        if reg == 8 {
360            self.lfo_frequency = value;
361            // counters pick up a changed period at their next reload
362            return;
363        }
364        if reg == 9 {
365            if value & 0x80 != 0 {
366                // [mfr 2.1.10] LF TRG: ch 2's wave counter and address reset
367                self.channels[1].index = 0;
368                self.channels[1].counter = self.period(1);
369            }
370            self.lfo_control = value;
371            return;
372        }
373        if reg > 7 || self.select > 5 {
374            return; // "no more than 6 channels"
375        }
376        let select = self.select as usize;
377        match reg {
378            2 => {
379                let channel = &mut self.channels[select];
380                channel.frequency = (channel.frequency & 0xF00) | value as i64;
381            }
382            3 => {
383                let channel = &mut self.channels[select];
384                channel.frequency = (channel.frequency & 0x0FF) | (((value & 0x0F) as i64) << 8);
385            }
386            4 => self.write_control(select, value),
387            5 => self.channels[select].balance = value,
388            6 => self.write_wave(select, value & 0x1F),
389            7 if select >= 4 => {
390                self.channels[select].noise_control = value;
391                self.set_noise_period(select);
392            }
393            _ => {}
394        }
395    }
396
397    fn write_control(&mut self, ch: usize, value: u8) {
398        let (was_dda, was_on) = (self.channels[ch].dda(), self.channels[ch].on());
399        self.channels[ch].control = value;
400        if value & 0x40 != 0 {
401            self.channels[ch].index = 0; // [mfr 2.1.5] DDA: the address counter is reset
402        } else if was_dda {
403            self.channels[ch].index = 0; // [pcetech 10] reset when DDA goes 1 -> 0
404            self.channels[ch].counter = self.period(ch);
405        }
406        if self.channels[ch].on() && !was_on && !self.channels[ch].dda() {
407            if self.switches.keyon_mode == KeyOnMode::Reload {
408                self.channels[ch].counter = self.period(ch);
409            } else {
410                self.channels[ch].index = (self.channels[ch].index + 1) & 31;
411            }
412        }
413        self.channels[ch].override_sample = None;
414    }
415
416    fn write_wave(&mut self, ch: usize, value: u8) {
417        let switches = self.switches;
418        let channel = &mut self.channels[ch];
419        if channel.dda() {
420            if channel.on() || !switches.dda_latch_needs_on {
421                channel.latch = value; // [mfr 2.1.7 (3)] "data is transferred directly to the D/A"
422            }
423        } else if !channel.on() {
424            channel.wave[channel.index] = value; // [mfr 2.1.5] write data mode
425            channel.index = (channel.index + 1) & 31;
426        } else if switches.write_wave_while_playing {
427            channel.wave[channel.index] = value;
428        }
429        if switches.r6_overrides_sample_while_on && channel.on() {
430            channel.override_sample = Some(value);
431        }
432    }
433
434    // -- running ----------------------------------------------------------------------------------
435
436    /// Per channel (sample, units left, units right) for the step about to run; sample is
437    /// -1 for a channel that is off (it contributes nothing).
438    pub fn state(&self) -> [(i32, usize, usize); 6] {
439        let mut out = [(0, 0, 0); 6];
440        for (ch, channel) in self.channels.iter().enumerate() {
441            let sample = if !channel.on() {
442                -1
443            } else if ch >= 4 && channel.noise_control & 0x80 != 0 {
444                // [mfr 2.1.8] noise overrides the wave
445                if channel.lfsr & 1 != 0 {
446                    31
447                } else {
448                    0
449                }
450            } else if channel.dda() {
451                channel.latch as i32
452            } else if let Some(sample) = channel.override_sample {
453                sample as i32
454            } else {
455                channel.wave[channel.index] as i32
456            };
457            out[ch] = (sample, self.attenuation(ch, 0), self.attenuation(ch, 1));
458        }
459        out
460    }
461
462    /// Run the steps up to (not including) step `target`.
463    pub fn advance_to(&mut self, target: i64) {
464        while self.step < target {
465            let remaining = target - self.step;
466            let mut n = remaining;
467            let lfo = self.lfo_modulating();
468            for (ch, channel) in self.channels.iter().enumerate() {
469                if self.clocked(ch, channel) {
470                    n = n.min(channel.counter);
471                }
472                if ch >= 4 && (self.switches.noise_free_running || plays_noise(channel)) {
473                    n = n.min(channel.noise_counter);
474                }
475            }
476            if n < 1 {
477                n = 1;
478            }
479            let snapshot = self.state();
480            self.emit(n, &snapshot);
481            self.step += n;
482            self.tick(n, lfo);
483        }
484    }
485
486    /// [mfr 2.1.5] the waveform address advances only in mixing mode (ON, not DDA); LF TRG
487    /// halts channel 2's counter (Mednafen: whatever the LF CTL bits).
488    fn clocked(&self, ch: usize, channel: &Channel) -> bool {
489        if !channel.on() || channel.dda() {
490            return false;
491        }
492        if ch == 1 && self.lfo_control & 0x80 != 0 {
493            return !self.switches.lf_trg_halts_always && self.lfo_control & 3 == 0;
494        }
495        true
496    }
497
498    fn tick(&mut self, n: i64, lfo: bool) {
499        // the modulating sample is read before channel 2 moves in the same step
500        let modulation = self.channels[1].wave[self.channels[1].index] as i64;
501        for ch in 0..6 {
502            if self.clocked(ch, &self.channels[ch]) {
503                self.channels[ch].counter -= n;
504                if self.channels[ch].counter <= 0 {
505                    self.channels[ch].index = (self.channels[ch].index + 1) & 31;
506                    self.channels[ch].override_sample = None;
507                    if ch == 0 && lfo {
508                        let shift = ((self.lfo_control & 3) as u32 - 1) * 2;
509                        let frequency = self.channels[ch].frequency + ((modulation - 16) << shift);
510                        self.channels[ch].counter = self.mask12(frequency);
511                    } else {
512                        self.channels[ch].counter = self.period(ch);
513                    }
514                }
515            }
516            if ch >= 4 && (self.switches.noise_free_running || plays_noise(&self.channels[ch])) {
517                let period = self.noise_period[ch];
518                let channel = &mut self.channels[ch];
519                channel.noise_counter -= n;
520                if channel.noise_counter <= 0 {
521                    let mut bit = 0;
522                    for tap in NOISE_TAPS {
523                        bit ^= (channel.lfsr >> tap) & 1;
524                    }
525                    channel.lfsr = (channel.lfsr >> 1) | (bit << 17);
526                    channel.noise_counter = period;
527                }
528            }
529        }
530    }
531
532    // -- host-rate output ---------------------------------------------------------------------------
533
534    fn emit(&mut self, n: i64, snapshot: &[(i32, usize, usize); 6]) {
535        if !self.switches.render_audio {
536            return;
537        }
538        let (mut left, mut right) = (0.0f64, 0.0f64);
539        for &(sample, ul, ur) in snapshot {
540            if sample >= 0 {
541                left += self.levels[ul] * (sample - 16) as f64;
542                right += self.levels[ur] * (sample - 16) as f64;
543            }
544        }
545        let scale = self.gain / (6 * 16) as f64;
546        let (left, right) = (left * scale, right * scale);
547        let per_sample = 3_579_545.0 / self.rate_hz;
548        let mut remaining = n as f64;
549        while remaining > 0.0 {
550            let room = per_sample - self.phase;
551            let take = room.min(remaining);
552            self.acc[0] += left * take;
553            self.acc[1] += right * take;
554            self.phase += take;
555            remaining -= take;
556            if self.phase >= per_sample - 1e-9 {
557                self.out.push((
558                    round_ties_even(self.acc[0] / per_sample * 32767.0) as i32,
559                    round_ties_even(self.acc[1] / per_sample * 32767.0) as i32,
560                ));
561                self.acc = [0.0, 0.0];
562                self.phase = 0.0;
563            }
564        }
565    }
566
567    /// Stereo samples at `rate_hz` up to `mclk` since the last call (a box average of the
568    /// step stream; the reference check is the unresampled step stream).
569    pub fn take_samples(&mut self, mclk: i64) -> Vec<(i32, i32)> {
570        self.advance_to(py_floordiv(mclk, PSG_CLOCK_DIVIDER));
571        std::mem::take(&mut self.out)
572    }
573}
574
575fn plays_noise(channel: &Channel) -> bool {
576    channel.on() && channel.noise_control & 0x80 != 0
577}
578
579impl PsgPins for Psg {
580    fn write(&mut self, offset: u32, value: u8, mclk: i64) {
581        Psg::write(self, offset, value, mclk);
582    }
583}
584
585impl DeviceState for Psg {}
586
587impl AudioSource for Psg {
588    fn rate_hz(&self) -> f64 {
589        self.rate_hz
590    }
591
592    fn gain(&self) -> f64 {
593        self.gain
594    }
595
596    fn applies_gain(&self) -> bool {
597        true // the mixer (mixer.rs) must not apply `gain` a second time
598    }
599
600    fn take_samples(&mut self, mclk: i64) -> Vec<(i32, i32)> {
601        Psg::take_samples(self, mclk)
602    }
603}