3b24ecef047d73234ce8810bef7a56f56f1503b9
[platform/core/api/audio-io.git] / src / cpp / CPulseAudioClient.cpp
1 /*
2  git st* Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17
18 #include "CAudioIODef.h"
19 #include <unistd.h>
20 #include <inttypes.h>
21
22 #ifdef ENABLE_DPM
23 #include <dpm/restriction.h>
24 #endif
25
26 using namespace std;
27 using namespace tizen_media_audio;
28
29
30 /**
31  * class CPulseAudioClient
32  */
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;
36
37 CPulseAudioClient::CPulseAudioClient(
38         EStreamDirection      direction,
39         CPulseStreamSpec&     spec,
40         IPulseStreamListener* listener) :
41     __mDirection(direction),
42     __mSpec(spec),
43     __mpListener(listener),
44     __mpMainloop(nullptr),
45     __mpContext(nullptr),
46     __mpStream(nullptr),
47     __mpPropList(nullptr),
48     __mIsInit(false),
49     __mIsOperationSuccess(false),
50     __mpSyncReadDataPtr(nullptr),
51     __mSyncReadIndex(0),
52     __mSyncReadLength(0),
53     __mIsUsedSyncRead(false),
54     __mIsFirstStream(false),
55     __mIsDraining(false),
56     __mIsStarted(false) {
57 }
58
59 CPulseAudioClient::~CPulseAudioClient() {
60     finalize();
61 }
62
63 void CPulseAudioClient::__contextStateChangeCb(pa_context* c, void* user_data) {
64     auto pClient = static_cast<CPulseAudioClient*>(user_data);
65     assert(pClient);
66     assert(c);
67
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);
72         break;
73
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);
78         break;
79
80     case PA_CONTEXT_UNCONNECTED:
81     case PA_CONTEXT_CONNECTING:
82     case PA_CONTEXT_AUTHORIZING:
83     case PA_CONTEXT_SETTING_NAME:
84         break;
85     }
86 }
87
88 //LCOV_EXCL_START
89 static bool __is_microphone_restricted(void) {
90     int state = 1;
91 #ifdef ENABLE_DPM
92     device_policy_manager_h dpm_h = nullptr;
93     int ret = 0;
94
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);
101     } else {
102         AUDIO_IO_LOGE("Failed to dpm_manager_create()");
103     }
104 #endif
105     return (state ? false : true);
106 }
107 //LCOV_EXCL_STOP
108
109 void CPulseAudioClient::__streamStateChangeCb(pa_stream* s, void* user_data) {
110     assert(s);
111     assert(user_data);
112
113     auto pClient = static_cast<CPulseAudioClient*>(user_data);
114
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);
123         break;
124
125     case PA_STREAM_FAILED:
126 //LCOV_EXCL_START
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);
131         break;
132 //LCOV_EXCL_STOP
133
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);
138         break;
139
140     case PA_STREAM_UNCONNECTED:
141     case PA_STREAM_CREATING:
142         break;
143     }
144 }
145
146 void CPulseAudioClient::__streamCaptureCb(pa_stream* s, size_t length, void* user_data) {
147     assert(s);
148     assert(user_data);
149
150     auto pClient = static_cast<CPulseAudioClient*>(user_data);
151     assert(pClient->__mpListener);
152     assert(pClient->__mpMainloop);
153
154     if (pClient->__mIsUsedSyncRead)
155         pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
156
157     pClient->__mpListener->onStream(pClient, length);
158 }
159
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);
165     delete [] dummy;
166 }
167 #endif
168
169 void CPulseAudioClient::__streamPlaybackCb(pa_stream* s, size_t length, void* user_data) {
170     assert(s);
171     assert(user_data);
172
173     auto pClient = static_cast<CPulseAudioClient*>(user_data);
174     assert(pClient->__mpListener);
175
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);
180         return;
181     }
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);
185         return;
186     }
187 #endif
188
189     pClient->__mpListener->onStream(pClient, length);
190
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;
199     }
200 #endif
201 }
202
203 void CPulseAudioClient::__streamLatencyUpdateCb(pa_stream* s, void* user_data) {
204     assert(s);
205     assert(user_data);
206
207     auto pClient = static_cast<CPulseAudioClient*>(user_data);
208
209     pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
210 }
211
212 void CPulseAudioClient::__streamStartedCb(pa_stream* s, void* user_data) {
213     assert(s);
214     assert(user_data);
215
216     auto pClient = static_cast<CPulseAudioClient*>(user_data);
217
218     AUDIO_IO_LOGD("stream %p started.", pClient);
219
220     pClient->__mIsStarted = true;
221 }
222
223 void CPulseAudioClient::__streamUnderflowCb(pa_stream* s, void* user_data) {
224     assert(s);
225     assert(user_data);
226
227     auto pClient = static_cast<CPulseAudioClient*>(user_data);
228
229     AUDIO_IO_LOGD("stream %p UnderFlow...", pClient);
230
231     pClient->__mIsStarted = false;
232 }
233
234 //LCOV_EXCL_START
235 void CPulseAudioClient::__streamEventCb(pa_stream* s, const char *name, pa_proplist *pl, void *user_data) {
236     assert(s);
237     assert(user_data);
238
239     AUDIO_IO_LOGE("NAME : %s, Prop : %p", name, pl);
240
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));
244 }
245 //LCOV_EXCL_STOP
246
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);
249     assert(s);
250     assert(user_data);
251
252     auto pClient = static_cast<CPulseAudioClient*>(user_data);
253     pClient->__mIsOperationSuccess = static_cast<bool>(success);
254
255     pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
256 }
257
258 //LCOV_EXCL_START
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);
261     assert(s);
262     assert(user_data);
263
264     auto pClient = static_cast<CPulseAudioClient*>(user_data);
265     pClient->__mIsOperationSuccess = static_cast<bool>(success);
266     pClient->__mIsDraining = false;
267 }
268 //LCOV_EXCL_STOP
269
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);
272     assert(s);
273     assert(user_data);
274
275     auto pClient = static_cast<CPulseAudioClient*>(user_data);
276     pClient->__mIsOperationSuccess = static_cast<bool>(success);
277     pClient->__mIsDraining = false;
278
279     pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
280 }
281
282 void CPulseAudioClient::initialize() {
283     if (__mIsInit)
284         return;
285
286     int ret = 0;
287     int err = 0;
288
289     try {
290         // Allocates PA proplist
291         __mpPropList = pa_proplist_new();
292         if (!__mpPropList)
293             THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_proplist_new()"); //LCOV_EXCL_LINE
294
295         // Adds values on proplist for delivery to PULSEAUDIO
296         pa_proplist_sets(__mpPropList, PA_PROP_MEDIA_ROLE, __mSpec.getAudioInfo().getConvertedStreamType());
297
298         int index = __mSpec.getAudioInfo().getAudioIndex();
299         if (index >= 0)
300             pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_PARENT_ID, "%u", (unsigned int) index);
301
302         // Adds latency on proplist for delivery to PULSEAUDIO
303         AUDIO_IO_LOGD("LATENCY : %s[%d]", __mSpec.getStreamLatencyToString(), static_cast<int>(__mSpec.getStreamLatency()));
304         pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_TIZEN_AUDIO_LATENCY, "%s", __mSpec.getStreamLatencyToString());
305
306         // Allocates PA mainloop
307         __mpMainloop = pa_threaded_mainloop_new();
308         if (!__mpMainloop)
309             THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_threaded_mainloop_new()"); //LCOV_EXCL_LINE
310
311         // Allocates PA context
312         __mpContext = pa_context_new(pa_threaded_mainloop_get_api(__mpMainloop), CLIENT_NAME);
313         if (!__mpContext)
314             THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_context_new()"); //LCOV_EXCL_LINE
315
316         // Sets context state changed callback
317         pa_context_set_state_callback(__mpContext, __contextStateChangeCb, this);
318
319         // Connects this client with PA server
320         if (pa_context_connect(__mpContext, NULL, PA_CONTEXT_NOFLAGS, NULL) < 0)
321             THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_context_connect()"); //LCOV_EXCL_LINE
322
323         // LOCK for synchronous connection
324         pa_threaded_mainloop_lock(__mpMainloop);
325
326         // Start mainloop
327         if (pa_threaded_mainloop_start(__mpMainloop) < 0) {
328             pa_threaded_mainloop_unlock(__mpMainloop);
329             THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_threaded_mainloop_start()"); //LCOV_EXCL_LINE
330         }
331
332         // Connection process is asynchronously
333         // So, this function will be waited when occurred context state change event
334         // If I got a signal, do next processing
335         while (true) {
336             pa_context_state_t state;
337             state = pa_context_get_state(__mpContext);
338
339             if (state == PA_CONTEXT_READY)
340                 break;
341
342             if (!PA_CONTEXT_IS_GOOD(state)) {
343 //LCOV_EXCL_START
344                 err = pa_context_errno(__mpContext);
345                 pa_threaded_mainloop_unlock(__mpMainloop);
346                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "pa_context's state is not good : err[%d]", err);
347 //LCOV_EXCL_STOP
348             }
349
350             /* Wait until the context is ready */
351             pa_threaded_mainloop_wait(__mpMainloop);
352         }
353
354         // Allocates PA stream
355         pa_sample_spec ss   = __mSpec.getSampleSpec();
356         pa_channel_map map  = __mSpec.getChannelMap();
357
358         __mpStream = pa_stream_new_with_proplist(__mpContext, __mSpec.getStreamName(), &ss, &map, __mpPropList);
359         if (!__mpStream) {
360 //LCOV_EXCL_START
361             pa_threaded_mainloop_unlock(__mpMainloop);
362             THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_new_with_proplist()");
363 //LCOV_EXCL_STOP
364         }
365
366         // Sets stream callbacks
367         pa_stream_set_state_callback(__mpStream, __streamStateChangeCb, this);
368         pa_stream_set_read_callback(__mpStream, __streamCaptureCb, this);
369         pa_stream_set_write_callback(__mpStream, __streamPlaybackCb, this);
370         pa_stream_set_latency_update_callback(__mpStream, __streamLatencyUpdateCb, this);
371         pa_stream_set_event_callback(__mpStream, __streamEventCb, this);
372         if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
373             pa_stream_set_started_callback(__mpStream, __streamStartedCb, this);
374             pa_stream_set_underflow_callback(__mpStream, __streamUnderflowCb, this);
375         }
376
377         // Connect stream with PA Server
378
379         if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
380             auto flags = static_cast<pa_stream_flags_t>(
381                     PA_STREAM_INTERPOLATE_TIMING |
382                     PA_STREAM_ADJUST_LATENCY     |
383 #ifndef DISABLE_MOBILE_BACK_COMP
384                     PA_STREAM_START_CORKED       |
385 #endif
386                     PA_STREAM_AUTO_TIMING_UPDATE);
387
388             ret = pa_stream_connect_playback(__mpStream, NULL, NULL, flags, NULL, NULL);
389         } else {
390             auto flags = static_cast<pa_stream_flags_t>(
391                     PA_STREAM_INTERPOLATE_TIMING |
392                     PA_STREAM_ADJUST_LATENCY     |
393 #ifndef DISABLE_MOBILE_BACK_COMP
394                     PA_STREAM_START_CORKED       |
395 #endif
396                     PA_STREAM_AUTO_TIMING_UPDATE);
397
398             ret = pa_stream_connect_record(__mpStream, NULL, NULL, flags);
399         }
400
401         if (ret != 0) {
402 //LCOV_EXCL_START
403             err = pa_context_errno(__mpContext);
404             pa_threaded_mainloop_unlock(__mpMainloop);
405             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_connect() : err[%d]", err);
406 //LCOV_EXCL_STOP
407         }
408
409         while (true) {
410             pa_stream_state_t state = pa_stream_get_state(__mpStream);
411
412             if (state == PA_STREAM_READY) {
413                 AUDIO_IO_LOGD("STREAM READY");
414                 break;
415             }
416
417             if (!PA_STREAM_IS_GOOD(state)) {
418                 err = pa_context_errno(__mpContext);
419                 pa_threaded_mainloop_unlock(__mpMainloop);
420                 if (err == PA_ERR_ACCESS)
421                     THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_DEVICE_POLICY_RESTRICTION, "pa_stream's state is not good : err[%d]", err);
422                 else
423                     THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "pa_stream's state is not good : err[%d]", err); //LCOV_EXCL_LINE
424             }
425
426             /* Wait until the stream is ready */
427             pa_threaded_mainloop_wait(__mpMainloop);
428         }
429
430         // End of synchronous
431         pa_threaded_mainloop_unlock(__mpMainloop);
432
433         // __mIsInit = true;  // Moved to __streamStateChangeCb()
434     } catch (const CAudioError& e) {
435         finalize();
436         throw;
437     }
438 }
439
440 void CPulseAudioClient::finalize() {
441     AUDIO_IO_LOGD("");
442
443     if (__mpMainloop && !isInThread())
444         pa_threaded_mainloop_lock(__mpMainloop);
445
446     /* clear callbacks */
447     if (__mpStream) {
448         if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
449             pa_stream_set_write_callback(__mpStream, NULL, NULL);
450         else
451             pa_stream_set_read_callback(__mpStream, NULL, NULL);
452         pa_stream_set_latency_update_callback(__mpStream, NULL, NULL);
453         pa_stream_set_event_callback(__mpStream, NULL, NULL);
454     }
455
456     if (__mpMainloop && !isInThread())
457         pa_threaded_mainloop_unlock(__mpMainloop);
458
459     /* Wait for drain complete if draining before finalize */
460     if (__mIsDraining) {
461         unsigned int drain_wait_count = 0;
462         while (__mIsDraining && drain_wait_count++ < drain_wait_max_count)
463             usleep(drain_wait_interval);
464         AUDIO_IO_LOGD("wait for drain complete!!!! [%d * %d usec]",
465                       drain_wait_count, drain_wait_interval);
466     }
467
468     if (__mpMainloop)
469         pa_threaded_mainloop_stop(__mpMainloop);
470
471     if (__mpStream) {
472         pa_stream_disconnect(__mpStream);
473         pa_stream_unref(__mpStream);
474         __mpStream = nullptr;
475     }
476
477     if (__mpContext) {
478         pa_context_disconnect(__mpContext);
479         pa_context_unref(__mpContext);
480         __mpContext = nullptr;
481     }
482
483     if (__mpMainloop) {
484         pa_threaded_mainloop_free(__mpMainloop);
485         __mpMainloop = nullptr;
486     }
487
488     if (__mpPropList) {
489         pa_proplist_free(__mpPropList);
490         __mpPropList = nullptr;
491     }
492
493     __mIsInit = false;
494 }
495
496 int CPulseAudioClient::read(void* buffer, size_t length) {
497     if (!__mIsInit)
498         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
499
500     checkRunningState();
501
502     if (!buffer)
503         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "The parameter is invalid : buffer[%p]", buffer);
504
505     if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
506         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client couldn't use this function");
507
508     size_t lengthIter = length;
509     int ret = 0;
510
511     __mIsUsedSyncRead = true;
512
513     try {
514         pa_threaded_mainloop_lock(__mpMainloop);
515
516         while (lengthIter > 0) {
517             size_t l;
518
519             while (!__mpSyncReadDataPtr) {
520                 ret = pa_stream_peek(__mpStream, &__mpSyncReadDataPtr, &__mSyncReadLength);
521                 if (ret != 0)
522                     THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_peek() : ret[%d]", ret);
523
524                 if (__mSyncReadLength <= 0) {
525 #ifdef _AUDIO_IO_DEBUG_TIMING_
526                     AUDIO_IO_LOGD("readLength(%zu byte) is not valid. wait...", __mSyncReadLength);
527 #endif
528                     pa_threaded_mainloop_wait(__mpMainloop);
529                 } else if (!__mpSyncReadDataPtr) {
530                     // Data peeked, but it doesn't have any data
531                     ret = pa_stream_drop(__mpStream);
532                     if (ret != 0)
533                         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_drop() : ret[%d]", ret); //LCOV_EXCL_LINE
534                 } else {
535                     __mSyncReadIndex = 0;
536                 }
537             }
538
539             if (__mSyncReadLength < lengthIter)
540                 l = __mSyncReadLength;
541             else
542                 l = lengthIter;
543
544             // Copy partial pcm data on out parameter
545 #ifdef _AUDIO_IO_DEBUG_TIMING_
546             AUDIO_IO_LOGD("memcpy() that a peeked buffer[%p], index[%zu], length[%zu] on out buffer", (const uint8_t*)(__mpSyncReadDataPtr) + __mSyncReadIndex, __mSyncReadIndex, l);
547 #endif
548             memcpy(buffer, (const uint8_t*)__mpSyncReadDataPtr + __mSyncReadIndex, l);
549
550             // Move next position
551             buffer = (uint8_t*)buffer + l;
552             lengthIter -= l;
553
554             // Adjusts the rest length
555             __mSyncReadIndex  += l;
556             __mSyncReadLength -= l;
557
558             if (__mSyncReadLength == 0) {
559 #ifdef _AUDIO_IO_DEBUG_TIMING_
560                 AUDIO_IO_LOGD("__mSyncReadLength is zero, do drop()");
561 #endif
562                 ret = pa_stream_drop(__mpStream);
563                 if (ret != 0)
564                     THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_drop() : ret[%d]", ret); //LCOV_EXCL_LINE
565
566                 // Reset the internal pointer
567                 __mpSyncReadDataPtr = nullptr;
568                 __mSyncReadLength   = 0;
569                 __mSyncReadIndex    = 0;
570             }
571         }  // End of while (lengthIter > 0)
572
573         pa_threaded_mainloop_unlock(__mpMainloop);
574         __mIsUsedSyncRead = false;
575     } catch (const CAudioError& e) {
576         pa_threaded_mainloop_unlock(__mpMainloop);
577         __mIsUsedSyncRead = false;
578         throw;
579     }
580
581     return length;
582 }
583
584 int CPulseAudioClient::peek(const void** buffer, size_t* length) {
585     if (!__mIsInit)
586         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
587
588     checkRunningState();
589
590     if (!buffer || !length)
591         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "The parameter is invalid : buffer[%p], length[%p]", buffer, length);
592
593     if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
594         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client couldn't use this function");
595
596     int ret = 0;
597
598     if (!isInThread()) {
599         pa_threaded_mainloop_lock(__mpMainloop);
600         ret = pa_stream_peek(__mpStream, buffer, length);
601         pa_threaded_mainloop_unlock(__mpMainloop);
602     } else {
603         ret = pa_stream_peek(__mpStream, buffer, length);
604     }
605
606 #ifdef _AUDIO_IO_DEBUG_TIMING_
607     AUDIO_IO_LOGD("buffer[%p], length[%zu]", *buffer, *length);
608 #endif
609
610     if (ret < 0)
611         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_peek() : err[%d]", ret); //LCOV_EXCL_LINE
612
613     return ret;
614 }
615
616 int CPulseAudioClient::drop() {
617     if (!__mIsInit)
618         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
619
620 #ifdef _AUDIO_IO_DEBUG_TIMING_
621     AUDIO_IO_LOGD("");
622 #endif
623
624     checkRunningState();
625
626     if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
627         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client couldn't use this function");
628
629     int ret = 0;
630
631     if (!isInThread()) {
632         pa_threaded_mainloop_lock(__mpMainloop);
633         ret = pa_stream_drop(__mpStream);
634         pa_threaded_mainloop_unlock(__mpMainloop);
635     } else {
636         ret = pa_stream_drop(__mpStream);
637     }
638
639     if (ret < 0)
640         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_drop() : err[%d]", ret); //LCOV_EXCL_LINE
641
642     return ret;
643 }
644
645 int CPulseAudioClient::write(const void* data, size_t length) {
646     if (!data)
647         THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_ARGUMENT, "The parameter is invalid");
648
649     if (__mDirection == EStreamDirection::STREAM_DIRECTION_RECORD)
650         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client couldn't use this function");
651
652     int ret = 0;
653
654 #ifdef _AUDIO_IO_DEBUG_TIMING_
655     AUDIO_IO_LOGD("data[%p], length[%zu], First[%d]", data, length, __mIsFirstStream);
656 #endif
657
658     if (!isInThread()) {
659         pa_threaded_mainloop_lock(__mpMainloop);
660         if (pa_stream_is_corked(__mpStream)) {
661             AUDIO_IO_LOGW("stream is corked...do uncork here first!!!!");
662             pa_operation_unref(pa_stream_cork(__mpStream, 0, NULL, this));
663         }
664
665         ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
666         pa_threaded_mainloop_unlock(__mpMainloop);
667     } else {
668         if (pa_stream_is_corked(__mpStream)) {
669             AUDIO_IO_LOGW("stream is corked...do uncork here first!!!!");
670             pa_operation_unref(pa_stream_cork(__mpStream, 0, NULL, this));
671         }
672
673         if (__mIsFirstStream) {
674             const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
675             uint32_t prebuf = attr->prebuf;
676             // Compensate amount of prebuf in first stream callback when audio-io use prebuf(-1)
677             // Because a stream will never start when an application wrote less than prebuf at first
678             if (length < prebuf) {
679                 char* dummy = new char[prebuf - length];
680                 memset(dummy, 0, prebuf - length);
681                 pa_stream_write(__mpStream, dummy, prebuf - length, NULL, 0LL, PA_SEEK_RELATIVE);
682                 delete [] dummy;
683             }
684             __mIsFirstStream = false;
685             AUDIO_IO_LOGW("FIRST STREAM CALLBACK : length[%zu], prebuf[%d], dummy[%zu]",
686                           length, prebuf, (length < prebuf) ? prebuf - length : 0);
687         }
688         ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
689     }
690
691     if (ret < 0)
692         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_write() : err[%d]", ret); //LCOV_EXCL_LINE
693
694     return ret;
695 }
696
697 void CPulseAudioClient::cork(bool cork) {
698     AUDIO_IO_LOGD("cork[%d]", cork);
699
700     if (!__mIsInit)
701         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
702
703     if (isInThread())
704         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This operation is not supported in callback");
705
706     checkRunningState();
707
708     // Set __mIsFirstStream flag when uncork(resume) stream, because prebuf will be enable again
709     if (!cork)
710         __mIsFirstStream = true;
711
712     if (!isInThread()) {
713         pa_threaded_mainloop_lock(__mpMainloop);
714         pa_operation_unref(pa_stream_cork(__mpStream, static_cast<int>(cork), __successStreamCb, this));
715         pa_threaded_mainloop_unlock(__mpMainloop);
716     } else {
717         pa_operation_unref(pa_stream_cork(__mpStream, static_cast<int>(cork), __successStreamCb, this));
718     }
719 }
720
721 bool CPulseAudioClient::isCorked() {
722     if (!__mIsInit)
723         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
724
725     checkRunningState();
726
727     int isCork = 0;
728
729     if (!isInThread()) {
730         pa_threaded_mainloop_lock(__mpMainloop);
731         isCork = pa_stream_is_corked(__mpStream);
732         pa_threaded_mainloop_unlock(__mpMainloop);
733     } else {
734         isCork = pa_stream_is_corked(__mpStream);
735     }
736
737 #ifdef _AUDIO_IO_DEBUG_TIMING_
738     AUDIO_IO_LOGD("isCork[%d]", isCork);
739 #endif
740     return static_cast<bool>(isCork);
741 }
742
743 bool CPulseAudioClient::drain() {
744     if (!__mIsInit)
745         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
746
747     checkRunningState();
748
749     if (isCorked()) {
750         AUDIO_IO_LOGW("Corked...");
751         return true;
752     }
753
754     if (__mIsDraining) {
755         AUDIO_IO_LOGW("already draining...");
756         return true;
757     }
758
759     if (!__mIsStarted) {
760         AUDIO_IO_LOGW("stream not started yet...skip drain");
761         return true;
762     }
763
764     if (!isInThread()) {
765         AUDIO_IO_LOGD("drain");
766         pa_threaded_mainloop_lock(__mpMainloop);
767         pa_operation* o = pa_stream_drain(__mpStream, __successDrainCb, this);
768         __mIsDraining = true;
769         while (pa_operation_get_state(o) == PA_OPERATION_RUNNING)
770             pa_threaded_mainloop_wait(__mpMainloop);
771
772         pa_operation_unref(o);
773         pa_threaded_mainloop_unlock(__mpMainloop);
774         AUDIO_IO_LOGD("drain done");
775     } else {
776         AUDIO_IO_LOGD("drain in thread");
777         pa_operation_unref(pa_stream_drain(__mpStream, __successDrainCbInThread, this));
778         __mIsDraining = true;
779     }
780
781     return true;
782 }
783
784 bool CPulseAudioClient::flush() {
785     if (!__mIsInit)
786         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
787
788     checkRunningState();
789
790     if (!isInThread()) {
791         AUDIO_IO_LOGD("flush");
792         pa_threaded_mainloop_lock(__mpMainloop);
793         pa_operation_unref(pa_stream_flush(__mpStream, __successStreamCb, this));
794         pa_threaded_mainloop_unlock(__mpMainloop);
795     } else {
796         AUDIO_IO_LOGD("flush in thread");
797         pa_operation_unref(pa_stream_flush(__mpStream, __successStreamCb, this));
798     }
799
800     return true;
801 }
802
803 size_t CPulseAudioClient::getWritableSize() {
804     if (!__mIsInit)
805         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
806
807     checkRunningState();
808
809     if (__mDirection != EStreamDirection::STREAM_DIRECTION_PLAYBACK)
810         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Playback");
811
812     size_t ret = 0;
813
814     if (!isInThread()) {
815         pa_threaded_mainloop_lock(__mpMainloop);
816         ret = pa_stream_writable_size(__mpStream);
817         pa_threaded_mainloop_unlock(__mpMainloop);
818     } else {
819         ret = pa_stream_writable_size(__mpStream);
820     }
821
822     return ret;
823 }
824
825 void CPulseAudioClient::checkRunningState() {
826     if (!__mpContext || !PA_CONTEXT_IS_GOOD(pa_context_get_state(__mpContext)))
827         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, "The context[%p] is not created or not good state", __mpContext);
828
829     if (!__mpStream || !PA_STREAM_IS_GOOD(pa_stream_get_state(__mpStream)))
830         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, "The stream[%p] is not created or not good state", __mpStream);
831
832     if (pa_context_get_state(__mpContext) != PA_CONTEXT_READY || pa_stream_get_state(__mpStream) != PA_STREAM_READY)
833         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, "The context[%p] or stream[%p] state is not ready", __mpContext, __mpStream);
834
835 #ifdef _AUDIO_IO_DEBUG_TIMING_
836     AUDIO_IO_LOGD("This client is running");
837 #endif
838 }
839
840 bool CPulseAudioClient::isInThread() noexcept {
841     int ret = pa_threaded_mainloop_in_thread(__mpMainloop);
842
843 #ifdef _AUDIO_IO_DEBUG_TIMING_
844     AUDIO_IO_LOGD("isInThread[%d]", ret);
845 #endif
846     return static_cast<bool>(ret);
847 }
848
849 //LCOV_EXCL_START
850 size_t CPulseAudioClient::getReadableSize() {
851     if (!__mIsInit)
852         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
853
854     checkRunningState();
855
856     if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD)
857         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Capture");
858
859     size_t ret = 0;
860
861     if (!isInThread()) {
862         pa_threaded_mainloop_lock(__mpMainloop);
863         ret = pa_stream_readable_size(__mpStream);
864         pa_threaded_mainloop_unlock(__mpMainloop);
865     } else {
866         ret = pa_stream_writable_size(__mpStream);
867     }
868
869     return ret;
870 }
871
872 size_t CPulseAudioClient::getBufferSize() {
873     if (!__mIsInit)
874         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
875
876     checkRunningState();
877
878     size_t ret = 0;
879
880     try {
881         if (!isInThread())
882             pa_threaded_mainloop_lock(__mpMainloop);
883
884         const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
885         if (!attr) {
886             int _err = pa_context_errno(__mpContext);
887             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_buffer_attr() : err[%d]", _err);
888         }
889
890         if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
891             ret = attr->tlength;
892             AUDIO_IO_LOGD("PLAYBACK buffer size[%zu]", ret);
893         } else {
894             ret = attr->fragsize;
895             AUDIO_IO_LOGD("RECORD buffer size[%zu]", ret);
896         }
897     } catch (const CAudioError& e) {
898         if (!isInThread())
899             pa_threaded_mainloop_unlock(__mpMainloop);
900         throw;
901     }
902
903     if (!isInThread())
904         pa_threaded_mainloop_unlock(__mpMainloop);
905
906     return ret;
907 }
908
909 pa_usec_t CPulseAudioClient::getLatency() {
910     if (!__mIsInit)
911         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
912
913     checkRunningState();
914
915     pa_usec_t ret = 0;
916     int negative  = 0;
917
918     if (!isInThread()) {
919         if (pa_stream_get_latency(__mpStream, &ret, &negative) < 0) {
920             int _err = pa_context_errno(__mpContext);
921             if (_err != PA_ERR_NODATA)
922                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_latency() : err[%d]", _err);
923         }
924         return negative ? 0 : ret;
925     }
926
927     pa_threaded_mainloop_lock(__mpMainloop);
928
929     try {
930         while (true) {
931             if (pa_stream_get_latency(__mpStream, &ret, &negative) >= 0)
932                 break;
933
934             int _err = pa_context_errno(__mpContext);
935             if (_err != PA_ERR_NODATA)
936                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_latency() : err[%d]", _err);
937
938             /* Wait until latency data is available again */
939             pa_threaded_mainloop_wait(__mpMainloop);
940         }
941     } catch (const CAudioError& e) {
942         pa_threaded_mainloop_unlock(__mpMainloop);
943         throw;
944     }
945
946     pa_threaded_mainloop_unlock(__mpMainloop);
947
948     return negative ? 0 : ret;
949 }
950
951 pa_usec_t CPulseAudioClient::getFinalLatency() {
952     if (!__mIsInit)
953         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
954
955     checkRunningState();
956
957     pa_usec_t ret = 0;
958
959     try {
960         if (!isInThread())
961             pa_threaded_mainloop_lock(__mpMainloop);
962
963         uint32_t ver = pa_context_get_server_protocol_version(__mpContext);
964         if (ver >= 13) {
965             const pa_buffer_attr* buffer_attr = pa_stream_get_buffer_attr(__mpStream);
966             const pa_sample_spec* sample_spec = pa_stream_get_sample_spec(__mpStream);
967             const pa_timing_info* timing_info = pa_stream_get_timing_info(__mpStream);
968
969             if (!buffer_attr || !sample_spec || !timing_info)
970                 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",
971                         buffer_attr, sample_spec, timing_info);
972
973             if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
974                 ret = (pa_bytes_to_usec(buffer_attr->tlength, sample_spec) + timing_info->configured_sink_usec);
975                 AUDIO_IO_LOGD("FINAL PLAYBACK LATENCY[%" PRIu64 "]", ret);
976             } else {
977                 ret = (pa_bytes_to_usec(buffer_attr->fragsize, sample_spec) + timing_info->configured_source_usec);
978                 AUDIO_IO_LOGD("FINAL RECORD LATENCY[%" PRIu64 "]", ret);
979             }
980         } else {
981             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_SUPPORTED, "This version(ver.%d) is not supported", ver);
982         }
983
984         if (!isInThread())
985             pa_threaded_mainloop_unlock(__mpMainloop);
986     } catch (const CAudioError& e) {
987         if (!isInThread())
988             pa_threaded_mainloop_unlock(__mpMainloop);
989         throw;
990     }
991
992     return ret;
993 }
994 //LCOV_EXCL_STOP