Modify noise suppression functionality
[platform/core/api/audio-io.git] / src / cpp / CPulseAudioClient.cpp
index 2b598d7..34f769a 100644 (file)
@@ -21,6 +21,7 @@
 #include <string.h>
 #include <assert.h>
 #include <algorithm>
+#include <vector>
 
 #ifdef ENABLE_DPM
 #include <dpm/restriction.h>
 using namespace std;
 using namespace tizen_media_audio;
 
+/**
+ * class CMainloopLocker
+ */
+CPulseAudioClient::CPulseThreadLocker::CPulseThreadLocker(pa_threaded_mainloop* mainloop) : ml(nullptr) {
+    if (!mainloop || pa_threaded_mainloop_in_thread(mainloop))
+        return;
+
+    pa_threaded_mainloop_lock(mainloop);
+    ml = mainloop;
+}
+
+CPulseAudioClient::CPulseThreadLocker::~CPulseThreadLocker() {
+    if (ml)
+        pa_threaded_mainloop_unlock(const_cast<pa_threaded_mainloop*>(ml));
+    ml = nullptr;
+}
 
 /**
  * class CPulseAudioClient
  */
 const char* CPulseAudioClient::CLIENT_NAME = "AUDIO_IO_PA_CLIENT";
-static constexpr unsigned int drain_wait_interval = 10000;
-static constexpr unsigned int drain_wait_max_count = 30;
+const char* ec_method = "default";
+static constexpr auto drain_wait_interval = 10000;
+static constexpr auto drain_wait_max_count = 30;
 
 CPulseAudioClient::CPulseAudioClient(
         EStreamDirection      direction,
@@ -60,7 +78,11 @@ CPulseAudioClient::CPulseAudioClient(
 }
 
 CPulseAudioClient::~CPulseAudioClient() {
-    finalize();
+    try {
+        finalize();
+    } catch (const CAudioError& e) {
+        AUDIO_IO_LOGE("%s", e.getErrorMsg()); //LCOV_EXCL_LINE
+    }
 }
 
 void CPulseAudioClient::__contextStateChangeCb(pa_context* c, void* user_data) {
@@ -70,13 +92,13 @@ void CPulseAudioClient::__contextStateChangeCb(pa_context* c, void* user_data) {
 
     switch (pa_context_get_state(c)) {
     case PA_CONTEXT_READY:
-        AUDIO_IO_LOGD("The context is ready");
+        AUDIO_IO_LOGD("pa_context[%p] is ready", c);
         pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
         break;
 
     case PA_CONTEXT_FAILED:
     case PA_CONTEXT_TERMINATED:
-        AUDIO_IO_LOGD("The context is lost");
+        AUDIO_IO_LOGD("pa_context[%p] is lost", c);
         pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
         break;
 
@@ -114,36 +136,55 @@ void CPulseAudioClient::__streamStateChangeCb(pa_stream* s, void* user_data) {
     assert(user_data);
 
     auto pClient = static_cast<CPulseAudioClient*>(user_data);
+    pa_stream_state_t state = pa_stream_get_state(s);
+
+    switch (state) {
+    case PA_STREAM_UNCONNECTED:
+        break;
+
+    case PA_STREAM_CREATING:
+        break;
 
-    switch (pa_stream_get_state(s)) {
     case PA_STREAM_READY:
-        AUDIO_IO_LOGD("The stream is ready");
+        AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] is READY[%d]", pClient, s, PA_STREAM_READY);
+        pClient->__mpListener->setState(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING);
         pClient->__mpListener->onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING);
         if (pClient->__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
             pClient->__mIsFirstStream = true;
         pClient->__mIsInit = true;
-        pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
+
+        AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] now signaling...", pClient, s);
+        pa_threaded_mainloop_signal(pClient->__mpMainloop, 1);
+        AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] signal accepted", pClient, s);
         break;
 
 //LCOV_EXCL_START
     case PA_STREAM_FAILED:
-        AUDIO_IO_LOGD("The stream is failed");
+        AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] is FAILED[%d]", pClient, s, PA_STREAM_FAILED);
+        pClient->__mpListener->setState(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE);
         pClient->__mpListener->onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE,
                                               __is_microphone_restricted());
+
+        AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] now signaling...", pClient, s);
         pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
         break;
 //LCOV_EXCL_STOP
 
     case PA_STREAM_TERMINATED:
-        AUDIO_IO_LOGD("The stream is terminated");
+        AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] is TERMINATED[%d]", pClient, s, PA_STREAM_TERMINATED);
+        pClient->__mpListener->setState(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE);
         pClient->__mpListener->onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE);
+
+        AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] now signaling...", pClient, s);
         pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
         break;
 
-    case PA_STREAM_UNCONNECTED:
-    case PA_STREAM_CREATING:
+    default:
+        AUDIO_IO_LOGW("Unexpected state[%d]", state);
         break;
     }
