# SPDX-License-Identifier: MIT """The S-DSP: eight BRR voices, envelopes, noise, pitch modulation, echo; one step per S-SMP clock. Written from anomie's S-DSP document (r1212 with jwdonal's updates; cited "anomie" with its section), fullsnes ("SNES APU DSP ..." chapters) and the SNESdev wiki ("S-DSP registers", "DSP envelopes"). The step schedule is anomie's sample loop ("SOUND GENERATION"); where his order within a step is open, the order of ares's ``DSP::main`` (ISC) is used and said so. Evidence tags: - DOC: a document states it (section named). - OBSERVED: chosen to agree with snes_spc 0.9.0 run as a closed box (docs/dsp/validation.md), where the documents leave the reading open. - HYPOTHESIS: no source settles it; the comment says how a test could. The module shares the 64 KiB ARAM ``bytearray`` with the S-SMP, is reached through ``read`` and ``write`` (the S-SMP's $F3 port) and is clocked by ``step()`` once per S-SMP clock. It imports nothing from the board (tests/dsp/test_import_boundary.py). """ from __future__ import annotations from snes_python.dsp import tables from snes_python.dsp.brr import clamp16, decode_group, interpolate, wrap16 # Envelope states (DOC anomie "$x5-$x7": Attack, Decay, Sustain, Release). ATTACK, DECAY, SUSTAIN, RELEASE = range(4) # Register numbers. FLG, KON, KOFF, ENDX = 0x6C, 0x4C, 0x5C, 0x7C MVOLL, MVOLR, EVOLL, EVOLR, EFB = 0x0C, 0x1C, 0x2C, 0x3C, 0x0D PMON, NON, EON, DIR, ESA, EDL = 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D def _s8(value: int) -> int: return value - 256 if value & 0x80 else value class Voice: """One voice's internal state. Plain attributes, readable by tracers; not part of the contract.""" def __init__(self, index: int) -> None: self.index = index self.base = index << 4 self.bit = 1 << index self.ring = [0] * 12 # DOC anomie "BRR DECODING": a 12-sample ring, three groups of 4 self.ring_pos = 0 # where the next group is written; also the oldest sample self.position = 0 # interpolation position, 15 bits (DOC anomie "PITCH ADJUSTMENTS") self.brr_address = 0 self.brr_offset = 1 # 1, 3, 5, 7: the next data byte pair in the block self.loop_address = 0 # read at S2 each sample; S4 jumps to it after an end block self.srcn = 0 # latched at S1 self.directory = 0 # the directory entry's address, formed for S2 self.pitch_low = 0 # latched at S2 self.adsr1 = 0 # latched at S2 self.pitch = 0 # formed at S3a, used at S4 self.header = 0 # read at S3b self.byte1 = 0 # read at S3b self.envelope = 0 # 11 bits self.hidden = 0 # the previous candidate envelope, for bent increase self.state = RELEASE self.kon_delay = 0 # 5 at KON, counted down at S3c (DOC anomie, KON samples #0-#6) self.s4_action = 0 # what S4 does this sample (set at S3c) self.prekon_preload = False # a KON landed on a preload sample of an earlier KON (S4) self.kon_now = False # KON acted on this sample: ENDX bit cleared at S5 self.looped = False # an end block finished at S4: ENDX bit set at S5 self.output = 0 # after the envelope, 16-bit form (low bit 0) self.envx_source = 0 # the envelope that produced ``output`` self.endx_buf = 0 # prepared at S5, written at S7 # What S4 does (set by S3c from the KON sequence; DOC anomie "When a voice is keyed on"). S4_NORMAL, S4_KON, S4_HOLD, S4_PRELOAD = range(4) class SDSP: """The S-DSP behind its pins: ARAM, the $F3 register port, the clock, /RESET, the output. ``registers`` is the register file at power-on (128 bytes). DOC anomie "S-DSP REGISTERS" and fullsnes "DSP Registers": at power-on most registers hold chip-dependent garbage, so there is no documented table; the default is all zeros (HYPOTHESIS, owner's decision C11: the board may pass any table, e.g. random bytes). FLG acts as $E0 after power-on whatever reads back (DOC). """ def __init__(self, aram: bytearray, registers: bytes | None = None) -> None: if len(aram) != 0x10000: raise ValueError("ARAM must be 64 KiB") self.aram = aram self.regs = bytearray(registers if registers is not None else bytes(128)) if len(self.regs) != 128: raise ValueError("the register file is 128 bytes") self.voices = [Voice(i) for i in range(8)] # Set by the S-SMP side: TEST bit 1 ("RAM write enable ... SPC700 & S-DSP writes", # fullsnes "00F0h - TEST"). self.ram_writable = True self.samples: list[tuple[int, int]] = [] self.envx_latch = 0 # prepared at a voice's S7, written at its S9 self.outx_latch = 0 # prepared at S6, written at S8 self.phase = 0 # the step step() runs next, 0-31 self.every_other = 0 # the KON/KOFF poll runs when this is 1 after step 29's toggle self._schedule = self._build_schedule() self.reset() # -- pins ------------------------------------------------------------------------------ def reset(self) -> None: """The /RESET line. DOC anomie "S-DSP REGISTERS": registers keep their values; FLG acts as $E0; ENDX is 0; every voice is released (FLG.7), so ENVX/OUTX become 0. DOC anomie "COUNTERS": the counter is 0; "NON": noise is $4000. The echo offset, FIR history and step are not documented: 0 (HYPOTHESIS).""" self.flg = 0xE0 # the internal FLG, which the DSP acts on (DOC; C9) self.regs[ENDX] = 0 self.counter = 0 self.noise = 0x4000 # The KON/KOFF poll runs on the samples whose counter value (after step 29's decrement) # is even: the counter restarts at 0, its first decrement gives $77FF (odd, no poll). # TEST ROM: spc_dsp6 `Misc/brr addr wrap-around` keys on a voice with attack rate 31, # decay rate 28 (every 4 samples) and sustain level 7, and passes only if no decay step # lands 7 samples after the poll (the odd pairing stores one, $7F7 for $7FF). OBSERVED: # Mesen2 b9fa69d's echo buffer in that test holds the $7FF output; the snes_spc referee's # .spc alignment (SMP.load_spc) pairs them the same way. Which pairing a console takes # after /RESET is otherwise unknown: HYPOTHESIS that it is always this one (U22). self.every_other = 1 self.internal_kon = 0 self.kon_latch = 0 self.koff_latch = 0 self.kon_previous = 0 self.poll = False self.pmon = self.non = self.eon = 0 self.dir = 0 self.esa = 0 self.echo_pointer = 0 self.echo_offset = 0 self.echo_length = 0 self.echo_write_left = self.echo_write_right = False self.fir_history_left = [0] * 8 self.fir_history_right = [0] * 8 self.fir_index = 0 self.fir = [0] * 8 # coefficients as latched at steps 22-25 self.fir_left = self.fir_right = 0 self.efb = 0 self.main_left = self.main_right = 0 self.echo_left = self.echo_right = 0 self.echo_out_left = self.echo_out_right = 0 self.out_left = 0 for v in self.voices: v.state = RELEASE v.envelope = v.hidden = 0 v.kon_delay = 0 v.output = 0 def load_registers(self, registers: bytes, pending_kon: bool = True) -> None: """Replace the register file (an .spc snapshot); FLG's internal copy follows the file. A snapshot carries no internal state. With ``pending_kon`` the file's KON byte becomes the internal KON, so those voices are keyed on at the first poll: the convention the snes_spc referee follows (OBSERVED: game .spc files, docs/dsp/validation.md). Without it, KON is taken as already acted on and every voice stays released until the driver keys it on. """ self.regs[:] = registers self.flg = self.regs[FLG] self.internal_kon = self.regs[KON] if pending_kon else 0 self.dir = self.regs[DIR] self.esa = self.regs[ESA] def read(self, register: int) -> int: """$F3 read: the register file's byte (DOC fullsnes: $80-$FF read as mirrors).""" return self.regs[register & 0x7F] def write(self, register: int, value: int) -> None: """$F3 write with $F2 < $80 (the S-SMP side drops writes to $80-$FF: DOC anomie).""" register &= 0x7F value &= 0xFF low = register & 0x0F if register == ENDX: # DOC anomie "$7c ENDX": any write clears all bits; a write up to 2 cycles before the # DSP's update overwrites the prepared value. self.regs[ENDX] = 0 for v in self.voices: v.endx_buf = 0 return self.regs[register] = value if register == KON: self.internal_kon = value # DOC anomie "$4c KON": takes effect 'on write' elif register == FLG: self.flg = value elif low == 8: # DOC anomie "$x8 VxENVX": a write up to 2 cycles before the DSP's update overwrites # it. The value waits in one latch shared by all voices, so a write to any voice's # ENVX lands in the voice whose update is pending (OBSERVED: endx-override case; # per-voice latches disagree with the referee: docs/dsp/validation.md). self.envx_latch = value elif low == 9: self.outx_latch = value # the same for OUTX (DOC anomie "$x9"; OBSERVED) def step(self) -> None: """One S-SMP clock: run step ``phase``, then advance it.""" for operation in self._schedule[self.phase]: operation() self.phase = (self.phase + 1) & 31 def run(self, steps: int) -> None: for _ in range(steps): self.step() def take_samples(self) -> list[tuple[int, int]]: """Every (left, right) signed 16-bit sample made since the last call (32 kHz).""" out, self.samples = self.samples, [] return out # -- the schedule ---------------------------------------------------------------------- def _build_schedule(self) -> list[list]: """DOC anomie "SOUND GENERATION": the 32-step loop. Within a step, operations run in anomie's listed order, which equals ares's ``DSP::main`` order except where noted.""" steps: list[list] = [[] for _ in range(32)] voice_ops = [] for i, v in enumerate(self.voices): voice_ops += [ (tables.STEP_S1[i], 1, lambda v=v: self._s1(v)), (tables.STEP_S2[i], 2, lambda v=v: self._s2(v)), (tables.STEP_S4[i], 4, lambda v=v: self._s4(v)), (tables.STEP_S5[i], 5, lambda v=v: self._s5(v)), (tables.STEP_S6[i], 6, lambda v=v: self._s6(v)), (tables.STEP_S7[i], 7, lambda v=v: self._s7(v)), (tables.STEP_S8[i], 8, lambda v=v: self._s8(v)), (tables.STEP_S9[i], 9, lambda v=v: self._s9(v)), ] if i: voice_ops.append((tables.STEP_S3A[i], 3, lambda v=v: self._s3(v))) # Order within a step: anomie lists voice operations by voice slot, oldest operation # first (S9 before S1); ares's main() does the same (S1 of the new voice last, except on # step 17 where it is first: no shared state, so the order is unobservable). for step, op, fn in sorted(voice_ops, key=lambda t: (t[0], -t[1])): steps[step].append(fn) v0 = self.voices[0] steps[22].insert(0, lambda: self._s3a(v0)) steps[22].append(self._echo22) steps[23].append(self._echo23) steps[24].append(self._echo24) steps[25].insert(0, lambda: self._s3b(v0)) steps[25].append(self._echo25) steps[26].append(self._echo26) steps[27].append(self._misc27) steps[28].append(self._misc28) steps[29].append(self._misc29) # Step 30: anomie lists V0:S3c, the echo write and the KON/KOFF and noise loads without an # order; ares runs the global (misc) part first, then V0:S3c, then the echo part. That # order lets voice 0 act on the poll in the step it is made (OBSERVED: agrees with the # referee, docs/dsp/validation.md). steps[30] = [self._misc30, lambda: self._s3c(v0), self._echo30] return steps # -- voice operations (DOC anomie "SOUND GENERATION", S1-S9) ------------------------------- def _s1(self, v: Voice) -> None: """S1: load SRCN (the directory entry is formed at S2).""" v.srcn = self.regs[v.base | 4] def _s2(self, v: Voice) -> None: """S2: load the sample pointer if needed; latch PITCHL and ADSR1 (DOC anomie S2; anomie lists the steps under "$x2"/"$x5"). The start address is used on KON sample #1, the loop address after an end block (DOC anomie "$5d DIR", fullsnes "BRR Samples").""" aram = self.aram # The entry from DIR as latched at step 28 and SRCN from S1, formed here (DOC anomie S2: # "using previously loaded DIR and SRCN"). TEST ROM: spc_dsp6 `Timing/Misc/28 dir` fails # when it is formed at S1 (voice 1's S1 is before step 28, its S2 after). v.directory = (self.dir << 8) + (v.srcn << 2) if v.kon_delay == 5: a = v.directory & 0xFFFF v.brr_address = aram[a] | aram[(a + 1) & 0xFFFF] << 8 v.brr_offset = 1 else: # The loop address is read here, in the sample whose S4 may finish the block, and # S4 jumps to it. TEST ROM: spc_dsp6 `Order/loop addr read in prev sample` fails when # it is read at the next sample's S2. Read every sample: HYPOTHESIS (unobservable # but for timing, which the test fixes). a = (v.directory + 2) & 0xFFFF v.loop_address = aram[a] | aram[(a + 1) & 0xFFFF] << 8 v.pitch_low = self.regs[v.base | 2] v.adsr1 = self.regs[v.base | 5] def _s3(self, v: Voice) -> None: self._s3a(v) self._s3b(v) self._s3c(v) def _s3a(self, v: Voice) -> None: """S3a: load PITCHH and apply pitch modulation (DOC anomie S3a and "$2d PMON"): P + (((OUT[x-1] >> 5) * P) >> 10), OUT in 16-bit form. PMON applies to a noise voice too (DOC fullsnes "Pitch Counter" and anomie "$3d NON"; anomie's pseudocode excludes NON: C5).""" pitch = (self.regs[v.base | 3] & 0x3F) << 8 | v.pitch_low if self.pmon & v.bit & 0xFE: pitch += ((self.voices[v.index - 1].output >> 5) * pitch) >> 10 v.pitch = pitch def _s3b(self, v: Voice) -> None: """S3b: read the BRR header (every sample) and the first data byte (DOC anomie S3b).""" aram = self.aram v.header = aram[v.brr_address] v.byte1 = aram[(v.brr_address + v.brr_offset) & 0xFFFF] def _s3c(self, v: Voice) -> None: """S3c (DOC anomie S3c and "$4c KON/$5c KOFF" items 1-3): the sample (noise or interpolated), the envelope applied, FLG.7, the end check, KOFF/KON, ADSR2/GAIN, the envelope update.""" if self.non & v.bit: sample = ((self.noise & 0x7FFF) ^ 0x4000) - 0x4000 # DOC anomie "$3d NON": 15 bits else: base = v.ring_pos + (v.position >> 12) ring = v.ring sample = interpolate( ring[base % 12], ring[(base + 1) % 12], ring[(base + 2) % 12], ring[(base + 3) % 12], (v.position >> 4) & 0xFF, ) # DOC anomie "$x5": S = (S * E) >> 11 on 15 bits; then a 0 bit appended (SOUND GENERATION). v.output = ((sample * v.envelope) >> 11) << 1 v.envx_source = v.envelope entry = v.kon_delay if self.flg & 0x80: # DOC anomie: FLG.7 checked here, not latched v.state = RELEASE v.envelope = 0 if entry != 5 and (v.header & 3) == 1: # DOC anomie "BRR DECODING": a header with e set and l clear releases at once, E = 0. # Not checked on KON sample #1 (DOC anomie: "No BRR decoding or header checks"). v.state = RELEASE v.envelope = 0 if self.koff_latch & v.bit: v.state = RELEASE kon = bool(self.kon_latch & v.bit) v.kon_now = kon if kon: # DOC anomie KON #0: envelope 0, Attack, interpolation index and ring index to 0. # "The final pre-KON BRR decode also occurs here": the decode this sample's S4 would # have made without the KON, which inside an earlier KON's sequence (#2-#4) is that # sequence's preload group. TEST ROM + OBSERVED: spc_dsp6 `KON/kon decoding when # another kon` fails when only the normal decode is made; the referee's kon-redecode # case (KON again 2-4 samples into a KON) agrees with the preload reading. v.prekon_preload = entry in (4, 3, 2) v.kon_delay = 5 v.state = ATTACK v.envelope = 0 v.hidden = 0 v.s4_action = S4_KON return if entry: v.kon_delay = entry - 1 # DOC anomie #1: nothing; #2-#4: one group each at S4; #5: envelope runs, no S4 work. v.s4_action = S4_PRELOAD if entry in (4, 3, 2) else S4_HOLD if entry != 1: return else: v.s4_action = S4_NORMAL self._envelope(v) def _envelope(self, v: Voice) -> None: """The envelope update (DOC anomie "$x5-$x7 ADSR1/ADSR2/GAIN" and its steps 1-4; fullsnes "ADSR/Gain Envelope"; SNESdev wiki "DSP envelopes"). ADSR2/GAIN are read now (S3c).""" e = v.envelope if v.state == RELEASE: # DOC anomie: Release overrides everything, rate 31, E -= 8. e -= 8 v.envelope = max(0, e) v.hidden = e & 0x7FF return adsr2 = self.regs[v.base | 6] gain = self.regs[v.base | 7] if v.adsr1 & 0x80: sustain_level = adsr2 >> 5 if v.state == ATTACK: rate = (v.adsr1 & 0x0F) * 2 + 1 new = e + (1024 if rate == 31 else 32) elif v.state == DECAY: rate = ((v.adsr1 >> 4) & 7) * 2 + 16 new = e - (((e - 1) >> 8) + 1) else: rate = adsr2 & 0x1F new = e - (((e - 1) >> 8) + 1) else: # DOC anomie: "If 'e' is clear, the top 3 bits of VxGAIN are used instead" (U9). sustain_level = gain >> 5 if not gain & 0x80: rate = 31 # direct gain: E = g * 16, "R does not matter" new = (gain & 0x7F) << 4 else: rate = gain & 0x1F mode = (gain >> 5) & 3 if mode == 0: new = e - 32 elif mode == 1: new = e - (((e - 1) >> 8) + 1) elif mode == 2: new = e + 32 else: new = e + (32 if v.hidden < 0x600 else 8) # Step 1: store the clamped value only when the counter fires at this rate. if rate and (self.counter + tables.COUNTER_OFFSETS[rate]) % tables.COUNTER_RATES[rate] == 0: v.envelope = 0 if new < 0 else (min(new, 2047)) # Step 2: Decay -> Sustain when the upper 3 bits match the sustain level. if v.state == DECAY and (new >> 8) == sustain_level: v.state = SUSTAIN # Step 3: Attack -> Decay past $7FF; "Negative values also trigger this". if v.state == ATTACK and (new > 0x7FF or new < 0): v.state = DECAY # Step 4: the new value kept for bent increase. DOC fullsnes "Misc Notes": "Save the new # value, *clipped* to 11 bits ... a negative value ... will result in the clipped version # being greater than 0x600". anomie says "*pre-clamp*"; the two differ after a negative # candidate (C15). fullsnes's reading is chosen: OBSERVED, it agrees with the referee # (env-quirks case, docs/dsp/validation.md) where anomie's does not. # A positive value past $7FF is clipped to $7FF, not wrapped: TEST ROM (spc_dsp6 # `Envelope/gain $E0 threshold` fails with the wrap and passes with the clip, through the # board, 2026-11-23; fullsnes's "clipped" read as a clamp above, as its negative case # spells out a wrap below). v.hidden = new & 0x7FF if new < 0 else min(new, 0x7FF) def _s4(self, v: Voice) -> None: """S4: VOLL applied; a BRR group decoded if needed; the position advanced by the pitch and clamped to $7FFF (DOC anomie S4 and "PITCH ADJUSTMENTS").""" action = v.s4_action if action == S4_NORMAL: if v.position >= 0x4000: self._decode(v) v.position -= 0x4000 position = v.position + v.pitch v.position = min(32767, position) elif action == S4_KON: # DOC anomie KON #0: "The final pre-KON BRR decode also occurs here"; then the # interpolation index and the ring index are 0 (the pre-KON decode: see _s3c). if v.prekon_preload or v.position >= 0x4000: self._decode(v) v.position = 0 v.ring_pos = 0 elif action == S4_PRELOAD: self._decode(v) left = wrap16((v.output * _s8(self.regs[v.base])) >> 7) # DOC anomie "$x0 VxVOLL" self.main_left = clamp16(self.main_left + left) # DOC: clamped after each addition if self.eon & v.bit: self.echo_left = clamp16(self.echo_left + left) def _decode(self, v: Voice) -> None: """One group of four samples into the ring; the block pointer advances or the loop is flagged after the fourth group (DOC anomie S4 and "BRR DECODING").""" aram = self.aram byte2 = aram[(v.brr_address + v.brr_offset + 1) & 0xFFFF] ring = v.ring pos = v.ring_pos group = decode_group(v.header, v.byte1, byte2, ring[(pos - 1) % 12], ring[(pos - 2) % 12]) ring[pos : pos + 4] = group v.ring_pos = (pos + 4) % 12 v.brr_offset += 2 if v.brr_offset >= 9: v.brr_offset = 1 if v.header & 1: v.looped = True # ENDX set at S7 (prepared at S5) v.brr_address = v.loop_address # read at this sample's S2 (_s2) else: v.brr_address = (v.brr_address + 9) & 0xFFFF def _s5(self, v: Voice) -> None: """S5: VOLR applied; the ENDX bit prepared (DOC anomie S5; a KON clears it, and an end block in the same sample does not override that: anomie S4).""" right = wrap16((v.output * _s8(self.regs[v.base | 1])) >> 7) self.main_right = clamp16(self.main_right + right) if self.eon & v.bit: self.echo_right = clamp16(self.echo_right + right) bit = self.regs[ENDX] & v.bit if v.looped: bit = v.bit if v.kon_now: bit = 0 v.endx_buf = bit v.looped = False v.kon_now = False def _s6(self, v: Voice) -> None: """S6: OUTX prepared: the high byte of the voice's output (DOC anomie "$x9 VxOUTX").""" self.outx_latch = (v.output >> 8) & 0xFF def _s7(self, v: Voice) -> None: """S7: ENDX written; ENVX prepared, E >> 4 of the envelope behind this sample (DOC anomie S7, "$x8 VxENVX").""" self.regs[ENDX] = (self.regs[ENDX] & ~v.bit) | v.endx_buf self.envx_latch = v.envx_source >> 4 def _s8(self, v: Voice) -> None: self.regs[v.base | 9] = self.outx_latch def _s9(self, v: Voice) -> None: self.regs[v.base | 8] = self.envx_latch # -- echo and the global steps (DOC anomie "SOUND GENERATION" steps 22-30) ------------------ def _read_echo(self, address: int) -> int: aram = self.aram word = aram[address & 0xFFFF] | aram[(address + 1) & 0xFFFF] << 8 return (word - 0x10000 if word & 0x8000 else word) >> 1 # DOC anomie "$xf": 15 bits def _write_echo(self, address: int, value: int) -> None: if not self.ram_writable: return aram = self.aram aram[address & 0xFFFF] = value & 0xFF aram[(address + 1) & 0xFFFF] = (value >> 8) & 0xFF def _echo22(self) -> None: """Step 22: the echo pointer from ESA (latched at 29) and the offset; left sample; FIR0.""" self.echo_pointer = ((self.esa << 8) + self.echo_offset) & 0xFFFF self.fir_index = (self.fir_index + 1) & 7 self.fir_history_left[self.fir_index] = self._read_echo(self.echo_pointer) self.fir[0] = _s8(self.regs[0x0F]) def _echo23(self) -> None: self.fir_history_right[self.fir_index] = self._read_echo(self.echo_pointer + 2) self.fir[1] = _s8(self.regs[0x1F]) self.fir[2] = _s8(self.regs[0x2F]) def _echo24(self) -> None: self.fir[3] = _s8(self.regs[0x3F]) self.fir[4] = _s8(self.regs[0x4F]) self.fir[5] = _s8(self.regs[0x5F]) def _echo25(self) -> None: self.fir[6] = _s8(self.regs[0x6F]) self.fir[7] = _s8(self.regs[0x7F]) self.fir_left = self._fir(self.fir_history_left) self.fir_right = self._fir(self.fir_history_right) def _fir(self, history: list[int]) -> int: """DOC anomie "$xf FFCx" and fullsnes "Echo Registers": FIR0 on the oldest sample; the first seven products (>> 6) summed wrapping at 16 bits, the eighth added with clamping, then the low bit cleared.""" index = self.fir_index coefficients = self.fir total = 0 for tap in range(7): total += (history[(index - 7 + tap) & 7] * coefficients[tap]) >> 6 total = wrap16(total) # D1: the eighth product is itself cast to 16 bits before the clamped add (+$8000 from # -$4000 x -128 becomes -$8000). TEST ROM: spc_dsp6 `Random/echo data` fails without # the cast; OBSERVED: the referee does the same (saturation case). anomie and fullsnes # describe only the clamp. total = clamp16(total + wrap16((history[index] * coefficients[7]) >> 6)) return total & ~1 def _echo26(self) -> None: """Step 26: MVOLL, EVOLL, the left output; EFB and the echo-buffer values (DOC anomie steps 26 and "$0d EFB").""" self.out_left = self._output(self.main_left, self.fir_left, MVOLL, EVOLL) self.efb = _s8(self.regs[EFB]) self.echo_out_left = clamp16(self.echo_left + wrap16((self.fir_left * self.efb) >> 7)) & ~1 self.echo_out_right = ( clamp16(self.echo_right + wrap16((self.fir_right * self.efb) >> 7)) & ~1 ) self.main_left = 0 self.echo_left = 0 def _output(self, main: int, fir: int, mvol: int, evol: int) -> int: """DOC anomie "$0c MVOL", "$2c EVOL": each product cast to 16 bits, the sum clamped; FLG.6 mutes (DOC anomie "$6c FLG" m).""" if self.flg & 0x40: return 0 return clamp16( wrap16((main * _s8(self.regs[mvol])) >> 7) + wrap16((fir * _s8(self.regs[evol])) >> 7) ) def _misc27(self) -> None: """Step 27: MVOLR, EVOLR, the right output; PMON latched (DOC anomie step 27).""" right = self._output(self.main_right, self.fir_right, MVOLR, EVOLR) self.samples.append((self.out_left, right)) self.main_right = 0 self.echo_right = 0 self.pmon = self.regs[PMON] def _misc28(self) -> None: """Step 28: NON, EON, DIR latched; FLG.5 for the left echo write (DOC anomie step 28).""" self.non = self.regs[NON] self.eon = self.regs[EON] self.dir = self.regs[DIR] self.echo_write_left = not self.flg & 0x20 def _misc29(self) -> None: """Step 29 (DOC anomie): the counter; the left echo write; EDL applied when the offset is 0; ESA latched; FLG.5 for the right write; on poll samples the internal KON bits acted on at the previous poll are cleared.""" self.counter = (self.counter or tables.COUNTER_RANGE) - 1 self.every_other ^= 1 self.poll = bool(self.every_other) # paired with even counter values at reset (U22) if self.echo_write_left: self._write_echo(self.echo_pointer, self.echo_out_left) if self.echo_offset == 0: self.echo_length = (self.regs[EDL] & 0x0F) << 11 # DOC anomie "$7d EDL": D << 11 bytes self.esa = self.regs[ESA] self.echo_write_right = not self.flg & 0x20 if self.poll: self.internal_kon &= ~self.kon_previous def _misc30(self) -> None: """Step 30 (DOC anomie): KOFF and the internal KON loaded on poll samples; FLG.0-4 and the noise update (DOC anomie "$3d NON": N = (N >> 1) | (((N << 14) ^ (N << 13)) & $4000)).""" if self.poll: self.kon_latch = self.internal_kon self.kon_previous = self.kon_latch self.koff_latch = self.regs[KOFF] else: self.kon_latch = 0 self.koff_latch = 0 rate = self.flg & 0x1F if rate and (self.counter + tables.COUNTER_OFFSETS[rate]) % tables.COUNTER_RATES[rate] == 0: n = self.noise self.noise = (n >> 1) | (((n << 14) ^ (n << 13)) & 0x4000) def _echo30(self) -> None: """Step 30: the right echo write; the offset advances by 4, to 0 at the length (DOC anomie "$7d EDL"; EDL 0 gives a 4-byte buffer: DOC anomie, SNESdev wiki "EDL" errata).""" if self.echo_write_right: self._write_echo(self.echo_pointer + 2, self.echo_out_right) self.echo_offset += 4 if self.echo_offset >= self.echo_length: self.echo_offset = 0