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 ns_method = __mSpec.getAudioInfo().getEffectNoiseSuppressionMethod();
404 auto [ method_reference, device_id ] = __mSpec.getAudioInfo().getEffectMethodWithReference();
405 std::string agc_method = __mSpec.getAudioInfo().getEffectAutomaticGainControlMethod();
407 std::string method_all = ns_method + method_reference + agc_method;
409 if (!method_all.empty()) {
410 pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_PREPROCESSOR_METHOD, "%s", method_all.c_str());
411 pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_ECHO_CANCEL_REFERENCE_DEVICE, "%d", device_id);
413 AUDIO_IO_LOGD("preprocess will be set. method[%s], device_id[%d]", method_all.c_str(), device_id);
417 // Adds latency on proplist for delivery to PULSEAUDIO
418 AUDIO_IO_LOGD("LATENCY : %s[%d]", __mSpec.getStreamLatencyToString(), static_cast<int>(__mSpec.getStreamLatency()));
419 pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_TIZEN_AUDIO_LATENCY, "%s", __mSpec.getStreamLatencyToString());
421 // Allocates PA mainloop
422 __mpMainloop = pa_threaded_mainloop_new();
424 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_threaded_mainloop_new()"); //LCOV_EXCL_LINE
426 // Allocates PA context
427 __mpContext = pa_context_new(pa_threaded_mainloop_get_api(__mpMainloop), CLIENT_NAME);
429 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_context_new()"); //LCOV_EXCL_LINE
431 // Sets context state changed callback
432 pa_context_set_state_callback(__mpContext, __contextStateChangeCb, this);
434 // Connects this client with PA server
435 if (pa_context_connect(__mpContext, NULL, PA_CONTEXT_NOFLAGS, NULL) < 0)
436 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_context_connect()"); //LCOV_EXCL_LINE
438 // LOCK for synchronous connection
439 CPulseThreadLocker locker{__mpMainloop};
442 if (pa_threaded_mainloop_start(__mpMainloop) < 0) {
444 THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_threaded_mainloop_start()");
448 // Connection process is asynchronously
449 // So, this function will be waited when occurred context state change event
450 // If I got a signal, do next processing
452 pa_context_state_t state;
453 state = pa_context_get_state(__mpContext);
455 if (state == PA_CONTEXT_READY)
458 if (!PA_CONTEXT_IS_GOOD(state)) {
460 err = pa_context_errno(__mpContext);
461 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION,
462 "pa_context's state is not good : err[%d]", err);
466 /* Wait until the context is ready */
467 pa_threaded_mainloop_wait(__mpMainloop);
470 AUDIO_IO_LOGD("pa_context[%p] now ready", __mpContext);
472 // Allocates PA stream
473 pa_sample_spec ss = __mSpec.getSampleSpec();
474 pa_channel_map map = __mSpec.getChannelMap();
476 __mpStream = pa_stream_new_with_proplist(__mpContext, __mSpec.getStreamName(), &ss, &map, __mpPropList);
479 THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_new_with_proplist()");
483 // Sets stream callbacks
484 pa_stream_set_state_callback(__mpStream, __streamStateChangeCb, this);
485 pa_stream_set_read_callback(__mpStream, __streamCaptureCb, this);
486 pa_stream_set_write_callback(__mpStream, __streamPlaybackCb, this);
487 pa_stream_set_latency_update_callback(__mpStream, __streamLatencyUpdateCb, this);
488 pa_stream_set_event_callback(__mpStream, __streamEventCb, this);
489 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
490 pa_stream_set_started_callback(__mpStream, __streamStartedCb, this);
491 pa_stream_set_underflow_callback(__mpStream, __streamUnderflowCb, this);
492 pa_stream_set_overflow_callback(__mpStream, __streamOverflowCb, this);
495 // Connect stream with PA Server
497 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
498 auto flags = static_cast<pa_stream_flags_t>(
499 PA_STREAM_INTERPOLATE_TIMING |
500 PA_STREAM_ADJUST_LATENCY |
501 #ifndef DISABLE_MOBILE_BACK_COMP
502 PA_STREAM_START_CORKED |
504 PA_STREAM_AUTO_TIMING_UPDATE);
506 ret = pa_stream_connect_playback(__mpStream, NULL, NULL, flags, NULL, NULL);
508 auto flags = static_cast<pa_stream_flags_t>(
509 PA_STREAM_INTERPOLATE_TIMING |
510 PA_STREAM_ADJUST_LATENCY |
511 #ifndef DISABLE_MOBILE_BACK_COMP
512 PA_STREAM_START_CORKED |
514 PA_STREAM_AUTO_TIMING_UPDATE);
516 ret = pa_stream_connect_record(__mpStream, NULL, NULL, flags);
520 err = pa_context_errno(__mpContext);
521 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
522 "Failed pa_stream_connect() : err[%d]", err);
526 AUDIO_IO_LOGD("pa_stream[%p] now wait for stream ready...", __mpStream);
529 pa_stream_state_t state = pa_stream_get_state(__mpStream);
530 AUDIO_IO_LOGD("pa_stream[%p] current state[%d]", __mpStream, state);
532 if (state == PA_STREAM_READY)
535 if (!PA_STREAM_IS_GOOD(state)) {
536 err = pa_context_errno(__mpContext);
537 if (err == PA_ERR_ACCESS)
538 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_DEVICE_POLICY_RESTRICTION,
539 "pa_stream's state is not good : err[%d]", err);
541 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, //LCOV_EXCL_LINE
542 "pa_stream's state is not good : err[%d]", err); //LCOV_EXCL_LINE
545 /* Wait until the stream is ready */
546 AUDIO_IO_LOGD("pa_mainloop[%p] signal wait...", __mpMainloop);
547 pa_threaded_mainloop_wait(__mpMainloop);
548 AUDIO_IO_LOGD("pa_mainloop[%p] signal wait done", __mpMainloop);
550 pa_threaded_mainloop_accept(__mpMainloop);
552 // __mIsInit = true; // Moved to __streamStateChangeCb()
553 } catch (const CAudioError& e) {
555 resetStreamCallbacks();
556 resetInternalObjects();
561 AUDIO_IO_LOGD("Done : pa_context[%p], pa_mainloop[%p], pa_stream[%p]", __mpContext, __mpMainloop, __mpStream);
564 void CPulseAudioClient::finalize() {
565 AUDIO_IO_LOGD("pa_context[%p], pa_mainloop[%p], pa_stream[%p]", __mpContext, __mpMainloop, __mpStream);
570 bool is_in_thread = isInThread();
572 pa_threaded_mainloop_lock(__mpMainloop);
576 resetStreamCallbacks();
579 pa_threaded_mainloop_unlock(__mpMainloop);
581 /* Wait for drain complete if draining before finalize */
583 unsigned int drain_wait_count = 0;
584 while (__mIsDraining && drain_wait_count++ < drain_wait_max_count)
585 usleep(drain_wait_interval);
586 AUDIO_IO_LOGD("wait for drain complete!!!! [%d * %d usec]",
587 drain_wait_count, drain_wait_interval);
590 resetInternalObjects();
592 AUDIO_IO_LOGD("Done");
595 int CPulseAudioClient::read(void* buffer, size_t length) {
597 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); //LCOV_EXCL_LINE
602 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "invalid parameter : buffer[%p]", buffer); //LCOV_EXCL_LINE
604 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
605 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback client can't use this function"); //LCOV_EXCL_LINE
607 size_t lengthIter = length;
610 __mIsUsedSyncRead = true;
613 CPulseThreadLocker locker{__mpMainloop};
615 while (lengthIter > 0) {
618 while (!__mpSyncReadDataPtr) {
619 ret = pa_stream_peek(__mpStream, &__mpSyncReadDataPtr, &__mSyncReadLength);
621 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_peek() : ret[%d]", ret); //LCOV_EXCL_LINE
623 if (__mSyncReadLength <= 0) {
624 #ifdef _AUDIO_IO_DEBUG_TIMING_
625 AUDIO_IO_LOGD("readLength(%zu byte) is not valid. wait...", __mSyncReadLength);
627 pa_threaded_mainloop_wait(__mpMainloop);
628 } else if (!__mpSyncReadDataPtr) {
630 // Data peeked, but it doesn't have any data
631 ret = pa_stream_drop(__mpStream);
633 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_drop() : ret[%d]", ret);
636 __mSyncReadIndex = 0;
640 l = min(__mSyncReadLength, lengthIter);
642 // Copy partial pcm data on out parameter
643 #ifdef _AUDIO_IO_DEBUG_TIMING_
644 AUDIO_IO_LOGD("memcpy() that a peeked buffer[%p], index[%zu], length[%zu] on out buffer", (const uint8_t*)(__mpSyncReadDataPtr) + __mSyncReadIndex, __mSyncReadIndex, l);
646 memcpy(buffer, (const uint8_t*)__mpSyncReadDataPtr + __mSyncReadIndex, l);
648 // Move next position
649 buffer = (uint8_t*)buffer + l;
652 // Adjusts the rest length
653 __mSyncReadIndex += l;
654 __mSyncReadLength -= l;
656 if (__mSyncReadLength == 0) {
657 #ifdef _AUDIO_IO_DEBUG_TIMING_
658 AUDIO_IO_LOGD("__mSyncReadLength is zero, do drop()");
660 ret = pa_stream_drop(__mpStream);
662 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, //LCOV_EXCL_LINE
663 "Failed pa_stream_drop() : ret[%d]", ret); //LCOV_EXCL_LINE
665 // Reset the internal pointer
666 __mpSyncReadDataPtr = nullptr;
667 __mSyncReadLength = 0;
668 __mSyncReadIndex = 0;
670 } // End of while (lengthIter > 0)
672 __mIsUsedSyncRead = false;
673 } catch (const CAudioError& e) {
675 __mIsUsedSyncRead = false;
683 int CPulseAudioClient::peek(const void** buffer, size_t* length) {
685 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
689 if (!buffer || !length)
690 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, // LCOV_EXCL_LINE
691 "invalid parameter : buffer[%p], length[%p]", buffer, length); // LCOV_EXCL_LINE
693 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
694 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
696 CPulseThreadLocker locker{__mpMainloop};
698 int ret = pa_stream_peek(__mpStream, buffer, length);
701 #ifdef _AUDIO_IO_DEBUG_TIMING_
702 AUDIO_IO_LOGD("buffer[%p], length[%zu]", *buffer, *length);
706 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_peek() : err[%d]", ret); //LCOV_EXCL_LINE
711 int CPulseAudioClient::drop() {
713 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
715 #ifdef _AUDIO_IO_DEBUG_TIMING_
721 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
722 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
724 CPulseThreadLocker locker{__mpMainloop};
726 int ret = pa_stream_drop(__mpStream);
728 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_drop() : err[%d]", ret); //LCOV_EXCL_LINE
733 int CPulseAudioClient::write(const void* data, size_t length) {
735 THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_ARGUMENT, "invalid parameter"); // LCOV_EXCL_LINE
737 if (__mDirection == EStreamDirection::STREAM_DIRECTION_RECORD)
738 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
742 #ifdef _AUDIO_IO_DEBUG_TIMING_
743 AUDIO_IO_LOGD("data[%p], length[%zu], First[%d]", data, length, __mIsFirstStream);
747 CPulseThreadLocker locker{__mpMainloop};
748 if (pa_stream_is_corked(__mpStream)) {
749 AUDIO_IO_LOGW("pa_stream[%p] is corked...do uncork here first!!!!", __mpStream);
750 pa_operation* o = pa_stream_cork(__mpStream, 0, NULL, NULL);
752 AUDIO_IO_LOGE("pa_stream[%p] : uncork failed", __mpStream);
754 pa_operation_unref(o);
757 ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
760 if (pa_stream_is_corked(__mpStream)) {
761 AUDIO_IO_LOGW("pa_stream[%p] is corked...do uncork here first!!!!", __mpStream);
762 pa_operation* o = pa_stream_cork(__mpStream, 0, NULL, NULL);
764 AUDIO_IO_LOGE("pa_stream[%p] : uncork failed", __mpStream);
766 pa_operation_unref(o);
769 if (__mIsFirstStream) {
770 const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
771 uint32_t prebuf = attr->prebuf;
772 // Compensate amount of prebuf in first stream callback when audio-io use prebuf(-1)
773 // Because a stream will never start when an application wrote less than prebuf at first
775 __dummy_write(__mpStream, prebuf - length);
777 __mIsFirstStream = false;
778 AUDIO_IO_LOGW("FIRST STREAM CALLBACK : length[%zu], prebuf[%d], dummy[%zu]",
779 length, prebuf, (length < prebuf) ? prebuf - length : 0);
781 ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
786 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_write() : err[%d]", ret); //LCOV_EXCL_LINE
791 void CPulseAudioClient::cork(bool cork) {
792 AUDIO_IO_LOGD("cork[%d]", cork);
795 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
798 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This operation is not supported in callback"); // LCOV_EXCL_LINE
802 // Set __mIsFirstStream flag when uncork(resume) stream, because prebuf will be enable again
804 __mIsFirstStream = true;
806 CPulseThreadLocker locker{__mpMainloop};
808 /* FIXME: wait for completion like drain? */
809 pa_operation* o = pa_stream_cork(__mpStream, static_cast<int>(cork), __successStreamCb, this);
811 AUDIO_IO_LOGE("pa_stream[%p] : cork[%d] failed", __mpStream, cork);
814 pa_operation_unref(o);
815 AUDIO_IO_LOGD("cork[%d] done", cork);
818 bool CPulseAudioClient::isCorked() {
820 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
824 CPulseThreadLocker locker{__mpMainloop};
826 int isCorked = pa_stream_is_corked(__mpStream);
828 #ifdef _AUDIO_IO_DEBUG_TIMING_
829 AUDIO_IO_LOGD("isCorked[%d]", isCorked);
831 return static_cast<bool>(isCorked);
834 bool CPulseAudioClient::drain() {
836 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
841 AUDIO_IO_LOGW("Corked...");
846 AUDIO_IO_LOGW("already draining...");
851 AUDIO_IO_LOGW("stream not started yet...skip drain");
856 AUDIO_IO_LOGD("drain");
857 CPulseThreadLocker locker{__mpMainloop};
859 pa_operation* o = pa_stream_drain(__mpStream, __successDrainCb, this);
860 __mIsDraining = true;
861 while (pa_operation_get_state(o) == PA_OPERATION_RUNNING)
862 pa_threaded_mainloop_wait(__mpMainloop);
863 pa_operation_unref(o);
865 AUDIO_IO_LOGD("drain done");
867 AUDIO_IO_LOGD("drain in thread");
868 pa_operation* o = pa_stream_drain(__mpStream, __successDrainCbInThread, this);
870 AUDIO_IO_LOGE("pa_stream[%p] : drain failed", __mpStream);
873 pa_operation_unref(o);
874 __mIsDraining = true;
880 bool CPulseAudioClient::flush() {
882 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
886 CPulseThreadLocker locker{__mpMainloop};
888 /* FIXME: wait for completion like drain? */
889 pa_operation* o = pa_stream_flush(__mpStream, __successStreamCb, this);
891 AUDIO_IO_LOGE("pa_stream[%p] : flush failed", __mpStream);
894 pa_operation_unref(o);
899 size_t CPulseAudioClient::getWritableSize() {
901 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
905 if (__mDirection != EStreamDirection::STREAM_DIRECTION_PLAYBACK)
906 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Playback"); // LCOV_EXCL_LINE
908 CPulseThreadLocker locker{__mpMainloop};
910 return pa_stream_writable_size(__mpStream);
913 void CPulseAudioClient::checkRunningState() {
914 if (!__mpContext || !PA_CONTEXT_IS_GOOD(pa_context_get_state(__mpContext)))
915 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, // LCOV_EXCL_LINE
916 "The context[%p] is not created or not good state", __mpContext); // LCOV_EXCL_LINE
918 if (!__mpStream || !PA_STREAM_IS_GOOD(pa_stream_get_state(__mpStream)))
919 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, // LCOV_EXCL_LINE
920 "The stream[%p] is not created or not good state", __mpStream); // LCOV_EXCL_LINE
922 if (pa_context_get_state(__mpContext) != PA_CONTEXT_READY || pa_stream_get_state(__mpStream) != PA_STREAM_READY)
923 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, // LCOV_EXCL_LINE
924 "The context[%p] or stream[%p] state is not ready", __mpContext, __mpStream); // LCOV_EXCL_LINE
926 #ifdef _AUDIO_IO_DEBUG_TIMING_
927 AUDIO_IO_LOGD("This client is running");
931 bool CPulseAudioClient::isInThread() const {
933 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "__mIsInit is null");
936 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "__mpMainloop is null");
938 int ret = pa_threaded_mainloop_in_thread(__mpMainloop);
940 #ifdef _AUDIO_IO_DEBUG_TIMING_
941 AUDIO_IO_LOGD("isInThread[%d]", ret);
943 return static_cast<bool>(ret);
947 size_t CPulseAudioClient::getReadableSize() {
949 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
953 if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD)
954 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Capture");
956 CPulseThreadLocker locker{__mpMainloop};
958 return pa_stream_readable_size(__mpStream);
961 size_t CPulseAudioClient::getBufferSize() {
963 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
967 size_t buffer_size = 0;
968 CPulseThreadLocker locker{__mpMainloop};
970 const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
972 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
973 "Failed pa_stream_get_buffer_attr() : err[%d]", pa_context_errno(__mpContext));
975 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
976 buffer_size = attr->tlength;
977 AUDIO_IO_LOGD("PLAYBACK buffer size[%zu]", buffer_size);
979 buffer_size = attr->fragsize;
980 AUDIO_IO_LOGD("RECORD buffer size[%zu]", buffer_size);
986 pa_usec_t CPulseAudioClient::getLatency() {
988 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
992 pa_usec_t latency = 0;
996 if (pa_stream_get_latency(__mpStream, &latency, &negative) < 0) {
997 int _err = pa_context_errno(__mpContext);
998 if (_err != PA_ERR_NODATA)
999 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
1000 "Failed pa_stream_get_latency() : err[%d]", _err);
1002 return negative ? 0 : latency;
1005 CPulseThreadLocker locker{__mpMainloop};
1007 while (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);
1012 /* Wait until latency data is available again */
1013 pa_threaded_mainloop_wait(__mpMainloop);
1016 return negative ? 0 : latency;
1019 pa_usec_t CPulseAudioClient::getFinalLatency() {
1021 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
1023 checkRunningState();
1025 pa_usec_t latency = 0;
1027 CPulseThreadLocker locker{__mpMainloop};
1029 uint32_t ver = pa_context_get_server_protocol_version(__mpContext);
1031 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_SUPPORTED, "This version(ver.%d) is not supported", ver);
1033 const pa_buffer_attr* buffer_attr = pa_stream_get_buffer_attr(__mpStream);
1034 const pa_sample_spec* sample_spec = pa_stream_get_sample_spec(__mpStream);
1035 const pa_timing_info* timing_info = pa_stream_get_timing_info(__mpStream);
1037 if (!buffer_attr || !sample_spec || !timing_info)
1038 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_OUT_OF_MEMORY,
1039 "Failed to get buffer_attr[%p] or sample_spec[%p] or timing_info[%p] from a pa_stream",
1040 buffer_attr, sample_spec, timing_info);
1042 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
1043 latency = (pa_bytes_to_usec(buffer_attr->tlength, sample_spec) + timing_info->configured_sink_usec);
1044 AUDIO_IO_LOGD("FINAL PLAYBACK LATENCY[%" PRIu64 "]", latency);
1046 latency = (pa_bytes_to_usec(buffer_attr->fragsize, sample_spec) + timing_info->configured_source_usec);
1047 AUDIO_IO_LOGD("FINAL RECORD LATENCY[%" PRIu64 "]", latency);
1054 void CPulseAudioClient::applyRecordVolume(double volume) {
1057 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
1059 checkRunningState();
1061 if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD)
1062 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client can't use this function"); //LCOV_EXCL_LINE
1064 CPulseThreadLocker locker{__mpMainloop};
1066 pa_cvolume cv = { 0, };
1067 pa_volume_t v = PA_VOLUME_NORM * volume;
1069 pa_cvolume_set(&cv, __mSpec.getChannelMap().channels, v);
1071 pa_operation_unref(pa_context_set_source_output_volume(__mpContext,
1072 pa_stream_get_index(__mpStream), &cv, __successVolumeCb, NULL));