"""The sound unit: the Game Boy's four channels, the two DMA sound FIFOs, the mixer and SOUNDBIAS. - **The four Game Boy channels** are the ``gb-apu-python`` core's AGB row (user decision 4; never copied here). This module is their host: it maps the GBA's register bytes onto the core's Game Boy addresses, converts the system clock to the core's 4,194,304 Hz (four cycles each), and clocks the frame sequencer from the system clock's bit 14, the place the Game Boy's DIV bit 12 has at this clock: a step every 32,768 cycles (512 Hz) from power-on, as NanoBoyAdvance schedules it. The core is caught up only when something looks: a register access or a sample. - **The registers** read back through the GBA's masks (the mGBA suite's "I/O read" group). SOUNDCNT_X's master enable is the core's NR52 power bit: while it is off 4000060-4000081 read 0 and ignore writes, and turning it off empties both FIFOs (NanoBoyAdvance ``registers.cpp``). - **FIFO A and B** as NanoBoyAdvance models them (``hw/apu/channel/fifo.hpp``, ``apu.cpp``): seven words plus a one-word pipe; a timer overflow pops a sample and requests DMA when three words or fewer remain; a write to a full FIFO empties it. - **The mixer** (NanoBoyAdvance ``APU::StepMixer``, the rung's referee): every 512 cycles (32,768 Hz; SOUNDBIAS bits 14-15 halve the interval up to three times) each side sums its enabled channels around zero, scales the Game Boy sum by SOUNDCNT_H's 25/50/100 % and NR50's volume, adds the FIFO samples at 50 or 100 %, adds the bias level and clips to 10 bits. It runs only while ``capture`` is on; ``take_samples()`` returns signed 16-bit stereo at 32,768 Hz (the faster rates are averaged down, which is what the PWM output's filter does). What is not here, and why, is in docs/undocumented-behavior.md (C25-C28). """ from __future__ import annotations from array import array from gb_apu_python import ( AGB, NR10, NR11, NR12, NR13, NR14, NR21, NR22, NR23, NR24, NR30, NR31, NR32, NR33, NR34, NR41, NR42, NR43, NR44, NR50, NR51, NR52, WAVE_RAM, ) from gb_apu_python import APU as GameBoyChannels from gba_python.dma import DMA from gba_python.scheduler import Scheduler FIFO_WORDS = 7 SAMPLE_RATE = 32768 # take_samples(): the mixer's rate at SOUNDBIAS resolution 0 MIX_INTERVAL = 512 # cycles between mixer samples at resolution 0 SEQUENCER_HALF = 4096 # core T-cycles (16,384 system cycles) between frame sequencer edges PSG_VOLUME = (1, 2, 4, 0) # SOUNDCNT_H bits 1-0: 25 %, 50 %, 100 %, prohibited (silent in NBA) #: register byte offset from 4000000 -> the core's Game Boy address PSG_ADDRESS = { 0x60: NR10, 0x62: NR11, 0x63: NR12, 0x64: NR13, 0x65: NR14, 0x68: NR21, 0x69: NR22, 0x6C: NR23, 0x6D: NR24, 0x70: NR30, 0x72: NR31, 0x73: NR32, 0x74: NR33, 0x75: NR34, 0x78: NR41, 0x79: NR42, 0x7C: NR43, 0x7D: NR44, 0x80: NR50, 0x81: NR51, 0x84: NR52, } # fmt: skip #: readable bits of each sound register, by halfword offset from 4000000; absent = write-only #: (FIFOs) or unused (an unused half of a readable word reads 0: io.py) READ_MASK = { 0x60: 0x007F, 0x62: 0xFFC0, 0x64: 0x4000, 0x68: 0xFFC0, 0x6C: 0x4000, 0x70: 0x00E0, 0x72: 0xE000, 0x74: 0x4000, 0x78: 0xFF00, 0x7C: 0x40FF, 0x80: 0xFF77, 0x82: 0x770F, 0x84: 0x008F, # the master enable and the four channels' "playing" flags 0x88: 0xC3FE, # SOUNDBIAS } class FIFO: __slots__ = ("count", "data", "pipe", "pipe_size", "read", "sample", "write") def __init__(self) -> None: self.data = [0] * FIFO_WORDS self.read = self.write = self.count = 0 self.pipe = self.pipe_size = 0 self.sample = 0 # the latched signed sample the mixer will use def reset(self) -> None: self.data = [0] * FIFO_WORDS self.read = self.write = self.count = 0 def push(self, value: int, mask: int) -> None: if self.count < FIFO_WORDS: slot = self.write self.data[slot] = self.data[slot] & ~mask | value & mask self.write = (slot + 1) % FIFO_WORDS self.count += 1 else: self.reset() def pop(self) -> int: value = self.data[self.read] if self.count: self.read = (self.read + 1) % FIFO_WORDS self.count -= 1 return value class APU: def __init__(self, dma: DMA, scheduler: Scheduler) -> None: self.dma = dma self.scheduler = scheduler self.psg = GameBoyChannels(model=AGB) self.psg_t = 0 # core T-cycles the Game Boy channels have run (system cycles // 4) self.soundcnt_h = 0 self.soundbias = 0x200 # at power-on (GBATEK) self.fifo = [FIFO(), FIFO()] self.capture = False self._samples = array("h") self._sum_left = self._sum_right = self._summed = 0 @property def master_enable(self) -> bool: return self.psg.power @property def registers(self) -> list[int]: """Halfwords 4000000-400009E as written (only 60-8A used): for state reports.""" words = [0] * 0x50 raw = self.psg.registers for offset, address in PSG_ADDRESS.items(): if address != NR52: words[offset >> 1] |= raw[address - NR10] << (offset & 1) * 8 words[0x82 >> 1] = self.soundcnt_h words[0x84 >> 1] = 0x80 if self.psg.power else 0 words[0x88 >> 1] = self.soundbias return words # ----- the Game Boy channels' clock --------------------------------------------------- def sync(self) -> None: """Run the Game Boy channels up to now, with the frame sequencer's edges on the way.""" target = self.scheduler.now >> 2 t = self.psg_t psg = self.psg if not psg.power: # nothing runs and the sequencer's edges do nothing t = target while t < target: edge = (t | (SEQUENCER_HALF - 1)) + 1 if edge > target: psg.run(target - t) break psg.run(edge - t) t = edge if edge & SEQUENCER_HALF: psg.secondary_tick() else: psg.frame_tick() self.psg_t = target psg.frame_clock_high = bool(target & SEQUENCER_HALF) # ----- registers ---------------------------------------------------------------------- def read_register(self, offset: int) -> int | None: if 0x90 <= offset < 0xA0: self.sync() address = WAVE_RAM + offset - 0x90 return self.psg.read(address) | self.psg.read(address + 1) << 8 mask = READ_MASK.get(offset) if mask is None: return None if offset == 0x82: return self.soundcnt_h & mask if offset == 0x88: return self.soundbias & mask self.sync() psg = self.psg low, high = PSG_ADDRESS.get(offset), PSG_ADDRESS.get(offset + 1) value = psg.read(low) if low else 0 if high: value |= psg.read(high) << 8 return value & mask def write_register(self, offset: int, value: int, mask: int) -> None: if 0xA0 <= offset < 0xA8: if self.master_enable: shift = (offset & 2) * 8 self.fifo[(offset - 0xA0) >> 2].push(value << shift, mask << shift) return if offset == 0x82: self.soundcnt_h = self.soundcnt_h & ~mask | value & mask if mask & 0xFF00: if value & 0x0800: self.fifo[0].reset() if value & 0x8000: self.fifo[1].reset() return if offset == 0x88: self.soundbias = self.soundbias & ~mask | value & mask return if 0x90 <= offset < 0xA0: base = WAVE_RAM - 0x90 elif offset < 0x86: base = 0 else: return self.sync() psg = self.psg was_on = psg.power for byte in (offset, offset + 1): # the low byte first: NRx3 before NRx4's trigger if mask >> (byte & 1) * 8 & 0xFF: address = byte + base if base else PSG_ADDRESS.get(byte) if address: psg.write(address, value >> (byte & 1) * 8 & 0xFF) if was_on and not psg.power: self.fifo[0].reset() self.fifo[1].reset() def write_fifo_word(self, fifo: int, value: int) -> None: if self.master_enable: self.fifo[fifo].push(value, 0xFFFFFFFF) def timer_overflow(self, timer: int) -> None: """Timer 0 or 1 overflowed: each FIFO clocked by it plays its next sample.""" if not self.master_enable: return soundcnt_h = self.soundcnt_h for index, shift in ((0, 10), (1, 14)): if soundcnt_h >> shift & 1 != timer: continue fifo = self.fifo[index] if fifo.count <= 3: self.dma.request_fifo(index) if fifo.pipe_size == 0 and fifo.count > 0: fifo.pipe = fifo.pop() fifo.pipe_size = 4 byte = fifo.pipe & 0xFF fifo.sample = byte - 256 if byte & 0x80 else byte if fifo.pipe_size: fifo.pipe >>= 8 fifo.pipe_size -= 1 # ----- the mixer ---------------------------------------------------------------------- def start_capture(self) -> None: """Turn the mixer on: from now ``take_samples()`` fills. (Off, nothing is mixed: the registers, the FIFOs and the channels behave the same.)""" if not self.capture: self.capture = True self._schedule_mix() def _schedule_mix(self) -> None: interval = MIX_INTERVAL >> (self.soundbias >> 14) self.scheduler.add(interval - (self.scheduler.now & (interval - 1)), self._mix_event) def mix(self) -> tuple[int, int]: """The two 10-bit outputs now, less 200h: left and right, -512..511.""" self.sync() psg = self.psg if not psg.power: return 0, 0 cnt_h = self.soundcnt_h left = right = 0 on = psg.channel_on if on[0] or on[1] or on[2] or on[3]: # Each channel around zero, as NanoBoyAdvance's GetSample: a pulse or the noise is # +-8 x its envelope volume, the wave (digit - 8) x 4 x its volume in quarters. digital = psg.digital() volumes = psg.volumes() nr51 = psg.nr51 for channel, level in enumerate( ( (2 * digital[0] - volumes[0]) * 8, (2 * digital[1] - volumes[1]) * 8, (psg.wave_digit() - 8) * 4 * psg.wave_quarters(), (2 * digital[3] - volumes[2]) * 8, ) ): if on[channel]: if nr51 & 0x10 << channel: left += level if nr51 & 1 << channel: right += level scale = PSG_VOLUME[cnt_h & 3] nr50 = psg.nr50 left = left * scale * ((nr50 >> 4 & 7) + 1) >> 5 right = right * scale * ((nr50 & 7) + 1) >> 5 fifo_a = self.fifo[0].sample * (4 if cnt_h & 4 else 2) fifo_b = self.fifo[1].sample * (4 if cnt_h & 8 else 2) if cnt_h & 0x0100: right += fifo_a if cnt_h & 0x0200: left += fifo_a if cnt_h & 0x1000: right += fifo_b if cnt_h & 0x2000: left += fifo_b bias = self.soundbias & 0x3FE return ( min(max(left + bias, 0), 0x3FF) - 0x200, min(max(right + bias, 0), 0x3FF) - 0x200, ) def _mix_event(self, _arg: int) -> None: left, right = self.mix() self._sum_left += left self._sum_right += right self._summed += 1 if self._summed >= 1 << (self.soundbias >> 14): self._samples.append(self._sum_left * 64 // self._summed) self._samples.append(self._sum_right * 64 // self._summed) self._sum_left = self._sum_right = self._summed = 0 self._schedule_mix() def take_samples(self) -> array: """Interleaved signed 16-bit stereo at 32,768 Hz since the last call (``capture`` on).""" out, self._samples = self._samples, array("h") return out