From 1a97c69b59243c67f16d268162ae418305bf6162 Mon Sep 17 00:00:00 2001
From: Markus Henschel <markus.henschel@yager.de>
Date: Mon, 28 Oct 2013 20:34:59 +0100
Subject: [PATCH] fix crash when attaching empty stream to dsound voice

---
 addons/audio/dsound.cpp  | 8 ++++++++
 addons/audio/kcm_voice.c | 2 ++
 2 files changed, 10 insertions(+)

diff --git a/addons/audio/dsound.cpp b/addons/audio/dsound.cpp
index 125defb..e51a614 100644
--- a/addons/audio/dsound.cpp
+++ b/addons/audio/dsound.cpp
@@ -166,9 +166,16 @@ static void* _dsound_update(ALLEGRO_THREAD *self, void *arg)
       &ptr1, &block1_bytes, &ptr2, &block2_bytes,
       DSBLOCK_ENTIREBUFFER);
    if (!FAILED(hr)) {
+      unsigned int sample_bytes=0;
       samples = buffer_size / bytes_per_sample / ex_data->channels;
       data = (unsigned char *) _al_voice_update(voice, &samples);
+      sample_bytes=samples*bytes_per_sample*ex_data->channels;
+      if (sample_bytes<block1_bytes)
+         block1_bytes=sample_bytes;
       memcpy(ptr1, data, block1_bytes);
+      sample_bytes-=block1_bytes;
+      if (sample_bytes<block2_bytes)
+         block2_bytes=sample_bytes;
       memcpy(ptr2, data + block1_bytes, block2_bytes);
       ex_data->ds8_buffer->Unlock(ptr1, block1_bytes, ptr2, block2_bytes);
    }
@@ -554,6 +561,7 @@ static int _dsound_stop_voice(ALLEGRO_VOICE* voice)
       ALLEGRO_DEBUG("Destroying thread\n");
       al_destroy_thread(ex_data->thread);
       ALLEGRO_DEBUG("Thread destroyed\n");
+      ex_data->stop_voice = 1;	//this is required to restart the background thread when the voice restarts
    }
 
    ALLEGRO_DEBUG("Releasing buffer\n");
diff --git a/addons/audio/kcm_voice.c b/addons/audio/kcm_voice.c
index b6ac60f..56de650 100644
--- a/addons/audio/kcm_voice.c
+++ b/addons/audio/kcm_voice.c
@@ -198,6 +198,7 @@ static void stream_read(void *source, void **vbuf, unsigned int *samples,
 
    if (!stream->spl.is_playing) {
       *vbuf = NULL;
+      *samples=0;
       return;
    }
 
@@ -211,6 +212,7 @@ static void stream_read(void *source, void **vbuf, unsigned int *samples,
             stream->spl.is_playing = false;
          }
          *vbuf = NULL;
+         *samples=0;
          return;
       }
       *vbuf = stream->pending_bufs[0];
-- 
1.8.3.msysgit.0

