Revise cpp codes
[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         char *streamType = nullptr;
297         CAudioInfo::EAudioType audioType = __mSpec.getAudioInfo().getAudioType();
298         __mSpec.getAudioInfo().convertAudioType2StreamType(audioType, &streamType);
299         pa_proplist_sets(__mpPropList, PA_PROP_MEDIA_ROLE, streamType);
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 (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             if (__mSyncReadLength < lengthIter)
543                 l = __mSyncReadLength;
544             else
545                 l = lengthIter;
546
547             // Copy partial pcm data on out parameter
548 #ifdef _AUDIO_IO_DEBUG_TIMING_
549             AUDIO_IO_LOGD("memcpy() that a peeked buffer[%p], index[%zu], length[%zu] on out buffer", (const uint8_t*)(__mpSyncReadDataPtr) + __mSyncReadIndex, __mSyncReadIndex, l);
550 #endif
551             memcpy(buffer, (const uint8_t*)__mpSyncReadDataPtr + __mSyncReadIndex, l);
552
553             // Move next position
554             buffer = (uint8_t*)buffer + l;
555             lengthIter -= l;
556
557             // Adjusts the rest length
558             __mSyncReadIndex  += l;
559             __mSyncReadLength -= l;
560
561             if (__mSyncReadLength == 0) {
562 #ifdef _AUDIO_IO_DEBUG_TIMING_
563                 AUDIO_IO_LOGD("__mSyncReadLength is zero, do drop()");
564 #endif
565                 ret = pa_stream_drop(__mpStream);
566                 if (ret != 0)
567                     THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_drop() : ret[%d]", ret); //LCOV_EXCL_LINE
568
569                 // Reset the internal pointer
570                 __mpSyncReadDataPtr = nullptr;
571                 __mSyncReadLength   = 0;
572                 __mSyncReadIndex    = 0;
573             }
574         }  // End of while (lengthIter > 0)
575
576         pa_threaded_mainloop_unlock(__mpMainloop);
577         __mIsUsedSyncRead = false;
578     } catch (CAudioError& e) {
579         pa_threaded_mainloop_unlock(__mpMainloop);
580         __mIsUsedSyncRead = false;
581         throw;
582     }
583
584     return length;
585 }
586
587 int CPulseAudioClient::peek(const void** buffer, size_t* length) {
588     if (!__mIsInit)
589         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
590
591     checkRunningState();
592
593     if (!buffer || !length)
594         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "The parameter is invalid : buffer[%p], length[%p]", buffer, length);
595
596     if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
597         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client couldn't use this function");
598
599     int ret = 0;
600
601     if (!isInThread()) {
602         pa_threaded_mainloop_lock(__mpMainloop);
603         ret = pa_stream_peek(__mpStream, buffer, length);
604         pa_threaded_mainloop_unlock(__mpMainloop);
605     } else {
606         ret = pa_stream_peek(__mpStream, buffer, length);
607     }
608
609 #ifdef _AUDIO_IO_DEBUG_TIMING_
610     AUDIO_IO_LOGD("buffer[%p], length[%zu]", *buffer, *length);
611 #endif
612
613     if (ret < 0)
614         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_peek() : err[%d]", ret); //LCOV_EXCL_LINE
615
616     return ret;
617 }
618
619 int CPulseAudioClient::drop() {
620     if (!__mIsInit)
621         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
622
623 #ifdef _AUDIO_IO_DEBUG_TIMING_
624     AUDIO_IO_LOGD("");
625 #endif
626
627     checkRunningState();
628
629     if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
630         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client couldn't use this function");
631
632     int ret = 0;
633
634     if (!isInThread()) {
635         pa_threaded_mainloop_lock(__mpMainloop);
636         ret = pa_stream_drop(__mpStream);
637         pa_threaded_mainloop_unlock(__mpMainloop);
638     } else {
639         ret = pa_stream_drop(__mpStream);
640     }
641
642     if (ret < 0)
643         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_drop() : err[%d]", ret); //LCOV_EXCL_LINE
644
645     return ret;
646 }
647
648 int CPulseAudioClient::write(const void* data, size_t length) {
649     if (!data)
650         THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_ARGUMENT, "The parameter is invalid");
651
652     if (__mDirection == EStreamDirection::STREAM_DIRECTION_RECORD)
653         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client couldn't use this function");
654
655     int ret = 0;
656
657 #ifdef _AUDIO_IO_DEBUG_TIMING_
658     AUDIO_IO_LOGD("data[%p], length[%zu], First[%d]", data, length, __mIsFirstStream);
659 #endif
660
661     if (!isInThread()) {
662         pa_threaded_mainloop_lock(__mpMainloop);
663         if (pa_stream_is_corked(__mpStream)) {
664             AUDIO_IO_LOGW("stream is corked...do uncork here first!!!!");
665             pa_operation_unref(pa_stream_cork(__mpStream, 0, NULL, this));
666         }
667
668         ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
669         pa_threaded_mainloop_unlock(__mpMainloop);
670     } else {
671         if (pa_stream_is_corked(__mpStream)) {
672             AUDIO_IO_LOGW("stream is corked...do uncork here first!!!!");
673             pa_operation_unref(pa_stream_cork(__mpStream, 0, NULL, this));
674         }
675
676         if (__mIsFirstStream) {
677             const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
678             uint32_t prebuf = attr->prebuf;
679             // Compensate amount of prebuf in first stream callback when audio-io use prebuf(-1)
680             // Because a stream will never start when an application wrote less than prebuf at first
681             if (length < prebuf) {
682                 char* dummy = new char[prebuf - length];
683                 memset(dummy, 0, prebuf - length);
684                 pa_stream_write(__mpStream, dummy, prebuf - length, NULL, 0LL, PA_SEEK_RELATIVE);
685                 delete [] dummy;
686             }
687             __mIsFirstStream = false;
688             AUDIO_IO_LOGW("FIRST STREAM CALLBACK : length[%zu], prebuf[%d], dummy[%zu]",
689                           length, prebuf, (length < prebuf) ? prebuf - length : 0);
690         }
691         ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
692     }
693
694     if (ret < 0)
695         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_write() : err[%d]", ret); //LCOV_EXCL_LINE
696
697     return ret;
698 }
699
700 void CPulseAudioClient::cork(bool cork) {
701     AUDIO_IO_LOGD("cork[%d]", cork);
702
703     if (!__mIsInit)
704         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
705
706     if (isInThread())
707         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This operation is not supported in callback");
708
709     checkRunningState();
710
711     // Set __mIsFirstStream flag when uncork(resume) stream, because prebuf will be enable again
712     if (!cork)
713         __mIsFirstStream = true;
714
715     if (!isInThread()) {
716         pa_threaded_mainloop_lock(__mpMainloop);
717         pa_operation_unref(pa_stream_cork(__mpStream, static_cast<int>(cork), __successStreamCb, this));
718         pa_threaded_mainloop_unlock(__mpMainloop);
719     } else {
720         pa_operation_unref(pa_stream_cork(__mpStream, static_cast<int>(cork), __successStreamCb, this));
721     }
722 }
723
724 bool CPulseAudioClient::isCorked() {
725     if (!__mIsInit)
726         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
727
728     checkRunningState();
729
730     int isCork = 0;
731
732     if (!isInThread()) {
733         pa_threaded_mainloop_lock(__mpMainloop);
734         isCork = pa_stream_is_corked(__mpStream);
735         pa_threaded_mainloop_unlock(__mpMainloop);
736     } else {
737         isCork = pa_stream_is_corked(__mpStream);
738     }
739
740 #ifdef _AUDIO_IO_DEBUG_TIMING_
741     AUDIO_IO_LOGD("isCork[%d]", isCork);
742 #endif
743     return static_cast<bool>(isCork);
744 }
745
746 bool CPulseAudioClient::drain() {
747     if (!__mIsInit)
748         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
749
750     checkRunningState();
751
752     if (isCorked()) {
753         AUDIO_IO_LOGW("Corked...");
754         return true;
755     }
756
757     if (__mIsDraining) {
758         AUDIO_IO_LOGW("already draining...");
759         return true;
760     }
761
762     if (!__mIsStarted) {
763         AUDIO_IO_LOGW("stream not started yet...skip drain");
764         return true;
765     }
766
767     if (!isInThread()) {
768         AUDIO_IO_LOGD("drain");
769         pa_threaded_mainloop_lock(__mpMainloop);
770         pa_operation* o = pa_stream_drain(__mpStream, __successDrainCb, this);
771         __mIsDraining = true;
772         while (pa_operation_get_state(o) == PA_OPERATION_RUNNING)
773             pa_threaded_mainloop_wait(__mpMainloop);
774
775         pa_operation_unref(o);
776         pa_threaded_mainloop_unlock(__mpMainloop);
777         AUDIO_IO_LOGD("drain done");
778     } else {
779         AUDIO_IO_LOGD("drain in thread");
780         pa_operation_unref(pa_stream_drain(__mpStream, __successDrainCbInThread, this));
781         __mIsDraining = true;
782     }
783
784     return true;
785 }
786
787 bool CPulseAudioClient::flush() {
788     if (!__mIsInit)
789         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
790
791     checkRunningState();
792
793     if (!isInThread()) {
794         AUDIO_IO_LOGD("flush");
795         pa_threaded_mainloop_lock(__mpMainloop);
796         pa_operation_unref(pa_stream_flush(__mpStream, __successStreamCb, this));
797         pa_threaded_mainloop_unlock(__mpMainloop);
798     } else {
799         AUDIO_IO_LOGD("flush in thread");
800         pa_operation_unref(pa_stream_flush(__mpStream, __successStreamCb, this));
801     }
802
803     return true;
804 }
805
806 size_t CPulseAudioClient::getWritableSize() {
807     if (!__mIsInit)
808         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
809
810     checkRunningState();
811
812     if (__mDirection != EStreamDirection::STREAM_DIRECTION_PLAYBACK)
813         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Playback");
814
815     size_t ret = 0;
816
817     if (!isInThread()) {
818         pa_threaded_mainloop_lock(__mpMainloop);
819         ret = pa_stream_writable_size(__mpStream);
820         pa_threaded_mainloop_unlock(__mpMainloop);
821     } else {
822         ret = pa_stream_writable_size(__mpStream);
823     }
824
825     return ret;
826 }
827
828 void CPulseAudioClient::checkRunningState() {
829     if (!__mpContext || !PA_CONTEXT_IS_GOOD(pa_context_get_state(__mpContext)))
830         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, "The context[%p] is not created or not good state", __mpContext);
831
832     if (!__mpStream || !PA_STREAM_IS_GOOD(pa_stream_get_state(__mpStream)))
833         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, "The stream[%p] is not created or not good state", __mpStream);
834
835     if (pa_context_get_state(__mpContext) != PA_CONTEXT_READY || pa_stream_get_state(__mpStream) != PA_STREAM_READY)
836         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, "The context[%p] or stream[%p] state is not ready", __mpContext, __mpStream);
837
838 #ifdef _AUDIO_IO_DEBUG_TIMING_
839     AUDIO_IO_LOGD("This client is running");
840 #endif
841 }
842
843 bool CPulseAudioClient::isInThread() noexcept {
844     int ret = pa_threaded_mainloop_in_thread(__mpMainloop);
845
846 #ifdef _AUDIO_IO_DEBUG_TIMING_
847     AUDIO_IO_LOGD("isInThread[%d]", ret);
848 #endif
849     return static_cast<bool>(ret);
850 }
851
852 //LCOV_EXCL_START
853 size_t CPulseAudioClient::getReadableSize() {
854     if (!__mIsInit)
855         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
856
857     checkRunningState();
858
859     if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD)
860         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Capture");
861
862     size_t ret = 0;
863
864     if (!isInThread()) {
865         pa_threaded_mainloop_lock(__mpMainloop);
866         ret = pa_stream_readable_size(__mpStream);
867         pa_threaded_mainloop_unlock(__mpMainloop);
868     } else {
869         ret = pa_stream_writable_size(__mpStream);
870     }
871
872     return ret;
873 }
874
875 size_t CPulseAudioClient::getBufferSize() {
876     if (!__mIsInit)
877         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
878
879     checkRunningState();
880
881     size_t ret = 0;
882
883     try {
884         if (!isInThread())
885             pa_threaded_mainloop_lock(__mpMainloop);
886
887         const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
888         if (!attr) {
889             int _err = pa_context_errno(__mpContext);
890             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_buffer_attr() : err[%d]", _err);
891         }
892
893         if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
894             ret = attr->tlength;
895             AUDIO_IO_LOGD("PLAYBACK buffer size[%zu]", ret);
896         } else {
897             ret = attr->fragsize;
898             AUDIO_IO_LOGD("RECORD buffer size[%zu]", ret);
899         }
900     } catch (CAudioError& e) {
901         if (!isInThread())
902             pa_threaded_mainloop_unlock(__mpMainloop);
903         throw;
904     }
905
906     if (!isInThread())
907         pa_threaded_mainloop_unlock(__mpMainloop);
908
909     return ret;
910 }
911
912 pa_usec_t CPulseAudioClient::getLatency() {
913     if (!__mIsInit)
914         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
915
916     checkRunningState();
917
918     pa_usec_t ret = 0;
919     int negative  = 0;
920
921     if (!isInThread()) {
922         if (pa_stream_get_latency(__mpStream, &ret, &negative) < 0) {
923             int _err = pa_context_errno(__mpContext);
924             if (_err != PA_ERR_NODATA)
925                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_latency() : err[%d]", _err);
926         }
927         return negative ? 0 : ret;
928     }
929
930     pa_threaded_mainloop_lock(__mpMainloop);
931
932     try {
933         while (true) {
934             if (pa_stream_get_latency(__mpStream, &ret, &negative) >= 0)
935                 break;
936
937             int _err = pa_context_errno(__mpContext);
938             if (_err != PA_ERR_NODATA)
939                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_latency() : err[%d]", _err);
940
941             /* Wait until latency data is available again */
942             pa_threaded_mainloop_wait(__mpMainloop);
943         }
944     } catch (CAudioError& e) {
945         pa_threaded_mainloop_unlock(__mpMainloop);
946         throw;
947     }
948
949     pa_threaded_mainloop_unlock(__mpMainloop);
950
951     return negative ? 0 : ret;
952 }
953
954 pa_usec_t CPulseAudioClient::getFinalLatency() {
955     if (!__mIsInit)
956         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
957
958     checkRunningState();
959
960     pa_usec_t ret = 0;
961
962     try {
963         if (!isInThread())
964             pa_threaded_mainloop_lock(__mpMainloop);
965
966         uint32_t ver = pa_context_get_server_protocol_version(__mpContext);
967         if (ver >= 13) {
968             const pa_buffer_attr* buffer_attr = pa_stream_get_buffer_attr(__mpStream);
969             const pa_sample_spec* sample_spec = pa_stream_get_sample_spec(__mpStream);
970             const pa_timing_info* timing_info = pa_stream_get_timing_info(__mpStream);
971
972             if (!buffer_attr || !sample_spec || !timing_info)
973                 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",
974                         buffer_attr, sample_spec, timing_info);
975
976             if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
977                 ret = (pa_bytes_to_usec(buffer_attr->tlength, sample_spec) + timing_info->configured_sink_usec);
978                 AUDIO_IO_LOGD("FINAL PLAYBACK LATENCY[%" PRIu64 "]", ret);
979             } else {
980                 ret = (pa_bytes_to_usec(buffer_attr->fragsize, sample_spec) + timing_info->configured_source_usec);
981                 AUDIO_IO_LOGD("FINAL RECORD LATENCY[%" PRIu64 "]", ret);
982             }
983         } else {
984             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_SUPPORTED, "This version(ver.%d) is not supported", ver);
985         }
986
987         if (!isInThread())
988             pa_threaded_mainloop_unlock(__mpMainloop);
989     } catch (CAudioError& e) {
990         if (!isInThread())
991             pa_threaded_mainloop_unlock(__mpMainloop);
992         throw;
993     }
994
995     return ret;
996 }
997 //LCOV_EXCL_STOP