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) {
67 CPulseAudioClient::~CPulseAudioClient() {
70 } catch (const CAudioError& e) {
71 AUDIO_IO_LOGE("%s", e.getErrorMsg()); //LCOV_EXCL_LINE
75 void CPulseAudioClient::__contextStateChangeCb(pa_context* c, void* user_data) {
76 auto pClient = static_cast<CPulseAudioClient*>(user_data);
80 switch (pa_context_get_state(c)) {
81 case PA_CONTEXT_READY:
82 AUDIO_IO_LOGD("pa_context[%p] is ready", c);
83 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
86 case PA_CONTEXT_FAILED:
87 case PA_CONTEXT_TERMINATED:
88 AUDIO_IO_LOGD("pa_context[%p] is lost", c);
89 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
92 case PA_CONTEXT_UNCONNECTED:
93 case PA_CONTEXT_CONNECTING:
94 case PA_CONTEXT_AUTHORIZING:
95 case PA_CONTEXT_SETTING_NAME:
101 static bool __is_microphone_restricted(void) {
104 device_policy_manager_h dpm_h = nullptr;
107 if ((dpm_h = dpm_manager_create())) {
108 /* state: 0(disallowed), 1(allowed) */
109 if ((ret = dpm_restriction_get_microphone_state(dpm_h, &state)))
110 AUDIO_IO_LOGE("Failed to dpm_restriction_get_microphone_state(), ret(0x%x)", ret);
111 dpm_manager_destroy(dpm_h);
112 AUDIO_IO_LOGD("microphone restriction state: %d(1:allowed, 0:disallowed)", state);
114 AUDIO_IO_LOGE("Failed to dpm_manager_create()");
117 return (state ? false : true);
121 void CPulseAudioClient::__streamStateChangeCb(pa_stream* s, void* user_data) {
125 auto pClient = static_cast<CPulseAudioClient*>(user_data);
126 pa_stream_state_t state = pa_stream_get_state(s);
129 case PA_STREAM_UNCONNECTED:
132 case PA_STREAM_CREATING:
135 case PA_STREAM_READY:
136 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] is READY[%d]", pClient, s, PA_STREAM_READY);
137 pClient->__mpListener->setState(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING);
138 pClient->__mpListener->onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING);
139 if (pClient->__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
140 pClient->__mIsFirstStream = true;
141 pClient->__mIsInit = true;
143 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] now signaling...", pClient, s);
144 pa_threaded_mainloop_signal(pClient->__mpMainloop, 1);
145 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] signal accepted", pClient, s);
149 case PA_STREAM_FAILED:
150 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] is FAILED[%d]", pClient, s, PA_STREAM_FAILED);
151 pClient->__mpListener->setState(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE);
152 pClient->__mpListener->onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE,
153 __is_microphone_restricted());
155 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] now signaling...", pClient, s);
156 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
160 case PA_STREAM_TERMINATED:
161 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] is TERMINATED[%d]", pClient, s, PA_STREAM_TERMINATED);
162 pClient->__mpListener->setState(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE);
163 pClient->__mpListener->onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE);
165 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] now signaling...", pClient, s);
166 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
170 AUDIO_IO_LOGW("Unexpected state[%d]", state);
174 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] state[%d] done", pClient, s, state);
177 void CPulseAudioClient::__streamCaptureCb(pa_stream* s, size_t length, void* user_data) {
181 auto pClient = static_cast<CPulseAudioClient*>(user_data);
182 assert(pClient->__mpListener);
183 assert(pClient->__mpMainloop);
185 if (pClient->__mIsUsedSyncRead)
186 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
188 pClient->__mpListener->onStream(pClient, length);
191 static void __dummy_write(pa_stream* s, size_t length) {
192 pa_stream_write(s, std::vector<char>(length).data(), length, NULL, 0LL, PA_SEEK_RELATIVE);
195 void CPulseAudioClient::__streamPlaybackCb(pa_stream* s, size_t length, void* user_data) {
199 auto pClient = static_cast<CPulseAudioClient*>(user_data);
200 assert(pClient->__mpListener);
202 #ifndef DISABLE_MOBILE_BACK_COMP
203 if (!pClient->__mIsInit) {
204 AUDIO_IO_LOGD("pa_stream[%p] is on the way to create : Write dummy, length[%zu]", s, length);
205 __dummy_write(s, length);
208 if (pClient->isCorked()) {
209 AUDIO_IO_LOGD("pa_stream[%p] is CORKED : Write dummy, length[%zu]", s, length);
210 __dummy_write(s, length);
215 pClient->__mpListener->onStream(pClient, length);
217 #ifndef DISABLE_MOBILE_BACK_COMP
218 /* If stream is not written in first callback during prepare,
219 then write dummy data to ensure the start */
220 if (pClient->__mSpec.getStreamLatency() == CPulseStreamSpec::EStreamLatency::STREAM_LATENCY_OUTPUT_DEFAULT_ASYNC &&
221 pClient->__mIsFirstStream) {
222 AUDIO_IO_LOGW("[async] pa_stream[%p] : not written in the first callback during prepare, write dummy of length[%zu]",
224 __dummy_write(s, length);
225 pClient->__mIsFirstStream = false;
230 void CPulseAudioClient::__streamLatencyUpdateCb(pa_stream* s, void* user_data) {
234 auto pClient = static_cast<CPulseAudioClient*>(user_data);
236 #ifdef _AUDIO_IO_DEBUG_TIMING_
237 /* FIXME : print some useful latency info */
238 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] latency updated", pClient, s);
241 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
244 void CPulseAudioClient::__streamStartedCb(pa_stream* s, void* user_data) {
248 auto pClient = static_cast<CPulseAudioClient*>(user_data);
250 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] started", pClient, s);
252 pClient->__mIsStarted = true;
255 void CPulseAudioClient::__streamUnderflowCb(pa_stream* s, void* user_data) {
259 auto pClient = static_cast<CPulseAudioClient*>(user_data);
261 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] UnderFlow...", pClient, s);
263 pClient->__mIsStarted = false;
266 void CPulseAudioClient::__streamOverflowCb(pa_stream* s, void* user_data) {
270 auto pClient = static_cast<CPulseAudioClient*>(user_data);
272 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] OverFlow...", pClient, s);
276 void CPulseAudioClient::__streamEventCb(pa_stream* s, const char* name, pa_proplist* pl, void* user_data) {
280 auto pClient = static_cast<CPulseAudioClient*>(user_data);
282 AUDIO_IO_LOGW("pClient[%p] pa_stream[%p] : name[%s], proplist[%p]", pClient, s, name, pl);
284 if (strcmp(name, PA_STREAM_EVENT_POP_TIMEOUT) == 0) {
285 pa_operation* o = pa_stream_cork(pClient->__mpStream, 1, NULL, NULL);
287 AUDIO_IO_LOGE("pa_stream[%p] : cork failed", pClient->__mpStream);
290 pa_operation_unref(o);
295 void CPulseAudioClient::__successStreamCb(pa_stream* s, int success, void* user_data) {
299 auto pClient = static_cast<CPulseAudioClient*>(user_data);
301 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] success[%d] user_data[%p]", pClient, s, success, user_data);
303 pClient->__mIsOperationSuccess = static_cast<bool>(success);
305 /* FIXME : verify following action without any waiting */
306 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
310 void CPulseAudioClient::__successDrainCbInThread(pa_stream* s, int success, void* user_data) {
314 auto pClient = static_cast<CPulseAudioClient*>(user_data);
316 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] success[%d] user_data[%p]", pClient, s, success, user_data);
318 pClient->__mIsOperationSuccess = static_cast<bool>(success);
319 pClient->__mIsDraining = false;
323 void CPulseAudioClient::__successDrainCb(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;
334 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
337 void CPulseAudioClient::__successVolumeCb(pa_context* c, int success, void* user_data) {
338 AUDIO_IO_LOGD("pa_context[%p] success[%d] user_data[%p]", c, success, user_data);
341 void CPulseAudioClient::resetStreamCallbacks() {
345 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
346 pa_stream_set_write_callback(__mpStream, NULL, NULL);
348 pa_stream_set_read_callback(__mpStream, NULL, NULL);
350 pa_stream_set_latency_update_callback(__mpStream, NULL, NULL);
351 pa_stream_set_event_callback(__mpStream, NULL, NULL);
354 void CPulseAudioClient::resetInternalObjects() {
356 pa_threaded_mainloop_stop(__mpMainloop);
359 pa_stream_disconnect(__mpStream);
360 pa_stream_unref(__mpStream);
361 __mpStream = nullptr;
365 pa_context_disconnect(__mpContext);
366 pa_context_unref(__mpContext);
367 __mpContext = nullptr;
371 pa_threaded_mainloop_free(__mpMainloop);
372 __mpMainloop = nullptr;
376 pa_proplist_free(__mpPropList);
377 __mpPropList = nullptr;
381 void CPulseAudioClient::initialize() {
389 // Allocates PA proplist
390 __mpPropList = pa_proplist_new();
392 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_proplist_new()"); //LCOV_EXCL_LINE
394 // Adds values on proplist for delivery to PULSEAUDIO
395 auto [ streamType, streamIndex ] = __mSpec.getAudioInfo().getStreamProperties();
397 pa_proplist_sets(__mpPropList, PA_PROP_MEDIA_ROLE, streamType);
398 if (streamIndex >= 0)
399 pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_PARENT_ID, "%d", streamIndex);
401 if (__mDirection == EStreamDirection::STREAM_DIRECTION_RECORD) {
402 /* Noise-suppression effect should be set first. */
403 std::string method = __mSpec.getAudioInfo().getEffectMethod();
404 auto [ method_reference, device_id ] = __mSpec.getAudioInfo().getEffectMethodWithReference();
405 std::string method_all = method + method_reference;
407 if (!method_all.empty()) {
408 pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_PREPROCESSOR_METHOD, "%s", method_all.c_str());
409 pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_ECHO_CANCEL_REFERENCE_DEVICE, "%d", device_id);
411 AUDIO_IO_LOGD("preprocess will be set. method[%s], device_id[%d]", method_all.c_str(), device_id);
415 // Adds latency on proplist for delivery to PULSEAUDIO
416 AUDIO_IO_LOGD("LATENCY : %s[%d]", __mSpec.getStreamLatencyToString(), static_cast<int>(__mSpec.getStreamLatency()));
417 pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_TIZEN_AUDIO_LATENCY, "%s", __mSpec.getStreamLatencyToString());
419 // Allocates PA mainloop
420 __mpMainloop = pa_threaded_mainloop_new();
422 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_threaded_mainloop_new()"); //LCOV_EXCL_LINE
424 // Allocates PA context
425 __mpContext = pa_context_new(pa_threaded_mainloop_get_api(__mpMainloop), CLIENT_NAME);
427 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_context_new()"); //LCOV_EXCL_LINE
429 // Sets context state changed callback
430 pa_context_set_state_callback(__mpContext, __contextStateChangeCb, this);
432 // Connects this client with PA server
433 if (pa_context_connect(__mpContext, NULL, PA_CONTEXT_NOFLAGS, NULL) < 0)
434 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_context_connect()"); //LCOV_EXCL_LINE
436 // LOCK for synchronous connection
437 CPulseThreadLocker locker{__mpMainloop};
440 if (pa_threaded_mainloop_start(__mpMainloop) < 0) {
442 THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_threaded_mainloop_start()");
446 // Connection process is asynchronously
447 // So, this function will be waited when occurred context state change event
448 // If I got a signal, do next processing
450 pa_context_state_t state;
451 state = pa_context_get_state(__mpContext);
453 if (state == PA_CONTEXT_READY)
456 if (!PA_CONTEXT_IS_GOOD(state)) {
458 err = pa_context_errno(__mpContext);
459 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION,
460 "pa_context's state is not good : err[%d]", err);
464 /* Wait until the context is ready */
465 pa_threaded_mainloop_wait(__mpMainloop);
468 AUDIO_IO_LOGD("pa_context[%p] now ready", __mpContext);
470 // Allocates PA stream
471 pa_sample_spec ss = __mSpec.getSampleSpec();
472 pa_channel_map map = __mSpec.getChannelMap();
474 __mpStream = pa_stream_new_with_proplist(__mpContext, __mSpec.getStreamName(), &ss, &map, __mpPropList);
477 THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_new_with_proplist()");
481 // Sets stream callbacks
482 pa_stream_set_state_callback(__mpStream, __streamStateChangeCb, this);
483 pa_stream_set_read_callback(__mpStream, __streamCaptureCb, this);
484 pa_stream_set_write_callback(__mpStream, __streamPlaybackCb, this);
485 pa_stream_set_latency_update_callback(__mpStream, __streamLatencyUpdateCb, this);
486 pa_stream_set_event_callback(__mpStream, __streamEventCb, this);
487 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
488 pa_stream_set_started_callback(__mpStream, __streamStartedCb, this);
489 pa_stream_set_underflow_callback(__mpStream, __streamUnderflowCb, this);
490 pa_stream_set_overflow_callback(__mpStream, __streamOverflowCb, this);
493 // Connect stream with PA Server
495 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
496 auto flags = static_cast<pa_stream_flags_t>(
497 PA_STREAM_INTERPOLATE_TIMING |
498 PA_STREAM_ADJUST_LATENCY |
499 #ifndef DISABLE_MOBILE_BACK_COMP
500 PA_STREAM_START_CORKED |
502 PA_STREAM_AUTO_TIMING_UPDATE);
504 ret = pa_stream_connect_playback(__mpStream, NULL, NULL, flags, NULL, NULL);
506 auto flags = static_cast<pa_stream_flags_t>(
507 PA_STREAM_INTERPOLATE_TIMING |
508 PA_STREAM_ADJUST_LATENCY |
509 #ifndef DISABLE_MOBILE_BACK_COMP
510 PA_STREAM_START_CORKED |
512 PA_STREAM_AUTO_TIMING_UPDATE);
514 ret = pa_stream_connect_record(__mpStream, NULL, NULL, flags);
518 err = pa_context_errno(__mpContext);
519 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
520 "Failed pa_stream_connect() : err[%d]", err);
524 AUDIO_IO_LOGD("pa_stream[%p] now wait for stream ready...", __mpStream);
527 pa_stream_state_t state = pa_stream_get_state(__mpStream);
528 AUDIO_IO_LOGD("pa_stream[%p] current state[%d]", __mpStream, state);
530 if (state == PA_STREAM_READY)
533 if (!PA_STREAM_IS_GOOD(state)) {
534 err = pa_context_errno(__mpContext);
535 if (err == PA_ERR_ACCESS)
536 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_DEVICE_POLICY_RESTRICTION,
537 "pa_stream's state is not good : err[%d]", err);
539 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, //LCOV_EXCL_LINE
540 "pa_stream's state is not good : err[%d]", err); //LCOV_EXCL_LINE
543 /* Wait until the stream is ready */
544 AUDIO_IO_LOGD("pa_mainloop[%p] signal wait...", __mpMainloop);
545 pa_threaded_mainloop_wait(__mpMainloop);
546 AUDIO_IO_LOGD("pa_mainloop[%p] signal wait done", __mpMainloop);
548 pa_threaded_mainloop_accept(__mpMainloop);
550 // __mIsInit = true; // Moved to __streamStateChangeCb()
551 } catch (const CAudioError& e) {
553 resetStreamCallbacks();
554 resetInternalObjects();
559 AUDIO_IO_LOGD("Done : pa_context[%p], pa_mainloop[%p], pa_stream[%p]", __mpContext, __mpMainloop, __mpStream);
562 void CPulseAudioClient::finalize() {
563 AUDIO_IO_LOGD("pa_context[%p], pa_mainloop[%p], pa_stream[%p]", __mpContext, __mpMainloop, __mpStream);
568 bool is_in_thread = isInThread();
570 pa_threaded_mainloop_lock(__mpMainloop);
574 resetStreamCallbacks();
577 pa_threaded_mainloop_unlock(__mpMainloop);
579 /* Wait for drain complete if draining before finalize */
581 unsigned int drain_wait_count = 0;
582 while (__mIsDraining && drain_wait_count++ < drain_wait_max_count)
583 usleep(drain_wait_interval);
584 AUDIO_IO_LOGD("wait for drain complete!!!! [%d * %d usec]",
585 drain_wait_count, drain_wait_interval);
588 resetInternalObjects();
590 AUDIO_IO_LOGD("Done");
593 int CPulseAudioClient::read(void* buffer, size_t length) {
595 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); //LCOV_EXCL_LINE
600 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "invalid parameter : buffer[%p]", buffer); //LCOV_EXCL_LINE
602 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
603 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback client can't use this function"); //LCOV_EXCL_LINE
605 size_t lengthIter = length;
608 __mIsUsedSyncRead = true;
611 CPulseThreadLocker locker{__mpMainloop};
613 while (lengthIter > 0) {
616 while (!__mpSyncReadDataPtr) {
617 ret = pa_stream_peek(__mpStream, &__mpSyncReadDataPtr, &__mSyncReadLength);
619 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_peek() : ret[%d]", ret); //LCOV_EXCL_LINE
621 if (__mSyncReadLength <= 0) {
622 #ifdef _AUDIO_IO_DEBUG_TIMING_
623 AUDIO_IO_LOGD("readLength(%zu byte) is not valid. wait...", __mSyncReadLength);
625 pa_threaded_mainloop_wait(__mpMainloop);
626 } else if (!__mpSyncReadDataPtr) {
628 // Data peeked, but it doesn't have any data
629 ret = pa_stream_drop(__mpStream);
631 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_drop() : ret[%d]", ret);
634 __mSyncReadIndex = 0;
638 l = min(__mSyncReadLength, lengthIter);
640 // Copy partial pcm data on out parameter
641 #ifdef _AUDIO_IO_DEBUG_TIMING_
642 AUDIO_IO_LOGD("memcpy() that a peeked buffer[%p], index[%zu], length[%zu] on out buffer", (const uint8_t*)(__mpSyncReadDataPtr) + __mSyncReadIndex, __mSyncReadIndex, l);
644 memcpy(buffer, (const uint8_t*)__mpSyncReadDataPtr + __mSyncReadIndex, l);
646 // Move next position
647 buffer = (uint8_t*)buffer + l;
650 // Adjusts the rest length
651 __mSyncReadIndex += l;
652 __mSyncReadLength -= l;
654 if (__mSyncReadLength == 0) {
655 #ifdef _AUDIO_IO_DEBUG_TIMING_
656 AUDIO_IO_LOGD("__mSyncReadLength is zero, do drop()");
658 ret = pa_stream_drop(__mpStream);
660 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, //LCOV_EXCL_LINE
661 "Failed pa_stream_drop() : ret[%d]", ret); //LCOV_EXCL_LINE
663 // Reset the internal pointer
664 __mpSyncReadDataPtr = nullptr;
665 __mSyncReadLength = 0;
666 __mSyncReadIndex = 0;
668 } // End of while (lengthIter > 0)
670 __mIsUsedSyncRead = false;
671 } catch (const CAudioError& e) {
673 __mIsUsedSyncRead = false;
681 int CPulseAudioClient::peek(const void** buffer, size_t* length) {
683 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
687 if (!buffer || !length)
688 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, // LCOV_EXCL_LINE
689 "invalid parameter : buffer[%p], length[%p]", buffer, length); // LCOV_EXCL_LINE
691 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
692 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
694 CPulseThreadLocker locker{__mpMainloop};
696 int ret = pa_stream_peek(__mpStream, buffer, length);
699 #ifdef _AUDIO_IO_DEBUG_TIMING_
700 AUDIO_IO_LOGD("buffer[%p], length[%zu]", *buffer, *length);
704 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_peek() : err[%d]", ret); //LCOV_EXCL_LINE
709 int CPulseAudioClient::drop() {
711 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
713 #ifdef _AUDIO_IO_DEBUG_TIMING_
719 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
720 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
722 CPulseThreadLocker locker{__mpMainloop};
724 int ret = pa_stream_drop(__mpStream);
726 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_drop() : err[%d]", ret); //LCOV_EXCL_LINE
731 int CPulseAudioClient::write(const void* data, size_t length) {
733 THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_ARGUMENT, "invalid parameter"); // LCOV_EXCL_LINE
735 if (__mDirection == EStreamDirection::STREAM_DIRECTION_RECORD)
736 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
740 #ifdef _AUDIO_IO_DEBUG_TIMING_
741 AUDIO_IO_LOGD("data[%p], length[%zu], First[%d]", data, length, __mIsFirstStream);
745 CPulseThreadLocker locker{__mpMainloop};
746 if (pa_stream_is_corked(__mpStream)) {
747 AUDIO_IO_LOGW("pa_stream[%p] is corked...do uncork here first!!!!", __mpStream);
748 pa_operation* o = pa_stream_cork(__mpStream, 0, NULL, NULL);
750 AUDIO_IO_LOGE("pa_stream[%p] : uncork failed", __mpStream);
752 pa_operation_unref(o);
755 ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
758 if (pa_stream_is_corked(__mpStream)) {
759 AUDIO_IO_LOGW("pa_stream[%p] is corked...do uncork here first!!!!", __mpStream);
760 pa_operation* o = pa_stream_cork(__mpStream, 0, NULL, NULL);
762 AUDIO_IO_LOGE("pa_stream[%p] : uncork failed", __mpStream);
764 pa_operation_unref(o);
767 if (__mIsFirstStream) {
768 const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
769 uint32_t prebuf = attr->prebuf;
770 // Compensate amount of prebuf in first stream callback when audio-io use prebuf(-1)
771 // Because a stream will never start when an application wrote less than prebuf at first
773 __dummy_write(__mpStream, prebuf - length);
775 __mIsFirstStream = false;
776 AUDIO_IO_LOGW("FIRST STREAM CALLBACK : length[%zu], prebuf[%d], dummy[%zu]",
777 length, prebuf, (length < prebuf) ? prebuf - length : 0);
779 ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
784 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_write() : err[%d]", ret); //LCOV_EXCL_LINE
789 void CPulseAudioClient::cork(bool cork) {
790 AUDIO_IO_LOGD("cork[%d]", cork);
793 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
796 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This operation is not supported in callback"); // LCOV_EXCL_LINE
800 // Set __mIsFirstStream flag when uncork(resume) stream, because prebuf will be enable again
802 __mIsFirstStream = true;
804 CPulseThreadLocker locker{__mpMainloop};
806 /* FIXME: wait for completion like drain? */
807 pa_operation* o = pa_stream_cork(__mpStream, static_cast<int>(cork), __successStreamCb, this);
809 AUDIO_IO_LOGE("pa_stream[%p] : cork[%d] failed", __mpStream, cork);
812 pa_operation_unref(o);
813 AUDIO_IO_LOGD("cork[%d] done", cork);
816 bool CPulseAudioClient::isCorked() {
818 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
822 CPulseThreadLocker locker{__mpMainloop};
824 int isCorked = pa_stream_is_corked(__mpStream);
826 #ifdef _AUDIO_IO_DEBUG_TIMING_
827 AUDIO_IO_LOGD("isCorked[%d]", isCorked);
829 return static_cast<bool>(isCorked);
832 bool CPulseAudioClient::drain() {
834 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
839 AUDIO_IO_LOGW("Corked...");
844 AUDIO_IO_LOGW("already draining...");
849 AUDIO_IO_LOGW("stream not started yet...skip drain");
854 AUDIO_IO_LOGD("drain");
855 CPulseThreadLocker locker{__mpMainloop};
857 pa_operation* o = pa_stream_drain(__mpStream, __successDrainCb, this);
858 __mIsDraining = true;
859 while (pa_operation_get_state(o) == PA_OPERATION_RUNNING)
860 pa_threaded_mainloop_wait(__mpMainloop);
861 pa_operation_unref(o);
863 AUDIO_IO_LOGD("drain done");
865 AUDIO_IO_LOGD("drain in thread");
866 pa_operation* o = pa_stream_drain(__mpStream, __successDrainCbInThread, this);
868 AUDIO_IO_LOGE("pa_stream[%p] : drain failed", __mpStream);
871 pa_operation_unref(o);
872 __mIsDraining = true;
878 bool CPulseAudioClient::flush() {
880 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
884 CPulseThreadLocker locker{__mpMainloop};
886 /* FIXME: wait for completion like drain? */
887 pa_operation* o = pa_stream_flush(__mpStream, __successStreamCb, this);
889 AUDIO_IO_LOGE("pa_stream[%p] : flush failed", __mpStream);
892 pa_operation_unref(o);
897 size_t CPulseAudioClient::getWritableSize() {
899 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
903 if (__mDirection != EStreamDirection::STREAM_DIRECTION_PLAYBACK)
904 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Playback"); // LCOV_EXCL_LINE
906 CPulseThreadLocker locker{__mpMainloop};
908 return pa_stream_writable_size(__mpStream);
911 void CPulseAudioClient::checkRunningState() {
912 if (!__mpContext || !PA_CONTEXT_IS_GOOD(pa_context_get_state(__mpContext)))
913 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, // LCOV_EXCL_LINE
914 "The context[%p] is not created or not good state", __mpContext); // LCOV_EXCL_LINE
916 if (!__mpStream || !PA_STREAM_IS_GOOD(pa_stream_get_state(__mpStream)))
917 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, // LCOV_EXCL_LINE
918 "The stream[%p] is not created or not good state", __mpStream); // LCOV_EXCL_LINE
920 if (pa_context_get_state(__mpContext) != PA_CONTEXT_READY || pa_stream_get_state(__mpStream) != PA_STREAM_READY)
921 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, // LCOV_EXCL_LINE
922 "The context[%p] or stream[%p] state is not ready", __mpContext, __mpStream); // LCOV_EXCL_LINE
924 #ifdef _AUDIO_IO_DEBUG_TIMING_
925 AUDIO_IO_LOGD("This client is running");
929 bool CPulseAudioClient::isInThread() const {
931 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "__mIsInit is null");
934 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "__mpMainloop is null");
936 int ret = pa_threaded_mainloop_in_thread(__mpMainloop);
938 #ifdef _AUDIO_IO_DEBUG_TIMING_
939 AUDIO_IO_LOGD("isInThread[%d]", ret);
941 return static_cast<bool>(ret);
945 size_t CPulseAudioClient::getReadableSize() {
947 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
951 if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD)
952 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Capture");
954 CPulseThreadLocker locker{__mpMainloop};
956 return pa_stream_readable_size(__mpStream);
959 size_t CPulseAudioClient::getBufferSize() {
961 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
965 size_t buffer_size = 0;
966 CPulseThreadLocker locker{__mpMainloop};
968 const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
970 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
971 "Failed pa_stream_get_buffer_attr() : err[%d]", pa_context_errno(__mpContext));
973 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
974 buffer_size = attr->tlength;
975 AUDIO_IO_LOGD("PLAYBACK buffer size[%zu]", buffer_size);
977 buffer_size = attr->fragsize;
978 AUDIO_IO_LOGD("RECORD buffer size[%zu]", buffer_size);
984 pa_usec_t CPulseAudioClient::getLatency() {
986 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
990 pa_usec_t latency = 0;
994 if (pa_stream_get_latency(__mpStream, &latency, &negative) < 0) {
995 int _err = pa_context_errno(__mpContext);
996 if (_err != PA_ERR_NODATA)
997 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
998 "Failed pa_stream_get_latency() : err[%d]", _err);
1000 return negative ? 0 : latency;
1003 CPulseThreadLocker locker{__mpMainloop};
1005 while (pa_stream_get_latency(__mpStream, &latency, &negative) < 0) {
1006 int _err = pa_context_errno(__mpContext);
1007 if (_err != PA_ERR_NODATA)
1008 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
1009 "Failed pa_stream_get_latency() : err[%d]", _err);
1010 /* Wait until latency data is available again */
1011 pa_threaded_mainloop_wait(__mpMainloop);
1014 return negative ? 0 : latency;
1017 pa_usec_t CPulseAudioClient::getFinalLatency() {
1019 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
1021 checkRunningState();
1023 pa_usec_t latency = 0;
1025 CPulseThreadLocker locker{__mpMainloop};
1027 uint32_t ver = pa_context_get_server_protocol_version(__mpContext);
1029 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_SUPPORTED, "This version(ver.%d) is not supported", ver);
1031 const pa_buffer_attr* buffer_attr = pa_stream_get_buffer_attr(__mpStream);
1032 const pa_sample_spec* sample_spec = pa_stream_get_sample_spec(__mpStream);
1033 const pa_timing_info* timing_info = pa_stream_get_timing_info(__mpStream);
1035 if (!buffer_attr || !sample_spec || !timing_info)
1036 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_OUT_OF_MEMORY,
1037 "Failed to get buffer_attr[%p] or sample_spec[%p] or timing_info[%p] from a pa_stream",
1038 buffer_attr, sample_spec, timing_info);
1040 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
1041 latency = (pa_bytes_to_usec(buffer_attr->tlength, sample_spec) + timing_info->configured_sink_usec);
1042 AUDIO_IO_LOGD("FINAL PLAYBACK LATENCY[%" PRIu64 "]", latency);
1044 latency = (pa_bytes_to_usec(buffer_attr->fragsize, sample_spec) + timing_info->configured_source_usec);
1045 AUDIO_IO_LOGD("FINAL RECORD LATENCY[%" PRIu64 "]", latency);
1052 void CPulseAudioClient::applyRecordVolume(double volume) {
1055 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
1057 checkRunningState();
1059 if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD)
1060 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client can't use this function"); //LCOV_EXCL_LINE
1062 CPulseThreadLocker locker{__mpMainloop};
1064 pa_cvolume cv = { 0, };
1065 pa_volume_t v = PA_VOLUME_NORM * volume;
1067 pa_cvolume_set(&cv, __mSpec.getChannelMap().channels, v);
1069 pa_operation_unref(pa_context_set_source_output_volume(__mpContext,
1070 pa_stream_get_index(__mpStream), &cv, __successVolumeCb, NULL));