+
+    AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] state[%d] done", pClient, s, state);
 }
 
 void CPulseAudioClient::__streamCaptureCb(pa_stream* s, size_t length, void* user_data) {
@@ -160,14 +201,9 @@ void CPulseAudioClient::__streamCaptureCb(pa_stream* s, size_t length, void* use
     pClient->__mpListener->onStream(pClient, length);
 }
 
-#ifndef DISABLE_MOBILE_BACK_COMP
 static void __dummy_write(pa_stream* s, size_t length) {
-    char* dummy = new char[length];
-    memset(dummy, 0, length);
-    pa_stream_write(s, dummy, length, NULL, 0LL, PA_SEEK_RELATIVE);
-    delete [] dummy;
+    pa_stream_write(s, std::vector<char>(length).data(), length, NULL, 0LL, PA_SEEK_RELATIVE);
 }
-#endif
 
 void CPulseAudioClient::__streamPlaybackCb(pa_stream* s, size_t length, void* user_data) {
     assert(s);
@@ -178,12 +214,12 @@ void CPulseAudioClient::__streamPlaybackCb(pa_stream* s, size_t length, void* us
 
 #ifndef DISABLE_MOBILE_BACK_COMP
     if (!pClient->__mIsInit) {
-        AUDIO_IO_LOGD("Occurred this listener when an out stream is on the way to create : Write dummy, length[%zu]", length);
+        AUDIO_IO_LOGD("pa_stream[%p] is on the way to create : Write dummy, length[%zu]", s, length);
         __dummy_write(s, length);
         return;
     }
     if (pClient->isCorked()) {
-        AUDIO_IO_LOGD("Occurred this listener when an out stream is CORKED : Write dummy, length[%zu]", length);
+        AUDIO_IO_LOGD("pa_stream[%p] is CORKED : Write dummy, length[%zu]", s, length);
         __dummy_write(s, length);
         return;
     }
@@ -196,7 +232,8 @@ void CPulseAudioClient::__streamPlaybackCb(pa_stream* s, size_t length, void* us
        then write dummy data to ensure the start */
     if (pClient->__mSpec.getStreamLatency() == CPulseStreamSpec::EStreamLatency::STREAM_LATENCY_OUTPUT_DEFAULT_ASYNC &&
         pClient->__mIsFirstStream) {
-        AUDIO_IO_LOGW("[async] Write dummy of length[%zu] since not written in first callback during prepare", length);
+        AUDIO_IO_LOGW("[async] pa_stream[%p] : not written in the first callback during prepare, write dummy of length[%zu]",
+                      s, length);
         __dummy_write(s, length);
         pClient->__mIsFirstStream = false;
     }
@@ -209,6 +246,11 @@ void CPulseAudioClient::__streamLatencyUpdateCb(pa_stream* s, void* user_data) {
 
     auto pClient = static_cast<CPulseAudioClient*>(user_data);
 
+#ifdef _AUDIO_IO_DEBUG_TIMING_
+    /* FIXME : print some useful latency info */
+    AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] latency updated", pClient, s);
+#endif
+
     pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
 }
 
@@ -218,7 +260,7 @@ void CPulseAudioClient::__streamStartedCb(pa_stream* s, void* user_data) {
 
     auto pClient = static_cast<CPulseAudioClient*>(user_data);
 
-    AUDIO_IO_LOGD("stream %p started.", pClient);
+    AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] started", pClient, s);
 
     pClient->__mIsStarted = true;
 }
@@ -229,59 +271,126 @@ void CPulseAudioClient::__streamUnderflowCb(pa_stream* s, void* user_data) {
 
     auto pClient = static_cast<CPulseAudioClient*>(user_data);
 
-    AUDIO_IO_LOGD("stream %p UnderFlow...", pClient);
+    AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] UnderFlow...", pClient, s);
 
     pClient->__mIsStarted = false;
 }
 
-//LCOV_EXCL_START
-void CPulseAudioClient::__streamEventCb(pa_stream* s, const char *name, pa_proplist *pl, void *user_data) {
+void CPulseAudioClient::__streamOverflowCb(pa_stream* s, void* user_data) {
     assert(s);
     assert(user_data);
 
-    AUDIO_IO_LOGE("NAME : %s, Prop : %p", name, pl);
+    auto pClient = static_cast<CPulseAudioClient*>(user_data);
+
+    AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] OverFlow...", pClient, s);
+}
+
+//LCOV_EXCL_START
+void CPulseAudioClient::__streamEventCb(pa_stream* s, const char* name, pa_proplist* pl, void* user_data) {
+    assert(s);
+    assert(user_data);
 
     auto pClient = static_cast<CPulseAudioClient*>(user_data);
-    if (strcmp(name, PA_STREAM_EVENT_POP_TIMEOUT) == 0)
-        pa_operation_unref(pa_stream_cork(pClient->__mpStream, 1, NULL, NULL));
+
+    AUDIO_IO_LOGW("pClient[%p] pa_stream[%p] : name[%s], proplist[%p]", pClient, s, name, pl);
+
+    if (strcmp(name, PA_STREAM_EVENT_POP_TIMEOUT) == 0) {
+        pa_operation* o = pa_stream_cork(pClient->__mpStream, 1, NULL, NULL);
+        if (!o) {
+            AUDIO_IO_LOGE("pa_stream[%p] : cork failed", pClient->__mpStream);
+            return;
+        }
+        pa_operation_unref(o);
+    }
 }
 //LCOV_EXCL_STOP
 
 void CPulseAudioClient::__successStreamCb(pa_stream* s, int success, void* user_data) {
-    AUDIO_IO_LOGD("pa_stream[%p], success[%d], user_data[%p]", s, success, user_data);
     assert(s);
     assert(user_data);
 
     auto pClient = static_cast<CPulseAudioClient*>(user_data);
+
+    AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] success[%d] user_data[%p]", pClient, s, success, user_data);
+
     pClient->__mIsOperationSuccess = static_cast<bool>(success);
 
+    /* FIXME : verify following action without any waiting */
     pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
 }
 
 //LCOV_EXCL_START
 void CPulseAudioClient::__successDrainCbInThread(pa_stream* s, int success, void* user_data) {
-    AUDIO_IO_LOGD("pa_stream[%p], success[%d], user_data[%p]", s, success, user_data);
     assert(s);
     assert(user_data);
 
     auto pClient = static_cast<CPulseAudioClient*>(user_data);
+
+    AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] success[%d] user_data[%p]", pClient, s, success, user_data);
+
     pClient->__mIsOperationSuccess = static_cast<bool>(success);
     pClient->__mIsDraining = false;
 }
 //LCOV_EXCL_STOP
 
 void CPulseAudioClient::__successDrainCb(pa_stream* s, int success, void* user_data) {
-    AUDIO_IO_LOGD("pa_stream[%p], success[%d], user_data[%p]", s, success, user_data);
     assert(s);
     assert(user_data);
 
     auto pClient = static_cast<CPulseAudioClient*>(user_data);
+
+    AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] success[%d] user_data[%p]", pClient, s, success, user_data);
+
     pClient->__mIsOperationSuccess = static_cast<bool>(success);
     pClient->__mIsDraining = false;
 
     pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
 }
 
