"""The sound generator: three tone channels and a noise channel behind one write port. Every rule names where it comes from. "spec 5.1" is a section of ``docs/spec.md``, which names the document behind it (TI's and Sega's manuals, Maxim's SMS Power page, John Kortink's BBC Micro capture); U and C numbers are that document's unknowns and contradictions, D numbers the decisions in ``docs/handoff-brief.md``. A rule no source supports says CHOICE; one taken by decision says PROVISIONAL. What differs between the four parts is data on :class:`PSGVariant` (``variants.py``). Nothing here asks which variant it is running. The chip divides its input clock by 16 (spec 4.1). One *tick* is 16 input clocks, and nothing inside the chip changes between ticks, so the core produces one output level per tick (spec 4.3, a choice that follows). Filtering, resampling, a console's sag and a mono speaker are the board's (spec 7.7, 9.3). """ from __future__ import annotations from sn76489_python.variants import SEGA_VDP_PSG, PSGVariant #: Input clocks per tick and per output level: the chip's divide-by-16 (spec 4.1, #: documented: TI's data sheet, "decremented at a N/16 rate"). CLOCKS_PER_SAMPLE = 8 class SN76489: """One chip. All state is plain attributes (numbers and lists), named here. ``tone``: the three 10-bit tone values. ``noise``: the 3-bit noise control (bit 2 white, bits 1-0 the rate). ``volume``: four 4-bit attenuations, the fourth the noise channel's. ``stereo``: the Game Gear's port $06, $FF elsewhere. ``latched``: the register code (spec 2.2) the last latch byte chose. ``counters``, ``outputs``: each tone generator's down counter and flip-flop. ``noise_counter``, ``noise_input``: the fixed-rate noise divider and its flip-flop. ``lfsr``: the noise shift register, output end at bit 0. ``test``: the Mega Drive's three test bits. ``clock_remainder``: input clocks not yet making a tick. ``samples``: levels produced and not yet taken. """ def __init__(self, variant: PSGVariant = SEGA_VDP_PSG, *, silent_start: bool = False) -> None: self.variant = variant self.reset(silent_start=silent_start) def reset(self, *, silent_start: bool = False) -> None: """Power-on, as far as any source describes it (spec section 10). ``silent_start`` starts every channel at attenuation 15 whatever the part does. It is for a board that does not want the unreset TI chip's power-on tone (D5); it changes nothing on Sega's parts, which start silent. """ variant = self.variant # Tone and noise registers 0: documented at tier 3 for Sega's parts (spec # 10.2). On the TI chip, which is not reset at all (spec 10.4), zero is # MAME's rendering of "a medium volume tone": PROVISIONAL (D5, U13). self.tone = [0, 0, 0] self.noise = 0 self.volume = [15 if silent_start else variant.power_on_attenuation] * 4 # "After a power-on reset" every stereo bit is 1 (spec 9.2, Sega's manual). self.stereo = 0xFF self.latched = variant.power_on_latch # No source says where the counters, flip-flops, divider and shift register # stand at power-on (spec 10.6, U10). CHOICE, the seed's: counters at zero, # tone flip-flops set, so each falls on the first tick; the shift register # as a noise write leaves it; the divide-by-16 at the start of its cycle. # The seed's value for the flip-flops was kept after a closed-box model # of the Mega Drive's part was seen to start in that phase # (docs/validation.md, rung 5). That is a model's opinion, not evidence. self.counters = [0, 0, 0] self.outputs = [1, 1, 1] self.noise_counter = 0 self.noise_input = 0 self.lfsr = 1 << (variant.lfsr_bits - 1) self.test = 0 self.clock_remainder = 0 self.samples: list[tuple[float, float]] = [] # -- the write port ---------------------------------------------------------- def write(self, value: int) -> None: """One byte to the chip's only port (spec section 3). A write takes effect at once, at whatever point of the 16-clock tick it arrives; the next level produced shows it. When within the tick a real write lands is unknown (spec 3.9, U9): CHOICE. """ value &= 0xFF if value & 0x80: # A latch byte: bits 6-4 choose the register and stay chosen until the # next latch byte (spec 3.1; register codes, spec 2.2). self.latched = (value >> 4) & 7 elif (self.latched & 1 or self.latched == 6) and not ( self.variant.data_byte_reaches_all_registers ): # A data byte while an attenuation or the noise register is latched # writes its low bits there, as a latch byte would (spec 3.6), on the # parts where it does anything at all. return register = self.latched channel = register >> 1 if register & 1: # Attenuation: all four bits, from either kind of byte (spec 3.3, 3.6). self.volume[channel] = value & 0x0F elif channel == 3: # Noise control: feedback bit 2 and rate bits 1-0; bit 3 is ignored # (spec 3.4). self.noise = value & 0x07 # Every write to it clears the shift register and leaves one bit set at # the input end, even a write of the value already there (spec 3.7, # 6.4.1, 6.4.2). The output is the register's last stage (see `run`), # so it reads 0 from this moment: CHOICE (spec 6.4.4, U7). The rate # divider is not restarted: CHOICE (spec 6.4.5, U7). self.lfsr = 1 << (self.variant.lfsr_bits - 1) elif value & 0x80: # A latch byte replaces the low 4 bits of the tone value and leaves the # high 6; the value in use changes at once (spec 3.2). self.tone[channel] = (self.tone[channel] & 0x3F0) | (value & 0x0F) else: # A data byte replaces the high 6 bits; bit 6 is ignored (spec 3.5). self.tone[channel] = (self.tone[channel] & 0x00F) | ((value & 0x3F) << 4) def write_stereo(self, value: int) -> None: """The Game Gear's port $06 (spec 9.1): bits 7-4 put the noise and tones 2, 1, 0 on the left, bits 3-0 the same on the right. On a part without the register this does nothing (spec 9.4, a CHOICE carried from the seed). """ if self.variant.stereo: self.stereo = value & 0xFF def write_test(self, value: int) -> None: """The Mega Drive's VDP debug register 0, of which bits 11-9 are the PSG's. PROVISIONAL and untested (D7; spec section 11, U15). The only source is one paragraph on Plutiedev: "When bit 9 is clear, PSG works as normal. When it's set, however, all PSG channels get replaced with the volume level of one of them. Bits 11-10 pick which channel is the source of the volume level." That is taken literally in :meth:`run`. The override exists only on the Mega Drive's part: on the others there is nothing to write, and the call fails as a missing attribute does. """ if not self.variant.test_override: raise AttributeError(f"{self.variant.name} has no test register (spec section 11)") self.test = (value >> 9) & 7 # -- time -------------------------------------------------------------------- def run(self, clocks: int) -> None: """Advance by ``clocks`` input clocks, appending one level pair per tick.""" total = self.clock_remainder + clocks ticks, self.clock_remainder = divmod(total, CLOCKS_PER_SAMPLE) if ticks <= 0: return variant = self.variant # A tone value of n toggles the output every n ticks (spec 5.1, 5.2); 1 # toggles every tick (spec 5.5, C1); what 0 stands for is the variant's # (spec 5.6, 5.7: PROVISIONAL). The registers cannot change inside this # call, so they are read once. zero = variant.tone_zero_period period0 = self.tone[0] or zero period1 = self.tone[1] or zero period2 = self.tone[2] or zero counter0, counter1, counter2 = self.counters output0, output1, output2 = self.outputs # Noise rates 0 to 2 shift every 32, 64 or 128 ticks: a divider reloaded # with $10, $20 or $40 whose flip-flop shifts the register when it rises # (spec 6.1.1, 6.1.2). Rate 3 takes the third tone generator's output as the # shift clock instead (spec 6.1.3, C4). rate = self.noise & 3 follows_tone = rate == 3 noise_period = 0x10 << rate shift_level = variant.noise_shift_level noise_counter = self.noise_counter noise_input = self.noise_input # White noise feeds back the exclusive OR of the tapped stages; "periodic" # noise feeds the leaving bit back unchanged, a tap on bit 0 alone (spec # 6.2.2 to 6.2.4). taps = variant.white_noise_taps if self.noise & 4 else 0x0001 top = variant.lfsr_bits - 1 lfsr = self.lfsr # Each channel adds its level when its bit is 1 and nothing when it is 0 # (spec 7.5), to the sides the stereo register allows (spec 9.1). table = variant.volume_table levels = [table[attenuation] for attenuation in self.volume] # The Mega Drive's test override (spec section 11, PROVISIONAL): with its # enable bit set, every channel's output is replaced by the volume level of # the chosen channel. Read literally, the square waves and noise no longer # reach the output; they keep running underneath (CHOICE, U15). overridden = self.test & 1 if overridden: levels = [levels[(self.test >> 1) & 3]] * 4 stereo = self.stereo left0, left1, left2, left3 = ( levels[channel] if stereo & (0x10 << channel) else 0.0 for channel in range(4) ) right0, right1, right2, right3 = ( levels[channel] if stereo & (0x01 << channel) else 0.0 for channel in range(4) ) held = (left0 + left1 + left2 + left3, right0 + right1 + right2 + right3) append = self.samples.append for _ in range(ticks): # Tone generators (spec 5.1): the counter counts down once a tick; at # zero the flip-flop toggles and the counter is loaded again from the # register. A new value therefore waits for the next reload (spec 5.4, # U11). if counter0: counter0 -= 1 if not counter0: counter0 = period0 output0 ^= 1 if counter1: counter1 -= 1 if not counter1: counter1 = period1 output1 ^= 1 shift = False if counter2: counter2 -= 1 if not counter2: counter2 = period2 output2 ^= 1 # Rate 3: one shift for every full cycle of this output. shift = follows_tone and output2 == shift_level if not follows_tone: # The fixed-rate divider. While rate 3 is chosen it stands still and # picks up where it stopped: CHOICE, no source describes it. if noise_counter: noise_counter -= 1 if not noise_counter: noise_counter = noise_period noise_input ^= 1 shift = noise_input == 1 if shift: lfsr = (lfsr >> 1) | (((lfsr & taps).bit_count() & 1) << top) if overridden: append(held) else: # The noise channel's bit is the stage at the output end of the # register (spec 6.2.5; Kortink: the generator's output is bit 0 of # the new value; Maxim: "Output=ShiftRegister&1"). noise_bit = lfsr & 1 append( ( (left0 if output0 else 0.0) + (left1 if output1 else 0.0) + (left2 if output2 else 0.0) + (left3 if noise_bit else 0.0), (right0 if output0 else 0.0) + (right1 if output1 else 0.0) + (right2 if output2 else 0.0) + (right3 if noise_bit else 0.0), ) ) self.counters = [counter0, counter1, counter2] self.outputs = [output0, output1, output2] self.noise_counter = noise_counter self.noise_input = noise_input self.lfsr = lfsr def take_samples(self) -> list[tuple[float, float]]: """Return and clear the levels produced since the last call: one ``(left, right)`` pair per tick, each from 0.0 to 4.0 (four channels at full volume). """ samples, self.samples = self.samples, [] return samples