From 501d6ae608e0670e6e8620c32e8d5ca25eeed9d6 Mon Sep 17 00:00:00 2001
From: Varun Patil <radialapps@gmail.com>
Date: Mon, 4 May 2020 19:33:24 +0530
Subject: [PATCH] Fix audio fade

---
 src/alstream.cpp    |  7 +++++--
 src/audiostream.cpp | 20 +++++++++++++++++---
 2 files changed, 22 insertions(+), 5 deletions(-)

diff --git a/src/alstream.cpp b/src/alstream.cpp
index b37e99c..a8cddae 100644
--- a/src/alstream.cpp
+++ b/src/alstream.cpp
@@ -285,7 +285,9 @@ void ALStream::stopStream()
 
 	if (thread)
 	{
+#ifndef __EMSCRIPTEN__
 		SDL_WaitThread(thread, 0);
+#endif
 		thread = 0;
 		needsRewind.set();
 	}
@@ -312,6 +314,7 @@ void ALStream::startStream(float offset)
 
 #ifdef __EMSCRIPTEN__
 	streamData();
+	thread = (SDL_Thread *) 1;
 #else
 	thread = createSDLThread
 		<ALStream, &ALStream::streamData>(this, threadName);
@@ -420,7 +423,7 @@ void ALStream::streamData()
 #ifndef __EMSCRIPTEN__
 	while (true)
 	{
-		streamDevice();
+		update();
 
 		if (threadTermReq)
 			break;
@@ -430,7 +433,7 @@ void ALStream::streamData()
 }
 
 void ALStream::update() {
-	if (threadTermReq)
+	if (!thread || threadTermReq)
 		return;
 
 	shState->rtData().syncPoint.passSecondarySync();
diff --git a/src/audiostream.cpp b/src/audiostream.cpp
index 71aadc2..104e246 100644
--- a/src/audiostream.cpp
+++ b/src/audiostream.cpp
@@ -284,10 +284,8 @@ void AudioStream::finiFadeOutInt()
 
 void AudioStream::startFadeIn()
 {
-#ifdef __EMSCRIPTEN__
 	/* Previous fadein should always be terminated in play() */
 	assert(!fadeIn.thread);
-#endif
 
 	fadeIn.rqFini.clear();
 	fadeIn.rqTerm.clear();
@@ -295,6 +293,7 @@ void AudioStream::startFadeIn()
 
 #ifdef __EMSCRIPTEN__
 	fadeInThread();
+	fadeIn.thread = (SDL_Thread *) 1;
 #else
 	fadeIn.thread = createSDLThread
 		<AudioStream, &AudioStream::fadeInThread>(this, fadeIn.threadName);
@@ -357,11 +356,18 @@ void AudioStream::fadeOutThread()
 
 void AudioStream::fadeInThread()
 {
+#ifndef __EMSCRIPTEN__
 	while (true)
+#else
+	if (fadeIn.thread)
+#endif
 	{
 		if (fadeIn.rqTerm)
+#ifndef __EMSCRIPTEN__
 			break;
-
+#else
+			return;
+#endif
 		lockStream();
 
 		/* Fade in duration is always 1 second */
@@ -377,7 +383,12 @@ void AudioStream::fadeInThread()
 			setVolume(FadeIn, 1.0f);
 			unlockStream();
 
+#ifdef __EMSCRIPTEN__
+			fadeIn.thread = 0;
+			return;
+#else
 			break;
+#endif
 		}
 
 		/* Quadratic increase (not really the same as
@@ -386,12 +397,15 @@ void AudioStream::fadeInThread()
 
 		unlockStream();
 
+#ifndef __EMSCRIPTEN__
 		SDL_Delay(AUDIO_SLEEP);
+#endif
 	}
 }
 
 void AudioStream::update()
 {
 	fadeOutThread();
+	fadeInThread();
 	stream.update();
 }