+void CPulseAudioClient::__successVolumeCb(pa_context* c, int success, void* user_data) {
+    AUDIO_IO_LOGD("pa_context[%p] success[%d] user_data[%p]", c, success, user_data);
+}
+
+void CPulseAudioClient::resetStreamCallbacks() {
+    if (!__mpStream)
+        return;
+
+    if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
+        pa_stream_set_write_callback(__mpStream, NULL, NULL);
+    else
+        pa_stream_set_read_callback(__mpStream, NULL, NULL);
+
+    pa_stream_set_latency_update_callback(__mpStream, NULL, NULL);
+    pa_stream_set_event_callback(__mpStream, NULL, NULL);
+}
+
+void CPulseAudioClient::resetInternalObjects() {
+    if (__mpMainloop)
+        pa_threaded_mainloop_stop(__mpMainloop);
+
+    if (__mpStream) {
+        pa_stream_disconnect(__mpStream);
+        pa_stream_unref(__mpStream);
+        __mpStream = nullptr;
+    }
+
+    if (__mpContext) {
+        pa_context_disconnect(__mpContext);
+        pa_context_unref(__mpContext);
+        __mpContext = nullptr;
+    }
+
+    if (__mpMainloop) {
+        pa_threaded_mainloop_free(__mpMainloop);
+        __mpMainloop = nullptr;
+    }
+
+    if (__mpPropList) {
+        pa_proplist_free(__mpPropList);
+        __mpPropList = nullptr;
+    }
+}
+
 void CPulseAudioClient::initialize() {
     if (__mIsInit)
         return;
@@ -302,6 +411,17 @@ void CPulseAudioClient::initialize() {
         if (index >= 0)
             pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_PARENT_ID, "%u", (unsigned int) index);
 
+        if (__mDirection == EStreamDirection::STREAM_DIRECTION_RECORD) {
+            int reference_id = __mSpec.getAudioInfo().getEchoCancelReferenceDeviceId();
+            if (reference_id > 0) {
+                pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_ECHO_CANCEL_REFERENCE_DEVICE, "%d", reference_id);
+            }
+
+            if (!__mSpec.getAudioInfo().getProcessorProperty().empty())
+                pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_PREPROCESSOR_METHOD, "%s",
+                                    __mSpec.getAudioInfo().getProcessorProperty().c_str());
+        }
+
         // Adds latency on proplist for delivery to PULSEAUDIO
         AUDIO_IO_LOGD("LATENCY : %s[%d]", __mSpec.getStreamLatencyToString(), static_cast<int>(__mSpec.getStreamLatency()));
         pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_TIZEN_AUDIO_LATENCY, "%s", __mSpec.getStreamLatencyToString());
@@ -324,12 +444,11 @@ void CPulseAudioClient::initialize() {
             THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_context_connect()"); //LCOV_EXCL_LINE
 
         // LOCK for synchronous connection
-        pa_threaded_mainloop_lock(__mpMainloop);
+        CPulseThreadLocker locker{__mpMainloop};
 
         // Start mainloop
         if (pa_threaded_mainloop_start(__mpMainloop) < 0) {
 //LCOV_EXCL_START
-            pa_threaded_mainloop_unlock(__mpMainloop);
             THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_threaded_mainloop_start()");
 //LCOV_EXCL_STOP
         }
@@ -347,8 +466,8 @@ void CPulseAudioClient::initialize() {
             if (!PA_CONTEXT_IS_GOOD(state)) {
 //LCOV_EXCL_START
                 err = pa_context_errno(__mpContext);
-                pa_threaded_mainloop_unlock(__mpMainloop);
-                THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "pa_context's state is not good : err[%d]", err);
+                THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION,
+                                       "pa_context's state is not good : err[%d]", err);
 //LCOV_EXCL_STOP
             }
 
@@ -356,6 +475,8 @@ void CPulseAudioClient::initialize() {
             pa_threaded_mainloop_wait(__mpMainloop);
         }
 
+        AUDIO_IO_LOGD("pa_context[%p] now ready", __mpContext);
+
         // Allocates PA stream
         pa_sample_spec ss   = __mSpec.getSampleSpec();
         pa_channel_map map  = __mSpec.getChannelMap();
