"""The AY-3-8910 programmable sound generator and its Yamaha relatives, clock by clock. Three square-wave tone channels, one noise generator, one envelope generator, a mixer, two 8-bit I/O ports and sixteen registers behind an address latch. The engine follows the AY-3-8910's die as deathsoft drew it and lvd modelled it (``reference/src/ay-3-8910_reverse_engineered``, GPL-3.0: read, run as the referee and cited, never copied); at every input clock of the referee's streams the three channels drive what that model drives (docs/validation.md). What the Yamaha parts do differently is data on :class:`~ay8910_python.variants.PSGVariant`. What the die has and a programmer's-model PSG may not: * **One divider, two moments.** The input clock is divided by eight. Once per eight clocks one strobe (:data:`STROBE_PHASE`) asks each counter "have you reached your period?" (ay_model.v ``cnt_clk``, line 271, and ``ay_model_counter``); a counter that has is cleared and flips what it drives. On the next clock every counter counts (:data:`COUNT_PHASE`). Nothing else in the chip is clocked: the registers are transparent latches and the mixer and the volume are plain gates, so a write changes the output at once. * **Counters count up and are compared**, "greater than or equal" (ay_model.v lines 1220-1226). A counter that has just been cleared is held clear until the count, so it is at 1 or more when it is next compared: a period of 0 behaves as a period of 1, for the tones, the noise and the envelope alike. Shortening a period below the count ends the half-cycle at the next strobe. No register write restarts a tone or the noise; only the envelope's shape register restarts the envelope. * **The noise and the envelope run at half their counter's rate.** Each has a flip-flop after its counter (``noise_shift_clk_gen``, ``env_output``): the shift register steps, and the AY's 16-step envelope moves, on every second expiry. Yamaha's 32-step envelope moves on every one. * **The noise is a 17-bit register shifting left**, fed bit 16 XOR bit 13, or a 1 while it is all zero (ay_model.v line 647), which is how it leaves reset. A channel hears the *inverse* of bit 16 (line 652). """ from __future__ import annotations from collections.abc import Callable from .variants import AY8910, PSGVariant #: Internal clocks per count: the chip's divide-by-eight. CLOCKS_PER_STEP = 8 #: Where in the eight the strobe compares the counters and where they count, as #: clocks after /RESET is released. STROBE_PHASE = 2 COUNT_PHASE = 3 #: Register numbers, by GI's names (the data sheet counts them in octal, R0-R17). TONE_A_FINE, TONE_A_COARSE = 0, 1 NOISE_PERIOD, MIXER = 6, 7 VOLUME_A = 8 ENVELOPE_FINE, ENVELOPE_COARSE, ENVELOPE_SHAPE = 11, 12, 13 PORT_A, PORT_B = 14, 15 #: The shape register's bits. HOLD, ALTERNATE, ATTACK, CONTINUE = 1, 2, 4, 8 Levels = tuple[int, int, int] class PSG: """One chip: its pins, its sixteen registers and its five counters. ``registers`` holds what each register keeps of the last byte written: its own width on an AY, all eight bits on a Yamaha part (the engine uses only the bits a register has a use for). :meth:`levels` is the chip's digital output, the DAC code each channel drives this instant, and is what the referee is compared on. The I/O ports are pins, so they are callables the board supplies: ``port_a_in()`` returns the levels the outside drives onto port A's pins (unset: the chip's own pull-ups, $FF) and ``port_a_out(value)`` is called with the levels the chip drives whenever they change (a port set to input drives nothing and its pull-ups read $FF). The same for port B. """ def __init__(self, variant: PSGVariant = AY8910, *, record: bool = True) -> None: self.variant = variant #: Queue one :meth:`levels` per input clock for :meth:`take_outputs`. A board #: that asks for :meth:`levels` itself after each :meth:`tick` passes False. self.record = record self.port_a_in: Callable[[], int] | None = None self.port_b_in: Callable[[], int] | None = None self.port_a_out: Callable[[int], None] | None = None self.port_b_out: Callable[[int], None] | None = None self._envelope_top = variant.envelope_steps - 1 #: What the chip last drove on ports A and B ($FF: an input, pulled up). self._driven = [0xFF, 0xFF] self.reset() def reset(self) -> None: """/RESET, as at power-on: every register 0, every counter 0, the divider at the start of its eight, the tones high and the noise register empty. Register 7 at 0 enables every tone and both noise and tone on each channel and makes both ports inputs; the volumes at 0 keep the channels silent. A real part powers on in no particular state; boards pulse /RESET. """ self.registers = [0] * 16 #: The address latch, and whether the last address byte selected the chip. self.address = 0 self.selected = False #: The chip's internal data bus, which keeps its last byte as charge. self.bus = 0 #: The /SEL pin's effect: input clocks per internal clock (1 or 2). self.clock_divider = self.variant.clock_divider self._divider_count = 0 self.phase = 0 #: Each counter has a flip-flop that an expiry sets and the count clears, and #: that holds the counter at 0 in between: ``*_held``. self.tone_period = [0, 0, 0] self.tone_count = [0, 0, 0] self.tone_held = [True, True, True] self.tone_output = [1, 1, 1] self.noise_period = 0 self.noise_count = 0 self.noise_held = True self.noise_half = 0 self.noise_register = 0 self.envelope_period = 0 self.envelope_count = 0 self.envelope_held = True self.envelope_half = 0 self.envelope_step = 0 self.envelope_rising = False self.envelope_holding = False self.envelope_level = self._envelope_top self.clock = 0 self.outputs: list[Levels] = [] self._levels = self._mix_levels() self._drive_port(PORT_A) self._drive_port(PORT_B) # -- the bus ----------------------------------------------------------------------- def select(self, value: int) -> None: """Latch an address byte (BDIR and BC1 high). The low four bits name the register. The high four must be 0, the chip's mask-programmed address with A8 high and /A9 low: any other byte leaves the latch alone and deselects the chip, so the data writes and reads that follow do nothing (ay_model.v ``psg_cs``, ``make_psg_sel``, lines 297-338; the 5B's $C000 the same, Sunsoft_5B_audio.wiki). """ self.selected = (value & 0xF0) == 0 if self.selected: self.address = value & 0x0F self.bus = 0 def write(self, value: int) -> None: """Write a data byte to the selected register (BDIR high, BC1 low). The registers are latches open for as long as the strobe lasts and the chip has no clock of its own for them: the write is taken as an instant, between two input clocks. Bring the chip to the moment with :meth:`run` first. """ if self.selected: self.bus = value & 0xFF self._write_register(self.address, self.bus) def read(self) -> int: """Read the selected register (BDIR low, BC1 high). Registers 14 and 15 return their port's pins. The others return what they keep; an AY's register drives only its own bits onto the chip's internal bus, and the rest come back as the bus was left: 0 after an address byte, which clears it, and the last byte written otherwise (ay_model.v line 415: the bus ``b`` is driven to 0 while the chip is not selected, and is a ``trireg``, charge, when nothing drives it; a read leaves on it only what it found there). On a real chip that charge leaks away in time; here it does not. A deselected chip does not drive the data pins; this returns $FF for it, and a board with its own open bus checks ``selected``. """ if not self.selected: return 0xFF return self.read_register(self.address) def write_register(self, register: int, value: int) -> None: """An address byte and a data byte together: :meth:`select`, :meth:`write`.""" self.select(register) self.write(value) def read_register(self, register: int) -> int: """What a read of ``register`` (0-15) returns now, with the latch left as it is.""" register &= 0x0F if register == PORT_A: return self._port_pins(PORT_A, self.port_a_in) if register == PORT_B: return self._port_pins(PORT_B, self.port_b_in) return self.registers[register] | (self.bus & ~self.variant.register_masks[register]) def _write_register(self, register: int, value: int) -> None: registers = self.registers registers[register] = value & self.variant.register_masks[register] if register < NOISE_PERIOD: channel = register >> 1 fine, coarse = registers[channel * 2], registers[channel * 2 + 1] self.tone_period[channel] = (coarse & 0x0F) << 8 | fine elif register == NOISE_PERIOD: self.noise_period = registers[NOISE_PERIOD] & 0x1F elif register == MIXER: self._drive_port(PORT_A) self._drive_port(PORT_B) elif register in (ENVELOPE_FINE, ENVELOPE_COARSE): self.envelope_period = registers[ENVELOPE_COARSE] << 8 | registers[ENVELOPE_FINE] elif register == ENVELOPE_SHAPE: self._restart_envelope() elif register >= PORT_A: self._drive_port(register) if self.phase == STROBE_PHASE + 1: # The strobe lasts a whole clock and is still open: a period written # now is compared now, and a counter already past it expires at once. self._strobe() self._levels = self._mix_levels() # -- the ports --------------------------------------------------------------------- def _port_is_output(self, register: int) -> bool: """Register 7's bit 6 makes port A an output, bit 7 port B.""" return bool(self.registers[MIXER] & (0x40 if register == PORT_A else 0x80)) def _port_bonded(self, register: int) -> bool: return ("A" if register == PORT_A else "B") in self.variant.ports def _port_pins(self, register: int, outside: Callable[[], int] | None) -> int: """The levels on a port's pins, which is what a read returns whichever way the port is set (ay_model.v ``ay_model_gpio``, line 1043: the read path is the pins, not the latch). An output port's pins are its latch, pulled low wherever the outside pulls harder; an input port's are the outside's, or the pull-ups'.""" pins = outside() & 0xFF if outside is not None and self._port_bonded(register) else 0xFF if self._port_is_output(register): pins &= self.registers[register] return pins def _drive_port(self, register: int) -> None: """Tell the board what the chip now drives on a port, if that has changed.""" port = register - PORT_A value = self.registers[register] if self._port_is_output(register) else 0xFF if value != self._driven[port]: self._driven[port] = value out = self.port_a_out if register == PORT_A else self.port_b_out if out is not None and self._port_bonded(register): out(value) # -- time -------------------------------------------------------------------------- def tick(self) -> None: """One input clock. With the clock halved (:attr:`clock_divider` 2) the chip moves on every second input clock. Of each eight internal clocks one compares and the next counts; the other six only pass. """ self._divider_count += 1 if self._divider_count >= self.clock_divider: self._divider_count = 0 phase = self.phase if phase == STROBE_PHASE: self._strobe() elif phase == COUNT_PHASE: self._count() self.phase = (phase + 1) & 7 if self.record: self.outputs.append(self._levels) self.clock += 1 def run(self, clocks: int) -> None: """Advance ``clocks`` input clocks: :meth:`tick`, that many times.""" for _ in range(clocks): self.tick() def _strobe(self) -> None: """Each counter that has reached its period is cleared and clocks what follows it: a tone's output flip-flop, the noise's and the envelope's halving flip-flops (ay_model.v ``clk_conditioning``, lines 975-982: set by the strobe AND the comparator, it clears the counter for as long as it stays set). A counter still held from /RESET or from a shape write is not compared: its flip-flop is set already, and nothing is clocked twice. """ count, period, held = self.tone_count, self.tone_period, self.tone_held for channel in range(3): if not held[channel] and count[channel] >= period[channel]: count[channel] = 0 held[channel] = True self.tone_output[channel] ^= 1 if not self.noise_held and self.noise_count >= self.noise_period: self.noise_count = 0 self.noise_held = True self.noise_half ^= 1 if not self.noise_half: self._shift_noise() if not self.envelope_held and self.envelope_count >= self.envelope_period: self.envelope_count = 0 self.envelope_held = True self.envelope_half ^= 1 if self.variant.envelope_steps == 32 or not self.envelope_half: self._step_envelope() self._levels = self._mix_levels() def _count(self) -> None: """Every counter is let go and counts. They are ripple counters as wide as their period registers and never wrap: the strobe clears one that has reached its period, and no period is longer than its counter.""" count = self.tone_count count[0] += 1 count[1] += 1 count[2] += 1 self.tone_held = [False, False, False] self.noise_count += 1 self.noise_held = False self.envelope_count += 1 self.envelope_held = False def _shift_noise(self) -> None: """One step of the 17-bit register: left, taking in bit 16 XOR bit 13, or a 1 while the register is all zero (as /RESET leaves it).""" noise = self.noise_register feedback = ((noise >> 16) ^ (noise >> 13)) & 1 self.noise_register = ((noise << 1) | feedback | (noise == 0)) & 0x1FFFF # -- the envelope ------------------------------------------------------------------ def _restart_envelope(self) -> None: """A write to the shape register, whatever the value: the period counter and its flip-flop are cleared and the ramp starts again from its first step (ay_model.v ``env_rst``, line 659, into every envelope flip-flop). How the counter comes out depends on when. In the first half of the divider's eight (up to the count) it is cleared and held, as after an expiry, until it counts. In the second half nothing holds it, and the clear does not reach its lowest bit: that bit is a master and a slave, built without the clear that the other bits have (``counter_bit_0``, ``UP_RST`` 0, lines 1190-1200), and there the master puts the bit straight back. So the counter restarts from 0 or from 1, whichever its lowest bit was, and may be compared while still at 0: a restarted envelope's first step can come eight clocks sooner or later than a count from 0 would have it. """ if self._counters_counted(): self.envelope_count &= 1 else: self.envelope_count = 0 self.envelope_held = True self.envelope_half = 0 self.envelope_step = 0 self.envelope_rising = bool(self.registers[ENVELOPE_SHAPE] & ATTACK) self.envelope_holding = False self._ramp() def _counters_counted(self) -> bool: """Whether the divider is in the second half of its eight, the four clocks after the count.""" return self.phase > COUNT_PHASE def _ramp(self) -> None: top = self._envelope_top step = self.envelope_step self.envelope_level = step if self.envelope_rising else top - step def _step_envelope(self) -> None: """One step along the ramp. At the end of a ramp the shape decides: without CONTINUE the level is 0 from then on; with HOLD it stays where the ramp ended, or at the other end with ALTERNATE as well; otherwise the ramp repeats, turned round each time with ALTERNATE.""" if self.envelope_holding: return self.envelope_step += 1 if self.envelope_step <= self._envelope_top: self._ramp() return self.envelope_step = 0 shape = self.registers[ENVELOPE_SHAPE] if not shape & CONTINUE: self.envelope_holding = True self.envelope_level = 0 elif shape & HOLD: self.envelope_holding = True ends_high = self.envelope_rising ^ bool(shape & ALTERNATE) self.envelope_level = self._envelope_top if ends_high else 0 else: if shape & ALTERNATE: self.envelope_rising = not self.envelope_rising self._ramp() # -- the outputs ------------------------------------------------------------------- def _mix_levels(self) -> Levels: """The DAC code of each channel: its volume, or the envelope's level, while (tone OR tone-disabled) AND (noise OR noise-disabled); 0 otherwise. The AY's codes are the 4-bit volume itself. Yamaha's are the 5-bit envelope, and a 4-bit volume ``v`` drives ``2v + 1``.""" registers = self.registers mixer = registers[MIXER] noise = (~self.noise_register >> 16) & 1 wide = self.variant.envelope_steps == 32 codes = [] for channel in range(3): tone_gate = self.tone_output[channel] | (mixer >> channel) noise_gate = noise | (mixer >> (channel + 3)) if not tone_gate & noise_gate & 1: codes.append(0) continue volume = registers[VOLUME_A + channel] if volume & 0x10: codes.append(self.envelope_level) else: codes.append((volume & 0x0F) * 2 + 1 if wide else volume & 0x0F) return (codes[0], codes[1], codes[2]) def levels(self) -> Levels: """What channels A, B and C drive now: DAC codes, 0-15 on an AY part and 0-31 on a Yamaha one (``variant.dac`` turns a code into a level).""" return self._levels def mix(self) -> float: """The three channels' levels added, 0.0-3.0, by the variant's DAC table: what three output pins tied together through equal resistors would carry. The pins' shared load, the filters and the amplifier are the board's.""" dac = self.variant.dac a, b, c = self._levels return dac[a] + dac[b] + dac[c] def take_outputs(self) -> list[Levels]: """Return and clear the queued outputs: one :meth:`levels` per input clock run, each the state after that clock.""" outputs, self.outputs = self.outputs, [] return outputs def take_samples(self) -> list[float]: """Return and clear the queued outputs as mixed levels, one :meth:`mix` per input clock.""" dac = self.variant.dac return [dac[a] + dac[b] + dac[c] for a, b, c in self.take_outputs()]