# SPDX-License-Identifier: MIT """Sound: the TIA's stream, each cartridge POKEY's stream, and the mix (a fit, U15). **Streams** (the brief: "sound as separate streams"). The TIA's two channels tick twice a line from its own horizontal counter (a2600-python's ``audio.py``: one sample per tick, at the pads' phase B; DIE, inherited), which in 7800 mode free-runs at 228 colour clocks a line beside MARIA's 227 (docs/timing.md "2600 mode"), so the stream's rate is 2 x 3,579,545 / 228 = 31,399.5 samples a second on NTSC (31,113.9 on PAL), uneven by a few clocks within a line. A cartridge POKEY ticks once per Φ2 period (pokey-python, contract: one ``tick()`` per period; DOC: [1702B] p. 29, C22); its level is **sampled at the TIA's sample instants** (its ``mix()`` read just after each TIA tick B), so both streams share one clock and one length (not a hardware value). Point sampling at 31.4 kHz aliases POKEY tones above 15.7 kHz; that is a choice of this frontend stage, not of the chips, and the per-period levels remain available from pokey-python (``record=True``). **The mix** is not documented (docs/undocumented-behavior.md U15: the console's audio resistor network is not in the pinned schematics, and no console recording is pinned; its resistor values would settle it). It is a **fit** (FITTED), labelled: each stream is already 0..1 by its own chip's fit (a2600-python ``audio.mix``; pokey-python ``mix()``: the four channel codes through its DAC and fitted saturating curve, its B3.9), and the output is their weighted sum ``(tia + k * pokey) / (1 + k)`` with ``k = POKEY_WEIGHT`` per chip. The weight 1 is equal full scale; scripts/audio_compare.py prints the ratio MAME 0.285's own recording implies, as a detector's number, not a judge's. :func:`wav_bytes` writes 16-bit mono PCM at the stream's nominal rate. """ from __future__ import annotations import io import struct import wave # FITTED (U15): equal full scale, checked against MAME 0.285's recording as a detector # (Ballblazer 3-10 s level r 0.943 on the archived core, 0.949 on pokey-python 6ed1ffa, # scripts/audio_compare.py); other weights tried: not recorded POKEY_WEIGHT = 1.0 def tia_rate(machine) -> float: """TIA audio ticks a second: two per 228-colour-clock line of the TIA's own counter.""" colour_clock = machine.maria_hz / 2 # MARIA's clock / 2 = the TIA's colour clock (DOC) return 2 * colour_clock / 228 # DIE: the TIA's 228-clock counter (a2600-python) class SoundTap: """Records the TIA's samples and, at each one, every cartridge POKEY's level. Attach with :meth:`attach` before running; :meth:`take` returns the mixed samples since the last call, :attr:`tia` and :attr:`pokey` the raw streams. """ def __init__(self, board, *, keep_streams: bool = True) -> None: self.board = board self.pokeys = [socket.chip for socket in getattr(board.cartridge, "pokeys", {}).values()] self.keep_streams = keep_streams self.tia: list[float] = [] self.pokey: list[float] = [] self.mixed: list[float] = [] def attach(self) -> SoundTap: """Hook a2600-python's ``Audio.on_sample`` (its docs/api.md: called with each sample where it is made, phase B of the tick), so each POKEY is read at the TIA's sample instant.""" audio = self.board.tia.audio pokeys = self.pokeys weight = POKEY_WEIGHT * len(pokeys) scale = 1.0 / (1.0 + weight) mixed, tia_out, pokey_out = self.mixed, self.tia, self.pokey keep = self.keep_streams pending = [0] # samples left in the TIA's own list since the last drain def on_sample(t: float) -> None: p = sum(chip.mix() for chip in pokeys) / len(pokeys) if pokeys else 0.0 mixed.append((t + weight * p) * scale) if keep: tia_out.append(t) pokey_out.append(p) pending[0] += 1 if pending[0] > 4096: pending[0] = 0 audio.take_samples() # the TIA's own list, unread here: drained audio.on_sample = on_sample return self def take(self) -> list[float]: out = self.mixed[:] self.mixed.clear() return out def wav_bytes(samples: list[float], rate: float) -> bytes: """16-bit mono PCM, 0..1 mapped to -32767..32767 around the mean (DC removed). Output formatting: not a hardware value.""" mean = sum(samples) / len(samples) if samples else 0.0 frames = struct.pack( f"<{len(samples)}h", *(max(-32767, min(32767, round((s - mean) * 32767))) for s in samples) ) buffer = io.BytesIO() with wave.open(buffer, "wb") as w: w.setnchannels(1) w.setsampwidth(2) w.setframerate(round(rate)) w.writeframes(frames) return buffer.getvalue()