// SPDX-License-Identifier: MIT //! The 32X's PWM sound unit: five registers, two three-deep FIFOs, the cycle counter, the //! timer interrupt with DREQ1, and socket 8's stereo source. //! //! Written in 2026-11 from Sega's *32X Hardware Manual* (MAR-32-R4-072294: 3.2.1, 3.2.2, 3.4) //! and, where the Manual is silent, from the behaviour of ares (ISC, revision 9408cb4, //! `ares/md/m32x`; its notice is in NOTICE), described in prose in the quirk records and //! re-expressed here, not translated. Every rule names its source: **DOC** (the Manual), //! **OBSERVED** (an emulator's behaviour, named with its revision: provisional), **CHOICE** //! (the board's own, where nothing decides). Each choice is a `Quirk` (`pwm_*`). //! //! The model, in time measured in SH-2 states (MCLK x 3/7, Manual 3.3): //! //! - **Registers** (DOC, Manual 3.2.1): control (LMD bits 1-0, RMD bits 3-2, RTP bit 7, TM //! bits 11-8; the 68000 writes only LMD and RMD, "TM3-0 ... Read only from MD side", "RTP //! ... (SH2 side only)"), cycle (12 bits), the L, R and mono pulse width registers (FULL //! bit 15, EMPTY bit 14; bits 11-0 write only, read as 0: CHOICE, "undefined data is //! read"). A mono write queues the width in both FIFOs (DOC); a mono read gives the L //! FIFO's FULL/EMPTY (`pwm_registers`, CHOICE). //! - **Byte writes** (`pwm_byte_writes`, OBSERVED ares): a width register's even byte is //! held; its odd byte (or a word) queues the held high bits with it. //! - **FIFOs** (DOC): three deep; a write to a full FIFO discards the oldest. Both drain //! while the counter runs, the side routed off too. //! - **The counter** (`pwm_period`, DOC Manual 3.4): a period is `(cycle - 1) & $FFF` //! states, cycle 0 giving 4,095; cycle 1 stops it. It "does not operate when both L ch and //! R ch are off" (DOC, 3.2.1) and, by `pwm_needs_aden` (CHOICE), while ADEN = 0. Whether //! it may run is asked as each period would begin (OBSERVED ares: the period under way //! finishes); a stopped counter begins a new period at once when it may run again (CHOICE). //! - **Each period's start** (`pwm_fifo`, OBSERVED ares): each FIFO gives up its oldest //! width, or keeps the last (DOC, "When FIFO is empty, the previous pulse width is held"); //! the TM-th period start since the count was cleared raises the PWM interrupt (DOC, 3.2.2: //! TM periods, TM = 0 being 16) and, with RTP, DREQ1 (`pwm_dreq1`). //! - **A cycle write** keeps the period under way (`pwm_cycle_write`, OBSERVED ares); an //! SH-2 write of TM clears the period count (`pwm_timer_restart`, OBSERVED ares). //! - **The output** (`pwm_output_level`): each output's level is its pulse's duty cycle, //! `min((width - 1) & $FFF, period) / period` (the "set value - 1 is the height" rule: //! DOC, Manual 3.4; the rest CHOICE), routed by the table of 3.2.1 (`pwm_routing`), 0 //! while stopped. Socket 8 reads it as a step function sampled once per period's length //! (the current cycle's), so `rate` is the SH-2 clock over that length. //! //! The reference's `pwm.py`. What Rust forced: the reference's PWM keeps its device and //! reads ADEN, the SH-2 side and the board's master clock through it; here each call that //! needs them is lent a [`Links`] (ADEN and the SH-2 side, the device's other fields), and //! the master clock is the device's copy of the board's (`Sega32X::mclk_hz`). use crate::machine::Quirks; use crate::sh2side::SH2Side; /// `next` while the counter is stopped: never reached. pub const STOPPED: i64 = 1 << 62; /// The pulse width FIFOs' depth (DOC, Manual 3.2.1: "three separate FIFO steps"). pub const FIFO_DEPTH: usize = 3; /// Level changes kept for socket 8 before anyone takes them; past this the oldest are /// dropped (nothing is listening: about three seconds at 22 kHz). pub const EVENTS_CAP: usize = 1 << 16; /// The length the sample grid takes when the cycle register gives none (cycle 1): the /// longest period (DOC, Manual 3.4: cycle 0 is 4,095). pub const LONGEST: i64 = 4095; /// SH-2 states in one period for a cycle register value; 0 means the counter stops. /// DOC (Manual 3.4, "Cycle and Pulse Width Settings": "the set value - 1 as a multiple of /// the base clock cycle"; 0 is 4,095; 1 "PWM will no longer operate"). pub fn period_length(cycle: u16) -> i64 { (i64::from(cycle) - 1) & 0xFFF } /// What the PWM reaches of its device (the reference's `self.device`): lent for a call. pub struct Links<'a> { pub aden: bool, pub sh2: Option<&'a mut SH2Side>, } /// The PWM of one 32X: registers, FIFOs and counter, and socket 8's sound source /// (`System::audio_sources`: `rate`, `gain`, `take_samples`). #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct PWM { /// Socket 8's gain (`Quirks.pwm_gain`, an assumption). pub gain: f64, pub needs_aden: bool, /// SH-2 states this unit has run to. pub time: i64, /// The level changes since socket 8's last sample: (time, (left, right)). pub events: Vec<(i64, (f64, f64))>, /// The output now, socket 8's next sample time and the level as of it. pub level: (f64, f64), pub grid: i64, pub grid_level: (f64, f64), pub rate: f64, /// Control as written: LMD (bits 1-0), RMD (3-2), RTP (7), TM (11-8). pub control: u16, pub cycle: u16, /// The L and R FIFOs, oldest first, the 12-bit values as written. pub fifos: [Vec; 2], /// The held words of the L, R and mono width registers (`pwm_byte_writes`). pub latches: [u16; 3], /// The heights now playing on the L and R channels, in SH-2 states. pub heights: [i64; 2], /// Period starts since the count was last cleared (the timer interrupt). pub periods: i64, /// The next period's start, or STOPPED. pub next: i64, /// The length of the period under way (or the last one). pub length: i64, } impl PWM { pub fn new(q: &Quirks, mclk_hz: i64) -> PWM { // Only the chosen values are built; another value in a quirk is refused here. let chosen = [ ("pwm_period", q.pwm_period.value, "cycle - 1"), ("pwm_fifo", q.pwm_fifo.value, "pop at the period's start"), ("pwm_timer_restart", q.pwm_timer_restart.value, "on an SH-2 TM write"), ("pwm_cycle_write", q.pwm_cycle_write.value, "kept"), ("pwm_output_level", q.pwm_output_level.value, "duty cycle of width - 1"), ]; for (name, value, wanted) in chosen { assert_eq!(value, wanted, "Quirks.{name} = {value:?} is not built"); } let mut pwm = PWM { gain: q.pwm_gain.value, needs_aden: q.pwm_needs_aden.value, time: 0, events: Vec::new(), level: (0.0, 0.0), grid: 0, grid_level: (0.0, 0.0), rate: clock_hz(mclk_hz) / LONGEST as f64, control: 0, cycle: 0, fifos: [Vec::new(), Vec::new()], latches: [0; 3], heights: [0; 2], periods: 0, next: STOPPED, length: LONGEST, }; pwm.power_on(); pwm } /// Every register to its power-on value: 0 (DOC, Manual 3.2.1: RTP "0: OFF /// (initial value)"; 3.4: "Immediately after reset, FIFO is empty and the pulse /// width is 0"). The time base and socket 8's grid carry on. pub fn power_on(&mut self) { self.control = 0; self.cycle = 0; self.fifos = [Vec::new(), Vec::new()]; self.latches = [0; 3]; self.heights = [0; 2]; self.periods = 0; self.next = STOPPED; self.length = LONGEST; self.set_level(self.time, (0.0, 0.0)); } // -- time ---------------------------------------------------------------------------- /// DOC (Manual 3.2.1: not "when both L ch and R ch are off"; 3.4: not with cycle /// 1); `pwm_routing` (CHOICE: either field non-zero, 3 included); `pwm_needs_aden` /// (CHOICE). fn may_run(&self, links: &Links) -> bool { if self.control & 0x0F == 0 || period_length(self.cycle) == 0 { return false; } !self.needs_aden || links.aden } /// Run to SH-2 state `until`: every period start due by then, then a stopped /// counter that may now run begins a period. pub fn run(&mut self, until: i64, links: &mut Links) { if until <= self.time { return; } while self.next <= until { self.period_start(self.next, links); } self.time = until; self.kick(links); } fn kick(&mut self, links: &mut Links) { if self.next == STOPPED && self.may_run(links) { self.period_start(self.time, links); } } fn period_start(&mut self, at: i64, links: &mut Links) { if !self.may_run(links) { self.next = STOPPED; self.set_level(at, (0.0, 0.0)); return; } // The length is taken now: a later cycle write waits for the next period // (`pwm_cycle_write`, OBSERVED ares). self.length = period_length(self.cycle); // Each FIFO's oldest width, or the one held (`pwm_fifo`; DOC "held" when empty). for channel in 0..2 { if !self.fifos[channel].is_empty() { let width = self.fifos[channel].remove(0); self.heights[channel] = (i64::from(width) - 1) & 0xFFF; // DOC: "set value - 1" } } // The timer: every TM periods, 0 meaning 16 (DOC, Manual 3.2.2). self.periods += 1; let tm = i64::from((self.control >> 8) & 0xF); if self.periods >= if tm != 0 { tm } else { 16 } { self.periods = 0; self.timer(links); } let output = self.output(); self.set_level(at, output); self.next = at + self.length; } /// The PWM interrupt (DOC, Manual 3.2.2, level 6; latched where its mask allows: /// `SH2Side.raise_pwm`) and, with RTP, DREQ1 (`pwm_dreq1`: DOC, Manual 3.4, "the /// same signal"; both SH-2s, DOC as read from the System Overview's "DMA can set both /// master and slave"; dropped by `SH2Side` after each chip's next step, OBSERVED /// ares). fn timer(&mut self, links: &mut Links) { let Some(sh2) = links.sh2.as_deref_mut() else { return; }; sh2.raise_pwm(); if self.control & 0x80 != 0 { sh2.set_dreq1(1); } } // -- the output ---------------------------------------------------------------------- /// Each output's duty cycle (`pwm_output_level`), routed by 3.2.1's table /// (`pwm_routing`: LMD 1 L, 2 R; RMD 1 R, 2 L; 0 and 3 nothing). fn output(&self) -> (f64, f64) { let length = self.length; let [left_height, right_height] = self.heights; let (lmd, rmd) = (self.control & 3, (self.control >> 2) & 3); let left = match lmd { 1 => left_height, 2 => right_height, _ => 0, }; let right = match rmd { 1 => right_height, 2 => left_height, _ => 0, }; (left.min(length) as f64 / length as f64, right.min(length) as f64 / length as f64) } fn set_level(&mut self, at: i64, level: (f64, f64)) { if level == self.level { return; } self.level = level; self.events.push((at, level)); if self.events.len() > EVENTS_CAP { // Nobody is taking samples: keep only the present. self.events.clear(); self.grid_level = level; self.grid = at; } } /// The rate of the samples `take_samples` last returned (Hz). pub fn rate(&self) -> f64 { self.rate } /// Socket 8: run to `mclk` and return the output sampled once per period's /// length since the last call (one length per call: the period's under way, or while /// stopped the cycle register's, or 4,095 for cycle 1). pub fn take_samples(&mut self, mclk: i64, mclk_hz: i64, links: &mut Links) -> Vec<(f64, f64)> { self.run(mclk * 3 / 7, links); let stopped = self.next == STOPPED; let length = if stopped { let length = period_length(self.cycle); if length != 0 { length } else { LONGEST } } else { self.length }; let end = self.time; let count = self.events.len(); let mut index = 0; let mut level = self.grid_level; let mut at = self.grid; let mut samples = Vec::new(); while at < end { while index < count && self.events[index].0 <= at { level = self.events[index].1; index += 1; } samples.push(level); at += length; } self.events.drain(..index); self.grid = at; self.grid_level = level; self.rate = clock_hz(mclk_hz) / length as f64; samples } // -- registers ----------------------------------------------------------------------- /// FULL (bit 15) and EMPTY (bit 14); bits 11-0 read 0 (DOC: "undefined data"). fn status(&self, channel: usize) -> u16 { let size = self.fifos[channel].len(); (if size >= FIFO_DEPTH { 0x8000 } else { 0 }) | (if size == 0 { 0x4000 } else { 0 }) } /// A word of $A15130-$A1513F (`sh2` false) or $20004030-$2000403F. pub fn read(&self, offset: u32, _sh2: bool) -> u16 { match offset & 0x3E { 0x30 => self.control & 0x0F8F, 0x32 => self.cycle, 0x34 => self.status(0), 0x36 => self.status(1), 0x38 => self.status(0), // `pwm_registers`: mono reads L (CHOICE) _ => 0, // $3A-$3E: nothing there (CHOICE) } } /// A write of `value` on byte `lanes` ($FF00 even, $00FF odd, $FFFF a word). pub fn write(&mut self, offset: u32, value: u16, lanes: u16, sh2: bool, links: &mut Links) { let offset = offset & 0x3E; if offset == 0x30 { if lanes & 0x00FF != 0 { // The 68000 writes LMD and RMD only; RTP is the SH-2's (DOC, 3.2.1). let mask = if sh2 { 0x8F } else { 0x0F }; self.control = (self.control & !mask) | (value & mask); if sh2 && value & 0x80 == 0 { if let Some(side) = links.sh2.as_deref_mut() { side.set_dreq1(0); // `pwm_dreq1` (OBSERVED ares) } } } if lanes & 0xFF00 != 0 && sh2 { // TM, "set from SH2 side" (DOC); the count starts again // (`pwm_timer_restart`, OBSERVED ares). self.control = (self.control & !0x0F00) | (value & 0x0F00); self.periods = 0; } if self.next != STOPPED { let output = self.output(); self.set_level(self.time, output); } } else if offset == 0x32 { // 12 bits (DOC); the period under way keeps its length (`pwm_cycle_write`). self.cycle = ((self.cycle & !lanes) | (value & lanes)) & 0x0FFF; } else if offset == 0x34 || offset == 0x36 || offset == 0x38 { let which = ((offset - 0x34) >> 1) as usize; let mut held = self.latches[which]; if lanes & 0xFF00 != 0 { held = (held & 0x00FF) | (value & 0x0F00); } if lanes & 0x00FF != 0 { held = (held & 0x0F00) | (value & 0x00FF); let channels: &[usize] = if which == 2 { &[0, 1] } else { &[which] }; // mono: both (DOC) for &channel in channels { let fifo = &mut self.fifos[channel]; if fifo.len() >= FIFO_DEPTH { fifo.remove(0); // DOC: "the oldest data is discarded" } fifo.push(held); } } self.latches[which] = held; } self.kick(links); } } /// The SH-2's clock in Hz: the board's master clock x 3/7 (the reference's `_clock_hz`). pub fn clock_hz(mclk_hz: i64) -> f64 { mclk_hz as f64 * 3.0 / 7.0 }