@@ -363,7 +484,6 @@ void CPulseAudioClient::initialize() {
         __mpStream = pa_stream_new_with_proplist(__mpContext, __mSpec.getStreamName(), &ss, &map, __mpPropList);
         if (!__mpStream) {
 //LCOV_EXCL_START
-            pa_threaded_mainloop_unlock(__mpMainloop);
             THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_new_with_proplist()");
 //LCOV_EXCL_STOP
         }
@@ -377,6 +497,7 @@ void CPulseAudioClient::initialize() {
         if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
             pa_stream_set_started_callback(__mpStream, __streamStartedCb, this);
             pa_stream_set_underflow_callback(__mpStream, __streamUnderflowCb, this);
+            pa_stream_set_overflow_callback(__mpStream, __streamOverflowCb, this);
         }
 
         // Connect stream with PA Server
@@ -402,65 +523,67 @@ void CPulseAudioClient::initialize() {
 
             ret = pa_stream_connect_record(__mpStream, NULL, NULL, flags);
         }
-
         if (ret != 0) {
 //LCOV_EXCL_START
             err = pa_context_errno(__mpContext);
-            pa_threaded_mainloop_unlock(__mpMainloop);
-            THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_connect() : err[%d]", err);
+            THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
+                                   "Failed pa_stream_connect() : err[%d]", err);
 //LCOV_EXCL_STOP
         }
 
+        AUDIO_IO_LOGD("pa_stream[%p] now wait for stream ready...", __mpStream);
+
         while (true) {
             pa_stream_state_t state = pa_stream_get_state(__mpStream);
+            AUDIO_IO_LOGD("pa_stream[%p] current state[%d]", __mpStream, state);
 
-            if (state == PA_STREAM_READY) {
-                AUDIO_IO_LOGD("STREAM READY");
+            if (state == PA_STREAM_READY)
                 break;
-            }
 
             if (!PA_STREAM_IS_GOOD(state)) {
                 err = pa_context_errno(__mpContext);
-                pa_threaded_mainloop_unlock(__mpMainloop);
                 if (err == PA_ERR_ACCESS)
-                    THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_DEVICE_POLICY_RESTRICTION, "pa_stream's state is not good : err[%d]", err);
+                    THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_DEVICE_POLICY_RESTRICTION,
+                                           "pa_stream's state is not good : err[%d]", err);
                 else
-                    THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "pa_stream's state is not good : err[%d]", err); //LCOV_EXCL_LINE
+                    THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION,   //LCOV_EXCL_LINE
+                                           "pa_stream's state is not good : err[%d]", err); //LCOV_EXCL_LINE
             }
 
             /* Wait until the stream is ready */
+            AUDIO_IO_LOGD("pa_mainloop[%p] signal wait...", __mpMainloop);
             pa_threaded_mainloop_wait(__mpMainloop);
+            AUDIO_IO_LOGD("pa_mainloop[%p] signal wait done", __mpMainloop);
         }
-
-        // End of synchronous
-        pa_threaded_mainloop_unlock(__mpMainloop);
+        pa_threaded_mainloop_accept(__mpMainloop);
 
         // __mIsInit = true;  // Moved to __streamStateChangeCb()
     } catch (const CAudioError& e) {
 //LCOV_EXCL_START
-        finalize();
+        resetStreamCallbacks();
+        resetInternalObjects();
         throw;
 //LCOV_EXCL_END
     }
+
+    AUDIO_IO_LOGD("Done : pa_context[%p], pa_mainloop[%p], pa_stream[%p]", __mpContext, __mpMainloop, __mpStream);
 }
 
 void CPulseAudioClient::finalize() {
-    AUDIO_IO_LOGD("");
+    AUDIO_IO_LOGD("pa_context[%p], pa_mainloop[%p], pa_stream[%p]", __mpContext, __mpMainloop, __mpStream);
+
+    if (!__mpMainloop)
+        return;
 
-    if (__mpMainloop && !isInThread())
+    bool is_in_thread = isInThread();
+    if (!is_in_thread)
         pa_threaded_mainloop_lock(__mpMainloop);
 
-    /* clear callbacks */
-    if (__mpStream) {
-        if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
-            pa_stream_set_write_callback(__mpStream, NULL, NULL);
-        else
-            pa_stream_set_read_callback(__mpStream, NULL, NULL);
-        pa_stream_set_latency_update_callback(__mpStream, NULL, NULL);
-        pa_stream_set_event_callback(__mpStream, NULL, NULL);
-    }
+    __mIsInit = false;
+
+    resetStreamCallbacks();
 
-    if (__mpMainloop && !isInThread())
+    if (!is_in_thread)
         pa_threaded_mainloop_unlock(__mpMainloop);
 
     /* Wait for drain complete if draining before finalize */
@@ -472,45 +595,22 @@ void CPulseAudioClient::finalize() {
                       drain_wait_count, drain_wait_interval);
     }
 
-    if (__mpMainloop)
-        pa_threaded_mainloop_stop(__mpMainloop);
+    resetInternalObjects();
 
-    if (__mpStream) {
-        pa_stream_disconnect(__mpStream);
-        pa_stream_unref(__mpStream);
-        __mpStream = nullptr;
-    }
-
-    if (__mpContext) {
-        pa_context_disconnect(__mpContext);
-        pa_context_unref(__mpContext);
-        __mpContext = nullptr;
-    }
-
-    if (__mpMainloop) {
-        pa_threaded_mainloop_free(__mpMainloop);
-        __mpMainloop = nullptr;
-    }
-
-    if (__mpPropList) {
-        pa_proplist_free(__mpPropList);
-        __mpPropList = nullptr;
-    }
-
-    __mIsInit = false;
+    AUDIO_IO_LOGD("Done");
 }
 
 int CPulseAudioClient::read(void* buffer, size_t length) {
     if (!__mIsInit)
-        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient"); //LCOV_EXCL_LINE
+        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); //LCOV_EXCL_LINE
 
     checkRunningState();
 
     if (!buffer)
