"""Shared by the tests: ways to drive the chip and read its output as a board would. The tests look at what ``take_samples()`` returns wherever they can, and at state attributes only where the statement under test is about a register. """ from __future__ import annotations import hashlib from pathlib import Path from sn76489_python import CLOCKS_PER_SAMPLE, GAME_GEAR_PSG, SEGA_VDP_PSG, SN76489, YM7101_PSG ROOT = Path(__file__).resolve().parents[1] REFERENCE = ROOT / "reference" #: The clock Sega's manuals compute their tables with (Game Gear manual, psg-2). NTSC_CLOCK = 3_579_545 SEGA_PARTS = (SEGA_VDP_PSG, GAME_GEAR_PSG, YM7101_PSG) def variant_id(variant) -> str: return variant.name def left(psg: SN76489, ticks: int) -> list[float]: """Run ``ticks`` ticks and return the left level after each.""" psg.run(ticks * CLOCKS_PER_SAMPLE) return [pair[0] for pair in psg.take_samples()] def bits(psg: SN76489, ticks: int) -> list[int]: """The same as 0 or 1, for a chip with one channel audible at full volume.""" return [1 if level > 0.5 else 0 for level in left(psg, ticks)] def write_tone(psg: SN76489, channel: int, value: int) -> None: """The two-byte tone load of TI's data sheet, section 6.""" psg.write(0x80 | (channel << 5) | (value & 0x0F)) psg.write((value >> 4) & 0x3F) def write_volume(psg: SN76489, channel: int, attenuation: int) -> None: psg.write(0x90 | (channel << 5) | (attenuation & 0x0F)) def solo(variant, channel: int) -> SN76489: """A chip with every channel off but one, which is at full volume.""" psg = SN76489(variant, silent_start=True) write_volume(psg, channel, 0) return psg def changes(levels: list) -> list[int]: """Indices at which the level differs from the one before.""" return [index for index in range(1, len(levels)) if levels[index] != levels[index - 1]] def rises(stream: list[int]) -> list[int]: return [index for index in range(1, len(stream)) if stream[index] and not stream[index - 1]] def noise_bits(variant, control: int, shifts: int) -> list[int]: """The noise channel's bit after each of ``shifts`` shifts from a noise write. The register is clocked through rate 3 with the third tone value at 1, which toggles that tone every tick, so the register shifts once in two ticks. From power-on the tone's first toggle is a fall (the core's chosen starting state), so the first shift is on the second tick. """ psg = solo(variant, 3) write_tone(psg, 2, 1) psg.write(0xE0 | (control & 0x04) | 0x03) return bits(psg, 2 * shifts)[1::2] def sha256(data: bytes) -> str: return hashlib.sha256(data).hexdigest()