2 * 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.
19 #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),
49 __mIsOperationSuccess(false),
50 __mpSyncReadDataPtr(NULL),
53 __mIsUsedSyncRead(false),
54 __mIsFirstStream(false),
59 CPulseAudioClient::~CPulseAudioClient() {
63 void CPulseAudioClient::__contextStateChangeCb(pa_context* c, void* user_data) {
64 CPulseAudioClient* 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 void CPulseAudioClient::__successContextCb(pa_context* c, int success, void* user_data) {
90 AUDIO_IO_LOGD("pa_context[%p], success[%d], user_data[%p]", c, success, user_data);
94 CPulseAudioClient* pClient = static_cast<CPulseAudioClient*>(user_data);
95 pClient->__mIsOperationSuccess = static_cast<bool>(success);
97 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
100 static bool __is_microphone_restricted(void) {
103 device_policy_manager_h dpm_h = NULL;
106 if ((dpm_h = dpm_manager_create())) {
107 /* state: 0(disallowed), 1(allowed) */
108 if ((ret = dpm_restriction_get_microphone_state(dpm_h, &state)))
109 AUDIO_IO_LOGE("Failed to dpm_restriction_get_microphone_state(), ret(0x%x)", ret);
110 dpm_manager_destroy(dpm_h);
111 AUDIO_IO_LOGD("microphone restriction state: %d(1:allowed, 0:disallowed)", state);
113 AUDIO_IO_LOGE("Failed to dpm_manager_create()");
116 return (state ? false : true);
120 void CPulseAudioClient::__streamStateChangeCb(pa_stream* s, void* user_data) {
124 CPulseAudioClient* pClient = static_cast<CPulseAudioClient*>(user_data);
126 switch (pa_stream_get_state(s)) {
127 case PA_STREAM_READY:
128 AUDIO_IO_LOGD("The stream is ready");
129 pClient->__mpListener->onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING);
130 if (pClient->__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
131 pClient->__mIsFirstStream = true;
132 pClient->__mIsInit = true;
133 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
136 case PA_STREAM_FAILED:
137 AUDIO_IO_LOGD("The stream is failed");
138 pClient->__mpListener->onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE,
139 __is_microphone_restricted());
140 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
143 case PA_STREAM_TERMINATED:
144 AUDIO_IO_LOGD("The stream is terminated");
145 pClient->__mpListener->onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE);
146 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
149 case PA_STREAM_UNCONNECTED:
150 case PA_STREAM_CREATING:
155 void CPulseAudioClient::__streamCaptureCb(pa_stream* s, size_t length, void* user_data) {
159 CPulseAudioClient* pClient = static_cast<CPulseAudioClient*>(user_data);
160 assert(pClient->__mpListener);
161 assert(pClient->__mpMainloop);
163 if (pClient->__mIsUsedSyncRead == true) {
164 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
167 pClient->__mpListener->onStream(pClient, length);
170 #ifndef DISABLE_MOBILE_BACK_COMP
171 static void __dummy_write(pa_stream* s, size_t length) {
172 char* dummy = new char[length];
173 memset(dummy, 0, length);
174 pa_stream_write(s, dummy, length, NULL, 0LL, PA_SEEK_RELATIVE);
179 void CPulseAudioClient::__streamPlaybackCb(pa_stream* s, size_t length, void* user_data) {
183 CPulseAudioClient* pClient = static_cast<CPulseAudioClient*>(user_data);
184 assert(pClient->__mpListener);
186 #ifndef DISABLE_MOBILE_BACK_COMP
187 if (pClient->__mIsInit == false) {
188 AUDIO_IO_LOGD("Occurred this listener when an out stream is on the way to create : Write dummy, length[%d]", length);
189 __dummy_write(s, length);
192 if (pClient->isCorked()) {
193 AUDIO_IO_LOGD("Occurred this listener when an out stream is CORKED : Write dummy, length[%d]", length);
194 __dummy_write(s, length);
199 pClient->__mpListener->onStream(pClient, length);
201 #ifndef DISABLE_MOBILE_BACK_COMP
202 /* If stream is not written in first callback during prepare,
203 then write dummy data to ensure the start */
204 if (pClient->__mSpec.getStreamLatency() == CPulseStreamSpec::EStreamLatency::STREAM_LATENCY_OUTPUT_DEFAULT_ASYNC &&
205 pClient->__mIsFirstStream) {
206 AUDIO_IO_LOGW("[async] Write dummy of length[%d] since not written in first callback during prepare", length);
207 __dummy_write(s, length);
208 pClient->__mIsFirstStream = false;
213 void CPulseAudioClient::__streamLatencyUpdateCb(pa_stream* s, void* user_data) {
217 CPulseAudioClient* pClient = static_cast<CPulseAudioClient*>(user_data);
219 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
222 void CPulseAudioClient::__streamStartedCb(pa_stream* s, void* user_data) {
226 CPulseAudioClient* pClient = static_cast<CPulseAudioClient*>(user_data);
228 AUDIO_IO_LOGD("stream %p started.", pClient);
230 pClient->__mIsStarted = true;
233 void CPulseAudioClient::__streamUnderflowCb(pa_stream* s, void* user_data) {
237 CPulseAudioClient* pClient = static_cast<CPulseAudioClient*>(user_data);
239 AUDIO_IO_LOGD("stream %p UnderFlow...", pClient);
241 pClient->__mIsStarted = false;
245 void CPulseAudioClient::__streamEventCb(pa_stream* s, const char *name, pa_proplist *pl, void *user_data) {
249 AUDIO_IO_LOGE("NAME : %s, Prop : %p", name, pl);
251 CPulseAudioClient* pClient = static_cast<CPulseAudioClient*>(user_data);
252 if (strcmp(name, PA_STREAM_EVENT_POP_TIMEOUT) == 0) {
253 pa_operation_unref(pa_stream_cork(pClient->__mpStream, 1, NULL, NULL));
258 void CPulseAudioClient::__successStreamCb(pa_stream* s, int success, void* user_data) {
259 AUDIO_IO_LOGD("pa_stream[%p], success[%d], user_data[%p]", s, success, user_data);
263 CPulseAudioClient* pClient = static_cast<CPulseAudioClient*>(user_data);
264 pClient->__mIsOperationSuccess = static_cast<bool>(success);
266 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
270 void CPulseAudioClient::__successDrainCbInThread(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 CPulseAudioClient* pClient = static_cast<CPulseAudioClient*>(user_data);
276 pClient->__mIsOperationSuccess = static_cast<bool>(success);
277 pClient->__mIsDraining = false;
281 void CPulseAudioClient::__successDrainCb(pa_stream* s, int success, void* user_data) {
282 AUDIO_IO_LOGD("pa_stream[%p], success[%d], user_data[%p]", s, success, user_data);
286 CPulseAudioClient* pClient = static_cast<CPulseAudioClient*>(user_data);
287 pClient->__mIsOperationSuccess = static_cast<bool>(success);
288 pClient->__mIsDraining = false;
290 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
293 void CPulseAudioClient::initialize() {
294 if (__mIsInit == true) {
302 // Allocates PA proplist
303 __mpPropList = pa_proplist_new();
304 if (__mpPropList == NULL) {
305 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_proplist_new()");
308 // Adds values on proplist for delivery to PULSEAUDIO
309 char *streamType = NULL;
310 CAudioInfo::EAudioType audioType = __mSpec.getAudioInfo().getAudioType();
311 __mSpec.getAudioInfo().convertAudioType2StreamType(audioType, &streamType);
312 pa_proplist_sets(__mpPropList, PA_PROP_MEDIA_ROLE, streamType);
314 int index = __mSpec.getAudioInfo().getAudioIndex();
316 pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_PARENT_ID, "%u", (unsigned int) index);
319 // Adds latency on proplist for delivery to PULSEAUDIO
320 AUDIO_IO_LOGD("LATENCY : %s[%d]", __mSpec.getStreamLatencyToString(), static_cast<int>(__mSpec.getStreamLatency()));
321 pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_TIZEN_AUDIO_LATENCY, "%s", __mSpec.getStreamLatencyToString());
323 // Allocates PA mainloop
324 __mpMainloop = pa_threaded_mainloop_new();
325 if (__mpMainloop == NULL) {
326 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_threaded_mainloop_new()");
329 // Allocates PA context
330 __mpContext = pa_context_new(pa_threaded_mainloop_get_api(__mpMainloop), CLIENT_NAME);
331 if (__mpContext == NULL) {
332 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_context_new()");
335 // Sets context state changed callback
336 pa_context_set_state_callback(__mpContext, __contextStateChangeCb, this);
338 // Connects this client with PA server
339 if (pa_context_connect(__mpContext, NULL, PA_CONTEXT_NOFLAGS, NULL) < 0) {
340 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_context_connect()");
343 // LOCK for synchronous connection
344 pa_threaded_mainloop_lock(__mpMainloop);
347 if (pa_threaded_mainloop_start(__mpMainloop) < 0) {
348 pa_threaded_mainloop_unlock(__mpMainloop);
349 THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_threaded_mainloop_start()");
352 // Connection process is asynchronously
353 // So, this function will be waited when occurred context state change event
354 // If I got a signal, do next processing
356 pa_context_state_t state;
357 state = pa_context_get_state(__mpContext);
359 if (state == PA_CONTEXT_READY) {
363 if (!PA_CONTEXT_IS_GOOD(state)) {
364 err = pa_context_errno(__mpContext);
365 pa_threaded_mainloop_unlock(__mpMainloop);
366 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "pa_context's state is not good : err[%d]", err);
369 /* Wait until the context is ready */
370 pa_threaded_mainloop_wait(__mpMainloop);
373 // Allocates PA stream
374 pa_sample_spec ss = __mSpec.getSampleSpec();
375 pa_channel_map map = __mSpec.getChannelMap();
377 __mpStream = pa_stream_new_with_proplist(__mpContext, __mSpec.getStreamName(), &ss, &map, __mpPropList);
378 if (__mpStream == NULL) {
379 pa_threaded_mainloop_unlock(__mpMainloop);
380 THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_new_with_proplist()");
383 // Sets stream callbacks
384 pa_stream_set_state_callback(__mpStream, __streamStateChangeCb, this);
385 pa_stream_set_read_callback(__mpStream, __streamCaptureCb, this);
386 pa_stream_set_write_callback(__mpStream, __streamPlaybackCb, this);
387 pa_stream_set_latency_update_callback(__mpStream, __streamLatencyUpdateCb, this);
388 pa_stream_set_event_callback(__mpStream, __streamEventCb, this);
389 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
390 pa_stream_set_started_callback(__mpStream, __streamStartedCb, this);
391 pa_stream_set_underflow_callback(__mpStream, __streamUnderflowCb, this);
394 // Connect stream with PA Server
396 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
397 pa_stream_flags_t flags = static_cast<pa_stream_flags_t>(
398 PA_STREAM_INTERPOLATE_TIMING |
399 PA_STREAM_ADJUST_LATENCY |
400 #ifndef DISABLE_MOBILE_BACK_COMP
401 PA_STREAM_START_CORKED |
403 PA_STREAM_AUTO_TIMING_UPDATE);
405 ret = pa_stream_connect_playback(__mpStream, NULL, NULL, flags, NULL, NULL);
407 pa_stream_flags_t flags = static_cast<pa_stream_flags_t>(
408 PA_STREAM_INTERPOLATE_TIMING |
409 PA_STREAM_ADJUST_LATENCY |
410 #ifndef DISABLE_MOBILE_BACK_COMP
411 PA_STREAM_START_CORKED |
413 PA_STREAM_AUTO_TIMING_UPDATE);
415 ret = pa_stream_connect_record(__mpStream, NULL, NULL, flags);
419 err = pa_context_errno(__mpContext);
420 pa_threaded_mainloop_unlock(__mpMainloop);
421 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_connect() : err[%d]", err);
425 pa_stream_state_t state;
426 state = pa_stream_get_state(__mpStream);
428 if (state == PA_STREAM_READY) {
429 AUDIO_IO_LOGD("STREAM READY");
433 if (!PA_STREAM_IS_GOOD(state)) {
434 err = pa_context_errno(__mpContext);
435 pa_threaded_mainloop_unlock(__mpMainloop);
436 if (err == PA_ERR_ACCESS) {
437 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_DEVICE_POLICY_RESTRICTION, "pa_stream's state is not good : err[%d]", err);
439 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "pa_stream's state is not good : err[%d]", err);
443 /* Wait until the stream is ready */
444 pa_threaded_mainloop_wait(__mpMainloop);
447 // End of synchronous
448 pa_threaded_mainloop_unlock(__mpMainloop);
450 // __mIsInit = true; // Moved to __streamStateChangeCb()
451 } catch (CAudioError& e) {
457 void CPulseAudioClient::finalize() {
460 if (__mpMainloop && isInThread() == false)
461 pa_threaded_mainloop_lock(__mpMainloop);
463 /* clear callbacks */
465 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
466 pa_stream_set_write_callback(__mpStream, NULL, NULL);
468 pa_stream_set_read_callback(__mpStream, NULL, NULL);
469 pa_stream_set_latency_update_callback(__mpStream, NULL, NULL);
470 pa_stream_set_event_callback(__mpStream, NULL, NULL);
473 if (__mpMainloop && isInThread() == false)
474 pa_threaded_mainloop_unlock(__mpMainloop);
476 /* Wait for drain complete if draining before finalize */
478 unsigned int drain_wait_count = 0;
479 while (__mIsDraining && drain_wait_count++ < drain_wait_max_count) {
480 usleep(drain_wait_interval);
482 AUDIO_IO_LOGD("wait for drain complete!!!! [%d * %d usec]",
483 drain_wait_count, drain_wait_interval);
486 if (__mpMainloop != NULL) {
487 pa_threaded_mainloop_stop(__mpMainloop);
490 if (__mpStream != NULL) {
491 pa_stream_disconnect(__mpStream);
492 pa_stream_unref(__mpStream);
496 if (__mpContext != NULL) {
497 pa_context_disconnect(__mpContext);
498 pa_context_unref(__mpContext);
502 if (__mpMainloop != NULL) {
503 pa_threaded_mainloop_free(__mpMainloop);
507 if (__mpPropList != NULL) {
508 pa_proplist_free(__mpPropList);
515 int CPulseAudioClient::read(void* buffer, size_t length) {
516 if (__mIsInit == false) {
517 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
522 if (buffer == NULL) {
523 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "The parameter is invalid : buffer[%p]", buffer);
526 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
527 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client couldn't use this function");
530 size_t lengthIter = length;
533 __mIsUsedSyncRead = true;
536 pa_threaded_mainloop_lock(__mpMainloop);
538 while (lengthIter > 0) {
541 while (__mpSyncReadDataPtr == NULL) {
542 ret = pa_stream_peek(__mpStream, &__mpSyncReadDataPtr, &__mSyncReadLength);
544 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_peek() : ret[%d]", ret);
547 if (__mSyncReadLength <= 0) {
548 #ifdef _AUDIO_IO_DEBUG_TIMING_
549 AUDIO_IO_LOGD("readLength(%d byte) is not valid. wait...", __mSyncReadLength);
551 pa_threaded_mainloop_wait(__mpMainloop);
552 } else if (__mpSyncReadDataPtr == NULL) {
553 // Data peeked, but it doesn't have any data
554 ret = pa_stream_drop(__mpStream);
556 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_drop() : ret[%d]", ret);
559 __mSyncReadIndex = 0;
563 if (__mSyncReadLength < lengthIter) {
564 l = __mSyncReadLength;
569 // Copy partial pcm data on out parameter
570 #ifdef _AUDIO_IO_DEBUG_TIMING_
571 AUDIO_IO_LOGD("memcpy() that a peeked buffer[0x%x], index[%d], length[%d] on out buffer", (const uint8_t*)(__mpSyncReadDataPtr) + __mSyncReadIndex, __mSyncReadIndex, l);
573 memcpy(buffer, (const uint8_t*)__mpSyncReadDataPtr + __mSyncReadIndex, l);
575 // Move next position
576 buffer = (uint8_t*)buffer + l;
579 // Adjusts the rest length
580 __mSyncReadIndex += l;
581 __mSyncReadLength -= l;
583 if (__mSyncReadLength == 0) {
584 #ifdef _AUDIO_IO_DEBUG_TIMING_
585 AUDIO_IO_LOGD("__mSyncReadLength is zero, do drop()");
587 ret = pa_stream_drop(__mpStream);
589 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_drop() : ret[%d]", ret);
592 // Reset the internal pointer
593 __mpSyncReadDataPtr = NULL;
594 __mSyncReadLength = 0;
595 __mSyncReadIndex = 0;
597 } // End of while (lengthIter > 0)
599 pa_threaded_mainloop_unlock(__mpMainloop);
600 __mIsUsedSyncRead = false;
601 } catch (CAudioError& e) {
602 pa_threaded_mainloop_unlock(__mpMainloop);
603 __mIsUsedSyncRead = false;
610 int CPulseAudioClient::peek(const void** buffer, size_t* length) {
611 if (__mIsInit == false) {
612 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
617 if (buffer == NULL || length == NULL) {
618 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "The parameter is invalid : buffer[%p], length[%p]", buffer, length);
621 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
622 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client couldn't use this function");
627 if (isInThread() == false) {
628 pa_threaded_mainloop_lock(__mpMainloop);
629 ret = pa_stream_peek(__mpStream, buffer, length);
630 pa_threaded_mainloop_unlock(__mpMainloop);
632 ret = pa_stream_peek(__mpStream, buffer, length);
635 #ifdef _AUDIO_IO_DEBUG_TIMING_
636 AUDIO_IO_LOGD("buffer[%p], length[%d]", *buffer, *length);
640 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_peek() : err[%d]", ret);
646 int CPulseAudioClient::drop() {
647 if (__mIsInit == false) {
648 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
651 #ifdef _AUDIO_IO_DEBUG_TIMING_
657 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
658 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client couldn't use this function");
663 if (isInThread() == false) {
664 pa_threaded_mainloop_lock(__mpMainloop);
665 ret = pa_stream_drop(__mpStream);
666 pa_threaded_mainloop_unlock(__mpMainloop);
668 ret = pa_stream_drop(__mpStream);
672 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_drop() : err[%d]", ret);
678 int CPulseAudioClient::write(const void* data, size_t length) {
680 THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_ARGUMENT, "The parameter is invalid");
683 if (__mDirection == EStreamDirection::STREAM_DIRECTION_RECORD) {
684 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client couldn't use this function");
689 #ifdef _AUDIO_IO_DEBUG_TIMING_
690 AUDIO_IO_LOGD("data[%p], length[%d], First[%d]", data, length, __mIsFirstStream);
692 if (pa_stream_is_corked(__mpStream)) {
693 AUDIO_IO_LOGW("stream is corked...do uncork here first!!!!");
694 pa_operation_unref(pa_stream_cork(__mpStream, 0, NULL, this));
697 if (isInThread() == false) {
698 pa_threaded_mainloop_lock(__mpMainloop);
699 ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
700 pa_threaded_mainloop_unlock(__mpMainloop);
702 if (__mIsFirstStream) {
703 const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
704 uint32_t prebuf = attr->prebuf;
705 // Compensate amount of prebuf in first stream callback when audio-io use prebuf(-1)
706 // Because a stream will never start when an application wrote less than prebuf at first
707 if (length < prebuf) {
708 char* dummy = new char[prebuf - length];
709 memset(dummy, 0, prebuf - length);
710 pa_stream_write(__mpStream, dummy, prebuf - length, NULL, 0LL, PA_SEEK_RELATIVE);
713 __mIsFirstStream = false;
714 AUDIO_IO_LOGW("FIRST STREAM CALLBACK : length[%d], prebuf[%d], dummy[%d]",
715 length, prebuf, (length < prebuf) ? prebuf - length : 0);
717 ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
721 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_write() : err[%d]", ret);
727 void CPulseAudioClient::cork(bool cork) {
728 AUDIO_IO_LOGD("cork[%d]", cork);
730 if (__mIsInit == false) {
731 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
734 if (isInThread() == true) {
735 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This operation is not supported in callback");
740 // Set __mIsFirstStream flag when uncork(resume) stream, because prebuf will be enable again
742 __mIsFirstStream = true;
744 if (isInThread() == false) {
745 pa_threaded_mainloop_lock(__mpMainloop);
746 pa_operation_unref(pa_stream_cork(__mpStream, static_cast<int>(cork), __successStreamCb, this));
747 pa_threaded_mainloop_unlock(__mpMainloop);
749 pa_operation_unref(pa_stream_cork(__mpStream, static_cast<int>(cork), __successStreamCb, this));
755 bool CPulseAudioClient::isCorked() {
756 if (__mIsInit == false) {
757 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
764 if (isInThread() == false) {
765 pa_threaded_mainloop_lock(__mpMainloop);
766 isCork = pa_stream_is_corked(__mpStream);
767 pa_threaded_mainloop_unlock(__mpMainloop);
769 isCork = pa_stream_is_corked(__mpStream);
772 #ifdef _AUDIO_IO_DEBUG_TIMING_
773 AUDIO_IO_LOGD("isCork[%d]", isCork);
775 return static_cast<bool>(isCork);
778 bool CPulseAudioClient::drain() {
779 if (__mIsInit == false) {
780 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
786 AUDIO_IO_LOGW("Corked...");
791 AUDIO_IO_LOGW("already draining...");
796 AUDIO_IO_LOGW("stream not started yet...skip drain");
800 if (isInThread() == false) {
801 AUDIO_IO_LOGD("drain");
802 pa_threaded_mainloop_lock(__mpMainloop);
803 pa_operation* o = pa_stream_drain(__mpStream, __successDrainCb, this);
804 __mIsDraining = true;
805 while (pa_operation_get_state(o) == PA_OPERATION_RUNNING) {
806 pa_threaded_mainloop_wait(__mpMainloop);
808 pa_operation_unref(o);
809 pa_threaded_mainloop_unlock(__mpMainloop);
810 AUDIO_IO_LOGD("drain done");
812 AUDIO_IO_LOGD("drain in thread");
813 pa_operation_unref(pa_stream_drain(__mpStream, __successDrainCbInThread, this));
814 __mIsDraining = true;
820 bool CPulseAudioClient::flush() {
821 if (__mIsInit == false) {
822 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
827 if (isInThread() == false) {
828 AUDIO_IO_LOGD("flush");
829 pa_threaded_mainloop_lock(__mpMainloop);
830 pa_operation_unref(pa_stream_flush(__mpStream, __successStreamCb, this));
831 pa_threaded_mainloop_unlock(__mpMainloop);
833 AUDIO_IO_LOGD("flush in thread");
834 pa_operation_unref(pa_stream_flush(__mpStream, __successStreamCb, this));
840 size_t CPulseAudioClient::getWritableSize() {
841 if (__mIsInit == false) {
842 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
847 if (__mDirection != EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
848 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Playback");
853 if (isInThread() == false) {
854 pa_threaded_mainloop_lock(__mpMainloop);
855 ret = pa_stream_writable_size(__mpStream);
856 pa_threaded_mainloop_unlock(__mpMainloop);
858 ret = pa_stream_writable_size(__mpStream);
864 void CPulseAudioClient::checkRunningState() {
865 if (__mpContext == NULL || PA_CONTEXT_IS_GOOD(pa_context_get_state(__mpContext)) == 0) {
866 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, "The context[%p] is not created or not good state", __mpContext);
868 if (__mpStream == NULL || PA_STREAM_IS_GOOD(pa_stream_get_state(__mpStream)) == 0) {
869 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, "The stream[%p] is not created or not good state", __mpStream);
871 if (pa_context_get_state(__mpContext) != PA_CONTEXT_READY || pa_stream_get_state(__mpStream) != PA_STREAM_READY) {
872 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, "The context[%p] or stream[%p] state is not ready", __mpContext, __mpStream);
875 #ifdef _AUDIO_IO_DEBUG_TIMING_
876 AUDIO_IO_LOGD("This client is running");
880 bool CPulseAudioClient::isInThread() {
881 int ret = pa_threaded_mainloop_in_thread(__mpMainloop);
883 #ifdef _AUDIO_IO_DEBUG_TIMING_
884 AUDIO_IO_LOGD("isInThread[%d]", ret);
886 return static_cast<bool>(ret);
890 size_t CPulseAudioClient::getReadableSize() {
891 if (__mIsInit == false) {
892 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
897 if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD) {
898 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Capture");
903 if (isInThread() == false) {
904 pa_threaded_mainloop_lock(__mpMainloop);
905 ret = pa_stream_writable_size(__mpStream);
906 pa_threaded_mainloop_unlock(__mpMainloop);
908 ret = pa_stream_writable_size(__mpStream);
914 size_t CPulseAudioClient::getBufferSize() {
915 if (__mIsInit == false) {
916 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
924 if (isInThread() == false) {
925 pa_threaded_mainloop_lock(__mpMainloop);
928 const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
930 int _err = pa_context_errno(__mpContext);
931 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_buffer_attr() : err[%d]", _err);
934 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
936 AUDIO_IO_LOGD("PLAYBACK buffer size[%d]", ret);
938 ret = attr->fragsize;
939 AUDIO_IO_LOGD("RECORD buffer size[%d]", ret);
941 } catch (CAudioError& e) {
942 if (isInThread() == false) {
943 pa_threaded_mainloop_unlock(__mpMainloop);
948 if (isInThread() == false) {
949 pa_threaded_mainloop_unlock(__mpMainloop);
955 pa_usec_t CPulseAudioClient::getLatency() {
956 if (__mIsInit == false) {
957 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
965 if (isInThread() == false) {
966 if (pa_stream_get_latency(__mpStream, &ret, &negative) < 0) {
967 int _err = pa_context_errno(__mpContext);
968 if (_err != PA_ERR_NODATA) {
969 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_latency() : err[%d]", _err);
972 return negative ? 0 : ret;
975 pa_threaded_mainloop_lock(__mpMainloop);
979 if (pa_stream_get_latency(__mpStream, &ret, &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, "Failed pa_stream_get_latency() : err[%d]", _err);
988 /* Wait until latency data is available again */
989 pa_threaded_mainloop_wait(__mpMainloop);
991 } catch (CAudioError& e) {
992 pa_threaded_mainloop_unlock(__mpMainloop);
996 pa_threaded_mainloop_unlock(__mpMainloop);
998 return negative ? 0 : ret;
1001 pa_usec_t CPulseAudioClient::getFinalLatency() {
1002 if (__mIsInit == false) {
1003 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
1006 checkRunningState();
1012 if (isInThread() == false) {
1013 pa_threaded_mainloop_lock(__mpMainloop);
1016 ver = pa_context_get_server_protocol_version(__mpContext);
1018 const pa_buffer_attr* buffer_attr = pa_stream_get_buffer_attr(__mpStream);
1019 const pa_sample_spec* sample_spec = pa_stream_get_sample_spec(__mpStream);
1020 const pa_timing_info* timing_info = pa_stream_get_timing_info(__mpStream);
1022 if (buffer_attr == NULL || sample_spec == NULL || timing_info == NULL) {
1023 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",
1024 buffer_attr, sample_spec, timing_info);
1027 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
1028 ret = (pa_bytes_to_usec(buffer_attr->tlength, sample_spec) + timing_info->configured_sink_usec);
1029 AUDIO_IO_LOGD("FINAL PLAYBACK LATENCY[%" PRIu64 "]", ret);
1031 ret = (pa_bytes_to_usec(buffer_attr->fragsize, sample_spec) + timing_info->configured_source_usec);
1032 AUDIO_IO_LOGD("FINAL RECORD LATENCY[%" PRIu64 "]", ret);
1035 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_SUPPORTED, "This version(ver.%d) is not supported", ver);
1038 if (isInThread() == false) {
1039 pa_threaded_mainloop_unlock(__mpMainloop);
1041 } catch (CAudioError& e) {
1042 if (isInThread() == false) {
1043 pa_threaded_mainloop_unlock(__mpMainloop);
1051 CPulseAudioClient::EStreamDirection CPulseAudioClient::getStreamDirection() {
1052 return __mDirection;
1055 CPulseStreamSpec CPulseAudioClient::getStreamSpec() {