// SPDX-License-Identifier: MIT //! 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. //! //! A transcription of sn76489-python's `tests/test_manuals.py` at f8157f4. Parametrized //! tests are loops. `pytest.approx(x, abs=1e-9)` is written out as `abs() <= 1e-9`, and //! `approx(rel=1e-12)` as a relative bound (pytest also allows 1e-12 absolute; neither //! case comes near it). mod common; use common::{ bits, changes, left, rises, solo, write_tone, write_volume, ALL, NTSC_CLOCK, SEGA_PARTS, }; use sn76489::{ PSGVariant, CLOCKS_PER_SAMPLE, GAME_GEAR_PSG, SEGA_VDP_PSG, SN76489, SN76489AN, YM7101_PSG, }; fn max(values: impl IntoIterator) -> f64 { values.into_iter().fold(f64::MIN, f64::max) } // -- registers and the write protocol (spec sections 2 and 3) ------------------- /// 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. #[test] fn test_the_three_bit_address_field_reaches_all_eight_registers() { for variant in ALL { for code in 0..8u32 { let mut psg = SN76489::with_silent_start(variant, true); let before = (psg.tone, psg.noise, psg.volume); psg.write(0x80 | (code << 4) | 0x05); let (mut tone, mut noise, mut volume) = (psg.tone, psg.noise, psg.volume); let channel = (code >> 1) as usize; if code & 1 != 0 { assert_eq!(volume[channel], 5); volume[channel] = 15; } else if channel == 3 { assert_eq!(noise, 5); noise = 0; } else { assert_eq!(tone[channel], 5); tone[channel] = 0; } assert_eq!((tone, noise, volume), before); // and nothing else moved } } } /// S1 section 6, "Update frequency (two-byte transfer)"; S3. /// /// Seed: `test_tone_latch_then_data_byte`, kept. #[test] fn test_a_tone_takes_two_bytes_low_four_bits_then_high_six() { for variant in ALL { let mut psg = SN76489::new(variant); psg.write(0x80 | 0x0E); psg.write(0x0F); assert_eq!(psg.tone[0], 0x0FE); psg.write(0x80 | 0x20 | 0x05); assert_eq!(psg.tone[1], 0x005); assert_eq!(psg.tone[0], 0x0FE); psg.write(0x7F); // bit 6 of a data byte is ignored (S1 section 6 shows "x") assert_eq!(psg.tone[1], 0x3F5); } } /// S1 section 6: "Update noise source (single byte transfer)", "Update /// attenuator (single byte transfer)". Bit 3 of the noise byte is "x". #[test] fn test_attenuation_and_noise_take_one_byte() { for variant in ALL { let mut psg = SN76489::new(variant); psg.write(0xB7); let first = if variant != SN76489AN { 15 } else { 0 }; assert_eq!(psg.volume, [first, 7, psg.volume[2], psg.volume[3]]); psg.write(0xEF); assert_eq!(psg.noise, 0b111); } } /// S1 section 4: "The register address is latched on the chip, so the data /// will continue going into the same register". #[test] fn test_the_latched_register_persists_across_data_bytes() { for variant in ALL { let mut psg = SN76489::new(variant); psg.write(0xC3); // the third tone generator for high in [0x01, 0x20, 0x3F, 0x00] { psg.write(high); assert_eq!(psg.tone[2], (high << 4) | 3); } assert!(psg.tone[0] == 0 && 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. #[rustfmt::skip] const NOTES: [(u32, f64); 51] = [ (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), ]; /// The frequency of the square wave the model makes, read off its output. fn tone_hertz(variant: PSGVariant, value: u32, channel: u32) -> f64 { let mut psg = solo(variant, channel); write_tone(&mut psg, channel, value); let stream = bits(&mut psg, 6 * value.max(1) as u64 + 4); let up = rises(&stream); let cycle_ticks = up[1] - up[0]; assert_eq!(up[2] - up[1], cycle_ticks); NTSC_CLOCK as f64 / (CLOCKS_PER_SAMPLE as f64 * cycle_ticks as f64) } /// Python's `round(x, 3)` for the magnitudes here (well within f64's exact range). fn round3(x: f64) -> f64 { (x * 1000.0).round() / 1000.0 } #[test] fn test_the_note_table_has_its_51_rows() { assert_eq!(NOTES.len(), 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. const NOTE_TABLE_CLOCK: f64 = 3_579_550.0; /// 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. #[test] fn test_every_row_of_the_game_gear_note_table() { for variant in ALL { for (value, printed) in NOTES { let hertz = tone_hertz(variant, value, 0); assert_eq!(hertz, NTSC_CLOCK as f64 / (32 * value) as f64, "{value}"); assert!((hertz - printed).abs() < 0.004, "{value}"); assert!( (hertz * NOTE_TABLE_CLOCK / NTSC_CLOCK as f64 - printed).abs() < 0.00055, "{value}" ); } assert_eq!(round3(tone_hertz(variant, 254, 0)), 440.397); } } /// S4 psg-7: the same division ratio serves "Tone 1", "Tone 2" and "Tone 3". #[test] fn test_all_three_tone_generators_follow_the_formula() { for channel in 0..3 { assert_eq!(round3(tone_hertz(SEGA_VDP_PSG, 254, channel)), 440.397); } } /// 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. #[test] fn test_n_equals_one_is_the_top_note() { for variant in ALL { assert_eq!(tone_hertz(variant, 1, 0), NTSC_CLOCK as f64 / 32.0); } } /// S4 psg-7: "TONE 1 to 3, Duty 50%". #[test] fn test_tones_have_a_fifty_percent_duty() { for variant in ALL { for value in [1u32, 2, 3, 57, 254, 1017, 0x3FF] { let mut psg = solo(variant, 0); write_tone(&mut psg, 0, value); bits(&mut psg, 2 * value as u64); // let a rewritten counter settle into its cycle let stream = bits(&mut psg, 2 * value as u64 * 5); assert_eq!( stream.iter().map(|&b| b as usize).sum::() * 2, stream.len() ); let edges = changes(&stream); assert!(edges.windows(2).all(|w| w[1] - w[0] == value as usize)); } } } // -- attenuation (spec section 7) ------------------------------------------------ /// 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. #[test] fn test_the_sixteen_attenuation_rows() { for variant in ALL { let mut measured = vec![]; for step in 0..16 { let mut psg = SN76489::with_silent_start(variant, true); write_tone(&mut psg, 0, 4); write_volume(&mut psg, 0, step); measured.push(max(left(&mut psg, 16))); } assert_eq!(measured[0], 1.0); for (step, &level) in measured.iter().enumerate().take(15) { assert!((-20.0 * level.log10() - 2.0 * step as f64).abs() <= 1e-9); } assert_eq!(measured[15], 0.0); // "OFF" } } /// S1 Table 1: bits weigh 2, 4, 8 and 16 dB, and their sum is the attenuation. #[test] fn test_the_attenuator_weights_add() { let table = SEGA_VDP_PSG.volume_table; for step in 0..15 { let mut product = 1.0; for bit in 0..4 { if step & (1 << bit) != 0 { product *= table[1 << bit]; } } assert!((table[step] - product).abs() <= 1e-12 * product); } } /// S1 section 3: the outputs go to "a conventional operational amplifier /// summing circuit". #[test] fn test_the_four_channels_are_summed() { for variant in ALL { let mut psg = SN76489::with_silent_start(variant, true); for (channel, step) in [0, 3, 6].into_iter().enumerate() { write_tone(&mut psg, channel as u32, 1); write_volume(&mut psg, channel as u32, step); } let table = variant.volume_table; assert_eq!(max(left(&mut psg, 8)), table[0] + table[3] + table[6]); } } // -- noise (spec section 6) ------------------------------------------------------ /// Ticks from one pulse of "periodic" noise to the next. fn periodic_pulse_ticks(variant: PSGVariant, rate: u32, tone2: Option) -> usize { let mut psg = solo(variant, 3); if let Some(value) = tone2 { write_tone(&mut psg, 2, value); } psg.write(0xE0 | rate); let shift_ticks = match tone2 { Some(value) => 2 * value as u64, None => 32 << rate, }; let up = rises(&bits( &mut psg, shift_ticks * variant.lfsr_bits as u64 * 3 + 4, )); assert_eq!(up[2] - up[1], up[1] - up[0]); up[1] - up[0] } /// 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. #[test] fn test_the_three_fixed_noise_rates() { for variant in ALL { for (rate, divisor) in [(0, 512u64), (1, 1024), (2, 2048)] { let ticks = periodic_pulse_ticks(variant, rate, None); assert_eq!( ticks as u64 * CLOCKS_PER_SAMPLE, divisor * variant.lfsr_bits as u64 ); } } } /// 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. #[test] fn test_noise_rate_three_shifts_once_per_cycle_of_the_third_tone() { for variant in ALL { for value in [2u32, 5, 67, 428] { assert_eq!( periodic_pulse_ticks(variant, 3, Some(value)), 2 * value as usize * variant.lfsr_bits as usize ); } } } /// 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. #[test] fn test_noise_at_rate_three_changes_only_when_the_third_tone_does() { for variant in ALL { let mut psg = SN76489::with_silent_start(variant, true); write_volume(&mut psg, 2, 3); write_volume(&mut psg, 3, 0); write_tone(&mut psg, 2, 7); psg.write(0xE7); let (low, high) = (variant.volume_table[3], 1.0); let mut seen_noise_changes = 0; for value in [7, 3, 11, 2, 9, 7, 5] { write_tone(&mut psg, 2, value); let levels = left(&mut psg, 400); let tone: Vec = levels .iter() .map(|&l| (l == low || l == low + high) as u8) .collect(); let noise: Vec = levels.iter().map(|&l| (l >= high) as u8).collect(); let tone_rises = rises(&tone); for index in changes(&noise) { assert!(tone_rises.contains(&index)); 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. #[rustfmt::skip] const SYNCHRONOUS_NOTES: [(u32, f64); 33] = [ (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), ]; /// 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. #[test] fn test_every_row_of_the_synchronous_noise_table() { for variant in SEGA_PARTS { assert_eq!(SYNCHRONOUS_NOTES.len(), 33); for (value, printed) in SYNCHRONOUS_NOTES { let ticks = periodic_pulse_ticks(variant, 3, Some(value)); let hertz = NTSC_CLOCK as f64 / (CLOCKS_PER_SAMPLE as f64 * ticks as f64); assert_eq!(round3(hertz), printed, "{value}"); } } } /// S4 psg-7: "Base tone in synchronous noise mode, Duty 6.25%". #[test] fn test_synchronous_noise_is_one_pulse_in_sixteen() { for variant in SEGA_PARTS { let mut psg = solo(variant, 3); psg.write(0xE0); bits(&mut psg, 32 * 16); let stream = bits(&mut psg, 32 * 16 * 10); let ones = stream.iter().map(|&b| b as usize).sum::(); assert_eq!(ones as f64 / stream.len() as f64, 0.0625); } } /// 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. #[test] fn test_the_discrete_chips_periodic_noise_is_one_pulse_in_fifteen() { let mut psg = solo(SN76489AN, 3); psg.write(0xE0); bits(&mut psg, 32 * 15); let stream = bits(&mut psg, 32 * 15 * 10); assert_eq!( stream.iter().map(|&b| b as usize).sum::() * 15, stream.len() ); } /// 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". #[test] fn test_a_noise_register_write_clears_the_shift_register() { for variant in ALL { for control in [0xE0, 0xE4] { let mut psg = solo(variant, 3); psg.write(0xE4); bits(&mut psg, 5_000); // let white noise fill the register assert!(psg.lfsr.count_ones() > 1); psg.write(control); assert_eq!(psg.lfsr, 1 << (variant.lfsr_bits - 1)); let mut fresh = solo(variant, 3); fresh.write(control); (fresh.noise_counter, fresh.noise_input) = (psg.noise_counter, psg.noise_input); assert_eq!(bits(&mut psg, 20_000), bits(&mut fresh, 20_000)); } } } // -- the Game Gear's stereo register (spec section 9) ---------------------------- /// 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. #[test] fn test_each_stereo_bit_routes_one_channel_to_one_side() { for bit in 0..8u32 { let (channel, side) = (bit & 3, if bit >= 4 { 0 } else { 1 }); let mut psg = SN76489::new(GAME_GEAR_PSG); for each in 0..3 { write_tone(&mut psg, each, 1); } psg.write(0xE7); // white noise clocked by the third tone, so it soon shows a 1 for each in 0..4 { write_volume(&mut psg, each, 2 * each); // a different level for each channel } psg.write_stereo(1 << bit); psg.run(CLOCKS_PER_SAMPLE * 200); let samples = psg.take_samples(); let pick = |pair: &(f64, f64), s: usize| if s == 0 { pair.0 } else { pair.1 }; assert_eq!( max(samples.iter().map(|p| pick(p, side))), GAME_GEAR_PSG.volume_table[2 * channel as usize] ); assert_eq!(max(samples.iter().map(|p| pick(p, 1 - side))), 0.0); } } /// S4 main-4 stars the "1" state of each bit; main-2: the star "Indicates the /// state after a power-on reset". #[test] fn test_the_stereo_register_is_all_ones_after_power_on() { assert_eq!(SN76489::new(GAME_GEAR_PSG).stereo, 0xFF); } /// 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. #[test] fn test_the_other_parts_have_no_stereo_register() { for variant in [SN76489AN, SEGA_VDP_PSG, YM7101_PSG] { let mut psg = SN76489::with_silent_start(variant, true); psg.write_stereo(0x00); assert_eq!(psg.stereo, 0xFF); write_tone(&mut psg, 1, 1); write_volume(&mut psg, 1, 0); psg.run(CLOCKS_PER_SAMPLE * 4); // Python's max() of tuples: the largest left, then the largest right among those. let samples = psg.take_samples(); let best = samples .iter() .copied() .fold((f64::MIN, f64::MIN), |a, b| if b > a { b } else { a }); assert_eq!(best, (1.0, 1.0)); } } // -- power-on (spec section 10) -------------------------------------------------- /// S4 psg-1: "The sound output goes OFF in the case of a power-on reset". #[test] fn test_the_game_gear_is_silent_after_power_on() { let mut psg = SN76489::new(GAME_GEAR_PSG); psg.run(CLOCKS_PER_SAMPLE * 5_000); let samples = psg.take_samples(); assert!(!samples.is_empty() && samples.iter().all(|&p| p == (0.0, 0.0))); } /// 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). #[test] fn test_the_discrete_chip_holds_ready_low_for_about_32_clocks() { assert_eq!(SN76489AN.ready_clocks, 32); assert!(SEGA_PARTS.iter().all(|v| v.ready_clocks == 0)); }