"""The board's audio: the core PSG's samples at the host's rate. The chip's own rules (the latch/data protocol, the noise registers, the variants) are sn76489-python's tests; these check what the board adds. """ from __future__ import annotations import wave import pytest from sms_python.board import GAME_GEAR, SG1000, SMS2, Board from sms_python.cartridge import BANK, Cartridge from sms_python.wav import write_wav NTSC_CLOCK = 3_579_545 def rom(banks: int) -> Cartridge: return Cartridge(b"".join(bytes([bank]) * BANK for bank in range(banks))) def test_the_machines_take_their_variants(): assert SG1000.psg.name == "SN76489AN" assert SMS2.psg.name == "Sega VDP PSG" assert GAME_GEAR.psg.name == "Game Gear PSG" def test_one_second_gives_the_sample_rate(): board = Board(SMS2, rom(1), sample_rate=44_100) board.advance(NTSC_CLOCK) assert abs(len(board.take_samples()) - 44_100) <= 1 def mean_level(board: Board, side: int = 0) -> float: """The level of the last 40 samples, averaged over the tone's fast toggling.""" samples = board.take_samples()[-40:] return sum(sample[side] for sample in samples) / len(samples) def test_the_top_note_at_full_volume_averages_an_eighth_of_full_scale(): # Tone value 1 on Sega's parts toggles every tick (sn76489-python, provisional: # Sega's manual calls n = 1 the top note), so one channel of four at full # volume, high half the time, averages 1/8. Held high it would be 1/4. board = Board(SMS2, rom(1)) for value in (0x81, 0x00, 0x90): # tone 1 value 1, attenuation 0 board.write_port(0x7F, value) board.advance(32) board.advance(16 * 400) assert mean_level(board, 0) == pytest.approx(0.125, abs=0.005) def test_game_gear_stereo_routes_each_channel(): board = Board(GAME_GEAR, rom(1)) for value in (0x81, 0x00, 0x90): board.write_port(0x7F, value) board.advance(32) board.write_port(0x06, 0x10) # tone 1 left only board.advance(16 * 400) samples = board.take_samples()[-40:] assert sum(left for left, _ in samples) / len(samples) == pytest.approx(0.125, abs=0.005) assert all(right == 0.0 for _, right in samples) def test_samples_write_as_a_stereo_wav(tmp_path): board = Board(SMS2, rom(1), sample_rate=22_050) for value in (0x8E, 0x0F, 0x90): # 440 Hz board.write_port(0x7F, value) board.advance(32) # a CPU's writes are an instruction apart, at least board.advance(NTSC_CLOCK // 10) path = tmp_path / "tone.wav" write_wav(path, board.take_samples(), 22_050) with wave.open(str(path)) as audio: assert (audio.getnchannels(), audio.getsampwidth(), audio.getframerate()) == (2, 2, 22_050) assert abs(audio.getnframes() - 2_205) <= 1