commit c20878b6cb059f43ca41ab38a1991a4aaaac6c5b
Author: Jon Bell <j.to.the.bell@gmail.com>
AuthorDate: Sun Jan 30 21:18:21 2022 -0700
Commit: Jon Bell <j.to.the.bell@gmail.com>
CommitDate: Sun Jan 30 21:18:21 2022 -0700
Fix int16 overflow that was causing audio clipping
Credit to @eggs in the RetroGameHandhelds Discord
---
source/Audio.cpp | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)
diff --git a/source/Audio.cpp b/source/Audio.cpp
index 2cc32e1..1098e7c 100644
--- a/source/Audio.cpp
+++ b/source/Audio.cpp
@@ -196,12 +196,14 @@ void Audio::FillAudioBuffer(void *audioBuffer, size_t offset, size_t size){
uint32_t *buffer = (uint32_t *)audioBuffer;
for (size_t i = 0; i < size; ++i){
- int16_t sample = 0;
+ int32_t sample = 0;
for (int c = 0; c < 4; ++c) {
sample += this->getSampleForChannel(c);
}
+ if (sample > 0x7fff) sample = 0x7fff; else if (sample < -0x8000) sample = -0x8000;
+
//buffer is stereo, so just send the mono sample to both channels
buffer[i] = (sample<<16) | (sample & 0xffff);
}
@@ -215,12 +217,14 @@ void Audio::FillMonoAudioBuffer(void *audioBuffer, size_t offset, size_t size){
int16_t *buffer = (int16_t *)audioBuffer;
for (size_t i = 0; i < size; ++i){
- int16_t sample = 0;
+ int32_t sample = 0;
for (int c = 0; c < 4; ++c) {
sample += this->getSampleForChannel(c);
}
+ if (sample > 0x7fff) sample = 0x7fff; else if (sample < -0x8000) sample = -0x8000;
+
buffer[i] = sample;
}
}