"""The audio path: the SN76489A's levels, the expansion port's audio, a WAV file. The console's analogue path (levels, filtering, the mix with the expansion port's audio input on the way to the RF modulator) is not documented in anything in hand (U12). So: the chip's level per tick (sn76489-python: 0.0 to 4.0, mono on this part, one value per 16 CPU clocks = 223,721.6 Hz) is scaled to 0.0-1.0, averaged down to the output rate (a box filter over each output period: a choice), summed with the expansion audio at equal weight (a choice), and passed through a first-order DC blocker (about 20 Hz: a listening choice, not a model of the console's coupling capacitor, whose value nobody measured). """ from __future__ import annotations import math import struct from pathlib import Path from sn76489_python import CLOCKS_PER_SAMPLE from colecovision_python.machine import CPU_CLOCK_HZ class Mixer: """Turns the chip's ticks into samples at ``rate`` Hz.""" def __init__(self, rate: int = 44_100, dc_block_hz: float = 20.0) -> None: self.rate = rate self.ticks_per_sample = CPU_CLOCK_HZ / CLOCKS_PER_SAMPLE / rate self._acc = 0.0 self._count = 0.0 self._due = 0.0 # ticks into the current output period self._r = math.exp(-2 * math.pi * dc_block_hz / rate) if dc_block_hz else 1.0 self._x = 0.0 self._y = 0.0 def mix(self, ticks: list[tuple[float, float]], expansion: list[float] | None = None) -> list[float]: """Mono samples from ``ticks`` (the chip's ``take_samples()``); ``expansion`` (the AudioSource socket's samples, at ``rate``) is summed sample by sample.""" out = [] acc, count, pos, step = self._acc, self._count, self._due, self.ticks_per_sample for left, _right in ticks: acc += left * 0.25 count += 1.0 pos += 1.0 if pos >= step: # an output period is complete: emit its average out.append(acc / count) acc, count = 0.0, 0.0 pos -= step self._acc, self._count, self._due = acc, count, pos if expansion: for i, value in enumerate(expansion[: len(out)]): out[i] += value if self._r < 1.0: r, x_prev, y_prev = self._r, self._x, self._y for i, x in enumerate(out): y_prev = x - x_prev + r * y_prev x_prev = x out[i] = y_prev self._x, self._y = x_prev, y_prev return out def write_wav(path: str | Path, samples: list[float], rate: int = 44_100) -> None: """16-bit mono PCM; samples clipped to -1.0 .. 1.0.""" frames = b"".join(struct.pack("