# SPDX-License-Identifier: MIT """Rungs 0-1: the tables and the unit formulas against statements in the documents. Each test names the statement it checks (anomie's S-DSP document r1212, fullsnes, the SNESdev wiki). No expectation here comes from another program. """ from __future__ import annotations import hashlib import re import struct from pathlib import Path import pytest from snes_python.dsp import SDSP, tables from snes_python.dsp.brr import brr_filter, decode_group, interpolate, nibble_sample from snes_python.dsp.sdsp import ATTACK, DECAY, RELEASE, SUSTAIN ROOT = Path(__file__).resolve().parents[2] ANOMIE = ROOT / "reference" / "dsp" / "docs" / "anomie-s-dsp-r1212-jwdonal.txt" # -- rung 0: tables --------------------------------------------------------------------------- def test_gaussian_table_hash(): packed = struct.pack("<512h", *tables.GAUSS) assert hashlib.sha256(packed).hexdigest() == tables.GAUSSIAN_SHA256 def test_gaussian_table_equals_the_printed_table(): """anomie "PITCH ADJUSTMENTS" prints the 512 values; ares's formula must reproduce them.""" if not ANOMIE.exists(): pytest.skip("reference/dsp/docs not fetched") lines = ANOMIE.read_text(encoding="latin-1").splitlines() start = next(i for i, line in enumerate(lines) if "gauss_coeffs[512]" in line) values = [ int(v, 16) for v in re.findall(r"0x([0-9A-F]{3})", " ".join(lines[start : start + 70])) ] assert values[:512] == list(tables.GAUSS) def test_gaussian_taps_sum_near_2048(): """fullsnes: the four taps "do sum up to 7FFh..801h".""" for i in range(256): total = ( tables.GAUSS[i] + tables.GAUSS[255 - i] + tables.GAUSS[256 + i] + tables.GAUSS[511 - i] ) assert 0x7FF <= total <= 0x801 def test_counter_rates_are_1_3_5_shifted(): """fullsnes "ADSR/Gain (and Noise) Rates": "All values are 1,3,5 SHL n"; 31 is every sample.""" assert tables.COUNTER_RATES[31] == 1 and tables.COUNTER_RATES[0] == 0 for rate in tables.COUNTER_RATES[1:]: while rate % 2 == 0: rate //= 2 assert rate in (1, 3, 5) assert all(tables.COUNTER_RANGE % r == 0 for r in tables.COUNTER_RATES[1:]) def test_counter_fires_once_per_period(): """anomie "COUNTERS": (Counter + offset[R]) % rate[R] == 0 fires once per rate[R] samples.""" for r in range(1, 32): fires = [ c for c in range(tables.COUNTER_RANGE) if (c + tables.COUNTER_OFFSETS[r]) % tables.COUNTER_RATES[r] == 0 ] assert len(fires) == tables.COUNTER_RANGE // tables.COUNTER_RATES[r] # -- rung 1: BRR -------------------------------------------------------------------------------- def test_shift_13_to_15(): """anomie: shifts 13-15 force 0 or $F800 (-$800) by the sign of the nibble.""" for shift in (13, 14, 15): for nibble in range(16): assert nibble_sample(nibble, shift) == (-0x800 if nibble >= 8 else 0) def test_shift_0_to_12(): """anomie: RD = (D << shift) >> 1.""" assert nibble_sample(0x7, 12) == 0x3800 assert nibble_sample(0x8, 12) == -0x4000 assert nibble_sample(0x1, 0) == 0 assert nibble_sample(0xF, 0) == -1 def test_filters_match_their_fractions(): """fullsnes: filter 1 = old*0.9375, filter 2 = 1.90625/-0.9375, filter 3 = 1.796875/-0.8125.""" old, older = 8000, 4000 assert brr_filter(0, 1, old, older) == pytest.approx(old * 0.9375, abs=1) assert brr_filter(0, 2, old, older) == pytest.approx(old * 1.90625 - older * 0.9375, abs=2) assert brr_filter(0, 3, old, older) == pytest.approx(old * 1.796875 - older * 0.8125, abs=2) def test_brr_clamp_then_clip_glitches(): """fullsnes "BRR Samples": +4000h..+7FFFh become -4000h..-1; below -8000h clamps then clips to zero (anomie: clamped to 16 bits, then clipped to 15 bits).""" assert brr_filter(0x3800, 1, 0x3800, 0) < 0 # overshoots +$4000: the sign is lost assert brr_filter(-0x4000, 2, -0x4000, 0x3FFF) == 0 # below -$8000: clamp, then clip to 0 def test_decode_group_carries_history(): """anomie: the filters use the previous samples, carried between groups.""" group = decode_group(0xC4, 0x77, 0x77, 0, 0) # shift 12, filter 1, all +7 assert group[0] == 0x3800 # filter 1 with zero history: RD # the second sample adds old + (-old >> 4) = 0x3800 + 0x3480 = 0x6C80, clipped to 15 bits assert group[1] == 0x6C80 - 0x8000 def test_interpolation_overflow_example(): """fullsnes: three or more -8 SHL 12 samples with filter 0 give some results +3FF8h instead of -4000h (the 801h tap sums overflow the second addition).""" s = -0x4000 results = {interpolate(s, s, s, s, phase) for phase in range(256)} assert 0x3FF8 in results def test_interpolation_of_a_constant(): for phase in range(256): assert abs(interpolate(1000, 1000, 1000, 1000, phase) - 1000) <= 2 # -- rung 1: envelope, noise, registers ----------------------------------------------------- def _voice_dsp(): dsp = SDSP(bytearray(0x10000)) v = dsp.voices[0] dsp.counter = 0 # every rate's offset 0 fires at counter 0 for rates 1, 4, 7, ... return dsp, v def test_release_is_minus_8_every_sample(): """anomie "$x5-$x7": Release, rate 31, E -= 8, floor 0.""" dsp, v = _voice_dsp() v.state, v.envelope = RELEASE, 20 dsp._envelope(v) assert v.envelope == 12 dsp._envelope(v) dsp._envelope(v) assert v.envelope == 0 def test_direct_gain(): """anomie: ADSR1.7 = 0 and GAIN.7 = 0: E = %GGGGGGG0000.""" dsp, v = _voice_dsp() v.state, v.adsr1 = ATTACK, 0x00 dsp.regs[7] = 0x45 dsp._envelope(v) assert v.envelope == 0x450 def test_attack_rate_31_adds_1024_then_decays(): """anomie: aaaa = %1111: R = 31, E += 1024; past $7FF the state becomes Decay.""" dsp, v = _voice_dsp() v.state, v.adsr1, v.envelope = ATTACK, 0x8F, 0 dsp._envelope(v) assert v.envelope == 1024 and v.state == ATTACK dsp._envelope(v) assert v.envelope == 0x7FF and v.state == DECAY def test_exponential_decrease_and_sustain_level(): """anomie: Decay E -= ((E-1) >> 8) + 1; Sustain when the upper 3 bits equal the level.""" dsp, v = _voice_dsp() v.state, v.adsr1, v.envelope = DECAY, 0xF0, 0x7FF # decay rate 7*2+16 = 30 (every 2) dsp.regs[6] = 0x60 # sustain level 3 dsp.counter = 0 while v.state == DECAY: dsp._envelope(v) assert v.state == SUSTAIN and v.envelope >> 8 in (3, 4) def test_sustain_level_from_gain_in_gain_mode(): """anomie: "If 'e' is clear, the top 3 bits of VxGAIN are used instead" (U9).""" dsp, v = _voice_dsp() v.state, v.adsr1, v.envelope = DECAY, 0x00, 0x2FF dsp.regs[6] = 0xE0 # ADSR2 level 7: ignored in GAIN mode dsp.regs[7] = 0x40 | 0x20 # direct gain $60 -> E' = $600, GAIN top 3 bits = 3 dsp._envelope(v) assert v.envelope == 0x600 dsp.regs[7] = 0x5F # direct gain $5F0: E' >> 8 = 5, GAIN top bits 2: no match v.state = DECAY dsp._envelope(v) assert v.state == DECAY def test_noise_lfsr_period(): """anomie "$3d NON": N = (N>>1) | (((N<<14) ^ (N<<13)) & $4000), from $4000: a 15-bit LFSR.""" n, seen = 0x4000, 0 while True: n = (n >> 1) | (((n << 14) ^ (n << 13)) & 0x4000) seen += 1 if n == 0x4000: break assert seen == 32767 def test_registers_mirror_and_endx(): """anomie: $80-$FF read as mirrors; any write to ENDX clears all bits.""" dsp = SDSP(bytearray(0x10000)) dsp.write(0x12, 0x34) assert dsp.read(0x92) == 0x34 dsp.regs[0x7C] = 0xFF dsp.write(0x7C, 0x55) assert dsp.read(0x7C) == 0 def test_reset_acts_as_flg_e0(): """anomie/fullsnes: FLG acts as $E0 after reset even if the value read back differs.""" dsp = SDSP(bytearray(0x10000), registers=bytes(range(128))) assert dsp.read(0x6C) == 0x6C and dsp.flg == 0xE0 def test_one_sample_per_32_steps(): dsp = SDSP(bytearray(0x10000)) dsp.run(32 * 10) assert len(dsp.take_samples()) == 10 def _keyed_on_voice(dsp: SDSP, aram: bytearray) -> None: """Voice 0 plays a loud looping block, direct gain $7F, pitch $1000.""" aram[0x1000:0x1004] = bytes((0x00, 0x20, 0x00, 0x20)) # DIR $10, entry 0 -> $2000 aram[0x2000:0x2009] = bytes((0xC3,)) + bytes((0x77,)) * 8 # shift 12, end+loop regs = {0x5D: 0x10, 0x00: 0x7F, 0x01: 0x7F, 0x03: 0x10, 0x07: 0x7F, 0x0C: 0x7F, 0x1C: 0x7F} for r, value in regs.items(): dsp.write(r, value) dsp.write(0x6C, 0x20) # FLG: reset off, mute off, echo writes off def test_kon_gives_five_empty_samples(): """anomie "When a voice is keyed on, there are 5 '0x0000' samples output before the first sample encoded by the BRR data" (#1-#5, sample #6 is the first heard).""" aram = bytearray(0x10000) dsp = SDSP(aram) _keyed_on_voice(dsp, aram) dsp.run(64) # let DIR latch and FLG take effect dsp.take_samples() dsp.write(0x4C, 0x01) voice = dsp.voices[0] keyed = first_heard = None for sample in range(16): dsp.run(32) if keyed is None and voice.kon_delay == 5: keyed = sample # sample #0: the KON acted on at S3c if keyed is not None and first_heard is None and voice.output: first_heard = sample assert keyed is not None and first_heard - keyed == 6