Revise dummy stream write function using anonymous vector objects
[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 #include <vector>
25
26 #ifdef ENABLE_DPM
27 #include <dpm/restriction.h>
28 #endif
29
30 using namespace std;
31 using namespace tizen_media_audio;
32
33
34 /**
35  * class CPulseAudioClient
36  */
37 const char* CPulseAudioClient::CLIENT_NAME = "AUDIO_IO_PA_CLIENT";
38 static constexpr auto drain_wait_interval = 10000;
39 static constexpr auto drain_wait_max_count = 30;
40
41 CPulseAudioClient::CPulseAudioClient(
42         EStreamDirection      direction,
43         CPulseStreamSpec&     spec,
44         IPulseStreamListener* listener) :
45     __mDirection(direction),
46     __mSpec(spec),
47     __mpListener(listener),
48     __mpMainloop(nullptr),
49     __mpContext(nullptr),
50     __mpStream(nullptr),
51     __mpPropList(nullptr),
52     __mIsInit(false),
53     __mIsOperationSuccess(false),
54     __mpSyncReadDataPtr(nullptr),
55     __mSyncReadIndex(0),
56     __mSyncReadLength(0),
57     __mIsUsedSyncRead(false),
58     __mIsFirstStream(false),
59     __mIsDraining(false),
60     __mIsStarted(false) {
61 }
62
63 CPulseAudioClient::~CPulseAudioClient() {
64     finalize();
65 }
66
67 void CPulseAudioClient::__contextStateChangeCb(pa_context* c, void* user_data) {
68     auto pClient = static_cast<CPulseAudioClient*>(user_data);
69     assert(pClient);
70     assert(c);
71
72     switch (pa_context_get_state(c)) {
73     case PA_CONTEXT_READY:
74         AUDIO_IO_LOGD("The context is ready");
75         pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
76         break;
77
78     case PA_CONTEXT_FAILED:
79     case PA_CONTEXT_TERMINATED:
80         AUDIO_IO_LOGD("The context is lost");
81         pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
82         break;
83
84     case PA_CONTEXT_UNCONNECTED:
85     case PA_CONTEXT_CONNECTING:
86     case PA_CONTEXT_AUTHORIZING:
87     case PA_CONTEXT_SETTING_NAME:
88         break;
89     }
90 }
91
92 //LCOV_EXCL_START
93 static bool __is_microphone_restricted(void) {
94     int state = 1;
95 #ifdef ENABLE_DPM
96     device_policy_manager_h dpm_h = nullptr;
97     int ret = 0;
98
99     if ((dpm_h = dpm_manager_create())) {
100         /* state: 0(disallowed), 1(allowed) */
101         if ((ret = dpm_restriction_get_microphone_state(dpm_h, &state)))
102             AUDIO_IO_LOGE("Failed to dpm_restriction_get_microphone_state(), ret(0x%x)", ret);
103         dpm_manager_destroy(dpm_h);
104         AUDIO_IO_LOGD("microphone restriction state: %d(1:allowed, 0:disallowed)", state);
105     } else {
106         AUDIO_IO_LOGE("Failed to dpm_manager_create()");
107     }
108 #endif
109     return (state ? false : true);
110 }
111 //LCOV_EXCL_STOP
112
113 void CPulseAudioClient::__streamStateChangeCb(pa_stream* s, void* user_data) {
114     assert(s);
115     assert(user_data);
116
117     auto pClient = static_cast<CPulseAudioClient*>(user_data);
118
119     switch (pa_stream_get_state(s)) {
120     case PA_STREAM_READY:
121         AUDIO_IO_LOGD("The stream is ready");
122         pClient->__mpListener->onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING);
123         if (pClient->__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
124             pClient->__mIsFirstStream = true;
125         pClient->__mIsInit = true;
126         pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
127         break;
128
129 //LCOV_EXCL_START
130     case PA_STREAM_FAILED:
131         AUDIO_IO_LOGD("The stream is failed");
132         pClient->__mpListener->onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE,
133                                               __is_microphone_restricted());
134         pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
135         break;
136 //LCOV_EXCL_STOP
137
138     case PA_STREAM_TERMINATED:
139         AUDIO_IO_LOGD("The stream is terminated");
140         pClient->__mpListener->onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE);
141         pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
142         break;
143
144     case PA_STREAM_UNCONNECTED:
145     case PA_STREAM_CREATING:
146         break;
147     }
148 }
149
150 void CPulseAudioClient::__streamCaptureCb(pa_stream* s, size_t length, void* user_data) {
151     assert(s);
152     assert(user_data);
153
154     auto pClient = static_cast<CPulseAudioClient*>(user_data);
155     assert(pClient->__mpListener);
156     assert(pClient->__mpMainloop);
157
158     if (pClient->__mIsUsedSyncRead)
159         pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
160
161     pClient->__mpListener->onStream(pClient, length);
162 }
163
164 static void __dummy_write(pa_stream* s, size_t length) {
165     pa_stream_write(s, std::vector<char>(length).data(), length, NULL, 0LL, PA_SEEK_RELATIVE);
166 }
167
168 void CPulseAudioClient::__streamPlaybackCb(pa_stream* s, size_t length, void* user_data) {
169     assert(s);
170     assert(user_data);
171
172     auto pClient = static_cast<CPulseAudioClient*>(user_data);
173     assert(pClient->__mpListener);
174
175 #ifndef DISABLE_MOBILE_BACK_COMP
176     if (!pClient->__mIsInit) {
177         AUDIO_IO_LOGD("Occurred this listener when an out stream is on the way to create : Write dummy, length[%zu]", length);
178         __dummy_write(s, length);
179         return;
180     }
181     if (pClient->isCorked()) {
182         AUDIO_IO_LOGD("Occurred this listener when an out stream is CORKED : Write dummy, length[%zu]", length);
183         __dummy_write(s, length);
184         return;
185     }
186 #endif
187
188     pClient->__mpListener->onStream(pClient, length);
189
190 #ifndef DISABLE_MOBILE_BACK_COMP
191     /* If stream is not written in first callback during prepare,
192        then write dummy data to ensure the start */
193     if (pClient->__mSpec.getStreamLatency() == CPulseStreamSpec::EStreamLatency::STREAM_LATENCY_OUTPUT_DEFAULT_ASYNC &&
194         pClient->__mIsFirstStream) {
195         AUDIO_IO_LOGW("[async] Write dummy of length[%zu] since not written in first callback during prepare", length);
196         __dummy_write(s, length);
197         pClient->__mIsFirstStream = false;
198     }
199 #endif
200 }
201
202 void CPulseAudioClient::__streamLatencyUpdateCb(pa_stream* s, void* user_data) {
203     assert(s);
204     assert(user_data);
205
206     auto pClient = static_cast<CPulseAudioClient*>(user_data);
207
208     pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
209 }
210
211 void CPulseAudioClient::__streamStartedCb(pa_stream* s, void* user_data) {
212     assert(s);
213     assert(user_data);
214
215     auto pClient = static_cast<CPulseAudioClient*>(user_data);
216
217     AUDIO_IO_LOGD("stream %p started.", pClient);
218
219     pClient->__mIsStarted = true;
220 }
221
222 void CPulseAudioClient::__streamUnderflowCb(pa_stream* s, void* user_data) {
223     assert(s);
224     assert(user_data);
225
226     auto pClient = static_cast<CPulseAudioClient*>(user_data);
227
228     AUDIO_IO_LOGD("stream %p UnderFlow...", pClient);
229
230     pClient->__mIsStarted = false;
231 }
232
233 //LCOV_EXCL_START
234 void CPulseAudioClient::__streamEventCb(pa_stream* s, const char *name, pa_proplist *pl, void *user_data) {
235     assert(s);
236     assert(user_data);
237
238     AUDIO_IO_LOGE("NAME : %s, Prop : %p", name, pl);
239
240     auto pClient = static_cast<CPulseAudioClient*>(user_data);
241     if (strcmp(name, PA_STREAM_EVENT_POP_TIMEOUT) == 0)
242         pa_operation_unref(pa_stream_cork(pClient->__mpStream, 1, NULL, NULL));
243 }
244 //LCOV_EXCL_STOP
245
246 void CPulseAudioClient::__successStreamCb(pa_stream* s, int success, void* user_data) {
247     AUDIO_IO_LOGD("pa_stream[%p], success[%d], user_data[%p]", s, success, user_data);
248     assert(s);
249     assert(user_data);
250
251     auto pClient = static_cast<CPulseAudioClient*>(user_data);
252     pClient->__mIsOperationSuccess = static_cast<bool>(success);
253
254     pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
255 }
256
257 //LCOV_EXCL_START
258 void CPulseAudioClient::__successDrainCbInThread(pa_stream* s, int success, void* user_data) {
259     AUDIO_IO_LOGD("pa_stream[%p], success[%d], user_data[%p]", s, success, user_data);
260     assert(s);
261     assert(user_data);
262
263     auto pClient = static_cast<CPulseAudioClient*>(user_data);
264     pClient->__mIsOperationSuccess = static_cast<bool>(success);
265     pClient->__mIsDraining = false;
266 }
267 //LCOV_EXCL_STOP
268
269 void CPulseAudioClient::__successDrainCb(pa_stream* s, int success, void* user_data) {
270     AUDIO_IO_LOGD("pa_stream[%p], success[%d], user_data[%p]", s, success, user_data);
271     assert(s);
272     assert(user_data);
273
274     auto pClient = static_cast<CPulseAudioClient*>(user_data);
275     pClient->__mIsOperationSuccess = static_cast<bool>(success);
276     pClient->__mIsDraining = false;
277
278     pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
279 }
280
281 void CPulseAudioClient::__successVolumeCb(pa_context *c, int success, void *user_data) {
282     AUDIO_IO_LOGD("pa_context[%p], success[%d], user_data[%p]", c, success, user_data);
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                 __dummy_write(__mpStream, prebuf - length);
690
691             __mIsFirstStream = false;
692             AUDIO_IO_LOGW("FIRST STREAM CALLBACK : length[%zu], prebuf[%d], dummy[%zu]",
693                           length, prebuf, (length < prebuf) ? prebuf - length : 0);
694         }
695         ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
696 // LCOV_EXCL_STOP
697     }
698
699     if (ret < 0)
700         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_write() : err[%d]", ret); //LCOV_EXCL_LINE
701
702     return ret;
703 }
704
705 void CPulseAudioClient::cork(bool cork) {
706     AUDIO_IO_LOGD("cork[%d]", cork);
707
708     if (!__mIsInit)
709         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient"); // LCOV_EXCL_LINE
710
711     if (isInThread())
712         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This operation is not supported in callback"); // LCOV_EXCL_LINE
713
714     checkRunningState();
715
716     // Set __mIsFirstStream flag when uncork(resume) stream, because prebuf will be enable again
717     if (!cork)
718         __mIsFirstStream = true;
719
720     if (!isInThread()) {
721         pa_threaded_mainloop_lock(__mpMainloop);
722         pa_operation_unref(pa_stream_cork(__mpStream, static_cast<int>(cork), __successStreamCb, this));
723         pa_threaded_mainloop_unlock(__mpMainloop);
724     } else {
725         pa_operation_unref(pa_stream_cork(__mpStream, static_cast<int>(cork), __successStreamCb, this));
726     }
727 }
728
729 bool CPulseAudioClient::isCorked() {
730     if (!__mIsInit)
731         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient"); // LCOV_EXCL_LINE
732
733     checkRunningState();
734
735     int isCork = 0;
736
737     if (!isInThread()) {
738         pa_threaded_mainloop_lock(__mpMainloop);
739         isCork = pa_stream_is_corked(__mpStream);
740         pa_threaded_mainloop_unlock(__mpMainloop);
741     } else {
742         isCork = pa_stream_is_corked(__mpStream);
743     }
744
745 #ifdef _AUDIO_IO_DEBUG_TIMING_
746     AUDIO_IO_LOGD("isCork[%d]", isCork);
747 #endif
748     return static_cast<bool>(isCork);
749 }
750
751 bool CPulseAudioClient::drain() {
752     if (!__mIsInit)
753         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient"); // LCOV_EXCL_LINE
754
755     checkRunningState();
756
757     if (isCorked()) {
758         AUDIO_IO_LOGW("Corked...");
759         return true;
760     }
761
762     if (__mIsDraining) {
763         AUDIO_IO_LOGW("already draining...");
764         return true;
765     }
766
767     if (!__mIsStarted) {
768         AUDIO_IO_LOGW("stream not started yet...skip drain");
769         return true;
770     }
771
772     if (!isInThread()) {
773         AUDIO_IO_LOGD("drain");
774         pa_threaded_mainloop_lock(__mpMainloop);
775         pa_operation* o = pa_stream_drain(__mpStream, __successDrainCb, this);
776         __mIsDraining = true;
777         while (pa_operation_get_state(o) == PA_OPERATION_RUNNING)
778             pa_threaded_mainloop_wait(__mpMainloop);
779
780         pa_operation_unref(o);
781         pa_threaded_mainloop_unlock(__mpMainloop);
782         AUDIO_IO_LOGD("drain done");
783     } else {
784         AUDIO_IO_LOGD("drain in thread");
785         pa_operation_unref(pa_stream_drain(__mpStream, __successDrainCbInThread, this));
786         __mIsDraining = true;
787     }
788
789     return true;
790 }
791
792 bool CPulseAudioClient::flush() {
793     if (!__mIsInit)
794         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient"); // LCOV_EXCL_LINE
795
796     checkRunningState();
797
798     if (!isInThread()) {
799         AUDIO_IO_LOGD("flush");
800         pa_threaded_mainloop_lock(__mpMainloop);
801         pa_operation_unref(pa_stream_flush(__mpStream, __successStreamCb, this));
802         pa_threaded_mainloop_unlock(__mpMainloop);
803     } else {
804         AUDIO_IO_LOGD("flush in thread");
805         pa_operation_unref(pa_stream_flush(__mpStream, __successStreamCb, this));
806     }
807
808     return true;
809 }
810
811 size_t CPulseAudioClient::getWritableSize() {
812     if (!__mIsInit)
813         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient"); // LCOV_EXCL_LINE
814
815     checkRunningState();
816
817     if (__mDirection != EStreamDirection::STREAM_DIRECTION_PLAYBACK)
818         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Playback"); // LCOV_EXCL_LINE
819
820     size_t ret = 0;
821
822     if (!isInThread()) {
823         pa_threaded_mainloop_lock(__mpMainloop);
824         ret = pa_stream_writable_size(__mpStream);
825         pa_threaded_mainloop_unlock(__mpMainloop);
826     } else {
827         ret = pa_stream_writable_size(__mpStream);
828     }
829
830     return ret;
831 }
832
833 void CPulseAudioClient::checkRunningState() {
834     if (!__mpContext || !PA_CONTEXT_IS_GOOD(pa_context_get_state(__mpContext)))
835         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED,                       // LCOV_EXCL_LINE
836                                "The context[%p] is not created or not good state", __mpContext); // LCOV_EXCL_LINE
837
838     if (!__mpStream || !PA_STREAM_IS_GOOD(pa_stream_get_state(__mpStream)))
839         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED,                     // LCOV_EXCL_LINE
840                                "The stream[%p] is not created or not good state", __mpStream); // LCOV_EXCL_LINE
841
842     if (pa_context_get_state(__mpContext) != PA_CONTEXT_READY || pa_stream_get_state(__mpStream) != PA_STREAM_READY)
843         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED,                                   // LCOV_EXCL_LINE
844                                "The context[%p] or stream[%p] state is not ready", __mpContext, __mpStream); // LCOV_EXCL_LINE
845
846 #ifdef _AUDIO_IO_DEBUG_TIMING_
847     AUDIO_IO_LOGD("This client is running");
848 #endif
849 }
850
851 bool CPulseAudioClient::isInThread() noexcept {
852     int ret = pa_threaded_mainloop_in_thread(__mpMainloop);
853
854 #ifdef _AUDIO_IO_DEBUG_TIMING_
855     AUDIO_IO_LOGD("isInThread[%d]", ret);
856 #endif
857     return static_cast<bool>(ret);
858 }
859
860 //LCOV_EXCL_START
861 size_t CPulseAudioClient::getReadableSize() {
862     if (!__mIsInit)
863         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
864
865     checkRunningState();
866
867     if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD)
868         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Capture");
869
870     size_t ret = 0;
871
872     if (!isInThread()) {
873         pa_threaded_mainloop_lock(__mpMainloop);
874         ret = pa_stream_readable_size(__mpStream);
875         pa_threaded_mainloop_unlock(__mpMainloop);
876     } else {
877         ret = pa_stream_readable_size(__mpStream);
878     }
879
880     return ret;
881 }
882
883 size_t CPulseAudioClient::getBufferSize() {
884     if (!__mIsInit)
885         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
886
887     checkRunningState();
888
889     size_t ret = 0;
890
891     try {
892         if (!isInThread())
893             pa_threaded_mainloop_lock(__mpMainloop);
894
895         const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
896         if (!attr) {
897             int _err = pa_context_errno(__mpContext);
898             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_buffer_attr() : err[%d]", _err);
899         }
900
901         if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
902             ret = attr->tlength;
903             AUDIO_IO_LOGD("PLAYBACK buffer size[%zu]", ret);
904         } else {
905             ret = attr->fragsize;
906             AUDIO_IO_LOGD("RECORD buffer size[%zu]", ret);
907         }
908     } catch (const CAudioError& e) {
909         if (!isInThread())
910             pa_threaded_mainloop_unlock(__mpMainloop);
911         throw;
912     }
913
914     if (!isInThread())
915         pa_threaded_mainloop_unlock(__mpMainloop);
916
917     return ret;
918 }
919
920 pa_usec_t CPulseAudioClient::getLatency() {
921     if (!__mIsInit)
922         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
923
924     checkRunningState();
925
926     pa_usec_t ret = 0;
927     int negative  = 0;
928
929     if (!isInThread()) {
930         if (pa_stream_get_latency(__mpStream, &ret, &negative) < 0) {
931             int _err = pa_context_errno(__mpContext);
932             if (_err != PA_ERR_NODATA)
933                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_latency() : err[%d]", _err);
934         }
935         return negative ? 0 : ret;
936     }
937
938     pa_threaded_mainloop_lock(__mpMainloop);
939
940     try {
941         while (true) {
942             if (pa_stream_get_latency(__mpStream, &ret, &negative) >= 0)
943                 break;
944
945             int _err = pa_context_errno(__mpContext);
946             if (_err != PA_ERR_NODATA)
947                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_latency() : err[%d]", _err);
948
949             /* Wait until latency data is available again */
950             pa_threaded_mainloop_wait(__mpMainloop);
951         }
952     } catch (const CAudioError& e) {
953         pa_threaded_mainloop_unlock(__mpMainloop);
954         throw;
955     }
956
957     pa_threaded_mainloop_unlock(__mpMainloop);
958
959     return negative ? 0 : ret;
960 }
961
962 pa_usec_t CPulseAudioClient::getFinalLatency() {
963     if (!__mIsInit)
964         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
965
966     checkRunningState();
967
968     pa_usec_t ret = 0;
969
970     try {
971         if (!isInThread())
972             pa_threaded_mainloop_lock(__mpMainloop);
973
974         uint32_t ver = pa_context_get_server_protocol_version(__mpContext);
975         if (ver >= 13) {
976             const pa_buffer_attr* buffer_attr = pa_stream_get_buffer_attr(__mpStream);
977             const pa_sample_spec* sample_spec = pa_stream_get_sample_spec(__mpStream);
978             const pa_timing_info* timing_info = pa_stream_get_timing_info(__mpStream);
979
980             if (!buffer_attr || !sample_spec || !timing_info)
981                 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",
982                         buffer_attr, sample_spec, timing_info);
983
984             if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
985                 ret = (pa_bytes_to_usec(buffer_attr->tlength, sample_spec) + timing_info->configured_sink_usec);
986                 AUDIO_IO_LOGD("FINAL PLAYBACK LATENCY[%" PRIu64 "]", ret);
987             } else {
988                 ret = (pa_bytes_to_usec(buffer_attr->fragsize, sample_spec) + timing_info->configured_source_usec);
989                 AUDIO_IO_LOGD("FINAL RECORD LATENCY[%" PRIu64 "]", ret);
990             }
991         } else {
992             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_SUPPORTED, "This version(ver.%d) is not supported", ver);
993         }
994
995         if (!isInThread())
996             pa_threaded_mainloop_unlock(__mpMainloop);
997     } catch (const CAudioError& e) {
998         if (!isInThread())
999             pa_threaded_mainloop_unlock(__mpMainloop);
1000         throw;
1001     }
1002
1003     return ret;
1004 }
1005 //LCOV_EXCL_STOP
1006
1007 void CPulseAudioClient::applyRecordVolume(double volume) {
1008     if (!__mIsInit)
1009         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
1010
1011     checkRunningState();
1012
1013     if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD)
1014         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client can't use this function"); //LCOV_EXCL_LINE
1015
1016     try {
1017         if (!isInThread())
1018             pa_threaded_mainloop_lock(__mpMainloop);
1019
1020         pa_cvolume cv = { 0, };
1021         pa_volume_t v = PA_VOLUME_NORM * volume;
1022
1023         pa_cvolume_set(&cv, __mSpec.getChannelMap().channels, v);
1024
1025         pa_operation_unref(pa_context_set_source_output_volume(__mpContext,
1026                 pa_stream_get_index(__mpStream), &cv, __successVolumeCb, NULL));
1027
1028         if (!isInThread())
1029             pa_threaded_mainloop_unlock(__mpMainloop);
1030     } catch (const CAudioError& e) {
1031         if (!isInThread())
1032             pa_threaded_mainloop_unlock(__mpMainloop);
1033         throw;
1034     }
1035 }