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_unref(pa_stream_cork(pClient->__mpStream, 1, NULL, NULL));
292 void CPulseAudioClient::__successStreamCb(pa_stream* s, int success, void* user_data) {
296 auto pClient = static_cast<CPulseAudioClient*>(user_data);
298 AUDIO_IO_LOGD("pClient[%p], pa_stream[%p], success[%d], user_data[%p]", pClient, s, success, user_data);
300 pClient->__mIsOperationSuccess = static_cast<bool>(success);
302 /* FIXME : verify following action without any waiting */
303 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
307 void CPulseAudioClient::__successDrainCbInThread(pa_stream* s, int success, void* user_data) {
311 auto pClient = static_cast<CPulseAudioClient*>(user_data);
313 AUDIO_IO_LOGD("pClient[%p], pa_stream[%p], success[%d], user_data[%p]", pClient, s, success, user_data);
315 pClient->__mIsOperationSuccess = static_cast<bool>(success);
316 pClient->__mIsDraining = false;
320 void CPulseAudioClient::__successDrainCb(pa_stream* s, int success, void* user_data) {
324 auto pClient = static_cast<CPulseAudioClient*>(user_data);
326 AUDIO_IO_LOGD("pClient[%p], pa_stream[%p], success[%d], user_data[%p]", pClient, s, success, user_data);
328 pClient->__mIsOperationSuccess = static_cast<bool>(success);
329 pClient->__mIsDraining = false;
331 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
334 void CPulseAudioClient::__successVolumeCb(pa_context *c, int success, void *user_data) {
335 AUDIO_IO_LOGD("pa_context[%p], success[%d], user_data[%p]", c, success, user_data);
338 void CPulseAudioClient::resetStreamCallbacks() {
342 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
343 pa_stream_set_write_callback(__mpStream, NULL, NULL);
345 pa_stream_set_read_callback(__mpStream, NULL, NULL);
347 pa_stream_set_latency_update_callback(__mpStream, NULL, NULL);
348 pa_stream_set_event_callback(__mpStream, NULL, NULL);
351 void CPulseAudioClient::resetInternalObjects() {
353 pa_threaded_mainloop_stop(__mpMainloop);
356 pa_stream_disconnect(__mpStream);
357 pa_stream_unref(__mpStream);
358 __mpStream = nullptr;
362 pa_context_disconnect(__mpContext);
363 pa_context_unref(__mpContext);
364 __mpContext = nullptr;
368 pa_threaded_mainloop_free(__mpMainloop);
369 __mpMainloop = nullptr;
373 pa_proplist_free(__mpPropList);
374 __mpPropList = nullptr;
378 void CPulseAudioClient::initialize() {
386 // Allocates PA proplist
387 __mpPropList = pa_proplist_new();
389 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_proplist_new()"); //LCOV_EXCL_LINE
391 // Adds values on proplist for delivery to PULSEAUDIO
392 pa_proplist_sets(__mpPropList, PA_PROP_MEDIA_ROLE, __mSpec.getAudioInfo().getConvertedStreamType());
394 int index = __mSpec.getAudioInfo().getAudioIndex();
396 pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_PARENT_ID, "%u", (unsigned int) index);
398 // Adds latency on proplist for delivery to PULSEAUDIO
399 AUDIO_IO_LOGD("LATENCY : %s[%d]", __mSpec.getStreamLatencyToString(), static_cast<int>(__mSpec.getStreamLatency()));
400 pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_TIZEN_AUDIO_LATENCY, "%s", __mSpec.getStreamLatencyToString());
402 // Allocates PA mainloop
403 __mpMainloop = pa_threaded_mainloop_new();
405 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_threaded_mainloop_new()"); //LCOV_EXCL_LINE
407 // Allocates PA context
408 __mpContext = pa_context_new(pa_threaded_mainloop_get_api(__mpMainloop), CLIENT_NAME);
410 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_context_new()"); //LCOV_EXCL_LINE
412 // Sets context state changed callback
413 pa_context_set_state_callback(__mpContext, __contextStateChangeCb, this);
415 // Connects this client with PA server
416 if (pa_context_connect(__mpContext, NULL, PA_CONTEXT_NOFLAGS, NULL) < 0)
417 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_context_connect()"); //LCOV_EXCL_LINE
419 // LOCK for synchronous connection
420 CPulseThreadLocker locker{__mpMainloop};
423 if (pa_threaded_mainloop_start(__mpMainloop) < 0) {
425 THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_threaded_mainloop_start()");
429 // Connection process is asynchronously
430 // So, this function will be waited when occurred context state change event
431 // If I got a signal, do next processing
433 pa_context_state_t state;
434 state = pa_context_get_state(__mpContext);
436 if (state == PA_CONTEXT_READY)
439 if (!PA_CONTEXT_IS_GOOD(state)) {
441 err = pa_context_errno(__mpContext);
442 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION,
443 "pa_context's state is not good : err[%d]", err);
447 /* Wait until the context is ready */
448 pa_threaded_mainloop_wait(__mpMainloop);
451 AUDIO_IO_LOGD("pa_context[%p] now ready", __mpContext);
453 // Allocates PA stream
454 pa_sample_spec ss = __mSpec.getSampleSpec();
455 pa_channel_map map = __mSpec.getChannelMap();
457 __mpStream = pa_stream_new_with_proplist(__mpContext, __mSpec.getStreamName(), &ss, &map, __mpPropList);
460 THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_new_with_proplist()");
464 // Sets stream callbacks
465 pa_stream_set_state_callback(__mpStream, __streamStateChangeCb, this);
466 pa_stream_set_read_callback(__mpStream, __streamCaptureCb, this);
467 pa_stream_set_write_callback(__mpStream, __streamPlaybackCb, this);
468 pa_stream_set_latency_update_callback(__mpStream, __streamLatencyUpdateCb, this);
469 pa_stream_set_event_callback(__mpStream, __streamEventCb, this);
470 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
471 pa_stream_set_started_callback(__mpStream, __streamStartedCb, this);
472 pa_stream_set_underflow_callback(__mpStream, __streamUnderflowCb, this);
475 // Connect stream with PA Server
477 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
478 auto flags = static_cast<pa_stream_flags_t>(
479 PA_STREAM_INTERPOLATE_TIMING |
480 PA_STREAM_ADJUST_LATENCY |
481 #ifndef DISABLE_MOBILE_BACK_COMP
482 PA_STREAM_START_CORKED |
484 PA_STREAM_AUTO_TIMING_UPDATE);
486 ret = pa_stream_connect_playback(__mpStream, NULL, NULL, flags, NULL, NULL);
488 auto flags = static_cast<pa_stream_flags_t>(
489 PA_STREAM_INTERPOLATE_TIMING |
490 PA_STREAM_ADJUST_LATENCY |
491 #ifndef DISABLE_MOBILE_BACK_COMP
492 PA_STREAM_START_CORKED |
494 PA_STREAM_AUTO_TIMING_UPDATE);
496 ret = pa_stream_connect_record(__mpStream, NULL, NULL, flags);
500 err = pa_context_errno(__mpContext);
501 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
502 "Failed pa_stream_connect() : err[%d]", err);
506 AUDIO_IO_LOGD("pa_stream[%p] now wait for stream ready...", __mpStream);
509 pa_stream_state_t state = pa_stream_get_state(__mpStream);
510 AUDIO_IO_LOGD("pa_stream[%p] current state[%d]", __mpStream, state);
512 if (state == PA_STREAM_READY)
515 if (!PA_STREAM_IS_GOOD(state)) {
516 err = pa_context_errno(__mpContext);
517 if (err == PA_ERR_ACCESS)
518 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_DEVICE_POLICY_RESTRICTION,
519 "pa_stream's state is not good : err[%d]", err);
521 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, //LCOV_EXCL_LINE
522 "pa_stream's state is not good : err[%d]", err); //LCOV_EXCL_LINE
525 /* Wait until the stream is ready */
526 AUDIO_IO_LOGD("pa_mainloop[%p] signal wait...", __mpMainloop);
527 pa_threaded_mainloop_wait(__mpMainloop);
528 AUDIO_IO_LOGD("pa_mainloop[%p] signal wait done", __mpMainloop);
530 pa_threaded_mainloop_accept(__mpMainloop);
532 // __mIsInit = true; // Moved to __streamStateChangeCb()
533 } catch (const CAudioError& e) {
535 resetStreamCallbacks();
536 resetInternalObjects();
541 AUDIO_IO_LOGD("Done : pa_context[%p], pa_mainloop[%p], pa_stream[%p]", __mpContext, __mpMainloop, __mpStream);
544 void CPulseAudioClient::finalize() {
545 AUDIO_IO_LOGD("pa_context[%p], pa_mainloop[%p], pa_stream[%p]", __mpContext, __mpMainloop, __mpStream);
550 bool is_in_thread = isInThread();
552 pa_threaded_mainloop_lock(__mpMainloop);
556 resetStreamCallbacks();
559 pa_threaded_mainloop_unlock(__mpMainloop);
561 /* Wait for drain complete if draining before finalize */
563 unsigned int drain_wait_count = 0;
564 while (__mIsDraining && drain_wait_count++ < drain_wait_max_count)
565 usleep(drain_wait_interval);
566 AUDIO_IO_LOGD("wait for drain complete!!!! [%d * %d usec]",
567 drain_wait_count, drain_wait_interval);
570 resetInternalObjects();
572 AUDIO_IO_LOGD("Done");
575 int CPulseAudioClient::read(void* buffer, size_t length) {
577 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); //LCOV_EXCL_LINE
582 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "invalid parameter : buffer[%p]", buffer); //LCOV_EXCL_LINE
584 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
585 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback client can't use this function"); //LCOV_EXCL_LINE
587 size_t lengthIter = length;
590 __mIsUsedSyncRead = true;
593 CPulseThreadLocker locker{__mpMainloop};
595 while (lengthIter > 0) {
598 while (!__mpSyncReadDataPtr) {
599 ret = pa_stream_peek(__mpStream, &__mpSyncReadDataPtr, &__mSyncReadLength);
601 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_peek() : ret[%d]", ret); //LCOV_EXCL_LINE
603 if (__mSyncReadLength <= 0) {
604 #ifdef _AUDIO_IO_DEBUG_TIMING_
605 AUDIO_IO_LOGD("readLength(%zu byte) is not valid. wait...", __mSyncReadLength);
607 pa_threaded_mainloop_wait(__mpMainloop);
608 } else if (!__mpSyncReadDataPtr) {
610 // Data peeked, but it doesn't have any data
611 ret = pa_stream_drop(__mpStream);
613 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_drop() : ret[%d]", ret);
616 __mSyncReadIndex = 0;
620 l = min(__mSyncReadLength, lengthIter);
622 // Copy partial pcm data on out parameter
623 #ifdef _AUDIO_IO_DEBUG_TIMING_
624 AUDIO_IO_LOGD("memcpy() that a peeked buffer[%p], index[%zu], length[%zu] on out buffer", (const uint8_t*)(__mpSyncReadDataPtr) + __mSyncReadIndex, __mSyncReadIndex, l);
626 memcpy(buffer, (const uint8_t*)__mpSyncReadDataPtr + __mSyncReadIndex, l);
628 // Move next position
629 buffer = (uint8_t*)buffer + l;
632 // Adjusts the rest length
633 __mSyncReadIndex += l;
634 __mSyncReadLength -= l;
636 if (__mSyncReadLength == 0) {
637 #ifdef _AUDIO_IO_DEBUG_TIMING_
638 AUDIO_IO_LOGD("__mSyncReadLength is zero, do drop()");
640 ret = pa_stream_drop(__mpStream);
642 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, //LCOV_EXCL_LINE
643 "Failed pa_stream_drop() : ret[%d]", ret); //LCOV_EXCL_LINE
645 // Reset the internal pointer
646 __mpSyncReadDataPtr = nullptr;
647 __mSyncReadLength = 0;
648 __mSyncReadIndex = 0;
650 } // End of while (lengthIter > 0)
652 __mIsUsedSyncRead = false;
653 } catch (const CAudioError& e) {
655 __mIsUsedSyncRead = false;
663 int CPulseAudioClient::peek(const void** buffer, size_t* length) {
665 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
669 if (!buffer || !length)
670 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, // LCOV_EXCL_LINE
671 "invalid parameter : buffer[%p], length[%p]", buffer, length); // LCOV_EXCL_LINE
673 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
674 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
676 CPulseThreadLocker locker{__mpMainloop};
678 int ret = pa_stream_peek(__mpStream, buffer, length);
681 #ifdef _AUDIO_IO_DEBUG_TIMING_
682 AUDIO_IO_LOGD("buffer[%p], length[%zu]", *buffer, *length);
686 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_peek() : err[%d]", ret); //LCOV_EXCL_LINE
691 int CPulseAudioClient::drop() {
693 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
695 #ifdef _AUDIO_IO_DEBUG_TIMING_
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_drop(__mpStream);
708 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_drop() : err[%d]", ret); //LCOV_EXCL_LINE
713 int CPulseAudioClient::write(const void* data, size_t length) {
715 THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_ARGUMENT, "invalid parameter"); // LCOV_EXCL_LINE
717 if (__mDirection == EStreamDirection::STREAM_DIRECTION_RECORD)
718 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
722 #ifdef _AUDIO_IO_DEBUG_TIMING_
723 AUDIO_IO_LOGD("data[%p], length[%zu], First[%d]", data, length, __mIsFirstStream);
727 CPulseThreadLocker locker{__mpMainloop};
728 if (pa_stream_is_corked(__mpStream)) {
729 AUDIO_IO_LOGW("stream is corked...do uncork here first!!!!");
730 pa_operation_unref(pa_stream_cork(__mpStream, 0, NULL, this));
733 ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
736 if (pa_stream_is_corked(__mpStream)) {
737 AUDIO_IO_LOGW("stream is corked...do uncork here first!!!!");
738 pa_operation_unref(pa_stream_cork(__mpStream, 0, NULL, this));
741 if (__mIsFirstStream) {
742 const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
743 uint32_t prebuf = attr->prebuf;
744 // Compensate amount of prebuf in first stream callback when audio-io use prebuf(-1)
745 // Because a stream will never start when an application wrote less than prebuf at first
747 __dummy_write(__mpStream, prebuf - length);
749 __mIsFirstStream = false;
750 AUDIO_IO_LOGW("FIRST STREAM CALLBACK : length[%zu], prebuf[%d], dummy[%zu]",
751 length, prebuf, (length < prebuf) ? prebuf - length : 0);
753 ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
758 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_write() : err[%d]", ret); //LCOV_EXCL_LINE
763 void CPulseAudioClient::cork(bool cork) {
764 AUDIO_IO_LOGD("cork[%d]", cork);
767 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
770 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This operation is not supported in callback"); // LCOV_EXCL_LINE
774 // Set __mIsFirstStream flag when uncork(resume) stream, because prebuf will be enable again
776 __mIsFirstStream = true;
778 CPulseThreadLocker locker{__mpMainloop};
780 /* FIXME: wait for completion like drain? */
781 pa_operation_unref(pa_stream_cork(__mpStream, static_cast<int>(cork), __successStreamCb, this));
783 AUDIO_IO_LOGD("cork[%d] done", cork);
786 bool CPulseAudioClient::isCorked() {
788 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
792 CPulseThreadLocker locker{__mpMainloop};
794 int isCorked = pa_stream_is_corked(__mpStream);
796 #ifdef _AUDIO_IO_DEBUG_TIMING_
797 AUDIO_IO_LOGD("isCorked[%d]", isCorked);
799 return static_cast<bool>(isCorked);
802 bool CPulseAudioClient::drain() {
804 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
809 AUDIO_IO_LOGW("Corked...");
814 AUDIO_IO_LOGW("already draining...");
819 AUDIO_IO_LOGW("stream not started yet...skip drain");
824 AUDIO_IO_LOGD("drain");
825 CPulseThreadLocker locker{__mpMainloop};
827 pa_operation* o = pa_stream_drain(__mpStream, __successDrainCb, this);
828 __mIsDraining = true;
829 while (pa_operation_get_state(o) == PA_OPERATION_RUNNING)
830 pa_threaded_mainloop_wait(__mpMainloop);
831 pa_operation_unref(o);
833 AUDIO_IO_LOGD("drain done");
835 AUDIO_IO_LOGD("drain in thread");
836 pa_operation_unref(pa_stream_drain(__mpStream, __successDrainCbInThread, this));
837 __mIsDraining = true;
843 bool CPulseAudioClient::flush() {
845 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
849 CPulseThreadLocker locker{__mpMainloop};
851 /* FIXME: wait for completion like drain? */
852 pa_operation_unref(pa_stream_flush(__mpStream, __successStreamCb, this));
857 size_t CPulseAudioClient::getWritableSize() {
859 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
863 if (__mDirection != EStreamDirection::STREAM_DIRECTION_PLAYBACK)
864 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Playback"); // LCOV_EXCL_LINE
866 CPulseThreadLocker locker{__mpMainloop};
868 return pa_stream_writable_size(__mpStream);
871 void CPulseAudioClient::checkRunningState() {
872 if (!__mpContext || !PA_CONTEXT_IS_GOOD(pa_context_get_state(__mpContext)))
873 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, // LCOV_EXCL_LINE
874 "The context[%p] is not created or not good state", __mpContext); // LCOV_EXCL_LINE
876 if (!__mpStream || !PA_STREAM_IS_GOOD(pa_stream_get_state(__mpStream)))
877 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, // LCOV_EXCL_LINE
878 "The stream[%p] is not created or not good state", __mpStream); // LCOV_EXCL_LINE
880 if (pa_context_get_state(__mpContext) != PA_CONTEXT_READY || pa_stream_get_state(__mpStream) != PA_STREAM_READY)
881 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, // LCOV_EXCL_LINE
882 "The context[%p] or stream[%p] state is not ready", __mpContext, __mpStream); // LCOV_EXCL_LINE
884 #ifdef _AUDIO_IO_DEBUG_TIMING_
885 AUDIO_IO_LOGD("This client is running");
889 bool CPulseAudioClient::isInThread() const {
891 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "__mIsInit is null");
894 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "__mpMainloop is null");
896 int ret = pa_threaded_mainloop_in_thread(__mpMainloop);
898 #ifdef _AUDIO_IO_DEBUG_TIMING_
899 AUDIO_IO_LOGD("isInThread[%d]", ret);
901 return static_cast<bool>(ret);
905 size_t CPulseAudioClient::getReadableSize() {
907 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
911 if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD)
912 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Capture");
914 CPulseThreadLocker locker{__mpMainloop};
916 return pa_stream_readable_size(__mpStream);
919 size_t CPulseAudioClient::getBufferSize() {
921 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
925 size_t buffer_size = 0;
926 CPulseThreadLocker locker{__mpMainloop};
928 const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
930 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
931 "Failed pa_stream_get_buffer_attr() : err[%d]", pa_context_errno(__mpContext));
933 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
934 buffer_size = attr->tlength;
935 AUDIO_IO_LOGD("PLAYBACK buffer size[%zu]", buffer_size);
937 buffer_size = attr->fragsize;
938 AUDIO_IO_LOGD("RECORD buffer size[%zu]", buffer_size);
944 pa_usec_t CPulseAudioClient::getLatency() {
946 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
950 pa_usec_t latency = 0;
954 if (pa_stream_get_latency(__mpStream, &latency, &negative) < 0) {
955 int _err = pa_context_errno(__mpContext);
956 if (_err != PA_ERR_NODATA)
957 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
958 "Failed pa_stream_get_latency() : err[%d]", _err);
960 return negative ? 0 : latency;
963 CPulseThreadLocker locker{__mpMainloop};
965 while (pa_stream_get_latency(__mpStream, &latency, &negative) < 0) {
966 int _err = pa_context_errno(__mpContext);
967 if (_err != PA_ERR_NODATA)
968 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
969 "Failed pa_stream_get_latency() : err[%d]", _err);
970 /* Wait until latency data is available again */
971 pa_threaded_mainloop_wait(__mpMainloop);
974 return negative ? 0 : latency;
977 pa_usec_t CPulseAudioClient::getFinalLatency() {
979 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
983 pa_usec_t latency = 0;
985 CPulseThreadLocker locker{__mpMainloop};
987 uint32_t ver = pa_context_get_server_protocol_version(__mpContext);
989 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_SUPPORTED, "This version(ver.%d) is not supported", ver);
991 const pa_buffer_attr* buffer_attr = pa_stream_get_buffer_attr(__mpStream);
992 const pa_sample_spec* sample_spec = pa_stream_get_sample_spec(__mpStream);
993 const pa_timing_info* timing_info = pa_stream_get_timing_info(__mpStream);
995 if (!buffer_attr || !sample_spec || !timing_info)
996 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_OUT_OF_MEMORY,
997 "Failed to get buffer_attr[%p] or sample_spec[%p] or timing_info[%p] from a pa_stream",
998 buffer_attr, sample_spec, timing_info);
1000 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
1001 latency = (pa_bytes_to_usec(buffer_attr->tlength, sample_spec) + timing_info->configured_sink_usec);
1002 AUDIO_IO_LOGD("FINAL PLAYBACK LATENCY[%" PRIu64 "]", latency);
1004 latency = (pa_bytes_to_usec(buffer_attr->fragsize, sample_spec) + timing_info->configured_source_usec);
1005 AUDIO_IO_LOGD("FINAL RECORD LATENCY[%" PRIu64 "]", latency);
1012 void CPulseAudioClient::applyRecordVolume(double volume) {
1015 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
1017 checkRunningState();
1019 if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD)
1020 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client can't use this function"); //LCOV_EXCL_LINE
1022 CPulseThreadLocker locker{__mpMainloop};
1024 pa_cvolume cv = { 0, };
1025 pa_volume_t v = PA_VOLUME_NORM * volume;
1027 pa_cvolume_set(&cv, __mSpec.getChannelMap().channels, v);
1029 pa_operation_unref(pa_context_set_source_output_volume(__mpContext,
1030 pa_stream_get_index(__mpStream), &cv, __successVolumeCb, NULL));