-        THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "The parameter is invalid : buffer[%p]", buffer); //LCOV_EXCL_LINE
+        THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "invalid parameter : buffer[%p]", buffer); //LCOV_EXCL_LINE
 
     if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
-        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client couldn't use this function"); //LCOV_EXCL_LINE
+        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback client can't use this function"); //LCOV_EXCL_LINE
 
     size_t lengthIter = length;
     int ret = 0;
@@ -518,7 +618,7 @@ int CPulseAudioClient::read(void* buffer, size_t length) {
     __mIsUsedSyncRead = true;
 
     try {
-        pa_threaded_mainloop_lock(__mpMainloop);
+        CPulseThreadLocker locker{__mpMainloop};
 
         while (lengthIter > 0) {
             size_t l;
@@ -567,7 +667,8 @@ int CPulseAudioClient::read(void* buffer, size_t length) {
 #endif
                 ret = pa_stream_drop(__mpStream);
                 if (ret != 0)
-                    THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_drop() : ret[%d]", ret); //LCOV_EXCL_LINE
+                    THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, //LCOV_EXCL_LINE
+                                           "Failed pa_stream_drop() : ret[%d]", ret);     //LCOV_EXCL_LINE
 
                 // Reset the internal pointer
                 __mpSyncReadDataPtr = nullptr;
@@ -576,11 +677,9 @@ int CPulseAudioClient::read(void* buffer, size_t length) {
             }
         }  // End of while (lengthIter > 0)
 
-        pa_threaded_mainloop_unlock(__mpMainloop);
         __mIsUsedSyncRead = false;
     } catch (const CAudioError& e) {
 // LCOV_EXCL_START
-        pa_threaded_mainloop_unlock(__mpMainloop);
         __mIsUsedSyncRead = false;
         throw;
 // LCOV_EXCL_STOP
@@ -591,26 +690,21 @@ int CPulseAudioClient::read(void* buffer, size_t length) {
 
 int CPulseAudioClient::peek(const void** buffer, size_t* length) {
     if (!__mIsInit)
-        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient"); // LCOV_EXCL_LINE
+        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
 
     checkRunningState();
 
     if (!buffer || !length)
-        THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT,                          // LCOV_EXCL_LINE
-                               "The parameter is invalid : buffer[%p], length[%p]", buffer, length); // LCOV_EXCL_LINE
+        THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT,                   // LCOV_EXCL_LINE
+                               "invalid parameter : buffer[%p], length[%p]", buffer, length); // LCOV_EXCL_LINE
 
     if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
-        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client couldn't use this function"); // LCOV_EXCL_LINE
+        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
 
-    int ret = 0;
+    CPulseThreadLocker locker{__mpMainloop};
+
+    int ret = pa_stream_peek(__mpStream, buffer, length);
 
-    if (!isInThread()) {
-        pa_threaded_mainloop_lock(__mpMainloop);
-        ret = pa_stream_peek(__mpStream, buffer, length);
-        pa_threaded_mainloop_unlock(__mpMainloop);
-    } else {
-        ret = pa_stream_peek(__mpStream, buffer, length);
-    }
 
 #ifdef _AUDIO_IO_DEBUG_TIMING_
     AUDIO_IO_LOGD("buffer[%p], length[%zu]", *buffer, *length);
@@ -624,7 +718,7 @@ int CPulseAudioClient::peek(const void** buffer, size_t* length) {
 
 int CPulseAudioClient::drop() {
     if (!__mIsInit)
-        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient"); // LCOV_EXCL_LINE
+        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
 
 #ifdef _AUDIO_IO_DEBUG_TIMING_
     AUDIO_IO_LOGD("");
@@ -633,18 +727,11 @@ int CPulseAudioClient::drop() {
     checkRunningState();
 
     if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
-        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client couldn't use this function"); // LCOV_EXCL_LINE
+        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
 
-    int ret = 0;
-
-    if (!isInThread()) {
-        pa_threaded_mainloop_lock(__mpMainloop);
-        ret = pa_stream_drop(__mpStream);
-        pa_threaded_mainloop_unlock(__mpMainloop);
-    } else {
-        ret = pa_stream_drop(__mpStream);
-    }
+    CPulseThreadLocker locker{__mpMainloop};
 
+    int ret = pa_stream_drop(__mpStream);
     if (ret < 0)
         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_drop() : err[%d]", ret); //LCOV_EXCL_LINE
 
@@ -653,10 +740,10 @@ int CPulseAudioClient::drop() {
 
 int CPulseAudioClient::write(const void* data, size_t length) {
     if (!data)
-        THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_ARGUMENT, "The parameter is invalid"); // LCOV_EXCL_LINE
+        THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_ARGUMENT, "invalid parameter"); // LCOV_EXCL_LINE
 
     if (__mDirection == EStreamDirection::STREAM_DIRECTION_RECORD)
-        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client couldn't use this function"); // LCOV_EXCL_LINE
+        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
 
     int ret = 0;
 
@@ -665,19 +752,26 @@ int CPulseAudioClient::write(const void* data, size_t length) {
 #endif
 
     if (!isInThread()) {
-        pa_threaded_mainloop_lock(__mpMainloop);
+        CPulseThreadLocker locker{__mpMainloop};
         if (pa_stream_is_corked(__mpStream)) {
-            AUDIO_IO_LOGW("stream is corked...do uncork here first!!!!");
-            pa_operation_unref(pa_stream_cork(__mpStream, 0, NULL, this));
+            AUDIO_IO_LOGW("pa_stream[%p] is corked...do uncork here first!!!!", __mpStream);
+            pa_operation* o = pa_stream_cork(__mpStream, 0, NULL, NULL);
+            if (!o)
+                AUDIO_IO_LOGE("pa_stream[%p] : uncork failed", __mpStream);
+            else
+                pa_operation_unref(o);
         }
 
         ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
-        pa_threaded_mainloop_unlock(__mpMainloop);
     } else {
 // LCOV_EXCL_START
         if (pa_stream_is_corked(__mpStream)) {
-            AUDIO_IO_LOGW("stream is corked...do uncork here first!!!!");
-            pa_operation_unref(pa_stream_cork(__mpStream, 0, NULL, this));
+            AUDIO_IO_LOGW("pa_stream[%p] is corked...do uncork here first!!!!", __mpStream);
+            pa_operation* o = pa_stream_cork(__mpStream, 0, NULL, NULL);
+            if (!o)
+                AUDIO_IO_LOGE("pa_stream[%p] : uncork failed", __mpStream);
+            else
+                pa_operation_unref(o);
         }
 
         if (__mIsFirstStream) {
@@ -685,12 +779,9 @@ int CPulseAudioClient::write(const void* data, size_t length) {
             uint32_t prebuf = attr->prebuf;
             // Compensate amount of prebuf in first stream callback when audio-io use prebuf(-1)
             // Because a stream will never start when an application wrote less than prebuf at first
-            if (length < prebuf) {
-                char* dummy = new char[prebuf - length];
-                memset(dummy, 0, prebuf - length);
-                pa_stream_write(__mpStream, dummy, prebuf - length, NULL, 0LL, PA_SEEK_RELATIVE);
-                delete [] dummy;
-            }
+            if (length < prebuf)
+                __dummy_write(__mpStream, prebuf - length);
+
             __mIsFirstStream = false;
             AUDIO_IO_LOGW("FIRST STREAM CALLBACK : length[%zu], prebuf[%d], dummy[%zu]",
                           length, prebuf, (length < prebuf) ? prebuf - length : 0);
@@ -709,7 +800,7 @@ void CPulseAudioClient::cork(bool cork) {
     AUDIO_IO_LOGD("cork[%d]", cork);
 
     if (!__mIsInit)
-        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient"); // LCOV_EXCL_LINE
+        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
 
     if (isInThread())
         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This operation is not supported in callback"); // LCOV_EXCL_LINE
@@ -720,40 +811,37 @@ void CPulseAudioClient::cork(bool cork) {
     if (!cork)
         __mIsFirstStream = true;
 
-    if (!isInThread()) {
-        pa_threaded_mainloop_lock(__mpMainloop);
-        pa_operation_unref(pa_stream_cork(__mpStream, static_cast<int>(cork), __successStreamCb, this));
-        pa_threaded_mainloop_unlock(__mpMainloop);
-    } else {
-        pa_operation_unref(pa_stream_cork(__mpStream, static_cast<int>(cork), __successStreamCb, this));
+    CPulseThreadLocker locker{__mpMainloop};
+
+    /* FIXME: wait for completion like drain? */
+    pa_operation* o = pa_stream_cork(__mpStream, static_cast<int>(cork), __successStreamCb, this);
+    if (!o) {
+        AUDIO_IO_LOGE("pa_stream[%p] : cork[%d] failed", __mpStream, cork);
+        return;
     }
+    pa_operation_unref(o);
+    AUDIO_IO_LOGD("cork[%d] done", cork);
 }
 
 bool CPulseAudioClient::isCorked() {
     if (!__mIsInit)
-        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient"); // LCOV_EXCL_LINE
+        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
 
     checkRunningState();
 
-    int isCork = 0;
+    CPulseThreadLocker locker{__mpMainloop};
 
-    if (!isInThread()) {
-        pa_threaded_mainloop_lock(__mpMainloop);
-        isCork = pa_stream_is_corked(__mpStream);
-        pa_threaded_mainloop_unlock(__mpMainloop);
-    } else {
-        isCork = pa_stream_is_corked(__mpStream);
-    }
+    int isCorked = pa_stream_is_corked(__mpStream);
 
 #ifdef _AUDIO_IO_DEBUG_TIMING_
-    AUDIO_IO_LOGD("isCork[%d]", isCork);
+    AUDIO_IO_LOGD("isCorked[%d]", isCorked);
 #endif
-    return static_cast<bool>(isCork);
+    return static_cast<bool>(isCorked);
 }
 
 bool CPulseAudioClient::drain() {
     if (!__mIsInit)
-        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient"); // LCOV_EXCL_LINE
+        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
 
     checkRunningState();
 
@@ -774,18 +862,23 @@ bool CPulseAudioClient::drain() {
 
     if (!isInThread()) {
         AUDIO_IO_LOGD("drain");
-        pa_threaded_mainloop_lock(__mpMainloop);
+        CPulseThreadLocker locker{__mpMainloop};
+
         pa_operation* o = pa_stream_drain(__mpStream, __successDrainCb, this);
         __mIsDraining = true;
         while (pa_operation_get_state(o) == PA_OPERATION_RUNNING)
             pa_threaded_mainloop_wait(__mpMainloop);
-
         pa_operation_unref(o);
-        pa_threaded_mainloop_unlock(__mpMainloop);
+
         AUDIO_IO_LOGD("drain done");
     } else {
         AUDIO_IO_LOGD("drain in thread");
-        pa_operation_unref(pa_stream_drain(__mpStream, __successDrainCbInThread, this));
+        pa_operation* o = pa_stream_drain(__mpStream, __successDrainCbInThread, this);
+        if (!o) {
+            AUDIO_IO_LOGE("pa_stream[%p] : drain failed", __mpStream);
+            return false;
+        }
+        pa_operation_unref(o);
         __mIsDraining = true;
     }
 
@@ -794,43 +887,35 @@ bool CPulseAudioClient::drain() {
 
 bool CPulseAudioClient::flush() {
     if (!__mIsInit)
-        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient"); // LCOV_EXCL_LINE
+        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
 
     checkRunningState();
 
-    if (!isInThread()) {
-        AUDIO_IO_LOGD("flush");
-        pa_threaded_mainloop_lock(__mpMainloop);
-        pa_operation_unref(pa_stream_flush(__mpStream, __successStreamCb, this));
-        pa_threaded_mainloop_unlock(__mpMainloop);
-    } else {
-        AUDIO_IO_LOGD("flush in thread");
-        pa_operation_unref(pa_stream_flush(__mpStream, __successStreamCb, this));
+    CPulseThreadLocker locker{__mpMainloop};
+
+    /* FIXME: wait for completion like drain? */
+    pa_operation* o = pa_stream_flush(__mpStream, __successStreamCb, this);
+    if (!o) {
+        AUDIO_IO_LOGE("pa_stream[%p] : flush failed", __mpStream);
+        return false;
     }
+    pa_operation_unref(o);
 
     return true;
 }
 
 size_t CPulseAudioClient::getWritableSize() {
     if (!__mIsInit)
-        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient"); // LCOV_EXCL_LINE
+        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
 
     checkRunningState();
 
     if (__mDirection != EStreamDirection::STREAM_DIRECTION_PLAYBACK)
         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Playback"); // LCOV_EXCL_LINE
 
-    size_t ret = 0;
+    CPulseThreadLocker locker{__mpMainloop};
 
-    if (!isInThread()) {
-        pa_threaded_mainloop_lock(__mpMainloop);
-        ret = pa_stream_writable_size(__mpStream);
-        pa_threaded_mainloop_unlock(__mpMainloop);
-    } else {
-        ret = pa_stream_writable_size(__mpStream);
-    }
-
-    return ret;
+    return pa_stream_writable_size(__mpStream);
 }
 
 void CPulseAudioClient::checkRunningState() {
@@ -851,7 +936,13 @@ void CPulseAudioClient::checkRunningState() {
 #endif
 }
 
-bool CPulseAudioClient::isInThread() noexcept {
+bool CPulseAudioClient::isInThread() const {
+    if (!__mIsInit)
+        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "__mIsInit is null");
+
+    if (!__mpMainloop)
+        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "__mpMainloop is null");
+
     int ret = pa_threaded_mainloop_in_thread(__mpMainloop);
 
 #ifdef _AUDIO_IO_DEBUG_TIMING_
@@ -863,146 +954,128 @@ bool CPulseAudioClient::isInThread() noexcept {
 //LCOV_EXCL_START
 size_t CPulseAudioClient::getReadableSize() {
     if (!__mIsInit)
-        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
+        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
 
     checkRunningState();
 
     if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD)
         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Capture");
 
-    size_t ret = 0;
+    CPulseThreadLocker locker{__mpMainloop};
 
-    if (!isInThread()) {
-        pa_threaded_mainloop_lock(__mpMainloop);
-        ret = pa_stream_readable_size(__mpStream);
-        pa_threaded_mainloop_unlock(__mpMainloop);
-    } else {
-        ret = pa_stream_readable_size(__mpStream);
-    }
-
-    return ret;
+    return pa_stream_readable_size(__mpStream);
 }
 
 size_t CPulseAudioClient::getBufferSize() {
     if (!__mIsInit)
-        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
+        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
 
     checkRunningState();
 
-    size_t ret = 0;
+    size_t buffer_size = 0;
+    CPulseThreadLocker locker{__mpMainloop};
 
-    try {
-        if (!isInThread())
-            pa_threaded_mainloop_lock(__mpMainloop);
+    const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
+    if (!attr)
+        THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
+                               "Failed pa_stream_get_buffer_attr() : err[%d]", pa_context_errno(__mpContext));
 
-        const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
-        if (!attr) {
-            int _err = pa_context_errno(__mpContext);
-            THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_buffer_attr() : err[%d]", _err);
-        }
-
-        if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
-            ret = attr->tlength;
-            AUDIO_IO_LOGD("PLAYBACK buffer size[%zu]", ret);
-        } else {
-            ret = attr->fragsize;
-            AUDIO_IO_LOGD("RECORD buffer size[%zu]", ret);
-        }
-    } catch (const CAudioError& e) {
-        if (!isInThread())
-            pa_threaded_mainloop_unlock(__mpMainloop);
-        throw;
+    if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
+        buffer_size = attr->tlength;
+        AUDIO_IO_LOGD("PLAYBACK buffer size[%zu]", buffer_size);
+    } else {
+        buffer_size = attr->fragsize;
+        AUDIO_IO_LOGD("RECORD buffer size[%zu]", buffer_size);
     }
 
-    if (!isInThread())
-        pa_threaded_mainloop_unlock(__mpMainloop);
-
-    return ret;
+    return buffer_size;
 }
 
 pa_usec_t CPulseAudioClient::getLatency() {
     if (!__mIsInit)
-        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
+        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
 
     checkRunningState();
 
-    pa_usec_t ret = 0;
-    int negative  = 0;
+    pa_usec_t latency = 0;
+    int negative = 0;
 
     if (!isInThread()) {
-        if (pa_stream_get_latency(__mpStream, &ret, &negative) < 0) {
+        if (pa_stream_get_latency(__mpStream, &latency, &negative) < 0) {
             int _err = pa_context_errno(__mpContext);
             if (_err != PA_ERR_NODATA)
-                THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_latency() : err[%d]", _err);
+                THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
+                                       "Failed pa_stream_get_latency() : err[%d]", _err);
         }
-        return negative ? 0 : ret;
+        return negative ? 0 : latency;
     }
 
-    pa_threaded_mainloop_lock(__mpMainloop);
-
-    try {
-        while (true) {
-            if (pa_stream_get_latency(__mpStream, &ret, &negative) >= 0)
-                break;
-
-            int _err = pa_context_errno(__mpContext);
-            if (_err != PA_ERR_NODATA)
-                THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_latency() : err[%d]", _err);
+    CPulseThreadLocker locker{__mpMainloop};
 
-            /* Wait until latency data is available again */
-            pa_threaded_mainloop_wait(__mpMainloop);
-        }
-    } catch (const CAudioError& e) {
-        pa_threaded_mainloop_unlock(__mpMainloop);
-        throw;
+    while (pa_stream_get_latency(__mpStream, &latency, &negative) < 0) {
+        int _err = pa_context_errno(__mpContext);
+        if (_err != PA_ERR_NODATA)
+            THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
+                                   "Failed pa_stream_get_latency() : err[%d]", _err);
+        /* Wait until latency data is available again */
+        pa_threaded_mainloop_wait(__mpMainloop);
     }
 
-    pa_threaded_mainloop_unlock(__mpMainloop);
-
-    return negative ? 0 : ret;
+    return negative ? 0 : latency;
 }
 
 pa_usec_t CPulseAudioClient::getFinalLatency() {
     if (!__mIsInit)
-        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
+        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
 
     checkRunningState();
 
-    pa_usec_t ret = 0;
+    pa_usec_t latency = 0;
 
-    try {
-        if (!isInThread())
-            pa_threaded_mainloop_lock(__mpMainloop);
-
-        uint32_t ver = pa_context_get_server_protocol_version(__mpContext);
-        if (ver >= 13) {
-            const pa_buffer_attr* buffer_attr = pa_stream_get_buffer_attr(__mpStream);
-            const pa_sample_spec* sample_spec = pa_stream_get_sample_spec(__mpStream);
-            const pa_timing_info* timing_info = pa_stream_get_timing_info(__mpStream);
-
-            if (!buffer_attr || !sample_spec || !timing_info)
-                THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed to get buffer_attr[%p] or sample_spec[%p] or timing_info[%p] from a pa_stream",
-                        buffer_attr, sample_spec, timing_info);
-
-            if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
-                ret = (pa_bytes_to_usec(buffer_attr->tlength, sample_spec) + timing_info->configured_sink_usec);
-                AUDIO_IO_LOGD("FINAL PLAYBACK LATENCY[%" PRIu64 "]", ret);
-            } else {
-                ret = (pa_bytes_to_usec(buffer_attr->fragsize, sample_spec) + timing_info->configured_source_usec);
-                AUDIO_IO_LOGD("FINAL RECORD LATENCY[%" PRIu64 "]", ret);
-            }
-        } else {
-            THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_SUPPORTED, "This version(ver.%d) is not supported", ver);
-        }
+    CPulseThreadLocker locker{__mpMainloop};
 
-        if (!isInThread())
-            pa_threaded_mainloop_unlock(__mpMainloop);
-    } catch (const CAudioError& e) {
-        if (!isInThread())
-            pa_threaded_mainloop_unlock(__mpMainloop);
-        throw;
+    uint32_t ver = pa_context_get_server_protocol_version(__mpContext);
+    if (ver < 13)
+        THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_SUPPORTED, "This version(ver.%d) is not supported", ver);
+
+    const pa_buffer_attr* buffer_attr = pa_stream_get_buffer_attr(__mpStream);
+    const pa_sample_spec* sample_spec = pa_stream_get_sample_spec(__mpStream);
+    const pa_timing_info* timing_info = pa_stream_get_timing_info(__mpStream);
+
+    if (!buffer_attr || !sample_spec || !timing_info)
+        THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_OUT_OF_MEMORY,
+                "Failed to get buffer_attr[%p] or sample_spec[%p] or timing_info[%p] from a pa_stream",
+                buffer_attr, sample_spec, timing_info);
+
+    if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
+        latency = (pa_bytes_to_usec(buffer_attr->tlength, sample_spec) + timing_info->configured_sink_usec);
+        AUDIO_IO_LOGD("FINAL PLAYBACK LATENCY[%" PRIu64 "]", latency);
+    } else {
+        latency = (pa_bytes_to_usec(buffer_attr->fragsize, sample_spec) + timing_info->configured_source_usec);
+        AUDIO_IO_LOGD("FINAL RECORD LATENCY[%" PRIu64 "]", latency);
     }
 
-    return ret;
+    return latency;
 }
 //LCOV_EXCL_STOP
+
+void CPulseAudioClient::applyRecordVolume(double volume) {
+
+    if (!__mIsInit)
+        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
+
+    checkRunningState();
+
+    if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD)
+        THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client can't use this function"); //LCOV_EXCL_LINE
+
+    CPulseThreadLocker locker{__mpMainloop};
+
+    pa_cvolume cv = { 0, };
+    pa_volume_t v = PA_VOLUME_NORM * volume;
+
+    pa_cvolume_set(&cv, __mSpec.getChannelMap().channels, v);
+
+    pa_operation_unref(pa_context_set_source_output_volume(__mpContext,
+            pa_stream_get_index(__mpStream), &cv, __successVolumeCb, NULL));
+}