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