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"
23 #include <dpm/restriction.h>
27 using namespace tizen_media_audio;
31 * class CPulseAudioClient
33 const char* CPulseAudioClient::CLIENT_NAME = "AUDIO_IO_PA_CLIENT";
34 static const unsigned int drain_wait_interval = 10000;
35 static const unsigned int drain_wait_max_count = 30;
37 CPulseAudioClient::CPulseAudioClient(
38 EStreamDirection direction,
39 CPulseStreamSpec& spec,
40 IPulseStreamListener* listener) :
41 __mDirection(direction),
43 __mpListener(listener),
44 __mpMainloop(nullptr),
47 __mpPropList(nullptr),
49 __mIsOperationSuccess(false),
50 __mpSyncReadDataPtr(nullptr),
53 __mIsUsedSyncRead(false),
54 __mIsFirstStream(false),
59 CPulseAudioClient::~CPulseAudioClient() {
63 void CPulseAudioClient::__contextStateChangeCb(pa_context* c, void* user_data) {
64 auto pClient = static_cast<CPulseAudioClient*>(user_data);
68 switch (pa_context_get_state(c)) {
69 case PA_CONTEXT_READY:
70 AUDIO_IO_LOGD("The context is ready");
71 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
74 case PA_CONTEXT_FAILED:
75 case PA_CONTEXT_TERMINATED:
76 AUDIO_IO_LOGD("The context is lost");
77 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
80 case PA_CONTEXT_UNCONNECTED:
81 case PA_CONTEXT_CONNECTING:
82 case PA_CONTEXT_AUTHORIZING:
83 case PA_CONTEXT_SETTING_NAME:
89 static bool __is_microphone_restricted(void) {
92 device_policy_manager_h dpm_h = nullptr;
95 if ((dpm_h = dpm_manager_create())) {
96 /* state: 0(disallowed), 1(allowed) */
97 if ((ret = dpm_restriction_get_microphone_state(dpm_h, &state)))
98 AUDIO_IO_LOGE("Failed to dpm_restriction_get_microphone_state(), ret(0x%x)", ret);
99 dpm_manager_destroy(dpm_h);
100 AUDIO_IO_LOGD("microphone restriction state: %d(1:allowed, 0:disallowed)", state);
102 AUDIO_IO_LOGE("Failed to dpm_manager_create()");
105 return (state ? false : true);
109 void CPulseAudioClient::__streamStateChangeCb(pa_stream* s, void* user_data) {
113 auto pClient = static_cast<CPulseAudioClient*>(user_data);
115 switch (pa_stream_get_state(s)) {
116 case PA_STREAM_READY:
117 AUDIO_IO_LOGD("The stream is ready");
118 pClient->__mpListener->onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING);
119 if (pClient->__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
120 pClient->__mIsFirstStream = true;
121 pClient->__mIsInit = true;
122 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
125 case PA_STREAM_FAILED:
127 AUDIO_IO_LOGD("The stream is failed");
128 pClient->__mpListener->onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE,
129 __is_microphone_restricted());
130 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
134 case PA_STREAM_TERMINATED:
135 AUDIO_IO_LOGD("The stream is terminated");
136 pClient->__mpListener->onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE);
137 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
140 case PA_STREAM_UNCONNECTED:
141 case PA_STREAM_CREATING:
146 void CPulseAudioClient::__streamCaptureCb(pa_stream* s, size_t length, void* user_data) {
150 auto pClient = static_cast<CPulseAudioClient*>(user_data);
151 assert(pClient->__mpListener);
152 assert(pClient->__mpMainloop);
154 if (pClient->__mIsUsedSyncRead)
155 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
157 pClient->__mpListener->onStream(pClient, length);
160 #ifndef DISABLE_MOBILE_BACK_COMP
161 static void __dummy_write(pa_stream* s, size_t length) {
162 char* dummy = new char[length];
163 memset(dummy, 0, length);
164 pa_stream_write(s, dummy, length, NULL, 0LL, PA_SEEK_RELATIVE);
169 void CPulseAudioClient::__streamPlaybackCb(pa_stream* s, size_t length, void* user_data) {
173 auto pClient = static_cast<CPulseAudioClient*>(user_data);
174 assert(pClient->__mpListener);
176 #ifndef DISABLE_MOBILE_BACK_COMP
177 if (!pClient->__mIsInit) {
178 AUDIO_IO_LOGD("Occurred this listener when an out stream is on the way to create : Write dummy, length[%zu]", length);
179 __dummy_write(s, length);
182 if (pClient->isCorked()) {
183 AUDIO_IO_LOGD("Occurred this listener when an out stream is CORKED : Write dummy, length[%zu]", length);
184 __dummy_write(s, length);
189 pClient->__mpListener->onStream(pClient, length);
191 #ifndef DISABLE_MOBILE_BACK_COMP
192 /* If stream is not written in first callback during prepare,
193 then write dummy data to ensure the start */
194 if (pClient->__mSpec.getStreamLatency() == CPulseStreamSpec::EStreamLatency::STREAM_LATENCY_OUTPUT_DEFAULT_ASYNC &&
195 pClient->__mIsFirstStream) {
196 AUDIO_IO_LOGW("[async] Write dummy of length[%zu] since not written in first callback during prepare", length);
197 __dummy_write(s, length);
198 pClient->__mIsFirstStream = false;
203 void CPulseAudioClient::__streamLatencyUpdateCb(pa_stream* s, void* user_data) {
207 auto pClient = static_cast<CPulseAudioClient*>(user_data);
209 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
212 void CPulseAudioClient::__streamStartedCb(pa_stream* s, void* user_data) {
216 auto pClient = static_cast<CPulseAudioClient*>(user_data);
218 AUDIO_IO_LOGD("stream %p started.", pClient);
220 pClient->__mIsStarted = true;
223 void CPulseAudioClient::__streamUnderflowCb(pa_stream* s, void* user_data) {
227 auto pClient = static_cast<CPulseAudioClient*>(user_data);
229 AUDIO_IO_LOGD("stream %p UnderFlow...", pClient);
231 pClient->__mIsStarted = false;
235 void CPulseAudioClient::__streamEventCb(pa_stream* s, const char *name, pa_proplist *pl, void *user_data) {
239 AUDIO_IO_LOGE("NAME : %s, Prop : %p", name, pl);
241 auto pClient = static_cast<CPulseAudioClient*>(user_data);
242 if (strcmp(name, PA_STREAM_EVENT_POP_TIMEOUT) == 0)
243 pa_operation_unref(pa_stream_cork(pClient->__mpStream, 1, NULL, NULL));
247 void CPulseAudioClient::__successStreamCb(pa_stream* s, int success, void* user_data) {
248 AUDIO_IO_LOGD("pa_stream[%p], success[%d], user_data[%p]", s, success, user_data);
252 auto pClient = static_cast<CPulseAudioClient*>(user_data);
253 pClient->__mIsOperationSuccess = static_cast<bool>(success);
255 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
259 void CPulseAudioClient::__successDrainCbInThread(pa_stream* s, int success, void* user_data) {
260 AUDIO_IO_LOGD("pa_stream[%p], success[%d], user_data[%p]", s, success, user_data);
264 auto pClient = static_cast<CPulseAudioClient*>(user_data);
265 pClient->__mIsOperationSuccess = static_cast<bool>(success);
266 pClient->__mIsDraining = false;
270 void CPulseAudioClient::__successDrainCb(pa_stream* s, int success, void* user_data) {
271 AUDIO_IO_LOGD("pa_stream[%p], success[%d], user_data[%p]", s, success, user_data);
275 auto pClient = static_cast<CPulseAudioClient*>(user_data);
276 pClient->__mIsOperationSuccess = static_cast<bool>(success);
277 pClient->__mIsDraining = false;
279 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
282 void CPulseAudioClient::initialize() {
290 // Allocates PA proplist
291 __mpPropList = pa_proplist_new();
293 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_proplist_new()"); //LCOV_EXCL_LINE
295 // Adds values on proplist for delivery to PULSEAUDIO
296 char *streamType = nullptr;
297 CAudioInfo::EAudioType audioType = __mSpec.getAudioInfo().getAudioType();
298 __mSpec.getAudioInfo().convertAudioType2StreamType(audioType, &streamType);
299 pa_proplist_sets(__mpPropList, PA_PROP_MEDIA_ROLE, streamType);
301 int index = __mSpec.getAudioInfo().getAudioIndex();
303 pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_PARENT_ID, "%u", (unsigned int) index);
305 // Adds latency on proplist for delivery to PULSEAUDIO
306 AUDIO_IO_LOGD("LATENCY : %s[%d]", __mSpec.getStreamLatencyToString(), static_cast<int>(__mSpec.getStreamLatency()));
307 pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_TIZEN_AUDIO_LATENCY, "%s", __mSpec.getStreamLatencyToString());
309 // Allocates PA mainloop
310 __mpMainloop = pa_threaded_mainloop_new();
312 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_threaded_mainloop_new()"); //LCOV_EXCL_LINE
314 // Allocates PA context
315 __mpContext = pa_context_new(pa_threaded_mainloop_get_api(__mpMainloop), CLIENT_NAME);
317 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_context_new()"); //LCOV_EXCL_LINE
319 // Sets context state changed callback
320 pa_context_set_state_callback(__mpContext, __contextStateChangeCb, this);
322 // Connects this client with PA server
323 if (pa_context_connect(__mpContext, NULL, PA_CONTEXT_NOFLAGS, NULL) < 0)
324 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_context_connect()"); //LCOV_EXCL_LINE
326 // LOCK for synchronous connection
327 pa_threaded_mainloop_lock(__mpMainloop);
330 if (pa_threaded_mainloop_start(__mpMainloop) < 0) {
331 pa_threaded_mainloop_unlock(__mpMainloop);
332 THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_threaded_mainloop_start()"); //LCOV_EXCL_LINE
335 // Connection process is asynchronously
336 // So, this function will be waited when occurred context state change event
337 // If I got a signal, do next processing
339 pa_context_state_t state;
340 state = pa_context_get_state(__mpContext);
342 if (state == PA_CONTEXT_READY)
345 if (!PA_CONTEXT_IS_GOOD(state)) {
347 err = pa_context_errno(__mpContext);
348 pa_threaded_mainloop_unlock(__mpMainloop);
349 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "pa_context's state is not good : err[%d]", err);
353 /* Wait until the context is ready */
354 pa_threaded_mainloop_wait(__mpMainloop);
357 // Allocates PA stream
358 pa_sample_spec ss = __mSpec.getSampleSpec();
359 pa_channel_map map = __mSpec.getChannelMap();
361 __mpStream = pa_stream_new_with_proplist(__mpContext, __mSpec.getStreamName(), &ss, &map, __mpPropList);
364 pa_threaded_mainloop_unlock(__mpMainloop);
365 THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_new_with_proplist()");
369 // Sets stream callbacks
370 pa_stream_set_state_callback(__mpStream, __streamStateChangeCb, this);
371 pa_stream_set_read_callback(__mpStream, __streamCaptureCb, this);
372 pa_stream_set_write_callback(__mpStream, __streamPlaybackCb, this);
373 pa_stream_set_latency_update_callback(__mpStream, __streamLatencyUpdateCb, this);
374 pa_stream_set_event_callback(__mpStream, __streamEventCb, this);
375 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
376 pa_stream_set_started_callback(__mpStream, __streamStartedCb, this);
377 pa_stream_set_underflow_callback(__mpStream, __streamUnderflowCb, this);
380 // Connect stream with PA Server
382 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
383 auto flags = static_cast<pa_stream_flags_t>(
384 PA_STREAM_INTERPOLATE_TIMING |
385 PA_STREAM_ADJUST_LATENCY |
386 #ifndef DISABLE_MOBILE_BACK_COMP
387 PA_STREAM_START_CORKED |
389 PA_STREAM_AUTO_TIMING_UPDATE);
391 ret = pa_stream_connect_playback(__mpStream, NULL, NULL, flags, NULL, NULL);
393 auto flags = static_cast<pa_stream_flags_t>(
394 PA_STREAM_INTERPOLATE_TIMING |
395 PA_STREAM_ADJUST_LATENCY |
396 #ifndef DISABLE_MOBILE_BACK_COMP
397 PA_STREAM_START_CORKED |
399 PA_STREAM_AUTO_TIMING_UPDATE);
401 ret = pa_stream_connect_record(__mpStream, NULL, NULL, flags);
406 err = pa_context_errno(__mpContext);
407 pa_threaded_mainloop_unlock(__mpMainloop);
408 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_connect() : err[%d]", err);
413 pa_stream_state_t state = pa_stream_get_state(__mpStream);
415 if (state == PA_STREAM_READY) {
416 AUDIO_IO_LOGD("STREAM READY");
420 if (!PA_STREAM_IS_GOOD(state)) {
421 err = pa_context_errno(__mpContext);
422 pa_threaded_mainloop_unlock(__mpMainloop);
423 if (err == PA_ERR_ACCESS)
424 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_DEVICE_POLICY_RESTRICTION, "pa_stream's state is not good : err[%d]", err);
426 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "pa_stream's state is not good : err[%d]", err); //LCOV_EXCL_LINE
429 /* Wait until the stream is ready */
430 pa_threaded_mainloop_wait(__mpMainloop);
433 // End of synchronous
434 pa_threaded_mainloop_unlock(__mpMainloop);
436 // __mIsInit = true; // Moved to __streamStateChangeCb()
437 } catch (CAudioError& e) {
443 void CPulseAudioClient::finalize() {
446 if (__mpMainloop && !isInThread())
447 pa_threaded_mainloop_lock(__mpMainloop);
449 /* clear callbacks */
451 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
452 pa_stream_set_write_callback(__mpStream, NULL, NULL);
454 pa_stream_set_read_callback(__mpStream, NULL, NULL);
455 pa_stream_set_latency_update_callback(__mpStream, NULL, NULL);
456 pa_stream_set_event_callback(__mpStream, NULL, NULL);
459 if (__mpMainloop && !isInThread())
460 pa_threaded_mainloop_unlock(__mpMainloop);
462 /* Wait for drain complete if draining before finalize */
464 unsigned int drain_wait_count = 0;
465 while (__mIsDraining && drain_wait_count++ < drain_wait_max_count)
466 usleep(drain_wait_interval);
467 AUDIO_IO_LOGD("wait for drain complete!!!! [%d * %d usec]",
468 drain_wait_count, drain_wait_interval);
472 pa_threaded_mainloop_stop(__mpMainloop);
475 pa_stream_disconnect(__mpStream);
476 pa_stream_unref(__mpStream);
477 __mpStream = nullptr;
481 pa_context_disconnect(__mpContext);
482 pa_context_unref(__mpContext);
483 __mpContext = nullptr;
487 pa_threaded_mainloop_free(__mpMainloop);
488 __mpMainloop = nullptr;
492 pa_proplist_free(__mpPropList);
493 __mpPropList = nullptr;
499 int CPulseAudioClient::read(void* buffer, size_t length) {
501 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
506 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "The parameter is invalid : buffer[%p]", buffer);
508 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
509 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client couldn't use this function");
511 size_t lengthIter = length;
514 __mIsUsedSyncRead = true;
517 pa_threaded_mainloop_lock(__mpMainloop);
519 while (lengthIter > 0) {
522 while (!__mpSyncReadDataPtr) {
523 ret = pa_stream_peek(__mpStream, &__mpSyncReadDataPtr, &__mSyncReadLength);
525 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_peek() : ret[%d]", ret);
527 if (__mSyncReadLength <= 0) {
528 #ifdef _AUDIO_IO_DEBUG_TIMING_
529 AUDIO_IO_LOGD("readLength(%zu byte) is not valid. wait...", __mSyncReadLength);
531 pa_threaded_mainloop_wait(__mpMainloop);
532 } else if (!__mpSyncReadDataPtr) {
533 // Data peeked, but it doesn't have any data
534 ret = pa_stream_drop(__mpStream);
536 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_drop() : ret[%d]", ret); //LCOV_EXCL_LINE
538 __mSyncReadIndex = 0;
542 if (__mSyncReadLength < lengthIter)
543 l = __mSyncReadLength;
547 // Copy partial pcm data on out parameter
548 #ifdef _AUDIO_IO_DEBUG_TIMING_
549 AUDIO_IO_LOGD("memcpy() that a peeked buffer[%p], index[%zu], length[%zu] on out buffer", (const uint8_t*)(__mpSyncReadDataPtr) + __mSyncReadIndex, __mSyncReadIndex, l);
551 memcpy(buffer, (const uint8_t*)__mpSyncReadDataPtr + __mSyncReadIndex, l);
553 // Move next position
554 buffer = (uint8_t*)buffer + l;
557 // Adjusts the rest length
558 __mSyncReadIndex += l;
559 __mSyncReadLength -= l;
561 if (__mSyncReadLength == 0) {
562 #ifdef _AUDIO_IO_DEBUG_TIMING_
563 AUDIO_IO_LOGD("__mSyncReadLength is zero, do drop()");
565 ret = pa_stream_drop(__mpStream);
567 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_drop() : ret[%d]", ret); //LCOV_EXCL_LINE
569 // Reset the internal pointer
570 __mpSyncReadDataPtr = nullptr;
571 __mSyncReadLength = 0;
572 __mSyncReadIndex = 0;
574 } // End of while (lengthIter > 0)
576 pa_threaded_mainloop_unlock(__mpMainloop);
577 __mIsUsedSyncRead = false;
578 } catch (CAudioError& e) {
579 pa_threaded_mainloop_unlock(__mpMainloop);
580 __mIsUsedSyncRead = false;
587 int CPulseAudioClient::peek(const void** buffer, size_t* length) {
589 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
593 if (!buffer || !length)
594 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "The parameter is invalid : buffer[%p], length[%p]", buffer, length);
596 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
597 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client couldn't use this function");
602 pa_threaded_mainloop_lock(__mpMainloop);
603 ret = pa_stream_peek(__mpStream, buffer, length);
604 pa_threaded_mainloop_unlock(__mpMainloop);
606 ret = pa_stream_peek(__mpStream, buffer, length);
609 #ifdef _AUDIO_IO_DEBUG_TIMING_
610 AUDIO_IO_LOGD("buffer[%p], length[%zu]", *buffer, *length);
614 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_peek() : err[%d]", ret); //LCOV_EXCL_LINE
619 int CPulseAudioClient::drop() {
621 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
623 #ifdef _AUDIO_IO_DEBUG_TIMING_
629 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
630 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client couldn't use this function");
635 pa_threaded_mainloop_lock(__mpMainloop);
636 ret = pa_stream_drop(__mpStream);
637 pa_threaded_mainloop_unlock(__mpMainloop);
639 ret = pa_stream_drop(__mpStream);
643 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_drop() : err[%d]", ret); //LCOV_EXCL_LINE
648 int CPulseAudioClient::write(const void* data, size_t length) {
650 THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_ARGUMENT, "The parameter is invalid");
652 if (__mDirection == EStreamDirection::STREAM_DIRECTION_RECORD)
653 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client couldn't use this function");
657 #ifdef _AUDIO_IO_DEBUG_TIMING_
658 AUDIO_IO_LOGD("data[%p], length[%zu], First[%d]", data, length, __mIsFirstStream);
662 pa_threaded_mainloop_lock(__mpMainloop);
663 if (pa_stream_is_corked(__mpStream)) {
664 AUDIO_IO_LOGW("stream is corked...do uncork here first!!!!");
665 pa_operation_unref(pa_stream_cork(__mpStream, 0, NULL, this));
668 ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
669 pa_threaded_mainloop_unlock(__mpMainloop);
671 if (pa_stream_is_corked(__mpStream)) {
672 AUDIO_IO_LOGW("stream is corked...do uncork here first!!!!");
673 pa_operation_unref(pa_stream_cork(__mpStream, 0, NULL, this));
676 if (__mIsFirstStream) {
677 const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
678 uint32_t prebuf = attr->prebuf;
679 // Compensate amount of prebuf in first stream callback when audio-io use prebuf(-1)
680 // Because a stream will never start when an application wrote less than prebuf at first
681 if (length < prebuf) {
682 char* dummy = new char[prebuf - length];
683 memset(dummy, 0, prebuf - length);
684 pa_stream_write(__mpStream, dummy, prebuf - length, NULL, 0LL, PA_SEEK_RELATIVE);
687 __mIsFirstStream = false;
688 AUDIO_IO_LOGW("FIRST STREAM CALLBACK : length[%zu], prebuf[%d], dummy[%zu]",
689 length, prebuf, (length < prebuf) ? prebuf - length : 0);
691 ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
695 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_write() : err[%d]", ret); //LCOV_EXCL_LINE
700 void CPulseAudioClient::cork(bool cork) {
701 AUDIO_IO_LOGD("cork[%d]", cork);
704 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
707 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This operation is not supported in callback");
711 // Set __mIsFirstStream flag when uncork(resume) stream, because prebuf will be enable again
713 __mIsFirstStream = true;
716 pa_threaded_mainloop_lock(__mpMainloop);
717 pa_operation_unref(pa_stream_cork(__mpStream, static_cast<int>(cork), __successStreamCb, this));
718 pa_threaded_mainloop_unlock(__mpMainloop);
720 pa_operation_unref(pa_stream_cork(__mpStream, static_cast<int>(cork), __successStreamCb, this));
724 bool CPulseAudioClient::isCorked() {
726 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
733 pa_threaded_mainloop_lock(__mpMainloop);
734 isCork = pa_stream_is_corked(__mpStream);
735 pa_threaded_mainloop_unlock(__mpMainloop);
737 isCork = pa_stream_is_corked(__mpStream);
740 #ifdef _AUDIO_IO_DEBUG_TIMING_
741 AUDIO_IO_LOGD("isCork[%d]", isCork);
743 return static_cast<bool>(isCork);
746 bool CPulseAudioClient::drain() {
748 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
753 AUDIO_IO_LOGW("Corked...");
758 AUDIO_IO_LOGW("already draining...");
763 AUDIO_IO_LOGW("stream not started yet...skip drain");
768 AUDIO_IO_LOGD("drain");
769 pa_threaded_mainloop_lock(__mpMainloop);
770 pa_operation* o = pa_stream_drain(__mpStream, __successDrainCb, this);
771 __mIsDraining = true;
772 while (pa_operation_get_state(o) == PA_OPERATION_RUNNING)
773 pa_threaded_mainloop_wait(__mpMainloop);
775 pa_operation_unref(o);
776 pa_threaded_mainloop_unlock(__mpMainloop);
777 AUDIO_IO_LOGD("drain done");
779 AUDIO_IO_LOGD("drain in thread");
780 pa_operation_unref(pa_stream_drain(__mpStream, __successDrainCbInThread, this));
781 __mIsDraining = true;
787 bool CPulseAudioClient::flush() {
789 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
794 AUDIO_IO_LOGD("flush");
795 pa_threaded_mainloop_lock(__mpMainloop);
796 pa_operation_unref(pa_stream_flush(__mpStream, __successStreamCb, this));
797 pa_threaded_mainloop_unlock(__mpMainloop);
799 AUDIO_IO_LOGD("flush in thread");
800 pa_operation_unref(pa_stream_flush(__mpStream, __successStreamCb, this));
806 size_t CPulseAudioClient::getWritableSize() {
808 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
812 if (__mDirection != EStreamDirection::STREAM_DIRECTION_PLAYBACK)
813 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Playback");
818 pa_threaded_mainloop_lock(__mpMainloop);
819 ret = pa_stream_writable_size(__mpStream);
820 pa_threaded_mainloop_unlock(__mpMainloop);
822 ret = pa_stream_writable_size(__mpStream);
828 void CPulseAudioClient::checkRunningState() {
829 if (!__mpContext || !PA_CONTEXT_IS_GOOD(pa_context_get_state(__mpContext)))
830 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, "The context[%p] is not created or not good state", __mpContext);
832 if (!__mpStream || !PA_STREAM_IS_GOOD(pa_stream_get_state(__mpStream)))
833 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, "The stream[%p] is not created or not good state", __mpStream);
835 if (pa_context_get_state(__mpContext) != PA_CONTEXT_READY || pa_stream_get_state(__mpStream) != PA_STREAM_READY)
836 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, "The context[%p] or stream[%p] state is not ready", __mpContext, __mpStream);
838 #ifdef _AUDIO_IO_DEBUG_TIMING_
839 AUDIO_IO_LOGD("This client is running");
843 bool CPulseAudioClient::isInThread() noexcept {
844 int ret = pa_threaded_mainloop_in_thread(__mpMainloop);
846 #ifdef _AUDIO_IO_DEBUG_TIMING_
847 AUDIO_IO_LOGD("isInThread[%d]", ret);
849 return static_cast<bool>(ret);
853 size_t CPulseAudioClient::getReadableSize() {
855 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
859 if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD)
860 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Capture");
865 pa_threaded_mainloop_lock(__mpMainloop);
866 ret = pa_stream_readable_size(__mpStream);
867 pa_threaded_mainloop_unlock(__mpMainloop);
869 ret = pa_stream_writable_size(__mpStream);
875 size_t CPulseAudioClient::getBufferSize() {
877 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
885 pa_threaded_mainloop_lock(__mpMainloop);
887 const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
889 int _err = pa_context_errno(__mpContext);
890 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_buffer_attr() : err[%d]", _err);
893 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
895 AUDIO_IO_LOGD("PLAYBACK buffer size[%zu]", ret);
897 ret = attr->fragsize;
898 AUDIO_IO_LOGD("RECORD buffer size[%zu]", ret);
900 } catch (CAudioError& e) {
902 pa_threaded_mainloop_unlock(__mpMainloop);
907 pa_threaded_mainloop_unlock(__mpMainloop);
912 pa_usec_t CPulseAudioClient::getLatency() {
914 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
922 if (pa_stream_get_latency(__mpStream, &ret, &negative) < 0) {
923 int _err = pa_context_errno(__mpContext);
924 if (_err != PA_ERR_NODATA)
925 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_latency() : err[%d]", _err);
927 return negative ? 0 : ret;
930 pa_threaded_mainloop_lock(__mpMainloop);
934 if (pa_stream_get_latency(__mpStream, &ret, &negative) >= 0)
937 int _err = pa_context_errno(__mpContext);
938 if (_err != PA_ERR_NODATA)
939 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_latency() : err[%d]", _err);
941 /* Wait until latency data is available again */
942 pa_threaded_mainloop_wait(__mpMainloop);
944 } catch (CAudioError& e) {
945 pa_threaded_mainloop_unlock(__mpMainloop);
949 pa_threaded_mainloop_unlock(__mpMainloop);
951 return negative ? 0 : ret;
954 pa_usec_t CPulseAudioClient::getFinalLatency() {
956 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
964 pa_threaded_mainloop_lock(__mpMainloop);
966 uint32_t ver = pa_context_get_server_protocol_version(__mpContext);
968 const pa_buffer_attr* buffer_attr = pa_stream_get_buffer_attr(__mpStream);
969 const pa_sample_spec* sample_spec = pa_stream_get_sample_spec(__mpStream);
970 const pa_timing_info* timing_info = pa_stream_get_timing_info(__mpStream);
972 if (!buffer_attr || !sample_spec || !timing_info)
973 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed to get buffer_attr[%p] or sample_spec[%p] or timing_info[%p] from a pa_stream",
974 buffer_attr, sample_spec, timing_info);
976 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
977 ret = (pa_bytes_to_usec(buffer_attr->tlength, sample_spec) + timing_info->configured_sink_usec);
978 AUDIO_IO_LOGD("FINAL PLAYBACK LATENCY[%" PRIu64 "]", ret);
980 ret = (pa_bytes_to_usec(buffer_attr->fragsize, sample_spec) + timing_info->configured_source_usec);
981 AUDIO_IO_LOGD("FINAL RECORD LATENCY[%" PRIu64 "]", ret);
984 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_SUPPORTED, "This version(ver.%d) is not supported", ver);
988 pa_threaded_mainloop_unlock(__mpMainloop);
989 } catch (CAudioError& e) {
991 pa_threaded_mainloop_unlock(__mpMainloop);