"""The chip: registers, timers, LFO, six channels, and the output stage. Every rule names its section of ``docs/spec.md``, which names the document or measurement behind it; ``docs/provenance-audit.md`` gives each statement's chain. T numbers are the technical decisions of ``docs/handoff-brief.md``, all taken at their defaults and all PROVISIONAL. "Emulator tier" means no manufacturer's document and no measurement stated in prose gives the rule, and the default is ymfm's (BSD-3-Clause, Aaron Giles), named. CHOICE marks what no source speaks to. The model steps once per sample, which is 144 clocks of the chip's own clock pin (spec 4.2). It does not model anything inside a sample: when within the 24 internal clocks a write lands, lost writes, or the six output slots as a waveform (spec 4.6, 21). What differs between the discrete YM2612 and the YM3438 is data on :class:`FMVariant`. """ from __future__ import annotations from ym2612_python.operator import Operator from ym2612_python.tables import ( ALGORITHMS, KEY_CODE_NOTE, LFO_DIVIDERS, TREMOLO_SHIFT, vibrato_offset, ) from ym2612_python.variant import YM2612_DISCRETE, FMVariant #: Clocks of the chip's clock pin per sample (spec 4.2: documented by Yamaha's #: F-number formula, measured by Nemesis on an oscilloscope). CLOCKS_PER_SAMPLE = 144 #: Yamaha's required waits after a write, in clocks of the chip's pin (spec 2.7: #: documented in both manuals; 83 and 47 measured as real minimums by Stef). The #: core does not enforce them; they are here for a board that wants to warn. WAIT_AFTER_ADDRESS = 17 WAIT_AFTER_OPERATOR_DATA = 83 WAIT_AFTER_CHANNEL_DATA = 47 #: How long BUSY reads set after a data write (spec 12.2: measured by Eke on both #: chips, and a five-stage counter on the die). BUSY_CLOCKS = 192 #: Spec 9.6, contradiction C11, decision T4. PROVISIONAL: operator 3 takes #: operators 1 and 2 from the previous sample and operator 4 takes operator 2 from #: the previous sample (Sauraen's reading of the die). False gives every modulator #: from the current sample, as ymfm does. DELAYED_MODULATION = True #: Spec 3.3.5, contradiction C12, decision T7. PROVISIONAL, emulator tier: one #: holding latch per part for the high F-number byte, taken by the next low-byte #: write whatever its channel. False gives one latch per channel, which is how #: Nemesis's sentence reads (p5621). FNUM_LATCH_SHARED = True #: Spec 7.3.5, unknown U3, decision T13. PROVISIONAL: the envelope counter is 12 #: bits and skips 0 (GManiac, p18838, no test described). ENVELOPE_COUNTER_SKIPS_ZERO = True #: Operators in the order of the register addresses' bits 3-2 (spec 3.2: #: documented), as indexes into a channel's list, which is in Yamaha's order. REGISTER_SLOT_TO_OPERATOR = (0, 2, 1, 3) class Channel: """One of the six channels. ``operators`` is in Yamaha's order, 1 to 4. Registers (spec 3.3): ``f_number``, ``block``, ``feedback``, ``algorithm``, ``left``, ``right``, ``tremolo_depth``, ``vibrato_depth``. State: ``feedback_older`` and ``feedback_newer`` are operator 1's last two outputs (spec 9.4: two stores, measured by GManiac); ``operator2_previous`` is operator 2's last output (spec 9.6); ``output`` is the channel's signed 9-bit value of the last sample, before the DAC switch. """ __slots__ = ( "algorithm", "block", "f_number", "feedback", "feedback_newer", "feedback_older", "left", "operator2_previous", "operators", "output", "right", "tremolo_depth", "vibrato_depth", ) # fmt: skip def __init__(self) -> None: self.operators = [Operator(), Operator(), Operator(), Operator()] self.f_number = 0 self.block = 0 self.feedback = 0 self.algorithm = 0 # Spec 16.2 (lightly tested: p8020, p7999): both sides on after power-on. self.left = 1 self.right = 1 self.tremolo_depth = 0 self.vibrato_depth = 0 self.feedback_older = 0 self.feedback_newer = 0 self.operator2_previous = 0 self.output = 0 class YM2612: """One chip. All state is plain attributes: integers, lists, and the records above. ``variant`` is fixed at construction and never replaced. ``enabled`` is the board's switch: while False the operators are not stepped and each frame is (0, 0); timers and BUSY still run. ``samples`` holds the frames not yet taken. """ def __init__(self, variant: FMVariant = YM2612_DISCRETE) -> None: self.variant = variant self.enabled = True self.reset_held = False self.clock_remainder = 0 self.samples: list[tuple[int, int]] = [] self._power_on() def _power_on(self) -> None: """Spec 16, unknown U14, decision T14. PROVISIONAL: every register 0 with the panning bits set, operators in release at the quietest level, timers, flags, LFO and envelope counter cleared. Power-on and /IC are the same. """ self.channels = [Channel() for _ in range(6)] # Spec 2.5 (measured, p7673): one latch holds the address and its part. self.address = 0 self.address_part = 0 # Spec 3.3.5: pending high bytes of the F-number, per part and channel # (only index 0 of each part is used while FNUM_LATCH_SHARED). self.fnum_latch = [0, 0, 0, 0, 0, 0] # Spec 3.3.4, 10.1: channel 3's own frequencies for operators 1, 2, 3. self.channel3_latch = [0, 0, 0] self.channel3_f_number = [0, 0, 0] self.channel3_block = [0, 0, 0] self.channel3_mode = 0 self.lfo_enabled = 0 self.lfo_rate = 0 self.lfo_counter = 0 self.lfo_divider = 0 self.timer_a_register = 0 self.timer_b_register = 0 self.timer_a_counter = 0 self.timer_b_counter = 0 self.timer_b_prescaler = 0 self.timer_load = 0 self.timer_enable = 0 self.status_flags = 0 self.csm_key = 0 self.dac_data = 0x80 self.dac_enabled = 0 self.test_21 = 0 self.test_2c = 0 self.envelope_counter = 0 self.envelope_divider = 0 self.busy_clocks = 0 # -- the board's side -------------------------------------------------------- @property def irq(self) -> bool: """The /IRQ pin: low while either timer flag is set (spec 11.4: measured).""" return self.status_flags != 0 def reset_line(self, level: int) -> None: """Drive the /IC pin. ``level`` is the pin's level: 0 holds the chip in reset, 1 releases it (spec 16.1). While held, writes are ignored. CHOICE: the reset takes effect at once, not after the 192 clocks Yamaha asks the pulse to last, and the clock divider's remainder is kept. """ if not level: self._power_on() self.reset_held = not level def write(self, port: int, value: int) -> None: """Write a byte to one of the four addresses (spec 2.1, 2.2). Port 0 and 2 take an address for part I and II; 1 and 3 take data. A data byte goes to the latched register in the latched part whichever data port it came through (spec 2.5: measured). The register changes now and is heard from the next sample (decision T9, unknown U1: PROVISIONAL). """ if self.reset_held: return value &= 0xFF if not port & 1: self.address = value self.address_part = (port >> 1) & 1 return # Spec 12.2 (measured): a data write, and nothing else, sets BUSY. self.busy_clocks = BUSY_CLOCKS address = self.address if address < 0x30: # Spec 2.3 (measured, p5648): there are no global registers in part II. if self.address_part == 0: self._write_global(address, value) elif address < 0xA0: self._write_operator(address, value) else: self._write_channel(address, value) def read(self, port: int) -> int | None: """The status byte, or None where this part leaves the bus undriven (spec 12.1, 12.5). Bit 7 BUSY, bit 1 Timer B's flag, bit 0 Timer A's. """ if not self.variant.status_ports[port & 3]: return None return (0x80 if self.busy_clocks else 0) | self.status_flags def run(self, clocks: int) -> None: """Advance by clocks of the chip's clock pin; one frame per 144 (spec 4.2).""" self.busy_clocks = max(0, self.busy_clocks - clocks) remainder = self.clock_remainder + clocks while remainder >= CLOCKS_PER_SAMPLE: remainder -= CLOCKS_PER_SAMPLE self._sample() self.clock_remainder = remainder def take_samples(self) -> list[tuple[int, int]]: """The (left, right) frames since the last call, one per 144 clocks. Each side is the sum of the six slots in steps of the 9-bit converter (decision T11), after the variant's output stage: within -1,554 to +1,554. """ samples = self.samples self.samples = [] return samples def channel_values(self) -> list[int]: """The six signed 9-bit values of the last sample, channels 1 to 6, the sixth being the DAC value while the DAC is enabled. For validation.""" values = [channel.output for channel in self.channels] if self.dac_enabled: values[5] = self._dac_value() return values # -- registers (spec 3) ------------------------------------------------------ def _write_global(self, address: int, value: int) -> None: if address == 0x22: self.lfo_enabled = (value >> 3) & 1 self.lfo_rate = value & 7 elif address == 0x24: self.timer_a_register = (self.timer_a_register & 0x003) | (value << 2) elif address == 0x25: self.timer_a_register = (self.timer_a_register & 0x3FC) | (value & 3) elif address == 0x26: self.timer_b_register = value elif address == 0x27: self._write_timer_control(value) elif address == 0x28: # Spec 3.1.1: channel values 0 to 2 and 4 to 6. Values 3 and 7 are # ignored (unknown U2, decision T15: PROVISIONAL). select = value & 7 if select & 3 != 3: operators = self.channels[(select & 3) + (3 if select & 4 else 0)].operators operators[0].key_request = (value >> 4) & 1 operators[1].key_request = (value >> 5) & 1 operators[2].key_request = (value >> 6) & 1 operators[3].key_request = (value >> 7) & 1 elif address == 0x2A: self.dac_data = value elif address == 0x2B: self.dac_enabled = value >> 7 elif address == 0x21: self.test_21 = value # stored, not acted on (decision T8) elif address == 0x2C: self.test_2c = value # only bit 3 is used: the DAC's ninth bit (spec 13.3) # Spec 3.1.2 (measured, p5680): $29 and $2D to $2F do not exist. def _write_timer_control(self, value: int) -> None: """Register $27 (spec 10.1, 11.2, 11.3).""" self.channel3_mode = value >> 6 if self.channel3_mode != 2: self.csm_key = 0 # spec 10.4 (measured, p7967): leaving mode 10 clears it self._refresh_channel3() # Spec 11.2 (measured, p5687): a timer reloads when its load bit goes from # 0 to 1, not when 1 is written over 1. rising = value & ~self.timer_load if rising & 1: self.timer_a_counter = self.timer_a_register if rising & 2: self.timer_b_counter = self.timer_b_register self.timer_load = value & 3 self.timer_enable = (value >> 2) & 3 # Spec 11.3 (documented): writing 1 to a reset bit clears that flag. self.status_flags &= ~(value >> 4) & 3 def _write_operator(self, address: int, value: int) -> None: """Registers $30 to $9F (spec 3.2: documented).""" if address & 3 == 3: return channel = (address & 3) + 3 * self.address_part operator = self.channels[channel].operators[REGISTER_SLOT_TO_OPERATOR[(address >> 2) & 3]] group = address & 0xF0 if group == 0x30: operator.detune = (value >> 4) & 7 operator.multiple = value & 15 elif group == 0x40: operator.total_level = value & 0x7F elif group == 0x50: operator.key_scale = value >> 6 operator.attack_rate = value & 0x1F elif group == 0x60: operator.tremolo = value >> 7 operator.decay_rate = value & 0x1F elif group == 0x70: operator.sustain_rate = value & 0x1F elif group == 0x80: operator.sustain_level = value >> 4 operator.release_rate = value & 15 else: # Spec 3.2.3 (measured, p8037, p14196): the upper four bits do nothing. operator.ssg = value & 15 def _write_channel(self, address: int, value: int) -> None: """Registers $A0 to $B6 (spec 3.3).""" index = address & 3 if index == 3: return part = self.address_part channel = self.channels[index + 3 * part] latch = 3 * part + (0 if FNUM_LATCH_SHARED else index) group = address & 0xFC if group == 0xA4: # Spec 3.3.5 (documented and measured, p5621): the high byte waits. self.fnum_latch[latch] = value & 0x3F channel.block = value >> 3 & 7 elif group == 0xA0: high = self.fnum_latch[latch] channel.f_number = ((high & 7) << 8) | value channel.block = high >> 3 self._refresh_frequency(channel) if part == 0 and index == 2: self._refresh_channel3() elif group == 0xAC: if part == 0: self.channel3_latch[0 if FNUM_LATCH_SHARED else index] = value & 0x3F elif group == 0xA8: # Spec 3.3.4 (documented, and measured by Shiru): $A9 is operator 1, # $AA operator 2, $A8 operator 3. Part I only. if part == 0: high = self.channel3_latch[0 if FNUM_LATCH_SHARED else index] operator = (2, 0, 1)[index] self.channel3_f_number[operator] = ((high & 7) << 8) | value self.channel3_block[operator] = high >> 3 self._refresh_channel3() elif group == 0xB0: channel.feedback = (value >> 3) & 7 channel.algorithm = value & 7 elif group == 0xB4: channel.left = value >> 7 channel.right = (value >> 6) & 1 channel.tremolo_depth = (value >> 4) & 3 channel.vibrato_depth = value & 7 @staticmethod def _set_frequency(operator: Operator, f_number: int, block: int) -> None: operator.f_number = f_number operator.block = block # Spec 5.5 (documented): the key code is the block and two bits made from # the F-number's top four, taken before vibrato (die, p31049). operator.key_code = (block << 2) | KEY_CODE_NOTE[f_number >> 7] def _refresh_frequency(self, channel: Channel) -> None: for operator in channel.operators: self._set_frequency(operator, channel.f_number, channel.block) def _refresh_channel3(self) -> None: """Spec 10.1, 10.2: in modes 01, 10 and 11 operators 1 to 3 of channel 3 take their own F-number, block and so key code; operator 4 keeps the channel's. Mode 01 documented (YM3438 manual), 10 measured (p5650); mode 11 PROVISIONAL, emulator tier (unknown U25). """ channel = self.channels[2] self._refresh_frequency(channel) if self.channel3_mode: for index in range(3): self._set_frequency( channel.operators[index], self.channel3_f_number[index], self.channel3_block[index], ) # -- one sample (spec 18) ---------------------------------------------------- def _step_timers(self) -> None: """Spec 11.1, 11.2: Timer A steps every sample, Timer B every sixteenth.""" if self.timer_load & 1: self.timer_a_counter += 1 if self.timer_a_counter >= 1024: self.timer_a_counter = self.timer_a_register if self.timer_enable & 1: self.status_flags |= 1 # Spec 10.3, 10.4 (measured, p5650, p7967): in mode 10 an overflow # sets the CSM key flag, whatever the enable bit says. if self.channel3_mode == 2: self.csm_key = 1 # Spec 11.5, unknown U9, decision T16. PROVISIONAL, emulator tier: the # divide-by-16 runs freely and is not restarted by the load bit. self.timer_b_prescaler = (self.timer_b_prescaler + 1) & 15 if self.timer_b_prescaler == 0 and self.timer_load & 2: self.timer_b_counter += 1 if self.timer_b_counter >= 256: self.timer_b_counter = self.timer_b_register if self.timer_enable & 2: self.status_flags |= 2 def _dac_value(self) -> int: """Spec 13.3 (die, p26996): $2A with its top bit inverted is the upper eight of nine signed bits; $2C bit 3 is the ninth.""" return ((self.dac_data - 0x80) << 1) | ((self.test_2c >> 3) & 1) def _sample(self) -> None: """One sample, in the order of spec 18. Where the timers and the LFO come in that order is a CHOICE (unknowns U6, U8).""" self._step_timers() if not self.enabled or self.reset_held: self.samples.append((0, 0)) return # The LFO (spec 8.1 to 8.3). Its divider is the manual's (decision T2). # Held at 0 while disabled: PROVISIONAL, emulator tier (U26, decision T12). if self.lfo_enabled: self.lfo_divider += 1 if self.lfo_divider >= LFO_DIVIDERS[self.lfo_rate]: self.lfo_divider = 0 self.lfo_counter = (self.lfo_counter + 1) & 0x7F else: self.lfo_divider = 0 self.lfo_counter = 0 lfo_counter = self.lfo_counter # Spec 8.4: a triangle of 0 to 63 that starts at its maximum, doubled. triangle = lfo_counter & 0x3F if not lfo_counter & 0x40: triangle ^= 0x3F triangle <<= 1 # Spec 4.5, 7.3.1 (measured): the envelope's shared counter advances every # third sample. Which of the three is a CHOICE (unknown U4). self.envelope_divider += 1 envelope_update = self.envelope_divider == 3 if envelope_update: self.envelope_divider = 0 self.envelope_counter = (self.envelope_counter + 1) & 0xFFF if self.envelope_counter == 0 and ENVELOPE_COUNTER_SKIPS_ZERO: self.envelope_counter = 1 envelope_counter = self.envelope_counter csm_key = self.csm_key self.csm_key = 0 # spec 10.4: cleared once this sample has acted on it variant = self.variant low_limit = -256 high_limit = variant.accumulator_max left = right = 0 for number, channel in enumerate(self.channels): operators = channel.operators tremolo = triangle >> TREMOLO_SHIFT[channel.tremolo_depth] vibrato = channel.vibrato_depth # Spec 10.4 (measured, p7967): channel 3's operators are keyed by their # $28 bit or the CSM flag, and only a change of the two together acts. extra_key = csm_key if number == 2 else 0 increments = [0, 0, 0, 0] for index in range(4): operator = operators[index] operator.set_key(operator.key_request | extra_key) operator.ssg_step() if envelope_update: operator.envelope_step(envelope_counter) f_number = operator.f_number if vibrato: # Spec 8.5 (measured, p8905, p8908): added to the 11-bit # F-number before the block, the sum kept to 11 bits. f_number = (f_number + vibrato_offset(f_number, vibrato, lfo_counter)) & 0x7FF increments[index] = operator.phase_increment(f_number) # Spec 9: operators are worked in the order 1, 3, 2, 4 (spec 4.4: # measured on YM3438s by Sauraen). wiring = ALGORITHMS[channel.algorithm] older = channel.feedback_older newer = channel.feedback_newer previous2 = channel.operator2_previous # Spec 9.4: operator 1's last two outputs summed (measured: two # stores) and shifted by the feedback level (documented levels; the # shift is arithmetic from them, unknown U7). feedback = channel.feedback self_modulation = (older + newer) >> (10 - feedback) if feedback else 0 out1 = operators[0].clock(increments[0], self_modulation, tremolo) # Spec 9.3 (measured, p18814): a modulation input is the sum of the # modulators' outputs shifted right once. if DELAYED_MODULATION: modulation = (newer * wiring[1] + previous2 * wiring[2]) >> 1 out3 = operators[2].clock(increments[2], modulation, tremolo) out2 = operators[1].clock(increments[1], (out1 * wiring[0]) >> 1, tremolo) modulation = (out1 * wiring[3] + previous2 * wiring[4] + out3 * wiring[5]) >> 1 else: out2 = operators[1].clock(increments[1], (out1 * wiring[0]) >> 1, tremolo) modulation = (out1 * wiring[1] + out2 * wiring[2]) >> 1 out3 = operators[2].clock(increments[2], modulation, tremolo) modulation = (out1 * wiring[3] + out2 * wiring[4] + out3 * wiring[5]) >> 1 out4 = operators[3].clock(increments[3], modulation, tremolo) channel.feedback_older = newer channel.feedback_newer = out1 channel.operator2_previous = out2 # Spec 14.1 (measured, p11862, p11876): each carrier is cut to its # upper 9 bits before the sum. Spec 14.2: the sum is limited. value = out4 >> 5 if wiring[6]: value += out1 >> 5 if wiring[7]: value += out2 >> 5 if wiring[8]: value += out3 >> 5 if value > high_limit: value = high_limit elif value < low_limit: value = low_limit channel.output = value # Spec 13.1, 13.2: the DAC replaces channel 6's output; its operators # ran all the same. if number == 5 and self.dac_enabled: value = self._dac_value() # Spec 14.3, 15: the channel's slot on each side. The sum of the six # slots is the output (decision T11). if variant.ladder: # Spec 15.2.5, decision T10. PROVISIONAL, emulator tier (U12). value += variant.ladder_positive if value >= 0 else variant.ladder_negative left += value if channel.left else variant.ladder_idle right += value if channel.right else variant.ladder_idle else: if channel.left: left += value if channel.right: right += value self.samples.append((left, right))