# SPDX-License-Identifier: MIT """Shared by the tests: register writes spelled the way the manuals number things.""" from __future__ import annotations from ym2612_python import CLOCKS_PER_SAMPLE, YM2612, YM3438_ASIC #: Address offset of Yamaha's operators 1 to 4 (index 0 to 3): the register order #: is 1, 3, 2, 4 (spec 3.2). OPERATOR_OFFSET = (0, 8, 4, 12) def reg(fm: YM2612, address: int, value: int, part: int = 0) -> None: fm.write(part * 2, address) fm.write(part * 2 + 1, value) def op_reg(fm: YM2612, channel: int, operator: int, base: int, value: int) -> None: """Write an operator register; channel 0 to 5, operator 0 to 3 (Yamaha's 1 to 4).""" part, index = divmod(channel, 3) reg(fm, base + OPERATOR_OFFSET[operator] + index, value, part) def frequency(fm: YM2612, channel: int, f_number: int, block: int) -> None: part, index = divmod(channel, 3) reg(fm, 0xA4 + index, (block << 3) | (f_number >> 8), part) reg(fm, 0xA0 + index, f_number & 0xFF, part) def key(fm: YM2612, channel: int, mask: int = 0xF) -> None: """Key the operators in ``mask`` (bit 0 is operator 1) on and the rest off.""" reg(fm, 0x28, (mask << 4) | (channel + channel // 3)) def step(fm: YM2612, samples: int = 1) -> list[tuple[int, int]]: fm.run(CLOCKS_PER_SAMPLE * samples) return fm.take_samples() def voice( fm: YM2612, channel: int = 0, algorithm: int = 7, f_number: int = 0x269, block: int = 4, total_levels: tuple[int, int, int, int] = (127, 127, 127, 0), attack: int = 31, feedback: int = 0, ) -> None: """A plain voice: instant attack, no decay, multiple 1, both sides on.""" part, index = divmod(channel, 3) for operator in range(4): op_reg(fm, channel, operator, 0x30, 0x01) op_reg(fm, channel, operator, 0x40, total_levels[operator]) op_reg(fm, channel, operator, 0x50, attack) op_reg(fm, channel, operator, 0x60, 0) op_reg(fm, channel, operator, 0x70, 0) op_reg(fm, channel, operator, 0x80, 0x0F) op_reg(fm, channel, operator, 0x90, 0) reg(fm, 0xB0 + index, (feedback << 3) | algorithm, part) reg(fm, 0xB4 + index, 0xC0, part) frequency(fm, channel, f_number, block) def chip(variant=YM3438_ASIC) -> YM2612: return YM2612(variant) def values(fm: YM2612, samples: int, channel: int = 0) -> list[int]: """The channel's 9-bit value at each of the next ``samples`` samples.""" out = [] for _ in range(samples): fm.run(CLOCKS_PER_SAMPLE) out.append(fm.channel_values()[channel]) fm.take_samples() return out