From 297d600d307e9822bda5b6010fdc34ca1fbe4e09 Mon Sep 17 00:00:00 2001
From: Markus Henschel <markus.henschel@yager.de>
Date: Thu, 24 Oct 2013 12:10:52 +0200
Subject: [PATCH] Lock mutex of the audio stream before accessing the streams
 members to prevent a race condition when the mixer calls
 _al_kcm_refill_stream from another thread

---
 addons/audio/kcm_stream.c | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)

diff --git a/addons/audio/kcm_stream.c b/addons/audio/kcm_stream.c
index b8ccb5e..b3af639 100644
--- a/addons/audio/kcm_stream.c
+++ b/addons/audio/kcm_stream.c
@@ -542,9 +542,13 @@ bool al_set_audio_stream_fragment(ALLEGRO_AUDIO_STREAM *stream, void *val)
 bool _al_kcm_refill_stream(ALLEGRO_AUDIO_STREAM *stream)
 {
    ALLEGRO_SAMPLE_INSTANCE *spl = &stream->spl;
-   void *old_buf = spl->spl_data.buffer.ptr;
+   void *old_buf;
    void *new_buf;
    size_t i;
+   
+   maybe_lock_mutex(stream->spl.mutex);
+   
+   old_buf = spl->spl_data.buffer.ptr;
 
    if (old_buf) {
       /* Slide the buffers down one position and put the
@@ -565,6 +569,7 @@ bool _al_kcm_refill_stream(ALLEGRO_AUDIO_STREAM *stream)
    new_buf = stream->pending_bufs[0];
    stream->spl.spl_data.buffer.ptr = new_buf;
    if (!new_buf) {
+      maybe_unlock_mutex(stream->spl.mutex);
       ALLEGRO_WARN("Out of buffers\n");
       return false;
    }
@@ -583,7 +588,9 @@ bool _al_kcm_refill_stream(ALLEGRO_AUDIO_STREAM *stream)
    }
 
    stream->spl.pos = 0;
-
+   
+   maybe_unlock_mutex(stream->spl.mutex);
+   
    return true;
 }
 
-- 
1.8.3.msysgit.0

