From 000970b770c1951eab412159e5b6d39f5541838f Mon Sep 17 00:00:00 2001 From: rhargreaves Date: Sun, 8 Mar 2020 17:33:52 +0000 Subject: [PATCH] Handle lower limit of PSG frequencies if pitch is shifted lower --- src/midi_psg.c | 10 ++++++---- tests/unit/main.c | 1 + tests/unit/test_midi_psg.c | 19 +++++++++++++++++++ 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/src/midi_psg.c b/src/midi_psg.c index b6d7247e..0e59fe4f 100644 --- a/src/midi_psg.c +++ b/src/midi_psg.c @@ -7,6 +7,7 @@ #define MIN_PSG_CHAN 6 #define MAX_PSG_CHAN 9 #define MIN_MIDI_KEY 45 +#define MAX_MIDI_KEY 127 #define PITCH_SHIFTS 7 #define NUM_FREQUENCIES (128 - MIN_MIDI_KEY) @@ -232,10 +233,11 @@ void midi_psg_tick(void) static u16 freqForMidiKey(u8 midiKey) { - u8 index = midiKey - MIN_MIDI_KEY; - const u8 MAX_INDEX = NUM_FREQUENCIES - 1; - if (index > MAX_INDEX) { - return FREQUENCIES[MAX_INDEX]; + if (midiKey < MIN_MIDI_KEY) { + return FREQUENCIES[0]; + } + if (midiKey > MAX_MIDI_KEY) { + return FREQUENCIES[NUM_FREQUENCIES - 1]; } return FREQUENCIES[midiKey - MIN_MIDI_KEY]; } diff --git a/tests/unit/main.c b/tests/unit/main.c index 84d781c3..44a597dc 100644 --- a/tests/unit/main.c +++ b/tests/unit/main.c @@ -79,6 +79,7 @@ int main(void) test_midi_psg_envelope_with_loop_end_resets_release_note_after_note_silenced), midi_test(test_midi_shifts_semitone_in_psg_envelope), midi_test(test_midi_pitch_shift_handles_upper_limit_psg_envelope), + midi_test(test_midi_pitch_shift_handles_lower_limit_psg_envelope), midi_test(test_midi_channel_volume_sets_volume), midi_test(test_midi_pan_sets_synth_stereo_mode_right), midi_test(test_midi_pan_sets_synth_stereo_mode_left), diff --git a/tests/unit/test_midi_psg.c b/tests/unit/test_midi_psg.c index 28872211..c87b3919 100644 --- a/tests/unit/test_midi_psg.c +++ b/tests/unit/test_midi_psg.c @@ -385,3 +385,22 @@ static void test_midi_pitch_shift_handles_upper_limit_psg_envelope( expect_psg_attenuation(expectedPsgChan, PSG_ATTENUATION_LOUDEST); __real_midi_psg_tick(); } + +static void test_midi_pitch_shift_handles_lower_limit_psg_envelope( + UNUSED void** state) +{ + const u8 chan = MIN_PSG_CHAN; + const u8 expectedPsgChan = 0; + const u8 minPitch = 45; + const u16 expectedInitialFreq = 0x6e; + const u8 envelope[] = { EEF_LOOP_START, 0x00, 0x80, EEF_END }; + const u8* envelopes[] = { envelope }; + midi_psg_init(envelopes); + + expect_psg_frequency(expectedPsgChan, expectedInitialFreq); + expect_psg_attenuation(expectedPsgChan, PSG_ATTENUATION_LOUDEST); + __real_midi_noteOn(chan, minPitch, MAX_MIDI_VOLUME); + + expect_psg_attenuation(expectedPsgChan, PSG_ATTENUATION_LOUDEST); + __real_midi_psg_tick(); +}