2 git st* Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 #include "CAudioIODef.h"
27 #include <dpm/restriction.h>
31 using namespace tizen_media_audio;
34 * class CMainloopLocker
36 CPulseAudioClient::CPulseThreadLocker::CPulseThreadLocker(pa_threaded_mainloop* mainloop) : ml(nullptr) {
37 if (!mainloop || pa_threaded_mainloop_in_thread(mainloop))
40 pa_threaded_mainloop_lock(mainloop);
44 CPulseAudioClient::CPulseThreadLocker::~CPulseThreadLocker() {
46 pa_threaded_mainloop_unlock(const_cast<pa_threaded_mainloop*>(ml));
51 * class CPulseAudioClient
53 const char* CPulseAudioClient::CLIENT_NAME = "AUDIO_IO_PA_CLIENT";
54 const char* ec_method = "default";
55 static constexpr auto drain_wait_interval = 10000;
56 static constexpr auto drain_wait_max_count = 30;
58 CPulseAudioClient::CPulseAudioClient(
59 EStreamDirection direction,
60 CPulseStreamSpec& spec,
61 IPulseStreamListener* listener) :
62 __mDirection(direction),
64 __mpListener(listener),
65 __mpMainloop(nullptr),
68 __mpPropList(nullptr),
70 __mIsOperationSuccess(false),
71 __mpSyncReadDataPtr(nullptr),
74 __mIsUsedSyncRead(false),
75 __mIsFirstStream(false),
80 CPulseAudioClient::~CPulseAudioClient() {
83 } catch (const CAudioError& e) {
84 AUDIO_IO_LOGE("%s", e.getErrorMsg()); //LCOV_EXCL_LINE
88 void CPulseAudioClient::__contextStateChangeCb(pa_context* c, void* user_data) {
89 auto pClient = static_cast<CPulseAudioClient*>(user_data);
93 switch (pa_context_get_state(c)) {
94 case PA_CONTEXT_READY:
95 AUDIO_IO_LOGD("pa_context[%p] is ready", c);
96 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
99 case PA_CONTEXT_FAILED:
100 case PA_CONTEXT_TERMINATED:
101 AUDIO_IO_LOGD("pa_context[%p] is lost", c);
102 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
105 case PA_CONTEXT_UNCONNECTED:
106 case PA_CONTEXT_CONNECTING:
107 case PA_CONTEXT_AUTHORIZING:
108 case PA_CONTEXT_SETTING_NAME:
114 static bool __is_microphone_restricted(void) {
117 device_policy_manager_h dpm_h = nullptr;
120 if ((dpm_h = dpm_manager_create())) {
121 /* state: 0(disallowed), 1(allowed) */
122 if ((ret = dpm_restriction_get_microphone_state(dpm_h, &state)))
123 AUDIO_IO_LOGE("Failed to dpm_restriction_get_microphone_state(), ret(0x%x)", ret);
124 dpm_manager_destroy(dpm_h);
125 AUDIO_IO_LOGD("microphone restriction state: %d(1:allowed, 0:disallowed)", state);
127 AUDIO_IO_LOGE("Failed to dpm_manager_create()");
130 return (state ? false : true);
134 void CPulseAudioClient::__streamStateChangeCb(pa_stream* s, void* user_data) {
138 auto pClient = static_cast<CPulseAudioClient*>(user_data);
139 pa_stream_state_t state = pa_stream_get_state(s);
142 case PA_STREAM_UNCONNECTED:
145 case PA_STREAM_CREATING:
148 case PA_STREAM_READY:
149 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] is READY[%d]", pClient, s, PA_STREAM_READY);
150 pClient->__mpListener->setState(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING);
151 pClient->__mpListener->onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING);
152 if (pClient->__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
153 pClient->__mIsFirstStream = true;
154 pClient->__mIsInit = true;
156 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] now signaling...", pClient, s);
157 pa_threaded_mainloop_signal(pClient->__mpMainloop, 1);
158 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] signal accepted", pClient, s);
162 case PA_STREAM_FAILED:
163 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] is FAILED[%d]", pClient, s, PA_STREAM_FAILED);
164 pClient->__mpListener->setState(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE);
165 pClient->__mpListener->onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE,
166 __is_microphone_restricted());
168 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] now signaling...", pClient, s);
169 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
173 case PA_STREAM_TERMINATED:
174 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] is TERMINATED[%d]", pClient, s, PA_STREAM_TERMINATED);
175 pClient->__mpListener->setState(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE);
176 pClient->__mpListener->onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE);
178 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] now signaling...", pClient, s);
179 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
183 AUDIO_IO_LOGW("Unexpected state[%d]", state);
187 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] state[%d] done", pClient, s, state);
190 void CPulseAudioClient::__streamCaptureCb(pa_stream* s, size_t length, void* user_data) {
194 auto pClient = static_cast<CPulseAudioClient*>(user_data);
195 assert(pClient->__mpListener);
196 assert(pClient->__mpMainloop);
198 if (pClient->__mIsUsedSyncRead)
199 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
201 pClient->__mpListener->onStream(pClient, length);
204 static void __dummy_write(pa_stream* s, size_t length) {
205 pa_stream_write(s, std::vector<char>(length).data(), length, NULL, 0LL, PA_SEEK_RELATIVE);
208 void CPulseAudioClient::__streamPlaybackCb(pa_stream* s, size_t length, void* user_data) {
212 auto pClient = static_cast<CPulseAudioClient*>(user_data);
213 assert(pClient->__mpListener);
215 #ifndef DISABLE_MOBILE_BACK_COMP
216 if (!pClient->__mIsInit) {
217 AUDIO_IO_LOGD("pa_stream[%p] is on the way to create : Write dummy, length[%zu]", s, length);
218 __dummy_write(s, length);
221 if (pClient->isCorked()) {
222 AUDIO_IO_LOGD("pa_stream[%p] is CORKED : Write dummy, length[%zu]", s, length);
223 __dummy_write(s, length);
228 pClient->__mpListener->onStream(pClient, length);
230 #ifndef DISABLE_MOBILE_BACK_COMP
231 /* If stream is not written in first callback during prepare,
232 then write dummy data to ensure the start */
233 if (pClient->__mSpec.getStreamLatency() == CPulseStreamSpec::EStreamLatency::STREAM_LATENCY_OUTPUT_DEFAULT_ASYNC &&
234 pClient->__mIsFirstStream) {
235 AUDIO_IO_LOGW("[async] pa_stream[%p] : not written in the first callback during prepare, write dummy of length[%zu]",
237 __dummy_write(s, length);
238 pClient->__mIsFirstStream = false;
243 void CPulseAudioClient::__streamLatencyUpdateCb(pa_stream* s, void* user_data) {
247 auto pClient = static_cast<CPulseAudioClient*>(user_data);
249 #ifdef _AUDIO_IO_DEBUG_TIMING_
250 /* FIXME : print some useful latency info */
251 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] latency updated", pClient, s);
254 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
257 void CPulseAudioClient::__streamStartedCb(pa_stream* s, void* user_data) {
261 auto pClient = static_cast<CPulseAudioClient*>(user_data);
263 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] started", pClient, s);
265 pClient->__mIsStarted = true;
268 void CPulseAudioClient::__streamUnderflowCb(pa_stream* s, void* user_data) {
272 auto pClient = static_cast<CPulseAudioClient*>(user_data);
274 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] UnderFlow...", pClient, s);
276 pClient->__mIsStarted = false;
279 void CPulseAudioClient::__streamOverflowCb(pa_stream* s, void* user_data) {
283 auto pClient = static_cast<CPulseAudioClient*>(user_data);
285 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] OverFlow...", pClient, s);
289 void CPulseAudioClient::__streamEventCb(pa_stream* s, const char* name, pa_proplist* pl, void* user_data) {
293 auto pClient = static_cast<CPulseAudioClient*>(user_data);
295 AUDIO_IO_LOGW("pClient[%p] pa_stream[%p] : name[%s], proplist[%p]", pClient, s, name, pl);
297 if (strcmp(name, PA_STREAM_EVENT_POP_TIMEOUT) == 0) {
298 pa_operation* o = pa_stream_cork(pClient->__mpStream, 1, NULL, NULL);
300 AUDIO_IO_LOGE("pa_stream[%p] : cork failed", pClient->__mpStream);
303 pa_operation_unref(o);
308 void CPulseAudioClient::__successStreamCb(pa_stream* s, int success, void* user_data) {
312 auto pClient = static_cast<CPulseAudioClient*>(user_data);
314 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] success[%d] user_data[%p]", pClient, s, success, user_data);
316 pClient->__mIsOperationSuccess = static_cast<bool>(success);
318 /* FIXME : verify following action without any waiting */
319 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
323 void CPulseAudioClient::__successDrainCbInThread(pa_stream* s, int success, void* user_data) {
327 auto pClient = static_cast<CPulseAudioClient*>(user_data);
329 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] success[%d] user_data[%p]", pClient, s, success, user_data);
331 pClient->__mIsOperationSuccess = static_cast<bool>(success);
332 pClient->__mIsDraining = false;
336 void CPulseAudioClient::__successDrainCb(pa_stream* s, int success, void* user_data) {
340 auto pClient = static_cast<CPulseAudioClient*>(user_data);
342 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] success[%d] user_data[%p]", pClient, s, success, user_data);
344 pClient->__mIsOperationSuccess = static_cast<bool>(success);
345 pClient->__mIsDraining = false;
347 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
350 void CPulseAudioClient::__successVolumeCb(pa_context* c, int success, void* user_data) {
351 AUDIO_IO_LOGD("pa_context[%p] success[%d] user_data[%p]", c, success, user_data);
354 void CPulseAudioClient::resetStreamCallbacks() {
358 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
359 pa_stream_set_write_callback(__mpStream, NULL, NULL);
361 pa_stream_set_read_callback(__mpStream, NULL, NULL);
363 pa_stream_set_latency_update_callback(__mpStream, NULL, NULL);
364 pa_stream_set_event_callback(__mpStream, NULL, NULL);
367 void CPulseAudioClient::resetInternalObjects() {
369 pa_threaded_mainloop_stop(__mpMainloop);
372 pa_stream_disconnect(__mpStream);
373 pa_stream_unref(__mpStream);
374 __mpStream = nullptr;
378 pa_context_disconnect(__mpContext);
379 pa_context_unref(__mpContext);
380 __mpContext = nullptr;
384 pa_threaded_mainloop_free(__mpMainloop);
385 __mpMainloop = nullptr;
389 pa_proplist_free(__mpPropList);
390 __mpPropList = nullptr;
394 void CPulseAudioClient::initialize() {
402 // Allocates PA proplist
403 __mpPropList = pa_proplist_new();
405 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_proplist_new()"); //LCOV_EXCL_LINE
407 // Adds values on proplist for delivery to PULSEAUDIO
408 pa_proplist_sets(__mpPropList, PA_PROP_MEDIA_ROLE, __mSpec.getAudioInfo().getConvertedStreamType());
410 int index = __mSpec.getAudioInfo().getAudioIndex();
412 pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_PARENT_ID, "%u", (unsigned int) index);
414 if (__mDirection == EStreamDirection::STREAM_DIRECTION_RECORD) {
415 /* Noise-suppression effect should be set first. */
416 std::string method = __mSpec.getAudioInfo().getEffectMethod();
417 auto [ method_reference, device_id ] = __mSpec.getAudioInfo().getEffectMethodWithReference();
418 std::string method_all = method + method_reference;
420 if (!method_all.empty()) {
421 pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_PREPROCESSOR_METHOD, "%s", method_all.c_str());
422 pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_ECHO_CANCEL_REFERENCE_DEVICE, "%d", device_id);
424 AUDIO_IO_LOGD("preprocess will be set. method[%s], device_id[%d]", method_all.c_str(), device_id);
428 // Adds latency on proplist for delivery to PULSEAUDIO
429 AUDIO_IO_LOGD("LATENCY : %s[%d]", __mSpec.getStreamLatencyToString(), static_cast<int>(__mSpec.getStreamLatency()));
430 pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_TIZEN_AUDIO_LATENCY, "%s", __mSpec.getStreamLatencyToString());
432 // Allocates PA mainloop
433 __mpMainloop = pa_threaded_mainloop_new();
435 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_threaded_mainloop_new()"); //LCOV_EXCL_LINE
437 // Allocates PA context
438 __mpContext = pa_context_new(pa_threaded_mainloop_get_api(__mpMainloop), CLIENT_NAME);
440 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_context_new()"); //LCOV_EXCL_LINE
442 // Sets context state changed callback
443 pa_context_set_state_callback(__mpContext, __contextStateChangeCb, this);
445 // Connects this client with PA server
446 if (pa_context_connect(__mpContext, NULL, PA_CONTEXT_NOFLAGS, NULL) < 0)
447 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_context_connect()"); //LCOV_EXCL_LINE
449 // LOCK for synchronous connection
450 CPulseThreadLocker locker{__mpMainloop};
453 if (pa_threaded_mainloop_start(__mpMainloop) < 0) {
455 THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_threaded_mainloop_start()");
459 // Connection process is asynchronously
460 // So, this function will be waited when occurred context state change event
461 // If I got a signal, do next processing
463 pa_context_state_t state;
464 state = pa_context_get_state(__mpContext);
466 if (state == PA_CONTEXT_READY)
469 if (!PA_CONTEXT_IS_GOOD(state)) {
471 err = pa_context_errno(__mpContext);
472 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION,
473 "pa_context's state is not good : err[%d]", err);
477 /* Wait until the context is ready */
478 pa_threaded_mainloop_wait(__mpMainloop);
481 AUDIO_IO_LOGD("pa_context[%p] now ready", __mpContext);
483 // Allocates PA stream
484 pa_sample_spec ss = __mSpec.getSampleSpec();
485 pa_channel_map map = __mSpec.getChannelMap();
487 __mpStream = pa_stream_new_with_proplist(__mpContext, __mSpec.getStreamName(), &ss, &map, __mpPropList);
490 THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_new_with_proplist()");
494 // Sets stream callbacks
495 pa_stream_set_state_callback(__mpStream, __streamStateChangeCb, this);
496 pa_stream_set_read_callback(__mpStream, __streamCaptureCb, this);
497 pa_stream_set_write_callback(__mpStream, __streamPlaybackCb, this);
498 pa_stream_set_latency_update_callback(__mpStream, __streamLatencyUpdateCb, this);
499 pa_stream_set_event_callback(__mpStream, __streamEventCb, this);
500 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
501 pa_stream_set_started_callback(__mpStream, __streamStartedCb, this);
502 pa_stream_set_underflow_callback(__mpStream, __streamUnderflowCb, this);
503 pa_stream_set_overflow_callback(__mpStream, __streamOverflowCb, this);
506 // Connect stream with PA Server
508 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
509 auto flags = static_cast<pa_stream_flags_t>(
510 PA_STREAM_INTERPOLATE_TIMING |
511 PA_STREAM_ADJUST_LATENCY |
512 #ifndef DISABLE_MOBILE_BACK_COMP
513 PA_STREAM_START_CORKED |
515 PA_STREAM_AUTO_TIMING_UPDATE);
517 ret = pa_stream_connect_playback(__mpStream, NULL, NULL, flags, NULL, NULL);
519 auto flags = static_cast<pa_stream_flags_t>(
520 PA_STREAM_INTERPOLATE_TIMING |
521 PA_STREAM_ADJUST_LATENCY |
522 #ifndef DISABLE_MOBILE_BACK_COMP
523 PA_STREAM_START_CORKED |
525 PA_STREAM_AUTO_TIMING_UPDATE);
527 ret = pa_stream_connect_record(__mpStream, NULL, NULL, flags);
531 err = pa_context_errno(__mpContext);
532 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
533 "Failed pa_stream_connect() : err[%d]", err);
537 AUDIO_IO_LOGD("pa_stream[%p] now wait for stream ready...", __mpStream);
540 pa_stream_state_t state = pa_stream_get_state(__mpStream);
541 AUDIO_IO_LOGD("pa_stream[%p] current state[%d]", __mpStream, state);
543 if (state == PA_STREAM_READY)
546 if (!PA_STREAM_IS_GOOD(state)) {
547 err = pa_context_errno(__mpContext);
548 if (err == PA_ERR_ACCESS)
549 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_DEVICE_POLICY_RESTRICTION,
550 "pa_stream's state is not good : err[%d]", err);
552 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, //LCOV_EXCL_LINE
553 "pa_stream's state is not good : err[%d]", err); //LCOV_EXCL_LINE
556 /* Wait until the stream is ready */
557 AUDIO_IO_LOGD("pa_mainloop[%p] signal wait...", __mpMainloop);
558 pa_threaded_mainloop_wait(__mpMainloop);
559 AUDIO_IO_LOGD("pa_mainloop[%p] signal wait done", __mpMainloop);
561 pa_threaded_mainloop_accept(__mpMainloop);
563 // __mIsInit = true; // Moved to __streamStateChangeCb()
564 } catch (const CAudioError& e) {
566 resetStreamCallbacks();
567 resetInternalObjects();
572 AUDIO_IO_LOGD("Done : pa_context[%p], pa_mainloop[%p], pa_stream[%p]", __mpContext, __mpMainloop, __mpStream);
575 void CPulseAudioClient::finalize() {
576 AUDIO_IO_LOGD("pa_context[%p], pa_mainloop[%p], pa_stream[%p]", __mpContext, __mpMainloop, __mpStream);
581 bool is_in_thread = isInThread();
583 pa_threaded_mainloop_lock(__mpMainloop);
587 resetStreamCallbacks();
590 pa_threaded_mainloop_unlock(__mpMainloop);
592 /* Wait for drain complete if draining before finalize */
594 unsigned int drain_wait_count = 0;
595 while (__mIsDraining && drain_wait_count++ < drain_wait_max_count)
596 usleep(drain_wait_interval);
597 AUDIO_IO_LOGD("wait for drain complete!!!! [%d * %d usec]",
598 drain_wait_count, drain_wait_interval);
601 resetInternalObjects();
603 AUDIO_IO_LOGD("Done");
606 int CPulseAudioClient::read(void* buffer, size_t length) {
608 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); //LCOV_EXCL_LINE
613 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "invalid parameter : buffer[%p]", buffer); //LCOV_EXCL_LINE
615 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
616 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback client can't use this function"); //LCOV_EXCL_LINE
618 size_t lengthIter = length;
621 __mIsUsedSyncRead = true;
624 CPulseThreadLocker locker{__mpMainloop};
626 while (lengthIter > 0) {
629 while (!__mpSyncReadDataPtr) {
630 ret = pa_stream_peek(__mpStream, &__mpSyncReadDataPtr, &__mSyncReadLength);
632 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_peek() : ret[%d]", ret); //LCOV_EXCL_LINE
634 if (__mSyncReadLength <= 0) {
635 #ifdef _AUDIO_IO_DEBUG_TIMING_
636 AUDIO_IO_LOGD("readLength(%zu byte) is not valid. wait...", __mSyncReadLength);
638 pa_threaded_mainloop_wait(__mpMainloop);
639 } else if (!__mpSyncReadDataPtr) {
641 // Data peeked, but it doesn't have any data
642 ret = pa_stream_drop(__mpStream);
644 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_drop() : ret[%d]", ret);
647 __mSyncReadIndex = 0;
651 l = min(__mSyncReadLength, lengthIter);
653 // Copy partial pcm data on out parameter
654 #ifdef _AUDIO_IO_DEBUG_TIMING_
655 AUDIO_IO_LOGD("memcpy() that a peeked buffer[%p], index[%zu], length[%zu] on out buffer", (const uint8_t*)(__mpSyncReadDataPtr) + __mSyncReadIndex, __mSyncReadIndex, l);
657 memcpy(buffer, (const uint8_t*)__mpSyncReadDataPtr + __mSyncReadIndex, l);
659 // Move next position
660 buffer = (uint8_t*)buffer + l;
663 // Adjusts the rest length
664 __mSyncReadIndex += l;
665 __mSyncReadLength -= l;
667 if (__mSyncReadLength == 0) {
668 #ifdef _AUDIO_IO_DEBUG_TIMING_
669 AUDIO_IO_LOGD("__mSyncReadLength is zero, do drop()");
671 ret = pa_stream_drop(__mpStream);
673 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, //LCOV_EXCL_LINE
674 "Failed pa_stream_drop() : ret[%d]", ret); //LCOV_EXCL_LINE
676 // Reset the internal pointer
677 __mpSyncReadDataPtr = nullptr;
678 __mSyncReadLength = 0;
679 __mSyncReadIndex = 0;
681 } // End of while (lengthIter > 0)
683 __mIsUsedSyncRead = false;
684 } catch (const CAudioError& e) {
686 __mIsUsedSyncRead = false;
694 int CPulseAudioClient::peek(const void** buffer, size_t* length) {
696 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
700 if (!buffer || !length)
701 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, // LCOV_EXCL_LINE
702 "invalid parameter : buffer[%p], length[%p]", buffer, length); // LCOV_EXCL_LINE
704 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
705 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
707 CPulseThreadLocker locker{__mpMainloop};
709 int ret = pa_stream_peek(__mpStream, buffer, length);
712 #ifdef _AUDIO_IO_DEBUG_TIMING_
713 AUDIO_IO_LOGD("buffer[%p], length[%zu]", *buffer, *length);
717 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_peek() : err[%d]", ret); //LCOV_EXCL_LINE
722 int CPulseAudioClient::drop() {
724 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
726 #ifdef _AUDIO_IO_DEBUG_TIMING_
732 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
733 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
735 CPulseThreadLocker locker{__mpMainloop};
737 int ret = pa_stream_drop(__mpStream);
739 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_drop() : err[%d]", ret); //LCOV_EXCL_LINE
744 int CPulseAudioClient::write(const void* data, size_t length) {
746 THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_ARGUMENT, "invalid parameter"); // LCOV_EXCL_LINE
748 if (__mDirection == EStreamDirection::STREAM_DIRECTION_RECORD)
749 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
753 #ifdef _AUDIO_IO_DEBUG_TIMING_
754 AUDIO_IO_LOGD("data[%p], length[%zu], First[%d]", data, length, __mIsFirstStream);
758 CPulseThreadLocker locker{__mpMainloop};
759 if (pa_stream_is_corked(__mpStream)) {
760 AUDIO_IO_LOGW("pa_stream[%p] is corked...do uncork here first!!!!", __mpStream);
761 pa_operation* o = pa_stream_cork(__mpStream, 0, NULL, NULL);
763 AUDIO_IO_LOGE("pa_stream[%p] : uncork failed", __mpStream);
765 pa_operation_unref(o);
768 ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
771 if (pa_stream_is_corked(__mpStream)) {
772 AUDIO_IO_LOGW("pa_stream[%p] is corked...do uncork here first!!!!", __mpStream);
773 pa_operation* o = pa_stream_cork(__mpStream, 0, NULL, NULL);
775 AUDIO_IO_LOGE("pa_stream[%p] : uncork failed", __mpStream);
777 pa_operation_unref(o);
780 if (__mIsFirstStream) {
781 const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
782 uint32_t prebuf = attr->prebuf;
783 // Compensate amount of prebuf in first stream callback when audio-io use prebuf(-1)
784 // Because a stream will never start when an application wrote less than prebuf at first
786 __dummy_write(__mpStream, prebuf - length);
788 __mIsFirstStream = false;
789 AUDIO_IO_LOGW("FIRST STREAM CALLBACK : length[%zu], prebuf[%d], dummy[%zu]",
790 length, prebuf, (length < prebuf) ? prebuf - length : 0);
792 ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
797 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_write() : err[%d]", ret); //LCOV_EXCL_LINE
802 void CPulseAudioClient::cork(bool cork) {
803 AUDIO_IO_LOGD("cork[%d]", cork);
806 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
809 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This operation is not supported in callback"); // LCOV_EXCL_LINE
813 // Set __mIsFirstStream flag when uncork(resume) stream, because prebuf will be enable again
815 __mIsFirstStream = true;
817 CPulseThreadLocker locker{__mpMainloop};
819 /* FIXME: wait for completion like drain? */
820 pa_operation* o = pa_stream_cork(__mpStream, static_cast<int>(cork), __successStreamCb, this);
822 AUDIO_IO_LOGE("pa_stream[%p] : cork[%d] failed", __mpStream, cork);
825 pa_operation_unref(o);
826 AUDIO_IO_LOGD("cork[%d] done", cork);
829 bool CPulseAudioClient::isCorked() {
831 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
835 CPulseThreadLocker locker{__mpMainloop};
837 int isCorked = pa_stream_is_corked(__mpStream);
839 #ifdef _AUDIO_IO_DEBUG_TIMING_
840 AUDIO_IO_LOGD("isCorked[%d]", isCorked);
842 return static_cast<bool>(isCorked);
845 bool CPulseAudioClient::drain() {
847 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
852 AUDIO_IO_LOGW("Corked...");
857 AUDIO_IO_LOGW("already draining...");
862 AUDIO_IO_LOGW("stream not started yet...skip drain");
867 AUDIO_IO_LOGD("drain");
868 CPulseThreadLocker locker{__mpMainloop};
870 pa_operation* o = pa_stream_drain(__mpStream, __successDrainCb, this);
871 __mIsDraining = true;
872 while (pa_operation_get_state(o) == PA_OPERATION_RUNNING)
873 pa_threaded_mainloop_wait(__mpMainloop);
874 pa_operation_unref(o);
876 AUDIO_IO_LOGD("drain done");
878 AUDIO_IO_LOGD("drain in thread");
879 pa_operation* o = pa_stream_drain(__mpStream, __successDrainCbInThread, this);
881 AUDIO_IO_LOGE("pa_stream[%p] : drain failed", __mpStream);
884 pa_operation_unref(o);
885 __mIsDraining = true;
891 bool CPulseAudioClient::flush() {
893 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
897 CPulseThreadLocker locker{__mpMainloop};
899 /* FIXME: wait for completion like drain? */
900 pa_operation* o = pa_stream_flush(__mpStream, __successStreamCb, this);
902 AUDIO_IO_LOGE("pa_stream[%p] : flush failed", __mpStream);
905 pa_operation_unref(o);
910 size_t CPulseAudioClient::getWritableSize() {
912 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
916 if (__mDirection != EStreamDirection::STREAM_DIRECTION_PLAYBACK)
917 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Playback"); // LCOV_EXCL_LINE
919 CPulseThreadLocker locker{__mpMainloop};
921 return pa_stream_writable_size(__mpStream);
924 void CPulseAudioClient::checkRunningState() {
925 if (!__mpContext || !PA_CONTEXT_IS_GOOD(pa_context_get_state(__mpContext)))
926 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, // LCOV_EXCL_LINE
927 "The context[%p] is not created or not good state", __mpContext); // LCOV_EXCL_LINE
929 if (!__mpStream || !PA_STREAM_IS_GOOD(pa_stream_get_state(__mpStream)))
930 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, // LCOV_EXCL_LINE
931 "The stream[%p] is not created or not good state", __mpStream); // LCOV_EXCL_LINE
933 if (pa_context_get_state(__mpContext) != PA_CONTEXT_READY || pa_stream_get_state(__mpStream) != PA_STREAM_READY)
934 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, // LCOV_EXCL_LINE
935 "The context[%p] or stream[%p] state is not ready", __mpContext, __mpStream); // LCOV_EXCL_LINE
937 #ifdef _AUDIO_IO_DEBUG_TIMING_
938 AUDIO_IO_LOGD("This client is running");
942 bool CPulseAudioClient::isInThread() const {
944 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "__mIsInit is null");
947 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "__mpMainloop is null");
949 int ret = pa_threaded_mainloop_in_thread(__mpMainloop);
951 #ifdef _AUDIO_IO_DEBUG_TIMING_
952 AUDIO_IO_LOGD("isInThread[%d]", ret);
954 return static_cast<bool>(ret);
958 size_t CPulseAudioClient::getReadableSize() {
960 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
964 if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD)
965 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Capture");
967 CPulseThreadLocker locker{__mpMainloop};
969 return pa_stream_readable_size(__mpStream);
972 size_t CPulseAudioClient::getBufferSize() {
974 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
978 size_t buffer_size = 0;
979 CPulseThreadLocker locker{__mpMainloop};
981 const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
983 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
984 "Failed pa_stream_get_buffer_attr() : err[%d]", pa_context_errno(__mpContext));
986 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
987 buffer_size = attr->tlength;
988 AUDIO_IO_LOGD("PLAYBACK buffer size[%zu]", buffer_size);
990 buffer_size = attr->fragsize;
991 AUDIO_IO_LOGD("RECORD buffer size[%zu]", buffer_size);
997 pa_usec_t CPulseAudioClient::getLatency() {
999 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
1001 checkRunningState();
1003 pa_usec_t latency = 0;
1006 if (!isInThread()) {
1007 if (pa_stream_get_latency(__mpStream, &latency, &negative) < 0) {
1008 int _err = pa_context_errno(__mpContext);
1009 if (_err != PA_ERR_NODATA)
1010 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
1011 "Failed pa_stream_get_latency() : err[%d]", _err);
1013 return negative ? 0 : latency;
1016 CPulseThreadLocker locker{__mpMainloop};
1018 while (pa_stream_get_latency(__mpStream, &latency, &negative) < 0) {
1019 int _err = pa_context_errno(__mpContext);
1020 if (_err != PA_ERR_NODATA)
1021 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
1022 "Failed pa_stream_get_latency() : err[%d]", _err);
1023 /* Wait until latency data is available again */
1024 pa_threaded_mainloop_wait(__mpMainloop);
1027 return negative ? 0 : latency;
1030 pa_usec_t CPulseAudioClient::getFinalLatency() {
1032 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
1034 checkRunningState();
1036 pa_usec_t latency = 0;
1038 CPulseThreadLocker locker{__mpMainloop};
1040 uint32_t ver = pa_context_get_server_protocol_version(__mpContext);
1042 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_SUPPORTED, "This version(ver.%d) is not supported", ver);
1044 const pa_buffer_attr* buffer_attr = pa_stream_get_buffer_attr(__mpStream);
1045 const pa_sample_spec* sample_spec = pa_stream_get_sample_spec(__mpStream);
1046 const pa_timing_info* timing_info = pa_stream_get_timing_info(__mpStream);
1048 if (!buffer_attr || !sample_spec || !timing_info)
1049 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_OUT_OF_MEMORY,
1050 "Failed to get buffer_attr[%p] or sample_spec[%p] or timing_info[%p] from a pa_stream",
1051 buffer_attr, sample_spec, timing_info);
1053 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
1054 latency = (pa_bytes_to_usec(buffer_attr->tlength, sample_spec) + timing_info->configured_sink_usec);
1055 AUDIO_IO_LOGD("FINAL PLAYBACK LATENCY[%" PRIu64 "]", latency);
1057 latency = (pa_bytes_to_usec(buffer_attr->fragsize, sample_spec) + timing_info->configured_source_usec);
1058 AUDIO_IO_LOGD("FINAL RECORD LATENCY[%" PRIu64 "]", latency);
1065 void CPulseAudioClient::applyRecordVolume(double volume) {
1068 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
1070 checkRunningState();
1072 if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD)
1073 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client can't use this function"); //LCOV_EXCL_LINE
1075 CPulseThreadLocker locker{__mpMainloop};
1077 pa_cvolume cv = { 0, };
1078 pa_volume_t v = PA_VOLUME_NORM * volume;
1080 pa_cvolume_set(&cv, __mSpec.getChannelMap().channels, v);
1082 pa_operation_unref(pa_context_set_source_output_volume(__mpContext,
1083 pa_stream_get_index(__mpStream), &cv, __successVolumeCb, NULL));