diff --git a/src/gba/gba-audio.c b/src/gba/gba-audio.c index 1268ba1fa..3fe333a60 100644 --- a/src/gba/gba-audio.c +++ b/src/gba/gba-audio.c @@ -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); } diff --git a/src/gba/gba-audio.h b/src/gba/gba-audio.h index 536cf633e..56ead46d4 100644 --- a/src/gba/gba-audio.h +++ b/src/gba/gba-audio.h @@ -3,6 +3,7 @@ #include "circle-buffer.h" +#include #include struct GBADMA; @@ -175,6 +176,8 @@ struct GBAAudio { int32_t nextSample; int32_t sampleInterval; + + pthread_mutex_t bufferMutex; }; void GBAAudioInit(struct GBAAudio* audio); diff --git a/src/sdl/sdl-audio.c b/src/sdl/sdl-audio.c index f6ae71bee..7e9cf83a2 100644 --- a/src/sdl/sdl-audio.c +++ b/src/sdl/sdl-audio.c @@ -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); } }