"""The 32X's PWM sound (milestone 5): registers, FIFOs, the cycle counter, the timer interrupt, DREQ1, the routing, the output level and socket 8's audio source. **What the documents give** (Manual 3.2.1, 3.2.2, 3.4; "DMA Controller Settings" in chapter 5). Two channels, L and R, each a three-deep FIFO of 12-bit pulse widths; a 12-bit cycle register whose value "x Scyc becomes the cycle" (Scyc: one SH-2 clock); a width "x Scyc becomes the pulse width". The counter "does not operate when both L ch and R ch are off"; with one side on, "the OFF side FIFO is also operating, no sound will be output; however, data within FIFO will disappear"; a write to a full FIFO discards the oldest word. TM "set[s] the PWM timer interrupt interval and ROM to PWM transfer cycle": every TM periods (TM = 0: 16) the PWM interrupt (level 6) and, with RTP, DREQ1 to SH-2 DMA channel 1, whose settings the Manual fixes as an external request, rising edge (``CHCR1 = 00XX 01/10 00 1110 0XXX``). Routing per output (RMD, LMD): off, the same side's channel, the opposite side's, or "not allowed". **What the board chooses** where they stop, each a :class:`~sega32x_python.machine.Quirk` (docs/undocumented-behavior.md, "What the board chose for PWM"): the period in SH-2 states (``pwm_period``: cycle - 1, as every software detector; the Manual and the MiSTer core say cycle), the FIFO's pop at each period's end with the last width held while it is empty (``pwm_fifo``), the routing (``pwm_routing``), the TM count restarting on a control write (``pwm_timer_restart``), the counter's phase kept across a cycle write (``pwm_cycle_write``), DREQ1 as a request each SH-2's DMAC sees at its next step (``pwm_dreq1``), the counter stopped with ADEN = 0 (``pwm_needs_aden``), and the output: the duty cycle, min(width, period) / period, unipolar, with nothing of the 32X's own analog stage (``pwm_output_level``) and a gain against the Mega Drive's FM that is an **assumption** (``pwm_gain``; docs/claims.md: PWM rests on detectors). **Time.** Everything here counts SH-2 states (the board's ``mclk * 3 // 7``). The counter is lazy: :meth:`PWM.run` brings it to a state, period by period, from register accesses (either side), from the SH-2 side's catch-up loop when :attr:`PWM.next` falls due (so the interrupt and DREQ1 land on their period's end, give or take the instruction in flight), and from :meth:`PWM.take_samples`. **The stream** (socket 8, ``sockets.AudioSource``). Output is kept as runs of (states, left, right) levels -- a pulse-width modulator's integrated output is a step per period -- and :meth:`PWM.take_samples` reads them on a grid of the current period, so each call's samples share one rate, ``rate``, which follows the cycle register from call to call. A period's level is read at the period's end: one sample per period while the period is unchanged; a stretch played at another period (a cycle write between two calls) is read on the new grid by zero-order hold, exact in time. Nothing is handed over until the counter first runs, so a passive 32X adds nothing to megadrive-python's mix; the first samples handed over start with silence back to the previous take, since the mixer lines a source's first sample up with the start of the stretch it mixes. """ from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from .slot import Sega32X #: The FIFO's depth (Manual 3.2.1: "three separate FIFO steps"). FIFO_DEPTH = 3 #: Never: the next event's state while the counter is stopped. NEVER = 1 << 62 #: The Mega Drive's MCLK on NTSC, for a device not yet plugged in (the rate's base). NTSC_MCLK = 53_693_175 class PWM: """PWM of one 32X (``device``). Registers as both sides see them: :attr:`control` (TM 11-8, RTP 7, RMD 3-2, LMD 1-0), :attr:`cycle`, the FIFOs (L, R).""" def __init__(self, device: Sega32X) -> None: self.device = device q = device.machine.quirks self._period_rule = q.pwm_period.value self._needs_aden = q.pwm_needs_aden.value self._restart_timer = q.pwm_timer_restart.value self._restart_cycle = q.pwm_cycle_write.value != "kept" #: Socket 8's gain (an assumption, ``Quirks.pwm_gain``). self.gain = float(q.pwm_gain.value) self.power_on() def power_on(self) -> None: self.control = 0 self.cycle = 0 self.fifos: tuple[list[int], list[int]] = ([], []) #: The even (high) byte last written to each width register ($34, $36, $38). self.latches = {0x34: 0, 0x36: 0, 0x38: 0} #: The width each channel plays: the last word its FIFO gave (``pwm_fifo``). self.widths = [0, 0] #: The state the counter has run to, the current period's start, and periods since #: the last timer event. self.time = 0 self.period_start = 0 self.timer = 0 #: The state of the current period's end (the catch-up loop's event), or NEVER. self.next = NEVER #: The output levels (0.0-1.0 duty) during the current period. self.levels = (0.0, 0.0) #: Output runs not yet handed over: [states, left, right]. self.runs: list[list] = [] #: The counter has run since power-on, and from which state; whether socket 8 has #: been handed anything yet, and the state the last take reached. self.started = False self.started_at = 0 self.streaming = False self.taken_to = 0 #: take_samples: the grid (states per sample) and its phase carried between calls. self.grid = 0 self._phase = 0 #: DREQ1 pulses raised (count) and periods run (count): for tests and traces. self.dreq1_count = 0 self.periods = 0 # -- the counter ----------------------------------------------------------------- def period(self) -> int: """States per period, or 0 when the cycle register stops the counter (``Quirks.pwm_period``).""" if self._period_rule == "cycle - 1": return (self.cycle - 1) & 0xFFF # cycle 1: 0, stopped; cycle 0: 4,095 return self.cycle def counting(self) -> bool: """The cycle counter runs: a side routed (either field non-zero; Manual 3.2.1), a period, and ADEN (``Quirks.pwm_needs_aden``).""" if self._needs_aden and not self.device.adapter & 1: return False return bool(self.control & 0xF) and self.period() > 0 def run(self, now: int) -> None: """Bring the counter to SH-2 state ``now``.""" previous = self.time if now <= previous: return self.time = now period = self.period() if not self.counting(): if self.started: self._emit(now - previous, 0.0, 0.0) self.period_start = now self.next = NEVER return self._start_stream(previous) # ``previous`` is never before the period's start: what lies between them has # been emitted already. start = self.period_start end = start + period while end <= now: if end > previous: # a cycle write may have shortened a period already past self._emit(end - previous, *self.levels) previous = end start = end self._period_end(end) period = self.period() end = start + period self._emit(now - previous, *self.levels) self.period_start = start self.next = end def _period_end(self, at: int) -> None: """One period ends at state ``at``: each FIFO gives its next word (both, the side routed off too: Manual 3.2.1), the next period's levels follow, and every TM periods the timer fires.""" self.periods += 1 for side in (0, 1): fifo = self.fifos[side] if fifo: self.widths[side] = fifo.pop(0) self.levels = self._levels() self.timer += 1 if self.timer >= ((self.control >> 8) & 0xF or 16): self.timer = 0 self._timer_event() def _levels(self) -> tuple[float, float]: """Each output's duty cycle (``Quirks.pwm_routing``, ``Quirks.pwm_output_level``): LMD 1 plays L, 2 plays R; RMD 1 plays R, 2 plays L; 0 and 3 nothing.""" period = self.period() if not period: return (0.0, 0.0) control = self.control out = [] for mode, same, other in ((control & 3, 0, 1), ((control >> 2) & 3, 1, 0)): if mode == 1: width = self.widths[same] elif mode == 2: width = self.widths[other] else: out.append(0.0) continue out.append(min(width, period) / period) return (out[0], out[1]) def _timer_event(self) -> None: """The PWM interrupt to the SH-2s that enable it, and DREQ1 with RTP (``Quirks.pwm_dreq1``): raised on both SH-2s' DMACs, each sees it at the start of its next step and ``SH2Side.catch_up`` drops it after that step.""" sh2 = self.device.sh2 if sh2 is None or not sh2.running: return sh2.raise_pwm() if self.control & 0x80: self.dreq1_count += 1 for chip in sh2.chips: chip.dreq1 = 1 def _emit(self, states: int, left: float, right: float) -> None: if states <= 0: return runs = self.runs if runs and runs[-1][1] == left and runs[-1][2] == right: runs[-1][0] += states else: runs.append([states, left, right]) # -- registers ------------------------------------------------------------------- def read(self, offset: int, *, sh2: bool) -> int: """$30 control, $32 cycle, $34/$36/$38 pulse width (Manual 3.2.1): the width registers read FULL (bit 15) and EMPTY (bit 14) of their FIFO; mono reads the left one (``Quirks.pwm_registers``).""" if offset == 0x30: return self.control if sh2 else self.control & 0x0F8F if offset == 0x32: return self.cycle if offset in (0x34, 0x36, 0x38): fifo = self.fifos[1 if offset == 0x36 else 0] return (0x8000 if len(fifo) >= FIFO_DEPTH else 0) | (0x4000 if not fifo else 0) return 0 def write(self, offset: int, value: int, lanes: int, *, sh2: bool) -> None: """A register write, the counter already brought to the write's state.""" keep = ~lanes & 0xFFFF value &= lanes if offset == 0x30: was = self.counting() # The 68000 writes only the routing bits; TM and RTP are the SH-2s' (Manual). writable = 0x0F8F if sh2 else 0x000F self.control = (self.control & ~writable | (self.control & keep | value) & writable) & 0x0F8F # fmt: skip if self._restart_timer: self.timer = 0 # Quirks.pwm_timer_restart self._restarted(was) elif offset == 0x32: was = self.counting() self.cycle = ((self.cycle & keep) | value) & 0x0FFF if self._restart_cycle: self.period_start = self.time self._restarted(was) elif offset in (0x34, 0x36, 0x38): # Quirks.pwm_byte_writes: the even byte is held; the odd byte, or a word, # queues the width. if lanes == 0xFF00: self.latches[offset] = value >> 8 return if lanes == 0x00FF: value |= self.latches[offset] << 8 for side in (0, 1) if offset == 0x38 else (1 if offset == 0x36 else 0,): fifo = self.fifos[side] if len(fifo) >= FIFO_DEPTH: fifo.pop(0) # "the oldest data is discarded" (Manual 3.2.1) fifo.append(value & 0x0FFF) def _restarted(self, was: bool) -> None: """After a control or cycle write: a counter that starts begins a period now with its TM count at 0; the levels follow the routing and period at once.""" now = self.counting() if now and not was: self.period_start = self.time self.timer = 0 self._start_stream(self.time) self.levels = self._levels() if now else (0.0, 0.0) self.next = self.period_start + self.period() if now else NEVER def _start_stream(self, at: int) -> None: if not self.started: self.started = True self.started_at = at # -- socket 8 ------------------------------------------------------------------- @property def rate(self) -> float: """The samples' rate in Hz: the SH-2 clock (MCLK x 3/7) over the grid.""" board = self.device.board mclk = board.machine.mclk if board is not None else NTSC_MCLK return mclk * 3 / 7 / (self.grid or 4095) def take_samples(self, mclk: int) -> list[tuple[float, float]]: """Socket 8: the 32X caught up to ``mclk`` (socket 4's own catch-up), the counter run to it, and the output since the last call as (left, right) duty cycles, one per ``grid`` states (see the module's docstring).""" self.device.catch_up(mclk) now = mclk * 3 // 7 self.run(now) if not self.started: self.taken_to = now return [] if not self.streaming: # The mixer lines a source's first samples up with the start of the stretch # it is mixing (the last take's clock): what came before the counter started # is silence. self.streaming = True lead = self.started_at - self.taken_to if lead > 0: self.runs.insert(0, [lead, 0.0, 0.0]) self.taken_to = now period = self.period() if period and self.counting(): self.grid = period elif not self.grid: self.grid = period or 4095 grid = self.grid phase = self._phase out: list[tuple[float, float]] = [] append = out.append for states, left, right in self.runs: phase += states while phase >= grid: phase -= grid append((left, right)) self._phase = phase self.runs = [] return out __all__ = ["FIFO_DEPTH", "NEVER", "PWM"]