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