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);
139 switch (pa_stream_get_state(s)) {
140 case PA_STREAM_READY:
141 AUDIO_IO_LOGD("The pa_stream[%p] is ready", s);
142 pClient->__mpListener->setState(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING);
143 pClient->__mpListener->onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING);
144 if (pClient->__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
145 pClient->__mIsFirstStream = true;
146 pClient->__mIsInit = true;
147 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
151 case PA_STREAM_FAILED:
152 AUDIO_IO_LOGD("The pa_stream[%p] is failed", s);
153 pClient->__mpListener->setState(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE);
154 pClient->__mpListener->onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE,
155 __is_microphone_restricted());
156 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
160 case PA_STREAM_TERMINATED:
161 AUDIO_IO_LOGD("The pa_stream[%p] is terminated", s);
162 pClient->__mpListener->setState(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE);
163 pClient->__mpListener->onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE);
164 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
167 case PA_STREAM_UNCONNECTED:
168 case PA_STREAM_CREATING:
173 void CPulseAudioClient::__streamCaptureCb(pa_stream* s, size_t length, void* user_data) {
177 auto pClient = static_cast<CPulseAudioClient*>(user_data);
178 assert(pClient->__mpListener);
179 assert(pClient->__mpMainloop);
181 if (pClient->__mIsUsedSyncRead)
182 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
184 pClient->__mpListener->onStream(pClient, length);
187 static void __dummy_write(pa_stream* s, size_t length) {
188 pa_stream_write(s, std::vector<char>(length).data(), length, NULL, 0LL, PA_SEEK_RELATIVE);
191 void CPulseAudioClient::__streamPlaybackCb(pa_stream* s, size_t length, void* user_data) {
195 auto pClient = static_cast<CPulseAudioClient*>(user_data);
196 assert(pClient->__mpListener);
198 #ifndef DISABLE_MOBILE_BACK_COMP
199 if (!pClient->__mIsInit) {
200 AUDIO_IO_LOGD("pa_stream[%p] is on the way to create : Write dummy, length[%zu]", s, length);
201 __dummy_write(s, length);
204 if (pClient->isCorked()) {
205 AUDIO_IO_LOGD("pa_stream[%p] is CORKED : Write dummy, length[%zu]", s, length);
206 __dummy_write(s, length);
211 pClient->__mpListener->onStream(pClient, length);
213 #ifndef DISABLE_MOBILE_BACK_COMP
214 /* If stream is not written in first callback during prepare,
215 then write dummy data to ensure the start */
216 if (pClient->__mSpec.getStreamLatency() == CPulseStreamSpec::EStreamLatency::STREAM_LATENCY_OUTPUT_DEFAULT_ASYNC &&
217 pClient->__mIsFirstStream) {
218 AUDIO_IO_LOGW("[async] pa_stream[%p] : not written in the first callback during prepare, write dummy of length[%zu]",
220 __dummy_write(s, length);
221 pClient->__mIsFirstStream = false;
226 void CPulseAudioClient::__streamLatencyUpdateCb(pa_stream* s, void* user_data) {
230 auto pClient = static_cast<CPulseAudioClient*>(user_data);
232 #ifdef _AUDIO_IO_DEBUG_TIMING_
233 /* FIXME : print some useful latency info */
234 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] latency updated", pClient, s);
237 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
240 void CPulseAudioClient::__streamStartedCb(pa_stream* s, void* user_data) {
244 auto pClient = static_cast<CPulseAudioClient*>(user_data);
246 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] started", pClient, s);
248 pClient->__mIsStarted = true;
251 void CPulseAudioClient::__streamUnderflowCb(pa_stream* s, void* user_data) {
255 auto pClient = static_cast<CPulseAudioClient*>(user_data);
257 AUDIO_IO_LOGD("pClient[%p] pa_stream[%p] UnderFlow...", pClient, s);
259 pClient->__mIsStarted = false;
263 void CPulseAudioClient::__streamEventCb(pa_stream* s, const char *name, pa_proplist *pl, void *user_data) {
267 auto pClient = static_cast<CPulseAudioClient*>(user_data);
269 AUDIO_IO_LOGW("pClient[%p] pa_stream[%p] : name[%s], proplist[%p]", pClient, s, name, pl);
271 if (strcmp(name, PA_STREAM_EVENT_POP_TIMEOUT) == 0)
272 pa_operation_unref(pa_stream_cork(pClient->__mpStream, 1, NULL, NULL));
276 void CPulseAudioClient::__successStreamCb(pa_stream* s, int success, void* user_data) {
280 auto pClient = static_cast<CPulseAudioClient*>(user_data);
282 AUDIO_IO_LOGD("pClient[%p], pa_stream[%p], success[%d], user_data[%p]", pClient, s, success, user_data);
284 pClient->__mIsOperationSuccess = static_cast<bool>(success);
286 /* FIXME : verify following action without any waitings */
287 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
291 void CPulseAudioClient::__successDrainCbInThread(pa_stream* s, int success, void* user_data) {
295 auto pClient = static_cast<CPulseAudioClient*>(user_data);
297 AUDIO_IO_LOGD("pClient[%p], pa_stream[%p], success[%d], user_data[%p]", pClient, s, success, user_data);
299 pClient->__mIsOperationSuccess = static_cast<bool>(success);
300 pClient->__mIsDraining = false;
304 void CPulseAudioClient::__successDrainCb(pa_stream* s, int success, void* user_data) {
308 auto pClient = static_cast<CPulseAudioClient*>(user_data);
310 AUDIO_IO_LOGD("pClient[%p], pa_stream[%p], success[%d], user_data[%p]", pClient, s, success, user_data);
312 pClient->__mIsOperationSuccess = static_cast<bool>(success);
313 pClient->__mIsDraining = false;
315 pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
318 void CPulseAudioClient::__successVolumeCb(pa_context *c, int success, void *user_data) {
319 AUDIO_IO_LOGD("pa_context[%p], success[%d], user_data[%p]", c, success, user_data);
322 void CPulseAudioClient::initialize() {
330 // Allocates PA proplist
331 __mpPropList = pa_proplist_new();
333 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_proplist_new()"); //LCOV_EXCL_LINE
335 // Adds values on proplist for delivery to PULSEAUDIO
336 pa_proplist_sets(__mpPropList, PA_PROP_MEDIA_ROLE, __mSpec.getAudioInfo().getConvertedStreamType());
338 int index = __mSpec.getAudioInfo().getAudioIndex();
340 pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_PARENT_ID, "%u", (unsigned int) index);
342 // Adds latency on proplist for delivery to PULSEAUDIO
343 AUDIO_IO_LOGD("LATENCY : %s[%d]", __mSpec.getStreamLatencyToString(), static_cast<int>(__mSpec.getStreamLatency()));
344 pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_TIZEN_AUDIO_LATENCY, "%s", __mSpec.getStreamLatencyToString());
346 // Allocates PA mainloop
347 __mpMainloop = pa_threaded_mainloop_new();
349 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_threaded_mainloop_new()"); //LCOV_EXCL_LINE
351 // Allocates PA context
352 __mpContext = pa_context_new(pa_threaded_mainloop_get_api(__mpMainloop), CLIENT_NAME);
354 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_context_new()"); //LCOV_EXCL_LINE
356 // Sets context state changed callback
357 pa_context_set_state_callback(__mpContext, __contextStateChangeCb, this);
359 // Connects this client with PA server
360 if (pa_context_connect(__mpContext, NULL, PA_CONTEXT_NOFLAGS, NULL) < 0)
361 THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_context_connect()"); //LCOV_EXCL_LINE
363 // LOCK for synchronous connection
364 CPulseThreadLocker locker{__mpMainloop};
367 if (pa_threaded_mainloop_start(__mpMainloop) < 0) {
369 THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_threaded_mainloop_start()");
373 // Connection process is asynchronously
374 // So, this function will be waited when occurred context state change event
375 // If I got a signal, do next processing
377 pa_context_state_t state;
378 state = pa_context_get_state(__mpContext);
380 if (state == PA_CONTEXT_READY)
383 if (!PA_CONTEXT_IS_GOOD(state)) {
385 err = pa_context_errno(__mpContext);
386 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION,
387 "pa_context's state is not good : err[%d]", err);
391 /* Wait until the context is ready */
392 pa_threaded_mainloop_wait(__mpMainloop);
395 // Allocates PA stream
396 pa_sample_spec ss = __mSpec.getSampleSpec();
397 pa_channel_map map = __mSpec.getChannelMap();
399 __mpStream = pa_stream_new_with_proplist(__mpContext, __mSpec.getStreamName(), &ss, &map, __mpPropList);
402 THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_new_with_proplist()");
406 // Sets stream callbacks
407 pa_stream_set_state_callback(__mpStream, __streamStateChangeCb, this);
408 pa_stream_set_read_callback(__mpStream, __streamCaptureCb, this);
409 pa_stream_set_write_callback(__mpStream, __streamPlaybackCb, this);
410 pa_stream_set_latency_update_callback(__mpStream, __streamLatencyUpdateCb, this);
411 pa_stream_set_event_callback(__mpStream, __streamEventCb, this);
412 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
413 pa_stream_set_started_callback(__mpStream, __streamStartedCb, this);
414 pa_stream_set_underflow_callback(__mpStream, __streamUnderflowCb, this);
417 // Connect stream with PA Server
419 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
420 auto flags = static_cast<pa_stream_flags_t>(
421 PA_STREAM_INTERPOLATE_TIMING |
422 PA_STREAM_ADJUST_LATENCY |
423 #ifndef DISABLE_MOBILE_BACK_COMP
424 PA_STREAM_START_CORKED |
426 PA_STREAM_AUTO_TIMING_UPDATE);
428 ret = pa_stream_connect_playback(__mpStream, NULL, NULL, flags, NULL, NULL);
430 auto flags = static_cast<pa_stream_flags_t>(
431 PA_STREAM_INTERPOLATE_TIMING |
432 PA_STREAM_ADJUST_LATENCY |
433 #ifndef DISABLE_MOBILE_BACK_COMP
434 PA_STREAM_START_CORKED |
436 PA_STREAM_AUTO_TIMING_UPDATE);
438 ret = pa_stream_connect_record(__mpStream, NULL, NULL, flags);
443 err = pa_context_errno(__mpContext);
444 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
445 "Failed pa_stream_connect() : err[%d]", err);
450 pa_stream_state_t state = pa_stream_get_state(__mpStream);
452 if (state == PA_STREAM_READY) {
453 AUDIO_IO_LOGD("STREAM READY");
457 if (!PA_STREAM_IS_GOOD(state)) {
458 err = pa_context_errno(__mpContext);
459 if (err == PA_ERR_ACCESS)
460 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_DEVICE_POLICY_RESTRICTION,
461 "pa_stream's state is not good : err[%d]", err);
463 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, //LCOV_EXCL_LINE
464 "pa_stream's state is not good : err[%d]", err); //LCOV_EXCL_LINE
467 /* Wait until the stream is ready */
468 pa_threaded_mainloop_wait(__mpMainloop);
471 // __mIsInit = true; // Moved to __streamStateChangeCb()
472 } catch (const CAudioError& e) {
479 AUDIO_IO_LOGD("Done : pa_context[%p], pa_mainloop[%p], pa_stream[%p]", __mpContext, __mpMainloop, __mpStream);
482 void CPulseAudioClient::finalize() {
483 AUDIO_IO_LOGD("pa_context[%p], pa_mainloop[%p], pa_stream[%p]", __mpContext, __mpMainloop, __mpStream);
488 bool is_in_thread = isInThread();
493 pa_threaded_mainloop_lock(__mpMainloop);
495 /* clear callbacks */
497 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
498 pa_stream_set_write_callback(__mpStream, NULL, NULL);
500 pa_stream_set_read_callback(__mpStream, NULL, NULL);
501 pa_stream_set_latency_update_callback(__mpStream, NULL, NULL);
502 pa_stream_set_event_callback(__mpStream, NULL, NULL);
506 pa_threaded_mainloop_unlock(__mpMainloop);
508 /* Wait for drain complete if draining before finalize */
510 unsigned int drain_wait_count = 0;
511 while (__mIsDraining && drain_wait_count++ < drain_wait_max_count)
512 usleep(drain_wait_interval);
513 AUDIO_IO_LOGD("wait for drain complete!!!! [%d * %d usec]",
514 drain_wait_count, drain_wait_interval);
518 pa_threaded_mainloop_stop(__mpMainloop);
521 pa_stream_disconnect(__mpStream);
522 pa_stream_unref(__mpStream);
523 __mpStream = nullptr;
527 pa_context_disconnect(__mpContext);
528 pa_context_unref(__mpContext);
529 __mpContext = nullptr;
533 pa_threaded_mainloop_free(__mpMainloop);
534 __mpMainloop = nullptr;
538 pa_proplist_free(__mpPropList);
539 __mpPropList = nullptr;
542 AUDIO_IO_LOGD("Done");
545 int CPulseAudioClient::read(void* buffer, size_t length) {
547 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); //LCOV_EXCL_LINE
552 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "invalid parameter : buffer[%p]", buffer); //LCOV_EXCL_LINE
554 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
555 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback client can't use this function"); //LCOV_EXCL_LINE
557 size_t lengthIter = length;
560 __mIsUsedSyncRead = true;
563 CPulseThreadLocker locker{__mpMainloop};
565 while (lengthIter > 0) {
568 while (!__mpSyncReadDataPtr) {
569 ret = pa_stream_peek(__mpStream, &__mpSyncReadDataPtr, &__mSyncReadLength);
571 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_peek() : ret[%d]", ret); //LCOV_EXCL_LINE
573 if (__mSyncReadLength <= 0) {
574 #ifdef _AUDIO_IO_DEBUG_TIMING_
575 AUDIO_IO_LOGD("readLength(%zu byte) is not valid. wait...", __mSyncReadLength);
577 pa_threaded_mainloop_wait(__mpMainloop);
578 } else if (!__mpSyncReadDataPtr) {
580 // Data peeked, but it doesn't have any data
581 ret = pa_stream_drop(__mpStream);
583 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_drop() : ret[%d]", ret);
586 __mSyncReadIndex = 0;
590 l = min(__mSyncReadLength, lengthIter);
592 // Copy partial pcm data on out parameter
593 #ifdef _AUDIO_IO_DEBUG_TIMING_
594 AUDIO_IO_LOGD("memcpy() that a peeked buffer[%p], index[%zu], length[%zu] on out buffer", (const uint8_t*)(__mpSyncReadDataPtr) + __mSyncReadIndex, __mSyncReadIndex, l);
596 memcpy(buffer, (const uint8_t*)__mpSyncReadDataPtr + __mSyncReadIndex, l);
598 // Move next position
599 buffer = (uint8_t*)buffer + l;
602 // Adjusts the rest length
603 __mSyncReadIndex += l;
604 __mSyncReadLength -= l;
606 if (__mSyncReadLength == 0) {
607 #ifdef _AUDIO_IO_DEBUG_TIMING_
608 AUDIO_IO_LOGD("__mSyncReadLength is zero, do drop()");
610 ret = pa_stream_drop(__mpStream);
612 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, //LCOV_EXCL_LINE
613 "Failed pa_stream_drop() : ret[%d]", ret); //LCOV_EXCL_LINE
615 // Reset the internal pointer
616 __mpSyncReadDataPtr = nullptr;
617 __mSyncReadLength = 0;
618 __mSyncReadIndex = 0;
620 } // End of while (lengthIter > 0)
622 __mIsUsedSyncRead = false;
623 } catch (const CAudioError& e) {
625 __mIsUsedSyncRead = false;
633 int CPulseAudioClient::peek(const void** buffer, size_t* length) {
635 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
639 if (!buffer || !length)
640 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, // LCOV_EXCL_LINE
641 "invalid parameter : buffer[%p], length[%p]", buffer, length); // LCOV_EXCL_LINE
643 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
644 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
646 CPulseThreadLocker locker{__mpMainloop};
648 int ret = pa_stream_peek(__mpStream, buffer, length);
651 #ifdef _AUDIO_IO_DEBUG_TIMING_
652 AUDIO_IO_LOGD("buffer[%p], length[%zu]", *buffer, *length);
656 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_peek() : err[%d]", ret); //LCOV_EXCL_LINE
661 int CPulseAudioClient::drop() {
663 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
665 #ifdef _AUDIO_IO_DEBUG_TIMING_
671 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
672 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
674 CPulseThreadLocker locker{__mpMainloop};
676 int ret = pa_stream_drop(__mpStream);
678 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_drop() : err[%d]", ret); //LCOV_EXCL_LINE
683 int CPulseAudioClient::write(const void* data, size_t length) {
685 THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_ARGUMENT, "invalid parameter"); // LCOV_EXCL_LINE
687 if (__mDirection == EStreamDirection::STREAM_DIRECTION_RECORD)
688 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
692 #ifdef _AUDIO_IO_DEBUG_TIMING_
693 AUDIO_IO_LOGD("data[%p], length[%zu], First[%d]", data, length, __mIsFirstStream);
697 CPulseThreadLocker locker{__mpMainloop};
698 if (pa_stream_is_corked(__mpStream)) {
699 AUDIO_IO_LOGW("stream is corked...do uncork here first!!!!");
700 pa_operation_unref(pa_stream_cork(__mpStream, 0, NULL, this));
703 ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
706 if (pa_stream_is_corked(__mpStream)) {
707 AUDIO_IO_LOGW("stream is corked...do uncork here first!!!!");
708 pa_operation_unref(pa_stream_cork(__mpStream, 0, NULL, this));
711 if (__mIsFirstStream) {
712 const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
713 uint32_t prebuf = attr->prebuf;
714 // Compensate amount of prebuf in first stream callback when audio-io use prebuf(-1)
715 // Because a stream will never start when an application wrote less than prebuf at first
717 __dummy_write(__mpStream, prebuf - length);
719 __mIsFirstStream = false;
720 AUDIO_IO_LOGW("FIRST STREAM CALLBACK : length[%zu], prebuf[%d], dummy[%zu]",
721 length, prebuf, (length < prebuf) ? prebuf - length : 0);
723 ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
728 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_write() : err[%d]", ret); //LCOV_EXCL_LINE
733 void CPulseAudioClient::cork(bool cork) {
734 AUDIO_IO_LOGD("cork[%d]", cork);
737 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
740 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This operation is not supported in callback"); // LCOV_EXCL_LINE
744 // Set __mIsFirstStream flag when uncork(resume) stream, because prebuf will be enable again
746 __mIsFirstStream = true;
748 CPulseThreadLocker locker{__mpMainloop};
750 /* FIXME: wait for completion like drain? */
751 pa_operation_unref(pa_stream_cork(__mpStream, static_cast<int>(cork), __successStreamCb, this));
755 bool CPulseAudioClient::isCorked() {
757 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
761 CPulseThreadLocker locker{__mpMainloop};
763 int isCorked = pa_stream_is_corked(__mpStream);
765 #ifdef _AUDIO_IO_DEBUG_TIMING_
766 AUDIO_IO_LOGD("isCorked[%d]", isCorked);
768 return static_cast<bool>(isCorked);
771 bool CPulseAudioClient::drain() {
773 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
778 AUDIO_IO_LOGW("Corked...");
783 AUDIO_IO_LOGW("already draining...");
788 AUDIO_IO_LOGW("stream not started yet...skip drain");
793 AUDIO_IO_LOGD("drain");
794 CPulseThreadLocker locker{__mpMainloop};
796 pa_operation* o = pa_stream_drain(__mpStream, __successDrainCb, this);
797 __mIsDraining = true;
798 while (pa_operation_get_state(o) == PA_OPERATION_RUNNING)
799 pa_threaded_mainloop_wait(__mpMainloop);
800 pa_operation_unref(o);
802 AUDIO_IO_LOGD("drain done");
804 AUDIO_IO_LOGD("drain in thread");
805 pa_operation_unref(pa_stream_drain(__mpStream, __successDrainCbInThread, this));
806 __mIsDraining = true;
812 bool CPulseAudioClient::flush() {
814 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
818 CPulseThreadLocker locker{__mpMainloop};
820 /* FIXME: wait for completion like drain? */
821 pa_operation_unref(pa_stream_flush(__mpStream, __successStreamCb, this));
826 size_t CPulseAudioClient::getWritableSize() {
828 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
832 if (__mDirection != EStreamDirection::STREAM_DIRECTION_PLAYBACK)
833 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Playback"); // LCOV_EXCL_LINE
835 CPulseThreadLocker locker{__mpMainloop};
837 return pa_stream_writable_size(__mpStream);
840 void CPulseAudioClient::checkRunningState() {
841 if (!__mpContext || !PA_CONTEXT_IS_GOOD(pa_context_get_state(__mpContext)))
842 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, // LCOV_EXCL_LINE
843 "The context[%p] is not created or not good state", __mpContext); // LCOV_EXCL_LINE
845 if (!__mpStream || !PA_STREAM_IS_GOOD(pa_stream_get_state(__mpStream)))
846 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, // LCOV_EXCL_LINE
847 "The stream[%p] is not created or not good state", __mpStream); // LCOV_EXCL_LINE
849 if (pa_context_get_state(__mpContext) != PA_CONTEXT_READY || pa_stream_get_state(__mpStream) != PA_STREAM_READY)
850 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, // LCOV_EXCL_LINE
851 "The context[%p] or stream[%p] state is not ready", __mpContext, __mpStream); // LCOV_EXCL_LINE
853 #ifdef _AUDIO_IO_DEBUG_TIMING_
854 AUDIO_IO_LOGD("This client is running");
858 bool CPulseAudioClient::isInThread() const {
860 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "__mIsInit is null");
863 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "__mpMainloop is null");
865 int ret = pa_threaded_mainloop_in_thread(__mpMainloop);
867 #ifdef _AUDIO_IO_DEBUG_TIMING_
868 AUDIO_IO_LOGD("isInThread[%d]", ret);
870 return static_cast<bool>(ret);
874 size_t CPulseAudioClient::getReadableSize() {
876 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
880 if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD)
881 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Capture");
883 CPulseThreadLocker locker{__mpMainloop};
885 return pa_stream_readable_size(__mpStream);
888 size_t CPulseAudioClient::getBufferSize() {
890 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
894 size_t buffer_size = 0;
895 CPulseThreadLocker locker{__mpMainloop};
897 const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
899 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
900 "Failed pa_stream_get_buffer_attr() : err[%d]", pa_context_errno(__mpContext));
902 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
903 buffer_size = attr->tlength;
904 AUDIO_IO_LOGD("PLAYBACK buffer size[%zu]", buffer_size);
906 buffer_size = attr->fragsize;
907 AUDIO_IO_LOGD("RECORD buffer size[%zu]", buffer_size);
913 pa_usec_t CPulseAudioClient::getLatency() {
915 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
919 pa_usec_t latency = 0;
923 if (pa_stream_get_latency(__mpStream, &latency, &negative) < 0) {
924 int _err = pa_context_errno(__mpContext);
925 if (_err != PA_ERR_NODATA)
926 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
927 "Failed pa_stream_get_latency() : err[%d]", _err);
929 return negative ? 0 : latency;
932 CPulseThreadLocker locker{__mpMainloop};
934 while (pa_stream_get_latency(__mpStream, &latency, &negative) < 0) {
935 int _err = pa_context_errno(__mpContext);
936 if (_err != PA_ERR_NODATA)
937 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
938 "Failed pa_stream_get_latency() : err[%d]", _err);
939 /* Wait until latency data is available again */
940 pa_threaded_mainloop_wait(__mpMainloop);
943 return negative ? 0 : latency;
946 pa_usec_t CPulseAudioClient::getFinalLatency() {
948 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
952 pa_usec_t latency = 0;
954 CPulseThreadLocker locker{__mpMainloop};
956 uint32_t ver = pa_context_get_server_protocol_version(__mpContext);
958 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_SUPPORTED, "This version(ver.%d) is not supported", ver);
960 const pa_buffer_attr* buffer_attr = pa_stream_get_buffer_attr(__mpStream);
961 const pa_sample_spec* sample_spec = pa_stream_get_sample_spec(__mpStream);
962 const pa_timing_info* timing_info = pa_stream_get_timing_info(__mpStream);
964 if (!buffer_attr || !sample_spec || !timing_info)
965 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_OUT_OF_MEMORY,
966 "Failed to get buffer_attr[%p] or sample_spec[%p] or timing_info[%p] from a pa_stream",
967 buffer_attr, sample_spec, timing_info);
969 if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
970 latency = (pa_bytes_to_usec(buffer_attr->tlength, sample_spec) + timing_info->configured_sink_usec);
971 AUDIO_IO_LOGD("FINAL PLAYBACK LATENCY[%" PRIu64 "]", latency);
973 latency = (pa_bytes_to_usec(buffer_attr->fragsize, sample_spec) + timing_info->configured_source_usec);
974 AUDIO_IO_LOGD("FINAL RECORD LATENCY[%" PRIu64 "]", latency);
981 void CPulseAudioClient::applyRecordVolume(double volume) {
984 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
988 if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD)
989 THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client can't use this function"); //LCOV_EXCL_LINE
991 CPulseThreadLocker locker{__mpMainloop};
993 pa_cvolume cv = { 0, };
994 pa_volume_t v = PA_VOLUME_NORM * volume;
996 pa_cvolume_set(&cv, __mSpec.getChannelMap().channels, v);
998 pa_operation_unref(pa_context_set_source_output_volume(__mpContext,
999 pa_stream_get_index(__mpStream), &cv, __successVolumeCb, NULL));