ef7ddb3bb843f79be88d2feb7bc7f0b83fae3c11
[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     case PA_STREAM_FAILED:
129 //LCOV_EXCL_START
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             pa_threaded_mainloop_unlock(__mpMainloop);
332             THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_threaded_mainloop_start()"); //LCOV_EXCL_LINE
333         }
334
335         // Connection process is asynchronously
336         // So, this function will be waited when occurred context state change event
337         // If I got a signal, do next processing
338         while (true) {
339             pa_context_state_t state;
340             state = pa_context_get_state(__mpContext);
341
342             if (state == PA_CONTEXT_READY)
343                 break;
344
345             if (!PA_CONTEXT_IS_GOOD(state)) {
346 //LCOV_EXCL_START
347                 err = pa_context_errno(__mpContext);
348                 pa_threaded_mainloop_unlock(__mpMainloop);
349                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "pa_context's state is not good : err[%d]", err);
350 //LCOV_EXCL_STOP
351             }
352
353             /* Wait until the context is ready */
354             pa_threaded_mainloop_wait(__mpMainloop);
355         }
356
357         // Allocates PA stream
358         pa_sample_spec ss   = __mSpec.getSampleSpec();
359         pa_channel_map map  = __mSpec.getChannelMap();
360
361         __mpStream = pa_stream_new_with_proplist(__mpContext, __mSpec.getStreamName(), &ss, &map, __mpPropList);
362         if (!__mpStream) {
363 //LCOV_EXCL_START
364             pa_threaded_mainloop_unlock(__mpMainloop);
365             THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_new_with_proplist()");
366 //LCOV_EXCL_STOP
367         }
368
369         // Sets stream callbacks
370         pa_stream_set_state_callback(__mpStream, __streamStateChangeCb, this);
371         pa_stream_set_read_callback(__mpStream, __streamCaptureCb, this);
372         pa_stream_set_write_callback(__mpStream, __streamPlaybackCb, this);
373         pa_stream_set_latency_update_callback(__mpStream, __streamLatencyUpdateCb, this);
374         pa_stream_set_event_callback(__mpStream, __streamEventCb, this);
375         if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
376             pa_stream_set_started_callback(__mpStream, __streamStartedCb, this);
377             pa_stream_set_underflow_callback(__mpStream, __streamUnderflowCb, this);
378         }
379
380         // Connect stream with PA Server
381
382         if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
383             auto flags = static_cast<pa_stream_flags_t>(
384                     PA_STREAM_INTERPOLATE_TIMING |
385                     PA_STREAM_ADJUST_LATENCY     |
386 #ifndef DISABLE_MOBILE_BACK_COMP
387                     PA_STREAM_START_CORKED       |
388 #endif
389                     PA_STREAM_AUTO_TIMING_UPDATE);
390
391             ret = pa_stream_connect_playback(__mpStream, NULL, NULL, flags, NULL, NULL);
392         } else {
393             auto flags = static_cast<pa_stream_flags_t>(
394                     PA_STREAM_INTERPOLATE_TIMING |
395                     PA_STREAM_ADJUST_LATENCY     |
396 #ifndef DISABLE_MOBILE_BACK_COMP
397                     PA_STREAM_START_CORKED       |
398 #endif
399                     PA_STREAM_AUTO_TIMING_UPDATE);
400
401             ret = pa_stream_connect_record(__mpStream, NULL, NULL, flags);
402         }
403
404         if (ret != 0) {
405 //LCOV_EXCL_START
406             err = pa_context_errno(__mpContext);
407             pa_threaded_mainloop_unlock(__mpMainloop);
408             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_connect() : err[%d]", err);
409 //LCOV_EXCL_STOP
410         }
411
412         while (true) {
413             pa_stream_state_t state = pa_stream_get_state(__mpStream);
414
415             if (state == PA_STREAM_READY) {
416                 AUDIO_IO_LOGD("STREAM READY");
417                 break;
418             }
419
420             if (!PA_STREAM_IS_GOOD(state)) {
421                 err = pa_context_errno(__mpContext);
422                 pa_threaded_mainloop_unlock(__mpMainloop);
423                 if (err == PA_ERR_ACCESS)
424                     THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_DEVICE_POLICY_RESTRICTION, "pa_stream's state is not good : err[%d]", err);
425                 else
426                     THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "pa_stream's state is not good : err[%d]", err); //LCOV_EXCL_LINE
427             }
428
429             /* Wait until the stream is ready */
430             pa_threaded_mainloop_wait(__mpMainloop);
431         }
432
433         // End of synchronous
434         pa_threaded_mainloop_unlock(__mpMainloop);
435
436         // __mIsInit = true;  // Moved to __streamStateChangeCb()
437     } catch (const CAudioError& e) {
438         finalize();
439         throw;
440     }
441 }
442
443 void CPulseAudioClient::finalize() {
444     AUDIO_IO_LOGD("");
445
446     if (__mpMainloop && !isInThread())
447         pa_threaded_mainloop_lock(__mpMainloop);
448
449     /* clear callbacks */
450     if (__mpStream) {
451         if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
452             pa_stream_set_write_callback(__mpStream, NULL, NULL);
453         else
454             pa_stream_set_read_callback(__mpStream, NULL, NULL);
455         pa_stream_set_latency_update_callback(__mpStream, NULL, NULL);
456         pa_stream_set_event_callback(__mpStream, NULL, NULL);
457     }
458
459     if (__mpMainloop && !isInThread())
460         pa_threaded_mainloop_unlock(__mpMainloop);
461
462     /* Wait for drain complete if draining before finalize */
463     if (__mIsDraining) {
464         unsigned int drain_wait_count = 0;
465         while (__mIsDraining && drain_wait_count++ < drain_wait_max_count)
466             usleep(drain_wait_interval);
467         AUDIO_IO_LOGD("wait for drain complete!!!! [%d * %d usec]",
468                       drain_wait_count, drain_wait_interval);
469     }
470
471     if (__mpMainloop)
472         pa_threaded_mainloop_stop(__mpMainloop);
473
474     if (__mpStream) {
475         pa_stream_disconnect(__mpStream);
476         pa_stream_unref(__mpStream);
477         __mpStream = nullptr;
478     }
479
480     if (__mpContext) {
481         pa_context_disconnect(__mpContext);
482         pa_context_unref(__mpContext);
483         __mpContext = nullptr;
484     }
485
486     if (__mpMainloop) {
487         pa_threaded_mainloop_free(__mpMainloop);
488         __mpMainloop = nullptr;
489     }
490
491     if (__mpPropList) {
492         pa_proplist_free(__mpPropList);
493         __mpPropList = nullptr;
494     }
495
496     __mIsInit = false;
497 }
498
499 int CPulseAudioClient::read(void* buffer, size_t length) {
500     if (!__mIsInit)
501         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
502
503     checkRunningState();
504
505     if (!buffer)
506         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "The parameter is invalid : buffer[%p]", buffer);
507
508     if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
509         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client couldn't use this function");
510
511     size_t lengthIter = length;
512     int ret = 0;
513
514     __mIsUsedSyncRead = true;
515
516     try {
517         pa_threaded_mainloop_lock(__mpMainloop);
518
519         while (lengthIter > 0) {
520             size_t l;
521
522             while (!__mpSyncReadDataPtr) {
523                 ret = pa_stream_peek(__mpStream, &__mpSyncReadDataPtr, &__mSyncReadLength);
524                 if (ret != 0)
525                     THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_peek() : ret[%d]", ret);
526
527                 if (__mSyncReadLength <= 0) {
528 #ifdef _AUDIO_IO_DEBUG_TIMING_
529                     AUDIO_IO_LOGD("readLength(%zu byte) is not valid. wait...", __mSyncReadLength);
530 #endif
531                     pa_threaded_mainloop_wait(__mpMainloop);
532                 } else if (!__mpSyncReadDataPtr) {
533                     // Data peeked, but it doesn't have any data
534                     ret = pa_stream_drop(__mpStream);
535                     if (ret != 0)
536                         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_drop() : ret[%d]", ret); //LCOV_EXCL_LINE
537                 } else {
538                     __mSyncReadIndex = 0;
539                 }
540             }
541
542             l = min(__mSyncReadLength, 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