# SPDX-License-Identifier: MIT """The TIA's two sound channels, as the die wires them (docs/timing.md "Audio"). Evidence: the channel logic is DOC (TIA-1A schematic sheet 4) settled by DIE (the ``audio`` and ``audio_modes`` Sim2600 traces match both pads at every half clock, and the die's probed wires, milestone 3); the mix is DOC (the console's resistors) with a FITTED assumption (ideal switches). Each channel is three pieces of logic (TIA-1A logic diagram, sheet 4, "Audio circuits (2 req'd)", ``reference/schematics``): - the **frequency divider**: a 5-bit binary counter *compared* with AUDF, not loaded from it. A match enables the channel's next tick and clears the counter; otherwise it counts on, wrapping after 31, so lowering AUDF below the count lets it run on to 31 first (tia-fpga "Audio"); - the **noise generator**: a 5-bit shift register (the five ``D1`` cells), which AUDC D1-D0 make a 5-bit polynomial, the low end of a 9-bit one with the pulse counter, a gate that holds the pulse counter, or a plain divider; - the **pulse counter**: four set/reset latches (G6-G9) that shift as a 4-bit polynomial, a Johnson counter (divide by 6 or 2) or a follower of the noise register's output, picked by AUDC D3-D2. Its low bit is the tone; the volume register gates the four weighted pull-downs of the pad with it. **Ticks.** The horizontal counter clocks both channels twice a line. Each tick has two phases (tia-fpga sim/README.md "Audio", read off the netlist): phase A compares the divider and, on an enabled tick, latches the hold decision and the noise feedback from AUDC as it then stands; phase B shifts the registers, and the pads change there. The two channels differ by one latch: channel 0's phase A acts on the enable it latches in that same phase, channel 1's on the enable from the phase A before. **Output.** :meth:`Audio.take_samples` returns one float per tick, the pads' level at phase B (where they change), so the rate is two a line, uneven by four colour clocks; resampling is the frontend's job. An unmodified console joins the two pads: a 1 kΩ pull-up (2600 schematic, sheet 1) against each pad's pull-downs, weighted 30k, 15k, 7.5k and 3.75k (TIA sheet 4). With v the sum of the two pads' levels (AUDV where the tone is high, else 0) the pull-downs conduct v/30k and the pin falls by v/(30 + v) of the supply. :func:`mix` scales that to 0..1 at v = 30. **A fit**: the transistors are taken as ideal switches and no 2600's audio has been recorded to check it (docs/undocumented-behavior.md, open item 5). **No lockup guards.** The pulse counter can reach %0000 and %1010 and the netlist has no term to steer it away (tia-fpga): only the feedback below. In AUDC C-F that makes %0000 and %0001 step to %1111, which then alternates with %0000, a divide-by-two; the die does exactly that in the ``audio`` trace (docs/undocumented-behavior.md C26). """ from __future__ import annotations from collections.abc import Callable class Channel: __slots__ = ("audc", "audf", "audv", "divider", "enable", "hold", "noise", "noise_in", "noise_out", "pulse", "same_phase") # fmt: skip def __init__(self, same_phase: bool) -> None: self.same_phase = same_phase self.audc = 0 self.audf = 0 self.audv = 0 self.divider = 0 self.enable = False self.hold = False self.noise = 0 # 5 bits; bit 0 is the cell that feeds out self.noise_in = False # the feedback latched in phase A self.noise_out = False # the noise register's output, latched in phase A self.pulse = 0 # 4 bits; bit 0 is the tone def phase_a(self) -> None: match = self.divider == self.audf if self.same_phase: self.enable = match if self.enable: self._latch() if not self.same_phase: self.enable = match self.divider = 0 if (match or self.divider == 31) else self.divider + 1 def _latch(self) -> None: noise, pulse, audc = self.noise, self.pulse, self.audc self.noise_out = bool(noise & 1) mode = audc & 3 if mode == 2: # the pulse counter steps once per 31 noise steps self.hold = (noise & 0x1E) != 0x02 elif mode == 3: # it steps when the 5-bit polynomial's output is 1 self.hold = not noise & 1 else: self.hold = False if mode == 0: # The noise register follows the pulse counter: the low half of a # 9-bit polynomial when AUDC D3-D2 are 0 too (AUDC 0 and 8), with the # all-zeros escape both registers need to start. self.noise_in = bool( (pulse ^ noise) & 1 or (noise == 0 and pulse == 0x0A) or not audc & 0x0C ) else: # a 5-bit polynomial, x^5 + x^3 + 1, which escapes all-zeros self.noise_in = bool(((noise >> 2) ^ noise) & 1 or noise == 0) def phase_b(self) -> None: if not self.enable: return pulse = self.pulse kind = self.audc >> 2 if kind == 0: # 4-bit polynomial; AUDC 0 has no feedback and fills with ones feed = bool(((pulse >> 1) ^ pulse) & 1 and self.audc & 3) elif kind == 1: # Johnson counter: divide by 6 (the tone of AUDC 4/5) feed = not pulse & 0x08 elif kind == 2: # follow the noise register (AUDC 8-B) feed = not self.noise_out else: # Divide by 6, from any state but %0000 and %0001: those step to # %1111 and then alternate with %0000, dividing by 2 (the die steps # %0000 to %1111 in AUDC C; tia-fpga "Audio"). feed = not pulse & 0x02 self.noise = (self.noise >> 1) | (0x10 if self.noise_in else 0) if not self.hold: self.pulse = (~pulse >> 1) & 0x07 | (0x08 if feed else 0) @property def level(self) -> int: """The pad's weighted pull-downs: AUDV while the tone is high, else 0.""" return self.audv if self.pulse & 1 else 0 def mix(v: int) -> float: """The joined pads' swing for a summed level ``v`` (0-30), as 0..1 (a fit).""" return 2 * v / (30 + v) MIX = tuple(mix(v) for v in range(31)) # DOC + FITTED: mix() over every summed level class Audio: """Both channels; :meth:`tick_a` and :meth:`tick_b` come from the TIA's line.""" def __init__(self) -> None: self.channels = (Channel(same_phase=True), Channel(same_phase=False)) self.samples: list[float] = [] # Called with each sample as it is made, in phase B of the tick, where # the pads change: a host mixing another sound chip at the TIA's sample # instants (the 7800's cartridge POKEY) reads its own clock there; the # TIA's ``hclock`` and the board's ``cycles`` say when. Host code, no # hardware claim. self.on_sample: Callable[[float], None] | None = None def take_samples(self) -> list[float]: """The samples since the last call, one per tick, 0..1 (see :func:`mix`).""" samples, self.samples = self.samples, [] return samples def write(self, address: int, value: int) -> None: """AUDC0/1 $15/$16, AUDF0/1 $17/$18, AUDV0/1 $19/$1A.""" i = (address - 0x15) & 1 c = self.channels[i] if address <= 0x16: c.audc = value & 0x0F elif address <= 0x18: c.audf = value & 0x1F else: c.audv = value & 0x0F def tick_a(self) -> None: for c in self.channels: c.phase_a() def tick_b(self) -> None: c0, c1 = self.channels c0.phase_b() c1.phase_b() sample = MIX[c0.level + c1.level] self.samples.append(sample) if self.on_sample is not None: self.on_sample(sample)