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