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 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
226/// `10 ** (-1.5 * u / 20)` for u in 0..128, as the bits of each double: the reference's level curve
227/// (psg/chip.py `_levels`). Written out because `powf` is the platform's and is not the same
228/// everywhere: under wasm32 nine of these came out one unit in the last place away, so a state
229/// saved in a browser would not have had a native build's bytes. A test checks this build's `powf`
230/// against the table where the two are expected to agree.
231pub const LEVEL_BITS: [u64; 128] = [
232    0x3ff0000000000000,
233    0x3feaecb5810c240d,
234    0x3fe6a77deae8ab8a,
235    0x3fe30faa0e3d83f5,
236    0x3fe009b9cf334252,
237    0x3fdafd1354c40d50,
238    0x3fd6b54337bc3b65,
239    0x3fd31b4039db843f,
240    0x3fd0137987dd704c,
241    0x3fcb0d7b1b53e057,
242    0x3fc6c310e3769f3f,
243    0x3fc326dd708071b0,
244    0x3fc01d3f2d9684d0,
245    0x3fbb1decdac7bf4d,
246    0x3fb6d0e6f32e6ea2,
247    0x3fb33281b6744ae1,
248    0x3fb0270ac3f8a9fa,
249    0x3fab2e68992f7968,
250    0x3fa6dec56bfd58e5,
251    0x3fa33e2d1001a8a5,
252    0x3fa030dc4ea03a72,
253    0x3f9b3eee5c9e8d27,
254    0x3f96ecac53002712,
255    0x3f9349df8175bf98,
256    0x3f903ab3d12bc2c4,
257    0x3f8b4f7e2b2c2a95,
258    0x3f86fa9bad56bdb7,
259    0x3f8355990f2061bf,
260    0x3f8044914f3c02b0,
261    0x3f7b60180af33584,
262    0x3f77089380241edf,
263    0x3f736159bd540009,
264    0x3f704e74cc73ee88,
265    0x3f6b70bc021247bd,
266    0x3f671693d08e6bee,
267    0x3f636d219065ac0c,
268    0x3f60585e4c78b079,
269    0x3f5b816a16abb36c,
270    0x3f57249ca3bee77b,
271    0x3f5378f08cad1974,
272    0x3f50624dd2f1a9fc,
273    0x3f4b92224ee58528,
274    0x3f4732adfee1f757,
275    0x3f4384c6b6849fb2,
276    0x3f406c4363887513,
277    0x3f3ba2e4b0e98677,
278    0x3f3740c7e7272648,
279    0x3f3390a412493ba6,
280    0x3f30763f01e8e5ad,
281    0x3f2bb3b142e53fda,
282    0x3f274eea61c12623,
283    0x3f239c88a45a9114,
284    0x3f208040b1c10b13,
285    0x3f1bc4880b09fb2e,
286    0x3f175d1573e5d18e,
287    0x3f13a874711aec6c,
288    0x3f108a4876c1311e,
289    0x3f0bd5690f8cc604,
290    0x3f076b4922ce2e00,
291    0x3f03b4677cef4441,
292    0x3f009456549be1bd,
293    0x3efbe65456a673da,
294    0x3ef7798573b66d9e,
295    0x3ef3c061cc3f3b00,
296    0x3ef09e6a4f05e62b,
297    0x3eebf749e693a057,
298    0x3ee787ca6bddf15c,
299    0x3ee3cc636375207c,
300    0x3ee0a88469b64867,
301    0x3edc0849c594b1ae,
302    0x3ed7961810874a9f,
303    0x3ed3d86c46fdf3c0,
304    0x3ed0b2a4a866547e,
305    0x3ecc1953f9eddae6,
306    0x3ec7a46e66f83d5f,
307    0x3ec3e47c7b496466,
308    0x3ec0bccb0ed19a15,
309    0x3ebc2a6889e71e19,
310    0x3eb7b2cd7479c20e,
311    0x3eb3f09404c9d46e,
312    0x3eb0c6f7a0b5ed8d,
313    0x3eac3b877bcc4f03,
314    0x3ea7c1353e58077e,
315    0x3ea3fcb2e7f459d2,
316    0x3ea0d12a61d3698c,
317    0x3e9c4cb0d5ed14f5,
318    0x3e97cfa5c9e27506,
319    0x3e9408d92940c022,
320    0x3e90db6355ec7054,
321    0x3e8c5de49e9ced6b,
322    0x3e87de1f1c6bac2c,
323    0x3e841506cd298a52,
324    0x3e80e5a280c5ad1d,
325    0x3e7c6f22dc332e4c,
326    0x3e77eca13b498acf,
327    0x3e74213bd82bf425,
328    0x3e70efe7e62615a0,
329    0x3e6c806b950b0836,
330    0x3e67fb2c2bd52d0e,
331    0x3e642d784ec7f3f9,
332    0x3e60fa3389d6eb40,
333    0x3e5c91becf838911,
334    0x3e5809bff36aef39,
335    0x3e5439bc35803c6a,
336    0x3e5104856fa3bc97,
337    0x3e4ca31c91ff9e0b,
338    0x3e48185c976a6ffc,
339    0x3e44460790da3df0,
340    0x3e410edd9b5a66d0,
341    0x3e3cb484e2e61623,
342    0x3e3827021d36920b,
343    0x3e34525a655e28c0,
344    0x3e31193c10cb1708,
345    0x3e2cc5f7c8a1a4c3,
346    0x3e2835b08a357e47,
347    0x3e245eb4b796edfa,
348    0x3e2123a0d3c84be6,
349    0x3e1cd77549a0e36d,
350    0x3e184467e3d0a5f2,
351    0x3e146b168c1241ee,
352    0x3e112e0be826d695,
353    0x3e0ce8fd6c565511,
354    0x3e0853282f74c416,
355    0x3e04777fe7609d84,
356    0x3e01387d51bddcae,
357    0x3dfcfa9037386761,
358    0x3df861f17291e056,
359    0x3df483f0ce153f9f,
360];
361
362impl Psg {
363    pub fn new(rate_hz: f64, switches: PsgSwitches) -> Psg {
364        let levels = (0..128)
365            .map(|u| {
366                if u < switches.silent_units {
367                    f64::from_bits(LEVEL_BITS[u])
368                } else {
369                    0.0
370                }
371            })
372            .collect();
373        let mut psg = Psg {
374            switches,
375            channels: Default::default(),
376            select: 0,
377            balance: 0,
378            lfo_frequency: 0,
379            lfo_control: 0,
380            step: 0,
381            rate_hz,
382            gain: 1.0,
383            levels,
384            acc: [0.0, 0.0],
385            acc_steps: 0.0,
386            phase: 0.0,
387            out: Vec::new(),
388            noise_period: [0; 6],
389        };
390        for ch in 0..6 {
391            psg.channels[ch].counter = psg.period(ch);
392        }
393        for ch in [4, 5] {
394            psg.set_noise_period(ch);
395            psg.channels[ch].noise_counter = 1;
396        }
397        psg
398    }
399
400    /// A loaded state keeps the system's own switches and the table made from them.
401    pub(crate) fn keep_configuration(&mut self, live: &Psg) {
402        self.switches = live.switches;
403        self.levels = live.levels.clone();
404    }
405
406    // -- derived values -------------------------------------------------------------------------
407
408    /// [mfr 2.1.10 note] the LFO acts only when channel 1 and 2 are both on; LF TRG halts it.
409    fn lfo_modulating(&self) -> bool {
410        if self.lfo_control & 3 == 0 || self.lfo_control & 0x80 != 0 {
411            return false;
412        }
413        self.channels[1].on() || !self.switches.lfo_requires_ch2_on
414    }
415
416    fn mask12(&self, frequency: i64) -> i64 {
417        if self.switches.lfo_mask12 {
418            let masked = frequency & 0xFFF;
419            if masked != 0 {
420                masked
421            } else {
422                4096
423            }
424        } else {
425            frequency.max(1)
426        }
427    }
428
429    fn period(&self, ch: usize) -> i64 {
430        let channel = &self.channels[ch];
431        let mut frequency = if channel.frequency != 0 {
432            channel.frequency
433        } else {
434            4096
435        };
436        if ch == 0 && self.lfo_modulating() {
437            let shift = ((self.lfo_control & 3) as u32 - 1) * 2; // 0, 2, 4 [mfr 2.1.10]
438            let modulation = self.channels[1].wave[self.channels[1].index] as i64 - 16; // [mfr table]
439            frequency = self.mask12(channel.frequency + (modulation << shift));
440        } else if ch == 1 && self.lfo_control & 3 != 0 {
441            // [mfr 2.2.2] f_LFO = fmaster / (2x32xF2xFLF)
442            frequency *= if self.lfo_frequency != 0 {
443                self.lfo_frequency as i64
444            } else {
445                self.switches.lfo_zero_multiplier
446            };
447        }
448        frequency
449    }
450
451    fn set_noise_period(&mut self, ch: usize) {
452        let nf = 0x1F - (self.channels[ch].noise_control & 0x1F) as i64; // [mfr 2.3.3] NF is the complement
453        self.noise_period[ch] = if nf != 0 {
454            nf * 64
455        } else {
456            self.switches.noise_zero_period
457        }; // 2 x 32 x 2 / 2 steps
458    }
459
460    /// Units of 1.5 dB below the maximum for a channel on one side (0 left, 1 right):
461    /// 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.
462    pub fn attenuation(&self, ch: usize, side: usize) -> usize {
463        let channel = &self.channels[ch];
464        let shift = if side == 0 { 4 } else { 0 };
465        let main = (self.balance >> shift) & 0xF;
466        let pan = (channel.balance >> shift) & 0xF;
467        self.scale(main) + (31 - (channel.control & 0x1F) as usize) + self.scale(pan)
468    }
469
470    /// Units below the maximum for an R1/R5 nibble: 2 a step, 30 for 0 [mfr 2.1.2, 2.1.6].
471    fn scale(&self, nibble: u8) -> usize {
472        if self.switches.scale_table_quirk {
473            const TABLE: [usize; 16] = [0, 3, 5, 7, 9, 11, 13, 15, 16, 19, 21, 23, 25, 27, 29, 31];
474            return 31 - TABLE[nibble as usize];
475        }
476        2 * (15 - nibble as usize)
477    }
478
479    // -- the CPU's port --------------------------------------------------------------------------
480
481    pub fn write(&mut self, offset: u32, value: u8, mclk: i64) {
482        self.advance_to(py_floordiv(mclk, PSG_CLOCK_DIVIDER));
483        self.write_register((offset & 0x0F) as u8, value);
484    }
485
486    fn write_register(&mut self, reg: u8, value: u8) {
487        if reg == 0 {
488            self.select = value & 7;
489            return;
490        }
491        if reg == 1 {
492            self.balance = value;
493            return;
494        }
495        if reg == 8 {
496            self.lfo_frequency = value;
497            // counters pick up a changed period at their next reload
498            return;
499        }
500        if reg == 9 {
501            if value & 0x80 != 0 {
502                // [mfr 2.1.10] LF TRG: ch 2's wave counter and address reset
503                self.channels[1].index = 0;
504                self.channels[1].counter = self.period(1);
505            }
506            self.lfo_control = value;
507            return;
508        }
509        if reg > 7 || self.select > 5 {
510            return; // "no more than 6 channels"
511        }
512        let select = self.select as usize;
513        match reg {
514            2 => {
515                let channel = &mut self.channels[select];
516                channel.frequency = (channel.frequency & 0xF00) | value as i64;
517            }
518            3 => {
519                let channel = &mut self.channels[select];
520                channel.frequency = (channel.frequency & 0x0FF) | (((value & 0x0F) as i64) << 8);
521            }
522            4 => self.write_control(select, value),
523            5 => self.channels[select].balance = value,
524            6 => self.write_wave(select, value & 0x1F),
525            7 if select >= 4 => {
526                self.channels[select].noise_control = value;
527                self.set_noise_period(select);
528            }
529            _ => {}
530        }
531    }
532
533    fn write_control(&mut self, ch: usize, value: u8) {
534        let (was_dda, was_on) = (self.channels[ch].dda(), self.channels[ch].on());
535        self.channels[ch].control = value;
536        if value & 0x40 != 0 {
537            self.channels[ch].index = 0; // [mfr 2.1.5] DDA: the address counter is reset
538        } else if was_dda {
539            self.channels[ch].index = 0; // [pcetech 10] reset when DDA goes 1 -> 0
540            self.channels[ch].counter = self.period(ch);
541        }
542        if self.channels[ch].on() && !was_on && !self.channels[ch].dda() {
543            if self.switches.keyon_mode == KeyOnMode::Reload {
544                self.channels[ch].counter = self.period(ch);
545            } else {
546                self.channels[ch].index = (self.channels[ch].index + 1) & 31;
547            }
548        }
549        self.channels[ch].override_sample = None;
550    }
551
552    fn write_wave(&mut self, ch: usize, value: u8) {
553        let switches = self.switches;
554        let channel = &mut self.channels[ch];
555        if channel.dda() {
556            if channel.on() || !switches.dda_latch_needs_on {
557                channel.latch = value; // [mfr 2.1.7 (3)] "data is transferred directly to the D/A"
558            }
559        } else if !channel.on() {
560            channel.wave[channel.index] = value; // [mfr 2.1.5] write data mode
561            channel.index = (channel.index + 1) & 31;
562        } else if switches.write_wave_while_playing {
563            channel.wave[channel.index] = value;
564        }
565        if switches.r6_overrides_sample_while_on && channel.on() {
566            channel.override_sample = Some(value);
567        }
568    }
569
570    // -- running ----------------------------------------------------------------------------------
571
572    /// Per channel (sample, units left, units right) for the step about to run; sample is
573    /// -1 for a channel that is off (it contributes nothing).
574    pub fn state(&self) -> [(i32, usize, usize); 6] {
575        let mut out = [(0, 0, 0); 6];
576        for (ch, channel) in self.channels.iter().enumerate() {
577            let sample = if !channel.on() {
578                -1
579            } else if ch >= 4 && channel.noise_control & 0x80 != 0 {
580                // [mfr 2.1.8] noise overrides the wave
581                if channel.lfsr & 1 != 0 {
582                    31
583                } else {
584                    0
585                }
586            } else if channel.dda() {
587                channel.latch as i32
588            } else if let Some(sample) = channel.override_sample {
589                sample as i32
590            } else {
591                channel.wave[channel.index] as i32
592            };
593            out[ch] = (sample, self.attenuation(ch, 0), self.attenuation(ch, 1));
594        }
595        out
596    }
597
598    /// Run the steps up to (not including) step `target`.
599    pub fn advance_to(&mut self, target: i64) {
600        while self.step < target {
601            let remaining = target - self.step;
602            let mut n = remaining;
603            let lfo = self.lfo_modulating();
604            for (ch, channel) in self.channels.iter().enumerate() {
605                if self.clocked(ch, channel) {
606                    n = n.min(channel.counter);
607                }
608                if ch >= 4 && (self.switches.noise_free_running || plays_noise(channel)) {
609                    n = n.min(channel.noise_counter);
610                }
611            }
612            if n < 1 {
613                n = 1;
614            }
615            let snapshot = self.state();
616            self.emit(n, &snapshot);
617            self.step += n;
618            self.tick(n, lfo);
619        }
620    }
621
622    /// [mfr 2.1.5] the waveform address advances only in mixing mode (ON, not DDA); LF TRG
623    /// halts channel 2's counter (Mednafen: whatever the LF CTL bits).
624    fn clocked(&self, ch: usize, channel: &Channel) -> bool {
625        if !channel.on() || channel.dda() {
626            return false;
627        }
628        if ch == 1 && self.lfo_control & 0x80 != 0 {
629            return !self.switches.lf_trg_halts_always && self.lfo_control & 3 == 0;
630        }
631        true
632    }
633
634    fn tick(&mut self, n: i64, lfo: bool) {
635        // the modulating sample is read before channel 2 moves in the same step
636        let modulation = self.channels[1].wave[self.channels[1].index] as i64;
637        for ch in 0..6 {
638            if self.clocked(ch, &self.channels[ch]) {
639                self.channels[ch].counter -= n;
640                if self.channels[ch].counter <= 0 {
641                    self.channels[ch].index = (self.channels[ch].index + 1) & 31;
642                    self.channels[ch].override_sample = None;
643                    if ch == 0 && lfo {
644                        let shift = ((self.lfo_control & 3) as u32 - 1) * 2;
645                        let frequency = self.channels[ch].frequency + ((modulation - 16) << shift);
646                        self.channels[ch].counter = self.mask12(frequency);
647                    } else {
648                        self.channels[ch].counter = self.period(ch);
649                    }
650                }
651            }
652            if ch >= 4 && (self.switches.noise_free_running || plays_noise(&self.channels[ch])) {
653                let period = self.noise_period[ch];
654                let channel = &mut self.channels[ch];
655                channel.noise_counter -= n;
656                if channel.noise_counter <= 0 {
657                    let mut bit = 0;
658                    for tap in NOISE_TAPS {
659                        bit ^= (channel.lfsr >> tap) & 1;
660                    }
661                    channel.lfsr = (channel.lfsr >> 1) | (bit << 17);
662                    channel.noise_counter = period;
663                }
664            }
665        }
666    }
667
668    // -- host-rate output ---------------------------------------------------------------------------
669
670    fn emit(&mut self, n: i64, snapshot: &[(i32, usize, usize); 6]) {
671        if !self.switches.render_audio {
672            return;
673        }
674        let (mut left, mut right) = (0.0f64, 0.0f64);
675        for &(sample, ul, ur) in snapshot {
676            if sample >= 0 {
677                left += self.levels[ul] * (sample - 16) as f64;
678                right += self.levels[ur] * (sample - 16) as f64;
679            }
680        }
681        let scale = self.gain / (6 * 16) as f64;
682        let (left, right) = (left * scale, right * scale);
683        let per_sample = 3_579_545.0 / self.rate_hz;
684        let mut remaining = n as f64;
685        while remaining > 0.0 {
686            let room = per_sample - self.phase;
687            let take = room.min(remaining);
688            self.acc[0] += left * take;
689            self.acc[1] += right * take;
690            self.phase += take;
691            remaining -= take;
692            if self.phase >= per_sample - 1e-9 {
693                self.out.push((
694                    round_ties_even(self.acc[0] / per_sample * 32767.0) as i32,
695                    round_ties_even(self.acc[1] / per_sample * 32767.0) as i32,
696                ));
697                self.acc = [0.0, 0.0];
698                self.phase = 0.0;
699            }
700        }
701    }
702
703    /// Stereo samples at `rate_hz` up to `mclk` since the last call (a box average of the
704    /// step stream; the reference check is the unresampled step stream).
705    pub fn take_samples(&mut self, mclk: i64) -> Vec<(i32, i32)> {
706        self.advance_to(py_floordiv(mclk, PSG_CLOCK_DIVIDER));
707        std::mem::take(&mut self.out)
708    }
709}
710
711fn plays_noise(channel: &Channel) -> bool {
712    channel.on() && channel.noise_control & 0x80 != 0
713}
714
715impl PsgPins for Psg {
716    fn write(&mut self, offset: u32, value: u8, mclk: i64) {
717        Psg::write(self, offset, value, mclk);
718    }
719}
720
721impl DeviceState for Psg {}
722
723impl AudioSource for Psg {
724    fn rate_hz(&self) -> f64 {
725        self.rate_hz
726    }
727
728    fn gain(&self) -> f64 {
729        self.gain
730    }
731
732    fn applies_gain(&self) -> bool {
733        true // the mixer (mixer.rs) must not apply `gain` a second time
734    }
735
736    fn take_samples(&mut self, mclk: i64) -> Vec<(i32, i32)> {
737        Psg::take_samples(self, mclk)
738    }
739}