"""Rung 2: the manufacturers' documents (tier 2). Each check is a row of a printed table or a sentence, cited by document and page: - TI: the data sheet "SN 76489 AN" (phase0.md S1) and the SN76494/SN76496 data sheet D2801 (S2). - Sega: the Mark III hardware reference manual, PSG section (S3), and the Game Gear manual's "PSG Manual", pages cited as its scans are named, psg-1 to psg-8 and main-4 (S4). Decision D10: the manual's sentences are quoted one at a time and its tables are not reproduced; the tests carry only the numbers they check. These prove the model does what TI and Sega told programmers the chip does. They do not reach what the manuals leave out, which is most of what is contested. """ from __future__ import annotations import itertools import math import pytest from helpers import ( NTSC_CLOCK, SEGA_PARTS, bits, changes, left, rises, solo, variant_id, write_tone, write_volume, ) from sn76489_python import ( CLOCKS_PER_SAMPLE, GAME_GEAR_PSG, SEGA_VDP_PSG, SN76489, SN76489AN, YM7101_PSG, ) ALL = (SN76489AN, SEGA_VDP_PSG, GAME_GEAR_PSG, YM7101_PSG) # -- registers and the write protocol (spec sections 2 and 3) ------------------- @pytest.mark.parametrize("variant", ALL, ids=variant_id) def test_the_three_bit_address_field_reaches_all_eight_registers(variant): """S1 Table 4 and S4 section 3: codes 000 to 111 are tone 1 frequency, tone 1 attenuation, tone 2 frequency, ... noise control, noise attenuation.""" for code in range(8): psg = SN76489(variant, silent_start=True) before = (list(psg.tone), psg.noise, list(psg.volume)) psg.write(0x80 | (code << 4) | 0x05) tone, noise, volume = list(psg.tone), psg.noise, list(psg.volume) channel = code >> 1 if code & 1: assert volume[channel] == 5 volume[channel] = 15 elif channel == 3: assert noise == 5 noise = 0 else: assert tone[channel] == 5 tone[channel] = 0 assert (tone, noise, volume) == before # and nothing else moved @pytest.mark.parametrize("variant", ALL, ids=variant_id) def test_a_tone_takes_two_bytes_low_four_bits_then_high_six(variant): """S1 section 6, "Update frequency (two-byte transfer)"; S3. Seed: `test_tone_latch_then_data_byte`, kept. """ psg = SN76489(variant) psg.write(0x80 | 0x0E) psg.write(0x0F) assert psg.tone[0] == 0x0FE psg.write(0x80 | 0x20 | 0x05) assert psg.tone[1] == 0x005 assert psg.tone[0] == 0x0FE psg.write(0x7F) # bit 6 of a data byte is ignored (S1 section 6 shows "x") assert psg.tone[1] == 0x3F5 @pytest.mark.parametrize("variant", ALL, ids=variant_id) def test_attenuation_and_noise_take_one_byte(variant): """S1 section 6: "Update noise source (single byte transfer)", "Update attenuator (single byte transfer)". Bit 3 of the noise byte is "x".""" psg = SN76489(variant) psg.write(0xB7) assert psg.volume == [15 if variant is not SN76489AN else 0, 7, psg.volume[2], psg.volume[3]] psg.write(0xEF) assert psg.noise == 0b111 @pytest.mark.parametrize("variant", ALL, ids=variant_id) def test_the_latched_register_persists_across_data_bytes(variant): """S1 section 4: "The register address is latched on the chip, so the data will continue going into the same register".""" psg = SN76489(variant) psg.write(0xC3) # the third tone generator for high in (0x01, 0x20, 0x3F, 0x00): psg.write(high) assert psg.tone[2] == (high << 4) | 3 assert psg.tone[0] == 0 and psg.tone[1] == 0 # -- tone frequency (spec section 5) --------------------------------------------- #: Sega's Game Gear manual, psg-6: frequency division ratio n and the printed "PSG #: output" in hertz, 51 notes from A2 to B6 at 3.579545 MHz. NOTES = ( (1017, 109.991), (960, 116.522), (906, 123.467), (855, 130.832), (807, 138.613), (762, 146.799), (719, 155.578), (679, 164.744), (641, 174.510), (605, 184.894), (571, 195.904), (539, 207.534), (508, 220.199), (480, 233.044), (453, 246.934), (428, 261.357), (404, 276.884), (381, 293.598), (360, 310.725), (339, 329.973), (320, 349.565), (302, 370.400), (285, 392.495), (269, 415.840), (254, 440.397), (240, 466.087), (226, 494.960), (214, 522.715), (202, 553.767), (190, 588.742), (180, 621.450), (170, 658.005), (160, 699.131), (151, 740.801), (143, 782.244), (135, 828.600), (127, 880.795), (120, 932.174), (113, 989.920), (107, 1045.429), (101, 1107.534), (95, 1177.484), (90, 1242.899), (85, 1316.011), (80, 1398.262), (76, 1471.854), (71, 1575.506), (67, 1669.566), (64, 1747.827), (60, 1864.349), (57, 1962.473), ) # fmt: skip def tone_hertz(variant, value: int, channel: int = 0) -> float: """The frequency of the square wave the model makes, read off its output.""" psg = solo(variant, channel) write_tone(psg, channel, value) stream = bits(psg, 6 * max(value, 1) + 4) up = rises(stream) cycle_ticks = up[1] - up[0] assert up[2] - up[1] == cycle_ticks return NTSC_CLOCK / (CLOCKS_PER_SAMPLE * cycle_ticks) def test_the_note_table_has_its_51_rows(): assert len(NOTES) == 51 #: The clock the printed "PSG output" column was evidently computed from. FOUND #: here, not stated by the manual, which gives 3.579545 MHz: with 3,579,550 the #: formula reproduces 50 of the 51 printed values on rounding (the 51st, n = 170, #: is 658.0055 printed as 658.005); with 3,579,545 only 17. NOTE_TABLE_CLOCK = 3_579_550 @pytest.mark.parametrize("variant", ALL, ids=variant_id) def test_every_row_of_the_game_gear_note_table(variant): """S4 psg-6 and psg-7: "f = 3579545/(32 x n)", all 51 rows. What is checked of the model is the division: a cycle of exactly 2n ticks, 32n input clocks. Converted to hertz, that agrees with every printed value to within 0.004 Hz at the manual's stated clock, and to the three decimals printed at the clock the column was computed from (see NOTE_TABLE_CLOCK; the 0.00055 allows the one row that sits on a rounding tie). Seed: `test_tone_register_0x0fe_is_440_hz`, kept as the row n = 254, 440.397 Hz (psg-2's worked example), and widened to the whole table. """ for value, printed in NOTES: hertz = tone_hertz(variant, value) assert hertz == NTSC_CLOCK / (32 * value), value assert abs(hertz - printed) < 0.004, value assert abs(hertz * NOTE_TABLE_CLOCK / NTSC_CLOCK - printed) < 0.00055, value assert round(tone_hertz(variant, 254), 3) == 440.397 @pytest.mark.parametrize("channel", range(3)) def test_all_three_tone_generators_follow_the_formula(channel): """S4 psg-7: the same division ratio serves "Tone 1", "Tone 2" and "Tone 3".""" assert round(tone_hertz(SEGA_VDP_PSG, 254, channel), 3) == 440.397 @pytest.mark.parametrize("variant", ALL, ids=variant_id) def test_n_equals_one_is_the_top_note(variant): """S4 psg-7: "Maximum frequency is n = 1" and "The upper limit is 3579545/32ยท1". Spec 5.5 takes this over Maxim's "constant +1" (C1). Seed: `test_tone_register_zero_or_one_holds_the_output_high`, CORRECTED for value 1: the seed held the output at 1; the manual says a square wave. """ assert tone_hertz(variant, 1) == NTSC_CLOCK / 32 @pytest.mark.parametrize("variant", ALL, ids=variant_id) @pytest.mark.parametrize("value", [1, 2, 3, 57, 254, 1017, 0x3FF]) def test_tones_have_a_fifty_percent_duty(variant, value): """S4 psg-7: "TONE 1 to 3, Duty 50%".""" psg = solo(variant, 0) write_tone(psg, 0, value) bits(psg, 2 * value) # let a rewritten counter settle into its cycle stream = bits(psg, 2 * value * 5) assert sum(stream) * 2 == len(stream) edges = changes(stream) assert {b - a for a, b in itertools.pairwise(edges)} <= {value} # -- attenuation (spec section 7) ------------------------------------------------ @pytest.mark.parametrize("variant", ALL, ids=variant_id) def test_the_sixteen_attenuation_rows(variant): """S3 and S4 psg-3 print sixteen rows: 0, 2, 4, ... 28 dB, then OFF. Seed: `test_volume_table_is_two_decibels_per_step_and_fifteen_is_silent`, kept and read through the output instead of the table. """ measured = [] for step in range(16): psg = SN76489(variant, silent_start=True) write_tone(psg, 0, 4) write_volume(psg, 0, step) measured.append(max(left(psg, 16))) assert measured[0] == 1.0 for step in range(15): assert -20 * math.log10(measured[step]) == pytest.approx(2.0 * step, abs=1e-9) assert measured[15] == 0.0 # "OFF" def test_the_attenuator_weights_add(): """S1 Table 1: bits weigh 2, 4, 8 and 16 dB, and their sum is the attenuation.""" table = SEGA_VDP_PSG.volume_table for step in range(15): product = 1.0 for bit in range(4): if step & (1 << bit): product *= table[1 << bit] assert table[step] == pytest.approx(product, rel=1e-12) @pytest.mark.parametrize("variant", ALL, ids=variant_id) def test_the_four_channels_are_summed(variant): """S1 section 3: the outputs go to "a conventional operational amplifier summing circuit".""" psg = SN76489(variant, silent_start=True) for channel, step in enumerate((0, 3, 6)): write_tone(psg, channel, 1) write_volume(psg, channel, step) table = variant.volume_table assert max(left(psg, 8)) == table[0] + table[3] + table[6] # -- noise (spec section 6) ------------------------------------------------------ def periodic_pulse_ticks(variant, rate: int, tone2: int | None = None) -> int: """Ticks from one pulse of "periodic" noise to the next.""" psg = solo(variant, 3) if tone2 is not None: write_tone(psg, 2, tone2) psg.write(0xE0 | rate) shift_ticks = 2 * tone2 if tone2 is not None else 32 << rate up = rises(bits(psg, shift_ticks * variant.lfsr_bits * 3 + 4)) assert up[2] - up[1] == up[1] - up[0] return up[1] - up[0] @pytest.mark.parametrize("variant", ALL, ids=variant_id) @pytest.mark.parametrize("rate, divisor", [(0, 512), (1, 1024), (2, 2048)]) def test_the_three_fixed_noise_rates(variant, rate, divisor): """S1 Table 3 as S2 prints it correctly: NF 00, 01, 10 shift at N/512, N/1024, N/2048. S4 psg-4 gives the same as (N/32)/16, /32, /64. Read off "periodic" noise, which pulses once per trip round the register. """ ticks = periodic_pulse_ticks(variant, rate) assert ticks * CLOCKS_PER_SAMPLE == divisor * variant.lfsr_bits @pytest.mark.parametrize("variant", ALL, ids=variant_id) @pytest.mark.parametrize("value", [2, 5, 67, 428]) def test_noise_rate_three_shifts_once_per_cycle_of_the_third_tone(variant, value): """S1 Table 3: NF 11 is "Tone Generator #3 Output". S4 psg-4: "The noise frequency is (frequency TONE 3)/16" in synchronous mode. Seed: `test_noise_rate_three_follows_tone_two`, kept for the rate. """ assert periodic_pulse_ticks(variant, 3, tone2=value) == 2 * value * variant.lfsr_bits @pytest.mark.parametrize("variant", ALL, ids=variant_id) def test_noise_at_rate_three_changes_only_when_the_third_tone_does(variant): """S1's block diagram takes the noise clock from tone generator 3 itself; in Kortink's capture (S9) "the tone generator 3 signal and the noise generator signal are synchronous". Spec 6.1.4 (C4) takes that over a separate counter loaded from the tone value. Seed: CORRECTED. The seed ran such a counter; here the third tone is rewritten while the noise runs, which moves that tone's edges, and the noise must move with them. """ psg = SN76489(variant, silent_start=True) write_volume(psg, 2, 3) write_volume(psg, 3, 0) write_tone(psg, 2, 7) psg.write(0xE7) low, high = variant.volume_table[3], 1.0 seen_noise_changes = 0 for value in (7, 3, 11, 2, 9, 7, 5): write_tone(psg, 2, value) levels = left(psg, 400) tone = [1 if level in (low, low + high) else 0 for level in levels] noise = [1 if level >= high else 0 for level in levels] tone_rises = set(rises(tone)) for index in changes(noise): assert index in tone_rises seen_noise_changes += 1 assert seen_noise_changes > 50 #: Sega's Game Gear manual, psg-8: with the third tone's division ratio n and the #: noise control at E3H, "f = TONE 3 frequency/16 = 3579545/(32 x n x16)". The 33 #: printed rows, C0 to G#2. SYNCHRONOUS_NOTES = ( (428, 16.335), (404, 17.305), (381, 18.350), (360, 19.420), (339, 20.623), (320, 21.848), (302, 23.150), (285, 24.531), (269, 25.990), (254, 27.525), (240, 29.130), (226, 30.935), (214, 32.670), (202, 34.610), (190, 36.796), (180, 38.841), (170, 41.125), (160, 43.696), (151, 46.300), (143, 48.890), (135, 51.787), (127, 55.050), (120, 58.261), (113, 61.870), (107, 65.339), (101, 69.221), (95, 73.593), (90, 77.681), (85, 82.251), (80, 87.391), (76, 91.991), (71, 98.469), (67, 104.348), ) # fmt: skip @pytest.mark.parametrize("variant", SEGA_PARTS, ids=variant_id) def test_every_row_of_the_synchronous_noise_table(variant): """S4 psg-8, all 33 rows, to the three decimals printed. Sega's parts only: the table is the Game Gear's, and divides by its 16 stages.""" assert len(SYNCHRONOUS_NOTES) == 33 for value, printed in SYNCHRONOUS_NOTES: ticks = periodic_pulse_ticks(variant, 3, tone2=value) assert round(NTSC_CLOCK / (CLOCKS_PER_SAMPLE * ticks), 3) == printed, value @pytest.mark.parametrize("variant", SEGA_PARTS, ids=variant_id) def test_synchronous_noise_is_one_pulse_in_sixteen(variant): """S4 psg-7: "Base tone in synchronous noise mode, Duty 6.25%".""" psg = solo(variant, 3) psg.write(0xE0) bits(psg, 32 * 16) stream = bits(psg, 32 * 16 * 10) assert sum(stream) / len(stream) == 0.0625 def test_the_discrete_chips_periodic_noise_is_one_pulse_in_fifteen(): """Tier 1 for this one (S9): "the periodic noise generator ... has a cycle of 15 clocks", outputting on one of them. Seed: `test_periodic_noise_is_the_register_width`, kept, read off the output. """ psg = solo(SN76489AN, 3) psg.write(0xE0) bits(psg, 32 * 15) stream = bits(psg, 32 * 15 * 10) assert sum(stream) * 15 == len(stream) @pytest.mark.parametrize("variant", ALL, ids=variant_id) @pytest.mark.parametrize("control", [0xE0, 0xE4]) def test_a_noise_register_write_clears_the_shift_register(variant, control): """S1: "Whenever the noise control register is changed, the shift register is cleared". S4 psg-4: "Each time the noise control register changes, the shift register is cleared".""" psg = solo(variant, 3) psg.write(0xE4) bits(psg, 5_000) # let white noise fill the register assert psg.lfsr.bit_count() > 1 psg.write(control) assert psg.lfsr == 1 << (variant.lfsr_bits - 1) fresh = solo(variant, 3) fresh.write(control) fresh.noise_counter, fresh.noise_input = psg.noise_counter, psg.noise_input assert bits(psg, 20_000) == bits(fresh, 20_000) # -- the Game Gear's stereo register (spec section 9) ---------------------------- @pytest.mark.parametrize("bit", range(8)) def test_each_stereo_bit_routes_one_channel_to_one_side(bit): """S4 main-4: bit 7 to bit 0 are "NOSL TN3L TN2L TN1L NOSR TN3R TN2R TN1R". Seed: `test_game_gear_stereo_routes_each_channel`, kept and widened from one bit to all eight; its levels are now the api's 0.0 to 4.0. """ channel, side = bit & 3, 0 if bit >= 4 else 1 psg = SN76489(GAME_GEAR_PSG) for each in range(3): write_tone(psg, each, 1) psg.write(0xE7) # white noise clocked by the third tone, so it soon shows a 1 for each in range(4): write_volume(psg, each, 2 * each) # a different level for each channel psg.write_stereo(1 << bit) psg.run(CLOCKS_PER_SAMPLE * 200) samples = psg.take_samples() assert max(pair[side] for pair in samples) == GAME_GEAR_PSG.volume_table[2 * channel] assert max(pair[1 - side] for pair in samples) == 0.0 def test_the_stereo_register_is_all_ones_after_power_on(): """S4 main-4 stars the "1" state of each bit; main-2: the star "Indicates the state after a power-on reset".""" assert SN76489(GAME_GEAR_PSG).stereo == 0xFF @pytest.mark.parametrize("variant", [SN76489AN, SEGA_VDP_PSG, YM7101_PSG], ids=variant_id) def test_the_other_parts_have_no_stereo_register(variant): """Spec 9.4, a CHOICE carried from the seed (`test_stereo_register_only_exists_on_the_game_gear`, kept): the write does nothing and both sides carry every channel.""" psg = SN76489(variant, silent_start=True) psg.write_stereo(0x00) assert psg.stereo == 0xFF write_tone(psg, 1, 1) write_volume(psg, 1, 0) psg.run(CLOCKS_PER_SAMPLE * 4) assert max(psg.take_samples()) == (1.0, 1.0) # -- power-on (spec section 10) -------------------------------------------------- def test_the_game_gear_is_silent_after_power_on(): """S4 psg-1: "The sound output goes OFF in the case of a power-on reset".""" psg = SN76489(GAME_GEAR_PSG) psg.run(CLOCKS_PER_SAMPLE * 5_000) assert set(psg.take_samples()) == {(0.0, 0.0)} def test_the_discrete_chip_holds_ready_low_for_about_32_clocks(): """S1 section 7 and S2: a write takes about 32 input clocks, READY low; S4 (Game Gear): "there is no need for a wait". The core only exports the figure for a board that wires READY to the CPU (spec 3.8).""" assert SN76489AN.ready_clocks == 32 assert all(variant.ready_clocks == 0 for variant in SEGA_PARTS)