"""Rung 2: the manufacturers' documents (docs/validation.md). S2 is Yamaha's YM3438 application manual (April 1990), cited by printed page; S1 the YM2612 manual from the Sega binder (cited, not copied); S4 the YM2608 manual. Where S1 and S2 disagree the test says which is followed and why. """ from __future__ import annotations import math from itertools import pairwise import pytest from helpers import chip, frequency, key, op_reg, reg, step, values, voice from ym2612_python import YM2612_DISCRETE from ym2612_python.operator import ATTACK, DECAY, RELEASE, SUSTAIN, Operator from ym2612_python.tables import DETUNE, KEY_CODE_NOTE, LFO_DIVIDERS, vibrato_offset MANUAL_CLOCK = 8_000_000 # the manuals' figures assume 8 MHz # -- register map (S2 pages 9 to 16, table 2.1) ---------------------------------- def test_operator_registers_decode_every_field(): fm = chip() op = fm.channels[0].operators[0] for base, value in ((0x30, 0x7F), (0x40, 0xFF), (0x50, 0xFF), (0x60, 0xFF), (0x70, 0xFF), (0x80, 0xFF), (0x90, 0x0F)): # fmt: skip op_reg(fm, 0, 0, base, value) assert (op.detune, op.multiple, op.total_level) == (7, 15, 127) assert (op.key_scale, op.attack_rate, op.tremolo, op.decay_rate) == (3, 31, 1, 31) assert (op.sustain_rate, op.sustain_level, op.release_rate, op.ssg) == (31, 15, 15, 15) def test_register_addresses_run_operators_1_3_2_4_and_both_parts(): """S2 table 2.1, S4 table 2-2: address bits 3-2 choose 1, 3, 2, 4; bits 1-0 the channel; part II holds channels 4 to 6.""" fm = chip() for part in range(2): for low in range(16): reg(fm, 0x40 + low, 1 + low + 16 * part, part) for part in range(2): for index in range(3): levels = [op.total_level for op in fm.channels[index + 3 * part].operators] base = 1 + index + 16 * part assert levels == [base, base + 8, base + 4, base + 12] def test_channel_registers_decode_every_field(): fm = chip() reg(fm, 0xB1, 0x3D, part=1) reg(fm, 0xB5, 0xB5, part=1) frequency(fm, 4, 0x555, 5) channel = fm.channels[4] assert (channel.feedback, channel.algorithm) == (7, 5) assert (channel.left, channel.right, channel.tremolo_depth, channel.vibrato_depth) == ( 1, 0, 3, 5, ) assert (channel.f_number, channel.block) == (0x555, 5) def test_global_registers_decode_every_field(): fm = chip() reg(fm, 0x22, 0x0D) reg(fm, 0x24, 0xAB) reg(fm, 0x25, 0x02) reg(fm, 0x26, 0xCD) reg(fm, 0x27, 0x8F) reg(fm, 0x2A, 0x12) reg(fm, 0x2B, 0x80) assert (fm.lfo_enabled, fm.lfo_rate) == (1, 5) assert (fm.timer_a_register, fm.timer_b_register) == ((0xAB << 2) | 2, 0xCD) assert (fm.channel3_mode, fm.timer_enable, fm.timer_load) == (2, 3, 3) assert (fm.dac_data, fm.dac_enabled) == (0x12, 1) def test_key_register_chooses_channels_0_1_2_and_4_5_6(): """S1, S2: $28 bits 2-0, values 0, 1, 2 and 4, 5, 6; bits 7-4 operators 4 to 1.""" fm = chip() for channel, select in enumerate((0, 1, 2, 4, 5, 6)): reg(fm, 0x28, 0x50 | select) requests = [op.key_request for op in fm.channels[channel].operators] assert requests == [1, 0, 1, 0] # -- phase generator (S2 pages 23 to 25) ----------------------------------------- @pytest.mark.parametrize( ("note_hz", "printed"), [(277.2, 654.0), (293.7, 692.9), (440.0, 1038.1), (466.2, 1099.9), (493.9, 1165.3), (523.3, 1234.6)], ) # fmt: skip def test_f_number_formula_reproduces_the_manuals_note_table(note_hz, printed): """S2 printed pages 23 and 24: F-Number = (144 x f x 2^20 / fM) / 2^(B-1), block 4 at 8 MHz, six of the table's rows (A4 = 1038.1 is the worked example). The model's phase increment for the rounded F-number gives the note back.""" f_number = 144 * note_hz * 2**20 / MANUAL_CLOCK / 2 ** (4 - 1) assert abs(f_number - printed) < 0.06 op = Operator() op.block, op.multiple = 4, 1 played = op.phase_increment(round(printed)) * MANUAL_CLOCK / (144 * 2**20) assert abs(played - note_hz) < MANUAL_CLOCK / (144 * 2**20) * 8 # one F-number step def test_key_code_for_all_2048_f_numbers(): """S2 page 24, S4 2-4-1 B: N4 = F11; N3 = F11(F10 + F9 + F8) + !F11 F10 F9 F8.""" fm = chip() for f_number in range(2048): f11, f10, f9, f8 = (f_number >> 10) & 1, (f_number >> 9) & 1, (f_number >> 8) & 1, ( f_number >> 7) & 1 # fmt: skip n3 = 1 if (f11 and (f10 or f9 or f8)) or (not f11 and f10 and f9 and f8) else 0 frequency(fm, 0, f_number, 5) assert fm.channels[0].operators[0].key_code == (5 << 2) | (f11 << 1) | n3 assert KEY_CODE_NOTE == (0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 3, 3, 3, 3, 3, 3) #: The distinct values printed in S2's table 2.4, in millihertz. PRINTED_DETUNE_MILLIHERTZ = { 0, 53, 106, 159, 212, 264, 317, 370, 423, 476, 529, 582, 635, 688, 741, 846, 899, 1005, 1058, 1164, } # fmt: skip def test_detune_table_in_hertz_at_the_manuals_clock(): """S2 table 2.4 (printed page 25), at fM = 7.9872 MHz: every amount the model adds, turned into hertz, is a value the table prints, and the corner entries are where the table has them.""" unit = 7_987_200 / (144 * 2**20) for magnitude in (1, 2, 3): for key_code in range(32): millihertz = round(DETUNE[magnitude][key_code] * unit * 1000) assert millihertz in PRINTED_DETUNE_MILLIHERTZ, (magnitude, key_code) assert [DETUNE[m][0] for m in (1, 2, 3)] == [0, 1, 2] # 0.000, 0.053, 0.106 assert [DETUNE[m][31] for m in (1, 2, 3)] == [8, 16, 22] # 0.423, 0.846, 1.164 assert [DETUNE[m][16] for m in (1, 2, 3)] == [2, 5, 8] # block 4 note 0 assert all(list(row) == sorted(row) for row in DETUNE) def test_detune_register_is_a_sign_and_a_magnitude(): """S2 table 2.4: values 0 to 7 mean 0, 1, 2, 3, 0, -1, -2, -3.""" fm = chip() op = fm.channels[0].operators[0] frequency(fm, 0, 0x400, 4) op.multiple = 1 plain = (0x400 << 4) >> 1 amounts = [] for detune in range(8): op.detune = detune amounts.append(op.phase_increment(0x400) - plain) row = [DETUNE[m][op.key_code] for m in range(4)] assert amounts == [0, row[1], row[2], row[3], 0, -row[1], -row[2], -row[3]] def test_multiple_table(): """S2 table 2.3: 0 is one half, 1 to 15 are themselves.""" op = Operator() op.block = 4 base = (0x200 << 4) >> 1 for multiple in range(16): op.multiple = multiple assert op.phase_increment(0x200) == (base // 2 if multiple == 0 else base * multiple) # -- envelope generator (S2 pages 26 to 29) -------------------------------------- def test_rate_is_2r_plus_rks_zero_for_r_zero_and_at_most_63(): """S2 page 28: Rate = 2R + Rks; R = 0 gives 0; the limit is 63.""" op = Operator() for key_scale in range(4): for key_code in range(32): op.key_scale, op.key_code = key_scale, key_code assert op.rate(0) == 0 for register in range(1, 32): assert op.rate(register) == min(63, 2 * register + (key_code >> (3 - key_scale))) def test_key_scaling_table(): """S2 table 2.6: Rks is the key code divided by 8, 4, 2, 1 for KS 0 to 3: all 128 entries, through the register.""" fm = chip() op = fm.channels[0].operators[0] for key_scale in range(4): op_reg(fm, 0, 0, 0x50, (key_scale << 6) | 1) for block in range(8): for f_top in (0x000, 0x380, 0x400, 0x480): frequency(fm, 0, f_top, block) assert op.rate(1) - 2 == op.key_code // (8, 4, 2, 1)[key_scale] def test_total_level_is_three_quarters_of_a_db_and_sustain_level_3_db_a_step(): """S2 table 2.5: total level 0.75 dB a step (8 envelope units); sustain level 3 dB a step ($20 units), where a unit is 96 dB / 1024.""" op = Operator() op.envelope_phase, op.attenuation = SUSTAIN, 0 for total_level in range(128): op.total_level = total_level assert op.level(0) * 96 / 1024 == total_level * 0.75 for sustain_level in range(15): op = Operator() op.envelope_phase, op.attenuation = DECAY, sustain_level * 0x20 op.sustain_level = sustain_level op.envelope_step(1) assert op.envelope_phase == SUSTAIN assert op.attenuation * 96 / 1024 == sustain_level * 3.0 def test_attack_rate_31_reaches_the_total_level_at_once(): """S2 figure 2.4's note, S1: with SSG-EG "AR is fixed at 1F"; p5650 calls $1F "infinity". Key scale 0, lowest note: the rate is 62.""" fm = chip() voice(fm, f_number=0, block=0) key(fm, 0) step(fm, 1) assert fm.channels[0].operators[3].attenuation == 0 def envelope_shape(ssg_bits, samples=6000): """The carrier's output level, sample by sample, of one SSG-EG note.""" fm = chip() voice(fm) op_reg(fm, 0, 3, 0x60, 22) # decay op_reg(fm, 0, 3, 0x70, 22) # sustain rate op_reg(fm, 0, 3, 0x80, 0x0F) op_reg(fm, 0, 3, 0x90, 0x08 | ssg_bits) key(fm, 0) op = fm.channels[0].operators[3] trace = [] for _ in range(samples): step(fm, 1) trace.append(op.level(0)) return trace def describe(trace): """Classify a trace of attenuation: count the falling and rising ramps and say where it ends. A 'fall' is the sound getting quieter.""" ramps = [] direction = 0 for before, after in pairwise(trace): if abs(after - before) > 0x100: direction = 0 # a jump between ramps continue if after > before and direction != 1: direction = 1 ramps.append("fall") elif after < before and direction != -1: direction = -1 ramps.append("rise") end = "silent" if trace[-1] >= 0x3F0 else "loud" if trace[-1] == 0 else "moving" return ramps, end @pytest.mark.parametrize( ("bits", "first", "repeats", "end"), [ (0b000, "fall", True, "moving"), # repeated falling ramps (0b001, "fall", False, "silent"), # one ramp, then silence (0b010, "fall", True, "moving"), # down, up, down, up (0b011, "fall", False, "loud"), # one ramp, then held loud (0b100, "rise", True, "moving"), # repeated rising ramps (0b101, "rise", False, "loud"), # one rise, then held loud (0b110, "rise", True, "moving"), # up, down, up, down (0b111, "rise", False, "silent"), # one rise, then silence ], ) def test_the_eight_ssg_eg_shapes(bits, first, repeats, end): """S2 figure 2.4 (printed page 29), with the attack rate at 31 as it asks.""" ramps, ending = describe(envelope_shape(bits)) assert ramps[0] == first assert (len(ramps) > 3) is repeats if not repeats: assert len(ramps) == 1 and ending == end alternating = bits & 0b010 and repeats assert (len(set(ramps)) == 2) is bool(alternating) # -- algorithms and feedback (S2 figure 2.2, table 2.2) -------------------------- CARRIERS = ({3}, {3}, {3}, {3}, {1, 3}, {1, 2, 3}, {1, 2, 3}, {0, 1, 2, 3}) MODULATIONS = ( {(0, 1), (1, 2), (2, 3)}, {(0, 2), (1, 2), (2, 3)}, {(0, 3), (1, 2), (2, 3)}, {(0, 1), (1, 3), (2, 3)}, {(0, 1), (2, 3)}, {(0, 1), (0, 2), (0, 3)}, {(0, 1)}, set(), ) def heard_with(algorithm, loud, keyed): fm = chip() levels = [0 if operator in loud else 127 for operator in range(4)] voice(fm, algorithm=algorithm, total_levels=tuple(levels)) key(fm, 0, sum(1 << operator for operator in keyed)) return values(fm, 400) @pytest.mark.parametrize("algorithm", range(8)) def test_algorithm_carriers(algorithm): """S2 figure 2.2: an operator alone is heard only if it is a carrier.""" for operator in range(4): heard = heard_with(algorithm, {operator}, {operator}) assert (max(heard) > 100) is (operator in CARRIERS[algorithm]), operator @pytest.mark.parametrize("algorithm", range(8)) def test_algorithm_connections(algorithm): """S2 figure 2.2: adding operator a changes what is heard of operator b exactly when a modulates b directly or through another (the path is opened by keying everything on the way).""" reach = set(MODULATIONS[algorithm]) grew = True while grew: grew = False for a, b in list(reach): for c, d in MODULATIONS[algorithm]: if b == c and (a, d) not in reach: reach.add((a, d)) grew = True for carrier in CARRIERS[algorithm]: alone = heard_with(algorithm, {carrier}, {carrier}) for other in range(4): if other == carrier or other in CARRIERS[algorithm]: continue between = {o for o in range(4) if o not in CARRIERS[algorithm]} both = heard_with(algorithm, {carrier} | between, {carrier, other} | between) silent_other = heard_with(algorithm, {carrier} | between, {carrier} | between - {other}) changed = both != silent_other assert changed is ((other, carrier) in reach), (other, carrier) assert max(alone) > 100 def test_feedback_levels_are_the_manuals(): """S2 table 2.2: levels 1 to 7 are pi/16, pi/8, pi/4, pi/2, pi, 2 pi, 4 pi: the peak phase offset of operator 1 on itself at full output, where 1,024 phase units are 2 pi. (The shift that gives them is arithmetic from these levels: unknown U7.)""" peak = 8168 + 8168 for feedback, fraction in ((1, 1 / 16), (2, 1 / 8), (3, 1 / 4), (4, 1 / 2), (5, 1), (6, 2), (7, 4)): # fmt: skip offset = peak >> (10 - feedback) assert abs(offset * 2 * math.pi / 1024 / (fraction * math.pi) - 1) < 0.04 # 31 for 32 fm = chip() voice(fm, algorithm=7, total_levels=(0, 127, 127, 127), feedback=7) key(fm, 0) with_feedback = values(fm, 300) fm = chip() voice(fm, algorithm=7, total_levels=(0, 127, 127, 127), feedback=0) key(fm, 0) assert values(fm, 300) != with_feedback # -- LFO (S2 printed page 31) ---------------------------------------------------- @pytest.mark.parametrize( ("rate", "hertz"), list(enumerate((3.98, 5.56, 6.02, 6.37, 6.88, 9.63, 48.1, 72.2))), ) def test_lfo_rates(rate, hertz): """S2 page 31: the eight rates at 8 MHz. The model's divider is the manual's (decision T2); emulators use one fewer, which is 0.9 % to 20 % faster. The test states both and holds the model to the manual's within 0.5 %.""" fm = chip() reg(fm, 0x22, 0x08 | rate) wraps = 0 last = 0 samples = 128 * LFO_DIVIDERS[rate] * 3 for _ in range(samples): step(fm, 1) if fm.lfo_counter < last: wraps += 1 last = fm.lfo_counter assert wraps == 3 model_hertz = MANUAL_CLOCK / 144 / (128 * LFO_DIVIDERS[rate]) other_hertz = MANUAL_CLOCK / 144 / (128 * (LFO_DIVIDERS[rate] - 1)) assert abs(model_hertz / hertz - 1) < 0.005 assert abs(other_hertz / hertz - 1) > abs(model_hertz / hertz - 1) @pytest.mark.parametrize(("depth", "decibels"), [(0, 0.0), (1, 1.4), (2, 5.9), (3, 11.8)]) def test_tremolo_depths(depth, decibels): """S2 page 31: 0, 1.4, 5.9 and 11.8 dB, heard as the swing of a steady output (one operator held at its peak) over the LFO's cycle.""" fm = chip() voice(fm, f_number=0, block=0) op_reg(fm, 0, 3, 0x60, 0x80) reg(fm, 0xB4, 0xC0 | (depth << 4)) reg(fm, 0x22, 0x0F) key(fm, 0) step(fm, 1) fm.channels[0].operators[3].phase = 0x40000 # a quarter turn, and it stays there heard = values(fm, 128 * 6 + 10) assert max(heard) == 255 swing = 20 * math.log10(max(heard) / min(heard)) assert abs(swing - decibels) < 0.15 @pytest.mark.parametrize( ("depth", "cents"), [(1, 3.4), (2, 6.7), (3, 10), (4, 14), (5, 20), (6, 40), (7, 80)] ) def test_vibrato_depths(depth, cents): """S2 page 31: plus and minus 3.4 to 80 cents, as the peak deviation of an F-number of $400 (the table's last column is this row of the manual).""" f_number = 0x400 offsets = [vibrato_offset(f_number, depth, counter) for counter in range(128)] assert max(offsets) == -min(offsets) peak_cents = 1200 * math.log2((f_number + max(offsets)) / f_number) assert abs(peak_cents / cents - 1) < 0.05 # whole F-number steps: 13.5 for 14 assert offsets[0] == 0 # -- timers, status, DAC (S2 pages 11 to 15) ------------------------------------- def test_timer_formulas_are_the_ym3438_manuals_not_the_ym2612_manuals(): """S2 page 13: tA = 144 (1024 - NA) / fM, tB = 2304 (256 - NB) / fM: at 8 MHz, 18 microseconds to 18.4 ms, and steps of 288 microseconds. S1 and S4 print 72 and 1152 (contradiction C1): S2 is followed because Nemesis measured it (p5680).""" assert round(144 * (1024 - 1023) / MANUAL_CLOCK * 1e6) == 18 assert round(144 * 1024 / MANUAL_CLOCK * 1e6) == 18432 assert round(2304 / MANUAL_CLOCK * 1e6) == 288 for register in (0, 0x155, 0x3FE): fm = chip() reg(fm, 0x24, register >> 2) reg(fm, 0x25, register & 3) reg(fm, 0x27, 0x05) count = 0 while not fm.read(0) & 1: step(fm, 1) count += 1 assert count == 1024 - register def test_timer_flags_follow_the_enable_bits_and_clear_by_the_reset_bits(): """S1, S2 page 14: a flag is set on overflow if its enable bit is set; writing 1 to its reset bit clears it; the reset bit does not stay set.""" fm = chip() reg(fm, 0x24, 0xFF) reg(fm, 0x26, 0xFF) reg(fm, 0x27, 0x03) # loaded, not enabled step(fm, 40) assert fm.read(0) == 0 reg(fm, 0x27, 0x0F) step(fm, 40) assert fm.read(0) == 0x03 reg(fm, 0x27, 0x1F) assert fm.read(0) & 0x7F == 0x02 step(fm, 40) assert fm.read(0) == 0x03 # the reset bit did not stay set reg(fm, 0x27, 0x2F) assert fm.read(0) & 0x7F == 0x01 def test_status_byte_layout(): """S1 printed page 11, S2 page 11: bit 7 BUSY, bit 1 flag B, bit 0 flag A.""" fm = chip() reg(fm, 0x24, 0xFF) reg(fm, 0x25, 0x03) reg(fm, 0x27, 0x05) assert fm.read(0) == 0x80 step(fm, 2) assert fm.read(0) == 0x01 def test_dac_is_eight_bits_offset_binary_and_replaces_channel_6(): """S2 page 15: $2B bit 7 switches channel 6 to the DAC; $2A is offset binary, bit 7 the most significant. Sega's overview: only channel 6's panning acts.""" fm = chip() reg(fm, 0x2B, 0x80) seen = [] for data in (0x00, 0x7F, 0x80, 0x81, 0xFF): reg(fm, 0x2A, data) seen.append(step(fm, 1)[0][0]) assert seen == sorted(seen) and seen[2] == 0 and seen[0] == -seen[4] - 2 reg(fm, 0xB6, 0x80, part=1) assert step(fm, 1)[0] == (254, 0) reg(fm, 0x2B, 0x00) assert step(fm, 1)[0] == (0, 0) def test_panning_bits(): """S1, S2: $B4 bit 7 left, bit 6 right.""" for bits, (left, right) in ((0xC0, (1, 1)), (0x80, (1, 0)), (0x40, (0, 1)), (0x00, (0, 0))): fm = chip() voice(fm) reg(fm, 0xB4, bits) key(fm, 0) frames = step(fm, 300) assert any(frame[0] for frame in frames) is bool(left) assert any(frame[1] for frame in frames) is bool(right) def test_a_channel_panned_off_is_faintly_audible_on_the_discrete_chip(): """S1 section 2-7-2: a channel with both bits clear "may be faintly audible, depending on the voice parameters and total level". The model gives an idle slot a fixed level, so only the presence of an offset is checked here (its size is provisional: tests/test_provisional.py).""" fm = chip(YM2612_DISCRETE) voice(fm) reg(fm, 0xB4, 0x00) key(fm, 0) assert all(frame != (0, 0) for frame in step(fm, 50)) def test_total_level_advice_about_overflow(): """S2 page 42: algorithms 0 to 3 need no care; algorithm 7 with all four operators at total level 0 overflows (here: sits on the limit).""" for algorithm in range(4): fm = chip() voice(fm, algorithm=algorithm, total_levels=(0, 0, 0, 0)) key(fm, 0) heard = values(fm, 3000) assert heard.count(255) + heard.count(-256) < 600 # peaks only fm = chip() voice(fm, algorithm=7, total_levels=(0, 0, 0, 0)) key(fm, 0) heard = values(fm, 3000) assert heard.count(255) + heard.count(-256) > 1500 def test_reset_pin_clears_what_was_playing(): """S1, S2 page 37: /IC resets the chip.""" fm = chip() voice(fm) key(fm, 0) step(fm, 100) fm.reset_line(0) fm.reset_line(1) op = fm.channels[0].operators[3] assert (op.envelope_phase, op.attenuation, op.key_state) == (RELEASE, 0x3FF, 0) assert step(fm, 20) == [(0, 0)] * 20 assert ATTACK == 0