# SPDX-License-Identifier: MIT """The sound unit around gb-apu-python's AGB row: the register map, FIFOs A/B and their DMA requests, SOUNDCNT_H, SOUNDBIAS, and the mixer that makes the board's output samples. docs/sound.md (GBATEK §GBA Sound Control Registers, §GBA Sound Channel A and B; DOC) and the contract of gb-apu-python (README.md, docs/contract.md outside "The AGB row"). The APU runs on T-cycles of 4,194,304 Hz, exactly the board's clock / 4 (DOC; contract "The clock"); the board brings it up to time when a sound register is touched and at each sequencer step. """ from __future__ import annotations from gb_apu_python import AGB, APU, NR52, READ_MASKS_AGB, WAVE_RAM from gba_python.scheduler import ORDER_SOUND # GBA offset -> Game Boy register (GBATEK §GBA I/O Map pairs them; DOC; docs/sound.md). BYTE_MAP = { 0x60: 0xFF10, 0x62: 0xFF11, 0x63: 0xFF12, 0x64: 0xFF13, 0x65: 0xFF14, 0x68: 0xFF16, 0x69: 0xFF17, 0x6C: 0xFF18, 0x6D: 0xFF19, 0x70: 0xFF1A, 0x72: 0xFF1B, 0x73: 0xFF1C, 0x74: 0xFF1D, 0x75: 0xFF1E, 0x78: 0xFF20, 0x79: 0xFF21, 0x7C: 0xFF22, 0x7D: 0xFF23, 0x80: 0xFF24, 0x81: 0xFF25, 0x84: NR52, } # fmt: skip # The sequencer's period: one step every 32,768 cycles from power-on (HYPOTHESIS, U-SND-1). SEQUENCER_PERIOD = 32768 FIFO_A, FIFO_B = 0x040000A0, 0x040000A4 FIFO_BYTES = 32 # GBATEK's 8 x 32 bits (DOC; gbadoc says 8 bytes: U-SND-4) # When a FIFO asks for data. GBATEK: "If FIFO contains only 4 x 32bits (16 bytes) then request # more data per DMA" (DOC), read before 2026-11-23 as "16 bytes or fewer after the overflow's # move". TEST ROM (alyosha-tas fifo_dma, hardware-captured; docs/validation.md "The FIFO DMA # timing study"): fifo_4 loads 16 bytes and the console's DMA comes at the second overflow, # not the first, so the request is "fewer than 16 bytes before the move" (15 or fewer after); # fifo_5 loads 32 bytes and the console's DMA comes at the first overflow, so a full FIFO # asks as an empty one would (a 5-bit count that wraps at 32: the mechanism is a HYPOTHESIS; # whether the 32 bytes still play is not tested). Provisional (U-SND-6). REQUEST_BELOW = 16 # The output sample period for SOUNDBIAS bits 14-15: 32,768, 65,536, 131,072 or 262,144 Hz # (GBATEK §GBA Sound Control Registers; DOC), counted from power-on (HYPOTHESIS, U-SND-10). SAMPLE_PERIODS = (512, 256, 128, 64) CLOCK = 16777216 # the system clock (GBATEK §System Clock; DOC) def psg_level(digital: int, master: int, share: int) -> int: """One PSG channel's part of the 10-bit sum (U-SND-9, HYPOTHESIS): the DAC's 0-15 input as a level centred at 7.5, through NR50's 0-7 master volume as (v + 1) / 8, so that at the largest settings a channel spans GBATEK's +/-80h ("Max Output Levels"; DOC); then SOUNDCNT_H's 25/50/100 % (``share`` 2, 1, 0 bits of right shift; value 3 as 100 %, U-SND-3). """ return ((2 * digital - 15) * (master + 1) * 16 // 15) >> share def fifo_level(sample: int, full: bool) -> int: """A FIFO's signed 8-bit sample in the 10-bit sum: 100 % spans GBATEK's +/-200h (x 4), 50 % half of it (x 2) ("Max Output Levels"; DOC; the exact scale HYPOTHESIS, docs/sound.md).""" signed = sample - 256 if sample & 0x80 else sample return signed * (4 if full else 2) class Sound: def __init__(self, board) -> None: self.board = board self.apu = APU(model=AGB) self.apu_time = 0 # the board cycle the APU has been run to (a multiple of 4) self.soundcnt_h = 0 self.soundbias = 0 # the BIOS sets 0200 (DOC); before it, HYPOTHESIS 0 self.fifos = ([], []) self.samples = [0, 0] # the sample each FIFO is playing self.master = False # SOUNDCNT_X bit 7, the PSG/FIFO master enable board.scheduler.schedule(SEQUENCER_PERIOD, ORDER_SOUND, self.sequencer_step) # The output: off until a host asks (start_capture). Sampling changes nothing the # CPU can see; it only reads the channels' outputs at the sample times. self.capture = False self.output: list[tuple[int, int, int]] = [] # (left, right, period in cycles) def catch_up(self, time: int) -> None: cycles = (time - self.apu_time) & ~3 if cycles > 0: self.apu.run(cycles >> 2) self.apu_time += cycles def sequencer_step(self, time: int) -> None: self.catch_up(time) self.apu.frame_tick() self.board.scheduler.schedule( time + SEQUENCER_PERIOD // 2, ORDER_SOUND, self.sequencer_half ) self.board.scheduler.schedule(time + SEQUENCER_PERIOD, ORDER_SOUND, self.sequencer_step) def sequencer_half(self, time: int) -> None: # contract "The frame sequencer": the rising edge half a period later. self.catch_up(time) self.apu.secondary_tick() # ---------------------------------------------------------------------------------- # The FIFOs def timer_overflow(self, timer: int, time: int) -> None: """Each overflow of a FIFO's timer moves one sample to its output (GBATEK; DOC). The FIFO asks its DMA for more when it held fewer than 16 bytes before that move, counting a full FIFO of 32 bytes as 0 (REQUEST_BELOW, ``% FIFO_BYTES``; U-SND-6).""" for which in (0, 1): if (self.soundcnt_h >> (10 + 4 * which)) & 1 != timer: continue fifo = self.fifos[which] held = len(fifo) % FIFO_BYTES if fifo: self.samples[which] = fifo.pop(0) # An empty FIFO keeps the last sample (HYPOTHESIS, U-SND-8). if held < REQUEST_BELOW: self.board.dma.fifo_request(FIFO_B if which else FIFO_A, time) def push(self, which: int, value: int, count: int) -> None: if not self.master: # Writes while the master enable is off load nothing: alyosha-tas fifo_dma/fifo.asm # test 2 ("on console a DMA happens indicating no samples are loaded"; TEST ROM). return fifo = self.fifos[which] for i in range(count): if len(fifo) < FIFO_BYTES: fifo.append((value >> (8 * i)) & 0xFF) # ---------------------------------------------------------------------------------- # Registers def read16(self, offset: int) -> int | None: if offset == 0x82: return self.soundcnt_h & 0x770F # bits 11/15 (FIFO reset) read 0 (mGBA suite) if offset == 0x88: return self.soundbias & 0xC3FE if 0x90 <= offset < 0xA0: self.catch_up(self.board.bus.now) apu = self.apu index = offset - 0x90 return apu.read(WAVE_RAM + index) | apu.read(WAVE_RAM + index + 1) << 8 if 0x60 <= offset <= 0x84: low = BYTE_MAP.get(offset) high = BYTE_MAP.get(offset + 1) if low is None and high is None: # The unused halves next to readable ones read 0 (bus.read_io's rule); the # fragments 0x86, 0x8A read 0 per the mGBA suite (TEST ROM). return None if offset not in (0x66, 0x6A, 0x6E, 0x76, 0x7A, 0x7E) else 0 self.catch_up(self.board.bus.now) return self.read_byte(low) | self.read_byte(high) << 8 if offset in (0x86, 0x8A): return 0 return None def read_byte(self, register: int | None) -> int: if register is None: return 0 # The AGB row's masks name the bits that read as 1 on a Game Boy; on the GBA they # read 0 (mGBA suite io-read.c expectations; TEST ROM; gb-apu-python READ_MASKS_AGB). value = self.apu.read(register) & ~READ_MASKS_AGB[register - 0xFF10] & 0xFF if register == 0xFF24: # NR50's Vin bits 3 and 7 are unused on the GBA (GBATEK §GBA Comparison of CGB and # GBA Sound; DOC) and read 0 (mGBA suite io-read.c SOUNDCNT_LO = FF77; TEST ROM). value &= 0x77 return value def write16(self, offset: int, value: int, mask: int, time: int) -> None: if offset == 0x82: self.soundcnt_h = (self.soundcnt_h & ~mask) | (value & mask) if value & mask & 0x0800: self.fifos[0].clear() if value & mask & 0x8000: self.fifos[1].clear() return if offset == 0x88: self.soundbias = (self.soundbias & ~mask) | (value & mask) return if 0xA0 <= offset < 0xA8: which = 1 if offset >= 0xA4 else 0 # A 16-bit write pushes two bytes, an 8-bit write one (HYPOTHESIS, U-SND-5). if mask == 0xFFFF: self.push(which, value, 2) else: self.push(which, value >> 8 if mask == 0xFF00 else value, 1) return self.catch_up(time) apu = self.apu if offset == 0x84 and mask & 0x00FF: master = bool(value & 0x80) if self.master and not master: # Turning the master enable off empties both FIFOs: alyosha-tas # fifo_dma/fifo.asm test 3 ("Test if disabling clears the buffer": 24 samples # loaded, sound off and on, and the DMA comes at the first overflow; TEST ROM). # The playing samples go to 0 (HYPOTHESIS, U-SND-2). self.fifos[0].clear() self.fifos[1].clear() self.samples[0] = self.samples[1] = 0 self.master = master if 0x90 <= offset < 0xA0: index = offset - 0x90 if mask & 0x00FF: apu.write(WAVE_RAM + index, value & 0xFF) if mask & 0xFF00: apu.write(WAVE_RAM + index + 1, (value >> 8) & 0xFF) return if mask & 0x00FF and offset in BYTE_MAP: apu.write(BYTE_MAP[offset], value & 0xFF) if mask & 0xFF00 and offset + 1 in BYTE_MAP: apu.write(BYTE_MAP[offset + 1], (value >> 8) & 0xFF) # ---------------------------------------------------------------------------------- # The mixer and SOUNDBIAS (docs/sound.md "The mixer and SOUNDBIAS") def start_capture(self) -> None: """Begin making output samples (a host's call; changes nothing the CPU sees).""" if self.capture: return self.capture = True now = self.board.bus.now period = SAMPLE_PERIODS[self.soundbias >> 14] self.board.scheduler.schedule(now - now % period + period, ORDER_SOUND, self.sample) def take_output(self) -> list[tuple[int, int, int]]: """The samples since the last call: (left, right, period), left and right the PWM's 0-511 (9-bit), 0-255, 0-127 or 0-63 value, period its length in system cycles.""" out, self.output = self.output, [] return out def mix(self) -> tuple[int, int]: """The 10-bit sums for the right and left outputs, before the resolution cut: the six channels added, the bias added, clipped to 0..3FFh (GBATEK "Max Output Levels"; DOC).""" bias = self.soundbias & 0x3FE if not self.master: # "While Bit 7 is cleared, both PSG and FIFO sounds are disabled" (GBATEK; DOC); # SOUNDBIAS "does work even when sound is off" (DOC): the bias alone. return bias, bias apu = self.apu h = self.soundcnt_h right = left = 0 share = (2, 1, 0, 0)[h & 3] digital = apu.digital() dacs = apu.dacs() nr50 = apu.nr50 nr51 = apu.nr51 master_right = nr50 & 7 master_left = (nr50 >> 4) & 7 for channel in range(4): if not dacs[channel]: continue # an off DAC contributes nothing (gb-apu-python contract "Outputs") if nr51 >> channel & 1: right += psg_level(digital[channel], master_right, share) if nr51 >> (channel + 4) & 1: left += psg_level(digital[channel], master_left, share) for which in (0, 1): level = fifo_level(self.samples[which], bool(h >> (2 + which) & 1)) if h >> (8 + 4 * which) & 1: right += level if h >> (9 + 4 * which) & 1: left += level right = min(max(right + bias, 0), 0x3FF) left = min(max(left + bias, 0), 0x3FF) return right, left def sample(self, time: int) -> None: """One output sample at the SOUNDBIAS period: sample and hold of every channel's current output (HYPOTHESIS, U-SND-10), the 10-bit sum cut to 9, 8, 7 or 6 bits ("the above 10bit value, divided by two" at the default; DOC).""" self.catch_up(time) resolution = self.soundbias >> 14 right, left = self.mix() shift = 1 + resolution period = SAMPLE_PERIODS[resolution] self.output.append((left >> shift, right >> shift, period)) self.board.scheduler.schedule(time - time % period + period, ORDER_SOUND, self.sample) def pcm16_at_32768(output: list[tuple[int, int, int]]) -> bytes: """A host's conversion (not the GBA's): the board's samples as signed 16-bit stereo at 32,768 Hz, each 512-cycle span the average of the samples in it, centred on the default bias (200h of the 10-bit sum, 256 of 9 bits). The analogue filters after the PWM pin are outside the board (docs/sound.md).""" import struct frames = [] left = right = span = 0 for sample_left, sample_right, period in output: shift = {512: 0, 256: 1, 128: 2, 64: 3}[period] left += (sample_left << shift) * period right += (sample_right << shift) * period span += period if span >= 512: frames.append( struct.pack( " bytes: """A RIFF WAVE file around 16-bit stereo PCM.""" import struct return ( b"RIFF" + struct.pack("