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 int reference_id = __mSpec.getAudioInfo().getEchoCancelReferenceDeviceId();
416 if (reference_id > 0) {
417 pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_ECHO_CANCEL_REFERENCE_DEVICE, "%d", reference_id);
420 if (!__mSpec.getAudioInfo().getProcessorProperty().empty())
421 pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_PREPROCESSOR_METHOD, "%s",
422 __mSpec.getAudioInfo().getProcessorProperty().c_str());
425 // Adds latency on proplist for delivery to PULSEAUDIO
426 AUDIO_IO_LOGD("LATENCY : %s[%d]", __mSpec.getStreamLatencyToString(), static_cast<int>(__mSpec.getStreamLatency()));
427 pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_TIZEN_AUDIO_LATENCY, "%s", __mSpec.getStreamLatencyToString());
429 // Allocates PA mainloop
430 __mpMainloop = pa_threaded_mainloop_new();
432 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_threaded_mainloop_new()"); //LCOV_EXCL_LINE
434 // Allocates PA context
435 __mpContext = pa_context_new(pa_threaded_mainloop_get_api(__mpMainloop), CLIENT_NAME);
437 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_context_new()"); //LCOV_EXCL_LINE
439 // Sets context state changed callback
440 pa_context_set_state_callback(__mpContext, __contextStateChangeCb, this);
442 // Connects this client with PA server
443 if (pa_context_connect(__mpContext, NULL, PA_CONTEXT_NOFLAGS, NULL) < 0)
444 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_context_connect()"); //LCOV_EXCL_LINE
446 // LOCK for synchronous connection
447 CPulseThreadLocker locker{__mpMainloop};
450 if (pa_threaded_mainloop_start(__mpMainloop) < 0) {
452 THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_threaded_mainloop_start()");
456 // Connection process is asynchronously
457 // So, this function will be waited when occurred context state change event
458 // If I got a signal, do next processing
460 pa_context_state_t state;
461 state = pa_context_get_state(__mpContext);
463 if (state == PA_CONTEXT_READY)
466 if (!PA_CONTEXT_IS_GOOD(state)) {
468 err = pa_context_errno(__mpContext);
469 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION,
470 "pa_context's state is not good : err[%d]", err);
474 /* Wait until the context is ready */
475 pa_threaded_mainloop_wait(__mpMainloop);
478 AUDIO_IO_LOGD("pa_context[%p] now ready", __mpContext);
480 // Allocates PA stream
481 pa_sample_spec ss = __mSpec.getSampleSpec();
482 pa_channel_map map = __mSpec.getChannelMap();
484 __mpStream = pa_stream_new_with_proplist(__mpContext, __mSpec.getStreamName(), &ss, &map, __mpPropList);
487 THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_new_with_proplist()");
491 // Sets stream callbacks
492 pa_stream_set_state_callback(__mpStream, __streamStateChangeCb, this);
493 pa_stream_set_read_callback(__mpStream, __streamCaptureCb, this);
494 pa_stream_set_write_callback(__mpStream, __streamPlaybackCb, this);
495 pa_stream_set_latency_update_callback(__mpStream, __streamLatencyUpdateCb, this);
496 pa_stream_set_event_callback(__mpStream, __streamEventCb, this);
497 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
498 pa_stream_set_started_callback(__mpStream, __streamStartedCb, this);
499 pa_stream_set_underflow_callback(__mpStream, __streamUnderflowCb, this);
500 pa_stream_set_overflow_callback(__mpStream, __streamOverflowCb, this);
503 // Connect stream with PA Server
505 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
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_playback(__mpStream, NULL, NULL, flags, NULL, NULL);
516 auto flags = static_cast<pa_stream_flags_t>(
517 PA_STREAM_INTERPOLATE_TIMING |
518 PA_STREAM_ADJUST_LATENCY |
519 #ifndef DISABLE_MOBILE_BACK_COMP
520 PA_STREAM_START_CORKED |
522 PA_STREAM_AUTO_TIMING_UPDATE);
524 ret = pa_stream_connect_record(__mpStream, NULL, NULL, flags);
528 err = pa_context_errno(__mpContext);
529 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
530 "Failed pa_stream_connect() : err[%d]", err);
534 AUDIO_IO_LOGD("pa_stream[%p] now wait for stream ready...", __mpStream);
537 pa_stream_state_t state = pa_stream_get_state(__mpStream);
538 AUDIO_IO_LOGD("pa_stream[%p] current state[%d]", __mpStream, state);
540 if (state == PA_STREAM_READY)
543 if (!PA_STREAM_IS_GOOD(state)) {
544 err = pa_context_errno(__mpContext);
545 if (err == PA_ERR_ACCESS)
546 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_DEVICE_POLICY_RESTRICTION,
547 "pa_stream's state is not good : err[%d]", err);
549 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, //LCOV_EXCL_LINE
550 "pa_stream's state is not good : err[%d]", err); //LCOV_EXCL_LINE
553 /* Wait until the stream is ready */
554 AUDIO_IO_LOGD("pa_mainloop[%p] signal wait...", __mpMainloop);
555 pa_threaded_mainloop_wait(__mpMainloop);
556 AUDIO_IO_LOGD("pa_mainloop[%p] signal wait done", __mpMainloop);
558 pa_threaded_mainloop_accept(__mpMainloop);
560 // __mIsInit = true; // Moved to __streamStateChangeCb()
561 } catch (const CAudioError& e) {
563 resetStreamCallbacks();
564 resetInternalObjects();
569 AUDIO_IO_LOGD("Done : pa_context[%p], pa_mainloop[%p], pa_stream[%p]", __mpContext, __mpMainloop, __mpStream);
572 void CPulseAudioClient::finalize() {
573 AUDIO_IO_LOGD("pa_context[%p], pa_mainloop[%p], pa_stream[%p]", __mpContext, __mpMainloop, __mpStream);
578 bool is_in_thread = isInThread();
580 pa_threaded_mainloop_lock(__mpMainloop);
584 resetStreamCallbacks();
587 pa_threaded_mainloop_unlock(__mpMainloop);
589 /* Wait for drain complete if draining before finalize */
591 unsigned int drain_wait_count = 0;
592 while (__mIsDraining && drain_wait_count++ < drain_wait_max_count)
593 usleep(drain_wait_interval);
594 AUDIO_IO_LOGD("wait for drain complete!!!! [%d * %d usec]",
595 drain_wait_count, drain_wait_interval);
598 resetInternalObjects();
600 AUDIO_IO_LOGD("Done");
603 int CPulseAudioClient::read(void* buffer, size_t length) {
605 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); //LCOV_EXCL_LINE
610 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "invalid parameter : buffer[%p]", buffer); //LCOV_EXCL_LINE
612 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
613 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback client can't use this function"); //LCOV_EXCL_LINE
615 size_t lengthIter = length;
618 __mIsUsedSyncRead = true;
621 CPulseThreadLocker locker{__mpMainloop};
623 while (lengthIter > 0) {
626 while (!__mpSyncReadDataPtr) {
627 ret = pa_stream_peek(__mpStream, &__mpSyncReadDataPtr, &__mSyncReadLength);
629 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_peek() : ret[%d]", ret); //LCOV_EXCL_LINE
631 if (__mSyncReadLength <= 0) {
632 #ifdef _AUDIO_IO_DEBUG_TIMING_
633 AUDIO_IO_LOGD("readLength(%zu byte) is not valid. wait...", __mSyncReadLength);
635 pa_threaded_mainloop_wait(__mpMainloop);
636 } else if (!__mpSyncReadDataPtr) {
638 // Data peeked, but it doesn't have any data
639 ret = pa_stream_drop(__mpStream);
641 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_drop() : ret[%d]", ret);
644 __mSyncReadIndex = 0;
648 l = min(__mSyncReadLength, lengthIter);
650 // Copy partial pcm data on out parameter
651 #ifdef _AUDIO_IO_DEBUG_TIMING_
652 AUDIO_IO_LOGD("memcpy() that a peeked buffer[%p], index[%zu], length[%zu] on out buffer", (const uint8_t*)(__mpSyncReadDataPtr) + __mSyncReadIndex, __mSyncReadIndex, l);
654 memcpy(buffer, (const uint8_t*)__mpSyncReadDataPtr + __mSyncReadIndex, l);
656 // Move next position
657 buffer = (uint8_t*)buffer + l;
660 // Adjusts the rest length
661 __mSyncReadIndex += l;
662 __mSyncReadLength -= l;
664 if (__mSyncReadLength == 0) {
665 #ifdef _AUDIO_IO_DEBUG_TIMING_
666 AUDIO_IO_LOGD("__mSyncReadLength is zero, do drop()");
668 ret = pa_stream_drop(__mpStream);
670 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, //LCOV_EXCL_LINE
671 "Failed pa_stream_drop() : ret[%d]", ret); //LCOV_EXCL_LINE
673 // Reset the internal pointer
674 __mpSyncReadDataPtr = nullptr;
675 __mSyncReadLength = 0;
676 __mSyncReadIndex = 0;
678 } // End of while (lengthIter > 0)
680 __mIsUsedSyncRead = false;
681 } catch (const CAudioError& e) {
683 __mIsUsedSyncRead = false;
691 int CPulseAudioClient::peek(const void** buffer, size_t* length) {
693 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
697 if (!buffer || !length)
698 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, // LCOV_EXCL_LINE
699 "invalid parameter : buffer[%p], length[%p]", buffer, length); // LCOV_EXCL_LINE
701 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
702 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
704 CPulseThreadLocker locker{__mpMainloop};
706 int ret = pa_stream_peek(__mpStream, buffer, length);
709 #ifdef _AUDIO_IO_DEBUG_TIMING_
710 AUDIO_IO_LOGD("buffer[%p], length[%zu]", *buffer, *length);
714 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_peek() : err[%d]", ret); //LCOV_EXCL_LINE
719 int CPulseAudioClient::drop() {
721 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
723 #ifdef _AUDIO_IO_DEBUG_TIMING_
729 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
730 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
732 CPulseThreadLocker locker{__mpMainloop};
734 int ret = pa_stream_drop(__mpStream);
736 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_drop() : err[%d]", ret); //LCOV_EXCL_LINE
741 int CPulseAudioClient::write(const void* data, size_t length) {
743 THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_ARGUMENT, "invalid parameter"); // LCOV_EXCL_LINE
745 if (__mDirection == EStreamDirection::STREAM_DIRECTION_RECORD)
746 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
750 #ifdef _AUDIO_IO_DEBUG_TIMING_
751 AUDIO_IO_LOGD("data[%p], length[%zu], First[%d]", data, length, __mIsFirstStream);
755 CPulseThreadLocker locker{__mpMainloop};
756 if (pa_stream_is_corked(__mpStream)) {
757 AUDIO_IO_LOGW("pa_stream[%p] is corked...do uncork here first!!!!", __mpStream);
758 pa_operation* o = pa_stream_cork(__mpStream, 0, NULL, NULL);
760 AUDIO_IO_LOGE("pa_stream[%p] : uncork failed", __mpStream);
762 pa_operation_unref(o);
765 ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
768 if (pa_stream_is_corked(__mpStream)) {
769 AUDIO_IO_LOGW("pa_stream[%p] is corked...do uncork here first!!!!", __mpStream);
770 pa_operation* o = pa_stream_cork(__mpStream, 0, NULL, NULL);
772 AUDIO_IO_LOGE("pa_stream[%p] : uncork failed", __mpStream);
774 pa_operation_unref(o);
777 if (__mIsFirstStream) {
778 const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
779 uint32_t prebuf = attr->prebuf;
780 // Compensate amount of prebuf in first stream callback when audio-io use prebuf(-1)
781 // Because a stream will never start when an application wrote less than prebuf at first
783 __dummy_write(__mpStream, prebuf - length);
785 __mIsFirstStream = false;
786 AUDIO_IO_LOGW("FIRST STREAM CALLBACK : length[%zu], prebuf[%d], dummy[%zu]",
787 length, prebuf, (length < prebuf) ? prebuf - length : 0);
789 ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
794 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_write() : err[%d]", ret); //LCOV_EXCL_LINE
799 void CPulseAudioClient::cork(bool cork) {
800 AUDIO_IO_LOGD("cork[%d]", cork);
803 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
806 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This operation is not supported in callback"); // LCOV_EXCL_LINE
810 // Set __mIsFirstStream flag when uncork(resume) stream, because prebuf will be enable again
812 __mIsFirstStream = true;
814 CPulseThreadLocker locker{__mpMainloop};
816 /* FIXME: wait for completion like drain? */
817 pa_operation* o = pa_stream_cork(__mpStream, static_cast<int>(cork), __successStreamCb, this);
819 AUDIO_IO_LOGE("pa_stream[%p] : cork[%d] failed", __mpStream, cork);
822 pa_operation_unref(o);
823 AUDIO_IO_LOGD("cork[%d] done", cork);
826 bool CPulseAudioClient::isCorked() {
828 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
832 CPulseThreadLocker locker{__mpMainloop};
834 int isCorked = pa_stream_is_corked(__mpStream);
836 #ifdef _AUDIO_IO_DEBUG_TIMING_
837 AUDIO_IO_LOGD("isCorked[%d]", isCorked);
839 return static_cast<bool>(isCorked);
842 bool CPulseAudioClient::drain() {
844 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
849 AUDIO_IO_LOGW("Corked...");
854 AUDIO_IO_LOGW("already draining...");
859 AUDIO_IO_LOGW("stream not started yet...skip drain");
864 AUDIO_IO_LOGD("drain");
865 CPulseThreadLocker locker{__mpMainloop};
867 pa_operation* o = pa_stream_drain(__mpStream, __successDrainCb, this);
868 __mIsDraining = true;
869 while (pa_operation_get_state(o) == PA_OPERATION_RUNNING)
870 pa_threaded_mainloop_wait(__mpMainloop);
871 pa_operation_unref(o);
873 AUDIO_IO_LOGD("drain done");
875 AUDIO_IO_LOGD("drain in thread");
876 pa_operation* o = pa_stream_drain(__mpStream, __successDrainCbInThread, this);
878 AUDIO_IO_LOGE("pa_stream[%p] : drain failed", __mpStream);
881 pa_operation_unref(o);
882 __mIsDraining = true;
888 bool CPulseAudioClient::flush() {
890 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
894 CPulseThreadLocker locker{__mpMainloop};
896 /* FIXME: wait for completion like drain? */
897 pa_operation* o = pa_stream_flush(__mpStream, __successStreamCb, this);
899 AUDIO_IO_LOGE("pa_stream[%p] : flush failed", __mpStream);
902 pa_operation_unref(o);
907 size_t CPulseAudioClient::getWritableSize() {
909 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
913 if (__mDirection != EStreamDirection::STREAM_DIRECTION_PLAYBACK)
914 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Playback"); // LCOV_EXCL_LINE
916 CPulseThreadLocker locker{__mpMainloop};
918 return pa_stream_writable_size(__mpStream);
921 void CPulseAudioClient::checkRunningState() {
922 if (!__mpContext || !PA_CONTEXT_IS_GOOD(pa_context_get_state(__mpContext)))
923 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, // LCOV_EXCL_LINE
924 "The context[%p] is not created or not good state", __mpContext); // LCOV_EXCL_LINE
926 if (!__mpStream || !PA_STREAM_IS_GOOD(pa_stream_get_state(__mpStream)))
927 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, // LCOV_EXCL_LINE
928 "The stream[%p] is not created or not good state", __mpStream); // LCOV_EXCL_LINE
930 if (pa_context_get_state(__mpContext) != PA_CONTEXT_READY || pa_stream_get_state(__mpStream) != PA_STREAM_READY)
931 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, // LCOV_EXCL_LINE
932 "The context[%p] or stream[%p] state is not ready", __mpContext, __mpStream); // LCOV_EXCL_LINE
934 #ifdef _AUDIO_IO_DEBUG_TIMING_
935 AUDIO_IO_LOGD("This client is running");
939 bool CPulseAudioClient::isInThread() const {
941 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "__mIsInit is null");
944 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "__mpMainloop is null");
946 int ret = pa_threaded_mainloop_in_thread(__mpMainloop);
948 #ifdef _AUDIO_IO_DEBUG_TIMING_
949 AUDIO_IO_LOGD("isInThread[%d]", ret);
951 return static_cast<bool>(ret);
955 size_t CPulseAudioClient::getReadableSize() {
957 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
961 if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD)
962 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Capture");
964 CPulseThreadLocker locker{__mpMainloop};
966 return pa_stream_readable_size(__mpStream);
969 size_t CPulseAudioClient::getBufferSize() {
971 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
975 size_t buffer_size = 0;
976 CPulseThreadLocker locker{__mpMainloop};
978 const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
980 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
981 "Failed pa_stream_get_buffer_attr() : err[%d]", pa_context_errno(__mpContext));
983 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
984 buffer_size = attr->tlength;
985 AUDIO_IO_LOGD("PLAYBACK buffer size[%zu]", buffer_size);
987 buffer_size = attr->fragsize;
988 AUDIO_IO_LOGD("RECORD buffer size[%zu]", buffer_size);
994 pa_usec_t CPulseAudioClient::getLatency() {
996 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
1000 pa_usec_t latency = 0;
1003 if (!isInThread()) {
1004 if (pa_stream_get_latency(__mpStream, &latency, &negative) < 0) {
1005 int _err = pa_context_errno(__mpContext);
1006 if (_err != PA_ERR_NODATA)
1007 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
1008 "Failed pa_stream_get_latency() : err[%d]", _err);
1010 return negative ? 0 : latency;
1013 CPulseThreadLocker locker{__mpMainloop};
1015 while (pa_stream_get_latency(__mpStream, &latency, &negative) < 0) {
1016 int _err = pa_context_errno(__mpContext);
1017 if (_err != PA_ERR_NODATA)
1018 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
1019 "Failed pa_stream_get_latency() : err[%d]", _err);
1020 /* Wait until latency data is available again */
1021 pa_threaded_mainloop_wait(__mpMainloop);
1024 return negative ? 0 : latency;
1027 pa_usec_t CPulseAudioClient::getFinalLatency() {
1029 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
1031 checkRunningState();
1033 pa_usec_t latency = 0;
1035 CPulseThreadLocker locker{__mpMainloop};
1037 uint32_t ver = pa_context_get_server_protocol_version(__mpContext);
1039 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_SUPPORTED, "This version(ver.%d) is not supported", ver);
1041 const pa_buffer_attr* buffer_attr = pa_stream_get_buffer_attr(__mpStream);
1042 const pa_sample_spec* sample_spec = pa_stream_get_sample_spec(__mpStream);
1043 const pa_timing_info* timing_info = pa_stream_get_timing_info(__mpStream);
1045 if (!buffer_attr || !sample_spec || !timing_info)
1046 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_OUT_OF_MEMORY,
1047 "Failed to get buffer_attr[%p] or sample_spec[%p] or timing_info[%p] from a pa_stream",
1048 buffer_attr, sample_spec, timing_info);
1050 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
1051 latency = (pa_bytes_to_usec(buffer_attr->tlength, sample_spec) + timing_info->configured_sink_usec);
1052 AUDIO_IO_LOGD("FINAL PLAYBACK LATENCY[%" PRIu64 "]", latency);
1054 latency = (pa_bytes_to_usec(buffer_attr->fragsize, sample_spec) + timing_info->configured_source_usec);
1055 AUDIO_IO_LOGD("FINAL RECORD LATENCY[%" PRIu64 "]", latency);
1062 void CPulseAudioClient::applyRecordVolume(double volume) {
1065 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
1067 checkRunningState();
1069 if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD)
1070 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client can't use this function"); //LCOV_EXCL_LINE
1072 CPulseThreadLocker locker{__mpMainloop};
1074 pa_cvolume cv = { 0, };
1075 pa_volume_t v = PA_VOLUME_NORM * volume;
1077 pa_cvolume_set(&cv, __mSpec.getChannelMap().channels, v);
1079 pa_operation_unref(pa_context_set_source_output_volume(__mpContext,
1080 pa_stream_get_index(__mpStream), &cv, __successVolumeCb, NULL));