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 static constexpr auto drain_wait_interval = 10000;
55 static constexpr auto drain_wait_max_count = 30;
57 CPulseAudioClient::CPulseAudioClient(
58 EStreamDirection direction,
59 CPulseStreamSpec& spec,
60 IPulseStreamListener* listener) :
61 __mDirection(direction),
63 __mpListener(listener),
64 __mpMainloop(nullptr),
67 __mpPropList(nullptr),
69 __mIsOperationSuccess(false),
70 __mpSyncReadDataPtr(nullptr),
73 __mIsUsedSyncRead(false),
74 __mIsFirstStream(false),
79 CPulseAudioClient::~CPulseAudioClient() {
82 } catch (const CAudioError& e) {
83 AUDIO_IO_LOGE("%s", e.getErrorMsg()); //LCOV_EXCL_LINE
87 void CPulseAudioClient::__contextStateChangeCb(pa_context* c, void* user_data) {
88 auto pClient = static_cast<CPulseAudioClient*>(user_data);
92 switch (pa_context_get_state(c)) {
93 case PA_CONTEXT_READY:
94 AUDIO_IO_LOGD("pa_context[%p] is ready", c);
95 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
98 case PA_CONTEXT_FAILED:
99 case PA_CONTEXT_TERMINATED:
100 AUDIO_IO_LOGD("pa_context[%p] is lost", c);
101 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
104 case PA_CONTEXT_UNCONNECTED:
105 case PA_CONTEXT_CONNECTING:
106 case PA_CONTEXT_AUTHORIZING:
107 case PA_CONTEXT_SETTING_NAME:
113 static bool __is_microphone_restricted(void) {
116 device_policy_manager_h dpm_h = nullptr;
119 if ((dpm_h = dpm_manager_create())) {
120 /* state: 0(disallowed), 1(allowed) */
121 if ((ret = dpm_restriction_get_microphone_state(dpm_h, &state)))
122 AUDIO_IO_LOGE("Failed to dpm_restriction_get_microphone_state(), ret(0x%x)", ret);
123 dpm_manager_destroy(dpm_h);
124 AUDIO_IO_LOGD("microphone restriction state: %d(1:allowed, 0:disallowed)", state);
126 AUDIO_IO_LOGE("Failed to dpm_manager_create()");
129 return (state ? false : true);
133 void CPulseAudioClient::__streamStateChangeCb(pa_stream* s, void* user_data) {
137 auto pClient = static_cast<CPulseAudioClient*>(user_data);
138 pa_stream_state_t state = pa_stream_get_state(s);
141 case PA_STREAM_UNCONNECTED:
144 case PA_STREAM_CREATING:
147 case PA_STREAM_READY:
148 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] is READY[%d]", pClient, s, PA_STREAM_READY);
149 pClient->__mpListener->setState(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING);
150 pClient->__mpListener->onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING);
151 if (pClient->__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
152 pClient->__mIsFirstStream = true;
153 pClient->__mIsInit = true;
155 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] now signaling...", pClient, s);
156 pa_threaded_mainloop_signal(pClient->__mpMainloop, 1);
157 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] signal accepted", pClient, s);
161 case PA_STREAM_FAILED:
162 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] is FAILED[%d]", pClient, s, PA_STREAM_FAILED);
163 pClient->__mpListener->setState(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE);
164 pClient->__mpListener->onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE,
165 __is_microphone_restricted());
167 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] now signaling...", pClient, s);
168 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
172 case PA_STREAM_TERMINATED:
173 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] is TERMINATED[%d]", pClient, s, PA_STREAM_TERMINATED);
174 pClient->__mpListener->setState(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE);
175 pClient->__mpListener->onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE);
177 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] now signaling...", pClient, s);
178 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
182 AUDIO_IO_LOGW("Unexpected state[%d]", state);
186 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] state[%d] done", pClient, s, state);
189 void CPulseAudioClient::__streamCaptureCb(pa_stream* s, size_t length, void* user_data) {
193 auto pClient = static_cast<CPulseAudioClient*>(user_data);
194 assert(pClient->__mpListener);
195 assert(pClient->__mpMainloop);
197 if (pClient->__mIsUsedSyncRead)
198 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
200 pClient->__mpListener->onStream(pClient, length);
203 static void __dummy_write(pa_stream* s, size_t length) {
204 pa_stream_write(s, std::vector<char>(length).data(), length, NULL, 0LL, PA_SEEK_RELATIVE);
207 void CPulseAudioClient::__streamPlaybackCb(pa_stream* s, size_t length, void* user_data) {
211 auto pClient = static_cast<CPulseAudioClient*>(user_data);
212 assert(pClient->__mpListener);
214 #ifndef DISABLE_MOBILE_BACK_COMP
215 if (!pClient->__mIsInit) {
216 AUDIO_IO_LOGD("pa_stream[%p] is on the way to create : Write dummy, length[%zu]", s, length);
217 __dummy_write(s, length);
220 if (pClient->isCorked()) {
221 AUDIO_IO_LOGD("pa_stream[%p] is CORKED : Write dummy, length[%zu]", s, length);
222 __dummy_write(s, length);
227 pClient->__mpListener->onStream(pClient, length);
229 #ifndef DISABLE_MOBILE_BACK_COMP
230 /* If stream is not written in first callback during prepare,
231 then write dummy data to ensure the start */
232 if (pClient->__mSpec.getStreamLatency() == CPulseStreamSpec::EStreamLatency::STREAM_LATENCY_OUTPUT_DEFAULT_ASYNC &&
233 pClient->__mIsFirstStream) {
234 AUDIO_IO_LOGW("[async] pa_stream[%p] : not written in the first callback during prepare, write dummy of length[%zu]",
236 __dummy_write(s, length);
237 pClient->__mIsFirstStream = false;
242 void CPulseAudioClient::__streamLatencyUpdateCb(pa_stream* s, void* user_data) {
246 auto pClient = static_cast<CPulseAudioClient*>(user_data);
248 #ifdef _AUDIO_IO_DEBUG_TIMING_
249 /* FIXME : print some useful latency info */
250 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] latency updated", pClient, s);
253 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
256 void CPulseAudioClient::__streamStartedCb(pa_stream* s, void* user_data) {
260 auto pClient = static_cast<CPulseAudioClient*>(user_data);
262 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] started", pClient, s);
264 pClient->__mIsStarted = true;
267 void CPulseAudioClient::__streamUnderflowCb(pa_stream* s, void* user_data) {
271 auto pClient = static_cast<CPulseAudioClient*>(user_data);
273 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] UnderFlow...", pClient, s);
275 pClient->__mIsStarted = false;
279 void CPulseAudioClient::__streamEventCb(pa_stream* s, const char* name, pa_proplist* pl, void* user_data) {
283 auto pClient = static_cast<CPulseAudioClient*>(user_data);
285 AUDIO_IO_LOGW("pClient[%p] pa_stream[%p] : name[%s], proplist[%p]", pClient, s, name, pl);
287 if (strcmp(name, PA_STREAM_EVENT_POP_TIMEOUT) == 0) {
288 pa_operation* o = pa_stream_cork(pClient->__mpStream, 1, NULL, NULL);
290 AUDIO_IO_LOGE("pa_stream[%p] : cork failed", pClient->__mpStream);
293 pa_operation_unref(o);
298 void CPulseAudioClient::__successStreamCb(pa_stream* s, int success, void* user_data) {
302 auto pClient = static_cast<CPulseAudioClient*>(user_data);
304 AUDIO_IO_LOGD("pClient[%p], pa_stream[%p], success[%d], user_data[%p]", pClient, s, success, user_data);
306 pClient->__mIsOperationSuccess = static_cast<bool>(success);
308 /* FIXME : verify following action without any waiting */
309 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
313 void CPulseAudioClient::__successDrainCbInThread(pa_stream* s, int success, void* user_data) {
317 auto pClient = static_cast<CPulseAudioClient*>(user_data);
319 AUDIO_IO_LOGD("pClient[%p], pa_stream[%p], success[%d], user_data[%p]", pClient, s, success, user_data);
321 pClient->__mIsOperationSuccess = static_cast<bool>(success);
322 pClient->__mIsDraining = false;
326 void CPulseAudioClient::__successDrainCb(pa_stream* s, int success, void* user_data) {
330 auto pClient = static_cast<CPulseAudioClient*>(user_data);
332 AUDIO_IO_LOGD("pClient[%p], pa_stream[%p], success[%d], user_data[%p]", pClient, s, success, user_data);
334 pClient->__mIsOperationSuccess = static_cast<bool>(success);
335 pClient->__mIsDraining = false;
337 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
340 void CPulseAudioClient::__successVolumeCb(pa_context* c, int success, void* user_data) {
341 AUDIO_IO_LOGD("pa_context[%p], success[%d], user_data[%p]", c, success, user_data);
344 void CPulseAudioClient::resetStreamCallbacks() {
348 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
349 pa_stream_set_write_callback(__mpStream, NULL, NULL);
351 pa_stream_set_read_callback(__mpStream, NULL, NULL);
353 pa_stream_set_latency_update_callback(__mpStream, NULL, NULL);
354 pa_stream_set_event_callback(__mpStream, NULL, NULL);
357 void CPulseAudioClient::resetInternalObjects() {
359 pa_threaded_mainloop_stop(__mpMainloop);
362 pa_stream_disconnect(__mpStream);
363 pa_stream_unref(__mpStream);
364 __mpStream = nullptr;
368 pa_context_disconnect(__mpContext);
369 pa_context_unref(__mpContext);
370 __mpContext = nullptr;
374 pa_threaded_mainloop_free(__mpMainloop);
375 __mpMainloop = nullptr;
379 pa_proplist_free(__mpPropList);
380 __mpPropList = nullptr;
384 void CPulseAudioClient::initialize() {
392 // Allocates PA proplist
393 __mpPropList = pa_proplist_new();
395 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_proplist_new()"); //LCOV_EXCL_LINE
397 // Adds values on proplist for delivery to PULSEAUDIO
398 pa_proplist_sets(__mpPropList, PA_PROP_MEDIA_ROLE, __mSpec.getAudioInfo().getConvertedStreamType());
400 int index = __mSpec.getAudioInfo().getAudioIndex();
402 pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_PARENT_ID, "%u", (unsigned int) index);
404 // Adds latency on proplist for delivery to PULSEAUDIO
405 AUDIO_IO_LOGD("LATENCY : %s[%d]", __mSpec.getStreamLatencyToString(), static_cast<int>(__mSpec.getStreamLatency()));
406 pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_TIZEN_AUDIO_LATENCY, "%s", __mSpec.getStreamLatencyToString());
408 // Allocates PA mainloop
409 __mpMainloop = pa_threaded_mainloop_new();
411 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_threaded_mainloop_new()"); //LCOV_EXCL_LINE
413 // Allocates PA context
414 __mpContext = pa_context_new(pa_threaded_mainloop_get_api(__mpMainloop), CLIENT_NAME);
416 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_context_new()"); //LCOV_EXCL_LINE
418 // Sets context state changed callback
419 pa_context_set_state_callback(__mpContext, __contextStateChangeCb, this);
421 // Connects this client with PA server
422 if (pa_context_connect(__mpContext, NULL, PA_CONTEXT_NOFLAGS, NULL) < 0)
423 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_context_connect()"); //LCOV_EXCL_LINE
425 // LOCK for synchronous connection
426 CPulseThreadLocker locker{__mpMainloop};
429 if (pa_threaded_mainloop_start(__mpMainloop) < 0) {
431 THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_threaded_mainloop_start()");
435 // Connection process is asynchronously
436 // So, this function will be waited when occurred context state change event
437 // If I got a signal, do next processing
439 pa_context_state_t state;
440 state = pa_context_get_state(__mpContext);
442 if (state == PA_CONTEXT_READY)
445 if (!PA_CONTEXT_IS_GOOD(state)) {
447 err = pa_context_errno(__mpContext);
448 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION,
449 "pa_context's state is not good : err[%d]", err);
453 /* Wait until the context is ready */
454 pa_threaded_mainloop_wait(__mpMainloop);
457 AUDIO_IO_LOGD("pa_context[%p] now ready", __mpContext);
459 // Allocates PA stream
460 pa_sample_spec ss = __mSpec.getSampleSpec();
461 pa_channel_map map = __mSpec.getChannelMap();
463 __mpStream = pa_stream_new_with_proplist(__mpContext, __mSpec.getStreamName(), &ss, &map, __mpPropList);
466 THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_new_with_proplist()");
470 // Sets stream callbacks
471 pa_stream_set_state_callback(__mpStream, __streamStateChangeCb, this);
472 pa_stream_set_read_callback(__mpStream, __streamCaptureCb, this);
473 pa_stream_set_write_callback(__mpStream, __streamPlaybackCb, this);
474 pa_stream_set_latency_update_callback(__mpStream, __streamLatencyUpdateCb, this);
475 pa_stream_set_event_callback(__mpStream, __streamEventCb, this);
476 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
477 pa_stream_set_started_callback(__mpStream, __streamStartedCb, this);
478 pa_stream_set_underflow_callback(__mpStream, __streamUnderflowCb, this);
481 // Connect stream with PA Server
483 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
484 auto flags = static_cast<pa_stream_flags_t>(
485 PA_STREAM_INTERPOLATE_TIMING |
486 PA_STREAM_ADJUST_LATENCY |
487 #ifndef DISABLE_MOBILE_BACK_COMP
488 PA_STREAM_START_CORKED |
490 PA_STREAM_AUTO_TIMING_UPDATE);
492 ret = pa_stream_connect_playback(__mpStream, NULL, NULL, flags, NULL, NULL);
494 auto flags = static_cast<pa_stream_flags_t>(
495 PA_STREAM_INTERPOLATE_TIMING |
496 PA_STREAM_ADJUST_LATENCY |
497 #ifndef DISABLE_MOBILE_BACK_COMP
498 PA_STREAM_START_CORKED |
500 PA_STREAM_AUTO_TIMING_UPDATE);
502 ret = pa_stream_connect_record(__mpStream, NULL, NULL, flags);
506 err = pa_context_errno(__mpContext);
507 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
508 "Failed pa_stream_connect() : err[%d]", err);
512 AUDIO_IO_LOGD("pa_stream[%p] now wait for stream ready...", __mpStream);
515 pa_stream_state_t state = pa_stream_get_state(__mpStream);
516 AUDIO_IO_LOGD("pa_stream[%p] current state[%d]", __mpStream, state);
518 if (state == PA_STREAM_READY)
521 if (!PA_STREAM_IS_GOOD(state)) {
522 err = pa_context_errno(__mpContext);
523 if (err == PA_ERR_ACCESS)
524 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_DEVICE_POLICY_RESTRICTION,
525 "pa_stream's state is not good : err[%d]", err);
527 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, //LCOV_EXCL_LINE
528 "pa_stream's state is not good : err[%d]", err); //LCOV_EXCL_LINE
531 /* Wait until the stream is ready */
532 AUDIO_IO_LOGD("pa_mainloop[%p] signal wait...", __mpMainloop);
533 pa_threaded_mainloop_wait(__mpMainloop);
534 AUDIO_IO_LOGD("pa_mainloop[%p] signal wait done", __mpMainloop);
536 pa_threaded_mainloop_accept(__mpMainloop);
538 // __mIsInit = true; // Moved to __streamStateChangeCb()
539 } catch (const CAudioError& e) {
541 resetStreamCallbacks();
542 resetInternalObjects();
547 AUDIO_IO_LOGD("Done : pa_context[%p], pa_mainloop[%p], pa_stream[%p]", __mpContext, __mpMainloop, __mpStream);
550 void CPulseAudioClient::finalize() {
551 AUDIO_IO_LOGD("pa_context[%p], pa_mainloop[%p], pa_stream[%p]", __mpContext, __mpMainloop, __mpStream);
556 bool is_in_thread = isInThread();
558 pa_threaded_mainloop_lock(__mpMainloop);
562 resetStreamCallbacks();
565 pa_threaded_mainloop_unlock(__mpMainloop);
567 /* Wait for drain complete if draining before finalize */
569 unsigned int drain_wait_count = 0;
570 while (__mIsDraining && drain_wait_count++ < drain_wait_max_count)
571 usleep(drain_wait_interval);
572 AUDIO_IO_LOGD("wait for drain complete!!!! [%d * %d usec]",
573 drain_wait_count, drain_wait_interval);
576 resetInternalObjects();
578 AUDIO_IO_LOGD("Done");
581 int CPulseAudioClient::read(void* buffer, size_t length) {
583 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); //LCOV_EXCL_LINE
588 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "invalid parameter : buffer[%p]", buffer); //LCOV_EXCL_LINE
590 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
591 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback client can't use this function"); //LCOV_EXCL_LINE
593 size_t lengthIter = length;
596 __mIsUsedSyncRead = true;
599 CPulseThreadLocker locker{__mpMainloop};
601 while (lengthIter > 0) {
604 while (!__mpSyncReadDataPtr) {
605 ret = pa_stream_peek(__mpStream, &__mpSyncReadDataPtr, &__mSyncReadLength);
607 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_peek() : ret[%d]", ret); //LCOV_EXCL_LINE
609 if (__mSyncReadLength <= 0) {
610 #ifdef _AUDIO_IO_DEBUG_TIMING_
611 AUDIO_IO_LOGD("readLength(%zu byte) is not valid. wait...", __mSyncReadLength);
613 pa_threaded_mainloop_wait(__mpMainloop);
614 } else if (!__mpSyncReadDataPtr) {
616 // Data peeked, but it doesn't have any data
617 ret = pa_stream_drop(__mpStream);
619 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_drop() : ret[%d]", ret);
622 __mSyncReadIndex = 0;
626 l = min(__mSyncReadLength, lengthIter);
628 // Copy partial pcm data on out parameter
629 #ifdef _AUDIO_IO_DEBUG_TIMING_
630 AUDIO_IO_LOGD("memcpy() that a peeked buffer[%p], index[%zu], length[%zu] on out buffer", (const uint8_t*)(__mpSyncReadDataPtr) + __mSyncReadIndex, __mSyncReadIndex, l);
632 memcpy(buffer, (const uint8_t*)__mpSyncReadDataPtr + __mSyncReadIndex, l);
634 // Move next position
635 buffer = (uint8_t*)buffer + l;
638 // Adjusts the rest length
639 __mSyncReadIndex += l;
640 __mSyncReadLength -= l;
642 if (__mSyncReadLength == 0) {
643 #ifdef _AUDIO_IO_DEBUG_TIMING_
644 AUDIO_IO_LOGD("__mSyncReadLength is zero, do drop()");
646 ret = pa_stream_drop(__mpStream);
648 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, //LCOV_EXCL_LINE
649 "Failed pa_stream_drop() : ret[%d]", ret); //LCOV_EXCL_LINE
651 // Reset the internal pointer
652 __mpSyncReadDataPtr = nullptr;
653 __mSyncReadLength = 0;
654 __mSyncReadIndex = 0;
656 } // End of while (lengthIter > 0)
658 __mIsUsedSyncRead = false;
659 } catch (const CAudioError& e) {
661 __mIsUsedSyncRead = false;
669 int CPulseAudioClient::peek(const void** buffer, size_t* length) {
671 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
675 if (!buffer || !length)
676 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, // LCOV_EXCL_LINE
677 "invalid parameter : buffer[%p], length[%p]", buffer, length); // LCOV_EXCL_LINE
679 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
680 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
682 CPulseThreadLocker locker{__mpMainloop};
684 int ret = pa_stream_peek(__mpStream, buffer, length);
687 #ifdef _AUDIO_IO_DEBUG_TIMING_
688 AUDIO_IO_LOGD("buffer[%p], length[%zu]", *buffer, *length);
692 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_peek() : err[%d]", ret); //LCOV_EXCL_LINE
697 int CPulseAudioClient::drop() {
699 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
701 #ifdef _AUDIO_IO_DEBUG_TIMING_
707 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
708 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
710 CPulseThreadLocker locker{__mpMainloop};
712 int ret = pa_stream_drop(__mpStream);
714 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_drop() : err[%d]", ret); //LCOV_EXCL_LINE
719 int CPulseAudioClient::write(const void* data, size_t length) {
721 THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_ARGUMENT, "invalid parameter"); // LCOV_EXCL_LINE
723 if (__mDirection == EStreamDirection::STREAM_DIRECTION_RECORD)
724 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
728 #ifdef _AUDIO_IO_DEBUG_TIMING_
729 AUDIO_IO_LOGD("data[%p], length[%zu], First[%d]", data, length, __mIsFirstStream);
733 CPulseThreadLocker locker{__mpMainloop};
734 if (pa_stream_is_corked(__mpStream)) {
735 AUDIO_IO_LOGW("pa_stream[%p] is corked...do uncork here first!!!!", __mpStream);
736 pa_operation* o = pa_stream_cork(__mpStream, 0, NULL, NULL);
738 AUDIO_IO_LOGE("pa_stream[%p] : uncork failed", __mpStream);
740 pa_operation_unref(o);
743 ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
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 if (__mIsFirstStream) {
756 const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
757 uint32_t prebuf = attr->prebuf;
758 // Compensate amount of prebuf in first stream callback when audio-io use prebuf(-1)
759 // Because a stream will never start when an application wrote less than prebuf at first
761 __dummy_write(__mpStream, prebuf - length);
763 __mIsFirstStream = false;
764 AUDIO_IO_LOGW("FIRST STREAM CALLBACK : length[%zu], prebuf[%d], dummy[%zu]",
765 length, prebuf, (length < prebuf) ? prebuf - length : 0);
767 ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
772 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_write() : err[%d]", ret); //LCOV_EXCL_LINE
777 void CPulseAudioClient::cork(bool cork) {
778 AUDIO_IO_LOGD("cork[%d]", cork);
781 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
784 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This operation is not supported in callback"); // LCOV_EXCL_LINE
788 // Set __mIsFirstStream flag when uncork(resume) stream, because prebuf will be enable again
790 __mIsFirstStream = true;
792 CPulseThreadLocker locker{__mpMainloop};
794 /* FIXME: wait for completion like drain? */
795 pa_operation* o = pa_stream_cork(__mpStream, static_cast<int>(cork), __successStreamCb, this);
797 AUDIO_IO_LOGE("pa_stream[%p] : cork[%d] failed", __mpStream, cork);
800 pa_operation_unref(o);
801 AUDIO_IO_LOGD("cork[%d] done", cork);
804 bool CPulseAudioClient::isCorked() {
806 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
810 CPulseThreadLocker locker{__mpMainloop};
812 int isCorked = pa_stream_is_corked(__mpStream);
814 #ifdef _AUDIO_IO_DEBUG_TIMING_
815 AUDIO_IO_LOGD("isCorked[%d]", isCorked);
817 return static_cast<bool>(isCorked);
820 bool CPulseAudioClient::drain() {
822 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
827 AUDIO_IO_LOGW("Corked...");
832 AUDIO_IO_LOGW("already draining...");
837 AUDIO_IO_LOGW("stream not started yet...skip drain");
842 AUDIO_IO_LOGD("drain");
843 CPulseThreadLocker locker{__mpMainloop};
845 pa_operation* o = pa_stream_drain(__mpStream, __successDrainCb, this);
846 __mIsDraining = true;
847 while (pa_operation_get_state(o) == PA_OPERATION_RUNNING)
848 pa_threaded_mainloop_wait(__mpMainloop);
849 pa_operation_unref(o);
851 AUDIO_IO_LOGD("drain done");
853 AUDIO_IO_LOGD("drain in thread");
854 pa_operation* o = pa_stream_drain(__mpStream, __successDrainCbInThread, this);
856 AUDIO_IO_LOGE("pa_stream[%p] : drain failed", __mpStream);
859 pa_operation_unref(o);
860 __mIsDraining = true;
866 bool CPulseAudioClient::flush() {
868 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
872 CPulseThreadLocker locker{__mpMainloop};
874 /* FIXME: wait for completion like drain? */
875 pa_operation* o = pa_stream_flush(__mpStream, __successStreamCb, this);
877 AUDIO_IO_LOGE("pa_stream[%p] : flush failed", __mpStream);
880 pa_operation_unref(o);
885 size_t CPulseAudioClient::getWritableSize() {
887 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
891 if (__mDirection != EStreamDirection::STREAM_DIRECTION_PLAYBACK)
892 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Playback"); // LCOV_EXCL_LINE
894 CPulseThreadLocker locker{__mpMainloop};
896 return pa_stream_writable_size(__mpStream);
899 void CPulseAudioClient::checkRunningState() {
900 if (!__mpContext || !PA_CONTEXT_IS_GOOD(pa_context_get_state(__mpContext)))
901 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, // LCOV_EXCL_LINE
902 "The context[%p] is not created or not good state", __mpContext); // LCOV_EXCL_LINE
904 if (!__mpStream || !PA_STREAM_IS_GOOD(pa_stream_get_state(__mpStream)))
905 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, // LCOV_EXCL_LINE
906 "The stream[%p] is not created or not good state", __mpStream); // LCOV_EXCL_LINE
908 if (pa_context_get_state(__mpContext) != PA_CONTEXT_READY || pa_stream_get_state(__mpStream) != PA_STREAM_READY)
909 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, // LCOV_EXCL_LINE
910 "The context[%p] or stream[%p] state is not ready", __mpContext, __mpStream); // LCOV_EXCL_LINE
912 #ifdef _AUDIO_IO_DEBUG_TIMING_
913 AUDIO_IO_LOGD("This client is running");
917 bool CPulseAudioClient::isInThread() const {
919 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "__mIsInit is null");
922 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "__mpMainloop is null");
924 int ret = pa_threaded_mainloop_in_thread(__mpMainloop);
926 #ifdef _AUDIO_IO_DEBUG_TIMING_
927 AUDIO_IO_LOGD("isInThread[%d]", ret);
929 return static_cast<bool>(ret);
933 size_t CPulseAudioClient::getReadableSize() {
935 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
939 if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD)
940 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Capture");
942 CPulseThreadLocker locker{__mpMainloop};
944 return pa_stream_readable_size(__mpStream);
947 size_t CPulseAudioClient::getBufferSize() {
949 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
953 size_t buffer_size = 0;
954 CPulseThreadLocker locker{__mpMainloop};
956 const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
958 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
959 "Failed pa_stream_get_buffer_attr() : err[%d]", pa_context_errno(__mpContext));
961 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
962 buffer_size = attr->tlength;
963 AUDIO_IO_LOGD("PLAYBACK buffer size[%zu]", buffer_size);
965 buffer_size = attr->fragsize;
966 AUDIO_IO_LOGD("RECORD buffer size[%zu]", buffer_size);
972 pa_usec_t CPulseAudioClient::getLatency() {
974 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
978 pa_usec_t latency = 0;
982 if (pa_stream_get_latency(__mpStream, &latency, &negative) < 0) {
983 int _err = pa_context_errno(__mpContext);
984 if (_err != PA_ERR_NODATA)
985 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
986 "Failed pa_stream_get_latency() : err[%d]", _err);
988 return negative ? 0 : latency;
991 CPulseThreadLocker locker{__mpMainloop};
993 while (pa_stream_get_latency(__mpStream, &latency, &negative) < 0) {
994 int _err = pa_context_errno(__mpContext);
995 if (_err != PA_ERR_NODATA)
996 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
997 "Failed pa_stream_get_latency() : err[%d]", _err);
998 /* Wait until latency data is available again */
999 pa_threaded_mainloop_wait(__mpMainloop);
1002 return negative ? 0 : latency;
1005 pa_usec_t CPulseAudioClient::getFinalLatency() {
1007 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
1009 checkRunningState();
1011 pa_usec_t latency = 0;
1013 CPulseThreadLocker locker{__mpMainloop};
1015 uint32_t ver = pa_context_get_server_protocol_version(__mpContext);
1017 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_SUPPORTED, "This version(ver.%d) is not supported", ver);
1019 const pa_buffer_attr* buffer_attr = pa_stream_get_buffer_attr(__mpStream);
1020 const pa_sample_spec* sample_spec = pa_stream_get_sample_spec(__mpStream);
1021 const pa_timing_info* timing_info = pa_stream_get_timing_info(__mpStream);
1023 if (!buffer_attr || !sample_spec || !timing_info)
1024 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_OUT_OF_MEMORY,
1025 "Failed to get buffer_attr[%p] or sample_spec[%p] or timing_info[%p] from a pa_stream",
1026 buffer_attr, sample_spec, timing_info);
1028 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
1029 latency = (pa_bytes_to_usec(buffer_attr->tlength, sample_spec) + timing_info->configured_sink_usec);
1030 AUDIO_IO_LOGD("FINAL PLAYBACK LATENCY[%" PRIu64 "]", latency);
1032 latency = (pa_bytes_to_usec(buffer_attr->fragsize, sample_spec) + timing_info->configured_source_usec);
1033 AUDIO_IO_LOGD("FINAL RECORD LATENCY[%" PRIu64 "]", latency);
1040 void CPulseAudioClient::applyRecordVolume(double volume) {
1043 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
1045 checkRunningState();
1047 if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD)
1048 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client can't use this function"); //LCOV_EXCL_LINE
1050 CPulseThreadLocker locker{__mpMainloop};
1052 pa_cvolume cv = { 0, };
1053 pa_volume_t v = PA_VOLUME_NORM * volume;
1055 pa_cvolume_set(&cv, __mSpec.getChannelMap().channels, v);
1057 pa_operation_unref(pa_context_set_source_output_volume(__mpContext,
1058 pa_stream_get_index(__mpStream), &cv, __successVolumeCb, NULL));