From 303da32205c335d8ea9dcbcecf975417cf92a7b2 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Adrien=20B=C3=A9raud?= <adrien.beraud@savoirfairelinux.com>
Date: Sat, 27 Jul 2019 21:50:40 -0400
Subject: [PATCH] opensl: avoid blocking on stop

Change-Id: I9cb774da618e1a6e0a31e4915035a9faaaa4569b
---
 src/media/audio/opensl/opensllayer.cpp | 23 ++++++++++++-----------
 src/preferences.cpp                    |  2 +-
 2 files changed, 13 insertions(+), 12 deletions(-)

diff --git a/src/media/audio/opensl/opensllayer.cpp b/src/media/audio/opensl/opensllayer.cpp
index 12b5b74d7b..0b46a110e2 100644
--- a/src/media/audio/opensl/opensllayer.cpp
+++ b/src/media/audio/opensl/opensllayer.cpp
@@ -88,18 +88,18 @@ OpenSLLayer::startStream()
         startAudioPlayback();
         startAudioCapture();
         JAMI_WARN("OpenSL audio layer started");
-        {
-            std::lock_guard<std::mutex> lock(mutex_);
-            status_ = Status::Started;
-        }
+        std::lock_guard<std::mutex> lock(mutex_);
+        status_ = Status::Started;
         startedCv_.notify_all();
     });
+    startedCv_.notify_all();
 }
 
 void
 OpenSLLayer::stopStream()
 {
-    std::lock_guard<std::mutex> lock(mutex_);
+    std::unique_lock<std::mutex> lock(mutex_);
+    startedCv_.wait(lock, [this] { return status_ != Status::Starting; });
     if (startThread_.joinable()) {
         startThread_.join();
     }
@@ -126,6 +126,7 @@ OpenSLLayer::stopStream()
     recBufQueue_.clear();
     bufs_.clear();
     dcblocker_.reset();
+    startedCv_.notify_all();
 }
 
 std::vector<sample_buf>
@@ -246,7 +247,7 @@ OpenSLLayer::engineServiceRing(bool waiting) {
 
 void
 OpenSLLayer::engineServiceRec(bool /* waiting */) {
-    playCv.notify_one();
+    //playCv.notify_one();
     recCv.notify_one();
     return;
 }
@@ -334,10 +335,10 @@ OpenSLLayer::startAudioCapture()
         std::unique_lock<std::mutex> lck(recMtx);
         while (recorder_) {
             recCv.wait(lck);
-            while (true) {
-                sample_buf *buf;
-                if(!recBufQueue_.front(&buf))
-                    break;
+            if (not recorder_)
+                break;
+            sample_buf *buf;
+            while (recBufQueue_.front(&buf)) {
                 recBufQueue_.pop();
                 if (buf->size_ > 0) {
                     auto nb_samples = buf->size_ / hardwareFormat_.getBytesPerFrame();
@@ -394,8 +395,8 @@ OpenSLLayer::stopAudioCapture()
             recorder_.reset();
         }
     }
+    recCv.notify_all();
     if (recThread.joinable()) {
-        recCv.notify_all();
         recThread.join();
     }
 
diff --git a/src/preferences.cpp b/src/preferences.cpp
index 9f4bcb2f8d..ec643718e9 100644
--- a/src/preferences.cpp
+++ b/src/preferences.cpp
@@ -425,7 +425,7 @@ AudioPreference::createAudioLayer()
     }
     return nullptr;
 #endif
-#endif // __ANDROID__
+#endif // HAVE_OPENSL
 
     JAMI_WARN("No audio layer provided");
     return nullptr;
-- 
GitLab