Don't trample audio buffer

This commit is contained in:
Jeffrey Pfau 2013-10-03 12:08:52 -07:00
parent 4a09d41aab
commit 2f00e3d146
3 changed files with 12 additions and 1 deletions

View File

@ -19,6 +19,8 @@ void GBAAudioInit(struct GBAAudio* audio) {
CircleBufferInit(&audio->right, GBA_AUDIO_SAMPLES * sizeof(int32_t));
CircleBufferInit(&audio->chA.fifo, GBA_AUDIO_FIFO_SIZE);
CircleBufferInit(&audio->chB.fifo, GBA_AUDIO_FIFO_SIZE);
pthread_mutex_init(&audio->bufferMutex, 0);
}
void GBAAudioDeinit(struct GBAAudio* audio) {
@ -26,6 +28,8 @@ void GBAAudioDeinit(struct GBAAudio* audio) {
CircleBufferDeinit(&audio->right);
CircleBufferDeinit(&audio->chA.fifo);
CircleBufferDeinit(&audio->chB.fifo);
pthread_mutex_destroy(&audio->bufferMutex);
}
int32_t GBAAudioProcessEvents(struct GBAAudio* audio, int32_t cycles) {
@ -171,6 +175,8 @@ static void _sample(struct GBAAudio* audio) {
sampleRight += audio->chB.sample;
}
pthread_mutex_lock(&audio->bufferMutex);
CircleBufferWrite32(&audio->left, sampleLeft);
CircleBufferWrite32(&audio->right, sampleRight);
pthread_mutex_unlock(&audio->bufferMutex);
}

View File

@ -3,6 +3,7 @@
#include "circle-buffer.h"
#include <pthread.h>
#include <stdint.h>
struct GBADMA;
@ -175,6 +176,8 @@ struct GBAAudio {
int32_t nextSample;
int32_t sampleInterval;
pthread_mutex_t bufferMutex;
};
void GBAAudioInit(struct GBAAudio* audio);

View File

@ -13,7 +13,7 @@ int GBASDLInitAudio(struct GBASDLAudio* context) {
context->desiredSpec.freq = 44100;
context->desiredSpec.format = AUDIO_S16SYS;
context->desiredSpec.channels = 2;
context->desiredSpec.samples = GBA_AUDIO_SAMPLES >> 1;
context->desiredSpec.samples = GBA_AUDIO_SAMPLES >> 2;
context->desiredSpec.callback = _GBASDLAudioCallback;
context->desiredSpec.userdata = context;
context->audio = 0;
@ -58,6 +58,7 @@ static void _GBASDLAudioCallback(void* context, Uint8* data, int len) {
struct StereoSample* ssamples = (struct StereoSample*) data;
len /= 2 * audioContext->obtainedSpec.channels;
if (audioContext->obtainedSpec.channels == 2) {
pthread_mutex_lock(&audioContext->audio->bufferMutex);
for (i = 0; i < len; ++i) {
audioContext->drift += audioContext->audio->sampleRate / (float) audioContext->obtainedSpec.freq;
while (audioContext->drift >= 0) {
@ -66,5 +67,6 @@ static void _GBASDLAudioCallback(void* context, Uint8* data, int len) {
}
ssamples[i] = audioContext->currentSample;
}
pthread_mutex_unlock(&audioContext->audio->bufferMutex);
}
}