# 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 :class:`~sega32x_python.machine.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. """ from __future__ import annotations from typing import TYPE_CHECKING from megadrive_python.machine import MCLK_NTSC if TYPE_CHECKING: from .slot import Sega32X #: ``next`` while the counter is stopped: never reached. STOPPED = 1 << 62 #: The pulse width FIFOs' depth (DOC, Manual 3.2.1: "three separate FIFO steps"). FIFO_DEPTH = 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). EVENTS_CAP = 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). LONGEST = 4095 def period_length(cycle: int) -> int: """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").""" return (cycle - 1) & 0xFFF class PWM: """The PWM of one 32X: registers, FIFOs and counter, and socket 8's sound source (``System.audio_sources``: ``rate``, ``gain``, ``take_samples``).""" def __init__(self, device: Sega32X) -> None: self.device = device q = device.machine.quirks # Only the chosen values are built; another value in a quirk is refused here. chosen = { "pwm_period": "cycle - 1", "pwm_fifo": "pop at the period's start", "pwm_timer_restart": "on an SH-2 TM write", "pwm_cycle_write": "kept", "pwm_output_level": "duty cycle of width - 1", } for name, value in chosen.items(): if getattr(q, name).value != value: raise NotImplementedError(f"Quirks.{name} = {getattr(q, name).value!r}") #: Socket 8's gain (``Quirks.pwm_gain``, an assumption). self.gain = float(q.pwm_gain.value) self._needs_aden = bool(q.pwm_needs_aden.value) #: SH-2 states this unit has run to. self.time = 0 #: The level changes since socket 8's last sample: (time, (left, right)). self._events: list[tuple[int, tuple[float, float]]] = [] #: The output now, socket 8's next sample time and the level as of it. self._level = (0.0, 0.0) self._grid = 0 self._grid_level = (0.0, 0.0) self._rate = self._clock_hz() / LONGEST self.power_on() def power_on(self) -> None: """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.""" #: Control as written: LMD (bits 1-0), RMD (3-2), RTP (7), TM (11-8). self.control = 0 self.cycle = 0 #: The L and R FIFOs, oldest first, the 12-bit values as written. self.fifos: tuple[list[int], list[int]] = ([], []) #: The held words of the L, R and mono width registers (``pwm_byte_writes``). self.latches = [0, 0, 0] #: The heights now playing on the L and R channels, in SH-2 states. self.heights = [0, 0] #: Period starts since the count was last cleared (the timer interrupt). self.periods = 0 #: The next period's start, or STOPPED. self.next = STOPPED #: The length of the period under way (or the last one). self.length = LONGEST self._set_level(self.time, (0.0, 0.0)) # -- time ---------------------------------------------------------------------------- def _may_run(self) -> bool: """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).""" if not self.control & 0x0F or period_length(self.cycle) == 0: return False return not self._needs_aden or self.device.aden def run(self, until: int) -> None: """Run to SH-2 state ``until``: every period start due by then, then a stopped counter that may now run begins a period.""" if until <= self.time: return while self.next <= until: self._period_start(self.next) self.time = until self._kick() def _kick(self) -> None: if self.next == STOPPED and self._may_run(): self._period_start(self.time) def _period_start(self, at: int) -> None: if not self._may_run(): 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, fifo in enumerate(self.fifos): if fifo: self.heights[channel] = (fifo.pop(0) - 1) & 0xFFF # DOC: "set value - 1" # The timer: every TM periods, 0 meaning 16 (DOC, Manual 3.2.2). self.periods += 1 if self.periods >= ((self.control >> 8) & 0xF or 16): self.periods = 0 self._timer() self._set_level(at, self._output()) self.next = at + self.length def _timer(self) -> None: """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).""" sh2 = self.device.sh2 if sh2 is None: return sh2.raise_pwm() if self.control & 0x80: sh2.set_dreq1(1) # -- the output ---------------------------------------------------------------------- def _output(self) -> tuple[float, float]: """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).""" length = self.length left_height, right_height = self.heights lmd, rmd = self.control & 3, (self.control >> 2) & 3 left = left_height if lmd == 1 else right_height if lmd == 2 else 0 right = right_height if rmd == 1 else left_height if rmd == 2 else 0 return (min(left, length) / length, min(right, length) / length) def _set_level(self, at: int, level: tuple[float, float]) -> None: if level == self._level: return self._level = level events = self._events events.append((at, level)) if len(events) > EVENTS_CAP: # Nobody is taking samples: keep only the present. events.clear() self._grid_level = level self._grid = at def _clock_hz(self) -> float: board = self.device.board mclk = board.machine.mclk if board is not None else MCLK_NTSC return mclk * 3 / 7 @property def rate(self) -> float: """The rate of the samples ``take_samples`` last returned (Hz).""" return self._rate def take_samples(self, mclk: int) -> list[tuple[float, float]]: """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).""" self.run(mclk * 3 // 7) stopped = self.next == STOPPED length = (period_length(self.cycle) or LONGEST) if stopped else self.length end = self.time events = self._events count = len(events) index = 0 level = self._grid_level at = self._grid samples = [] while at < end: while index < count and events[index][0] <= at: level = events[index][1] index += 1 samples.append(level) at += length del events[:index] self._grid, self._grid_level = at, level self._rate = self._clock_hz() / length return samples # -- registers ----------------------------------------------------------------------- def _status(self, channel: int) -> int: """FULL (bit 15) and EMPTY (bit 14); bits 11-0 read 0 (DOC: "undefined data").""" size = len(self.fifos[channel]) return (0x8000 if size >= FIFO_DEPTH else 0) | (0x4000 if size == 0 else 0) def read(self, offset: int, *, sh2: bool) -> int: """A word of $A15130-$A1513F (``sh2`` False) or $20004030-$2000403F.""" offset &= 0x3E if offset == 0x30: return self.control & 0x0F8F if offset == 0x32: return self.cycle if offset == 0x34: return self._status(0) if offset == 0x36: return self._status(1) if offset == 0x38: return self._status(0) # ``pwm_registers``: mono reads L (CHOICE) return 0 # $3A-$3E: nothing there (CHOICE) def write(self, offset: int, value: int, lanes: int, *, sh2: bool) -> None: """A write of ``value`` on byte ``lanes`` ($FF00 even, $00FF odd, $FFFF a word).""" offset &= 0x3E if offset == 0x30: if lanes & 0x00FF: # The 68000 writes LMD and RMD only; RTP is the SH-2's (DOC, 3.2.1). mask = 0x8F if sh2 else 0x0F self.control = (self.control & ~mask) | (value & mask) if sh2 and not value & 0x80 and self.device.sh2 is not None: self.device.sh2.set_dreq1(0) # ``pwm_dreq1`` (OBSERVED ares) if lanes & 0xFF00 and 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: self._set_level(self.time, self._output()) elif offset == 0x32: # 12 bits (DOC); the period under way keeps its length (``pwm_cycle_write``). self.cycle = ((self.cycle & ~lanes) | (value & lanes)) & 0x0FFF elif offset in (0x34, 0x36, 0x38): which = (offset - 0x34) >> 1 held = self.latches[which] if lanes & 0xFF00: held = (held & 0x00FF) | (value & 0x0F00) if lanes & 0x00FF: held = (held & 0x0F00) | (value & 0x00FF) for channel in (0, 1) if which == 2 else (which,): # mono: both (DOC) fifo = self.fifos[channel] if len(fifo) >= FIFO_DEPTH: fifo.pop(0) # DOC: "the oldest data is discarded" fifo.append(held) self.latches[which] = held self._kick() __all__ = ["FIFO_DEPTH", "PWM", "period_length"]