CPulseAudioClient: fix improper initialize error handling
[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_unref(pa_stream_cork(pClient->__mpStream, 1, NULL, NULL));
289 }
290 //LCOV_EXCL_STOP
291
292 void CPulseAudioClient::__successStreamCb(pa_stream* s, int success, void* user_data) {
293     assert(s);
294     assert(user_data);
295
296     auto pClient = static_cast<CPulseAudioClient*>(user_data);
297
298     AUDIO_IO_LOGD("pClient[%p], pa_stream[%p], success[%d], user_data[%p]", pClient, s, success, user_data);
299
300     pClient->__mIsOperationSuccess = static_cast<bool>(success);
301
302     /* FIXME : verify following action without any waiting */
303     pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
304 }
305
306 //LCOV_EXCL_START
307 void CPulseAudioClient::__successDrainCbInThread(pa_stream* s, int success, void* user_data) {
308     assert(s);
309     assert(user_data);
310
311     auto pClient = static_cast<CPulseAudioClient*>(user_data);
312
313     AUDIO_IO_LOGD("pClient[%p], pa_stream[%p], success[%d], user_data[%p]", pClient, s, success, user_data);
314
315     pClient->__mIsOperationSuccess = static_cast<bool>(success);
316     pClient->__mIsDraining = false;
317 }
318 //LCOV_EXCL_STOP
319
320 void CPulseAudioClient::__successDrainCb(pa_stream* s, int success, void* user_data) {
321     assert(s);
322     assert(user_data);
323
324     auto pClient = static_cast<CPulseAudioClient*>(user_data);
325
326     AUDIO_IO_LOGD("pClient[%p], pa_stream[%p], success[%d], user_data[%p]", pClient, s, success, user_data);
327
328     pClient->__mIsOperationSuccess = static_cast<bool>(success);
329     pClient->__mIsDraining = false;
330
331     pa_threaded_mainloop_signal(pClient->__mpMainloop, 0);
332 }
333
334 void CPulseAudioClient::__successVolumeCb(pa_context *c, int success, void *user_data) {
335     AUDIO_IO_LOGD("pa_context[%p], success[%d], user_data[%p]", c, success, user_data);
336 }
337
338 void CPulseAudioClient::resetStreamCallbacks() {
339     if (!__mpStream)
340         return;
341
342     if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
343         pa_stream_set_write_callback(__mpStream, NULL, NULL);
344     else
345         pa_stream_set_read_callback(__mpStream, NULL, NULL);
346
347     pa_stream_set_latency_update_callback(__mpStream, NULL, NULL);
348     pa_stream_set_event_callback(__mpStream, NULL, NULL);
349 }
350
351 void CPulseAudioClient::resetInternalObjects() {
352     if (__mpMainloop)
353         pa_threaded_mainloop_stop(__mpMainloop);
354
355     if (__mpStream) {
356         pa_stream_disconnect(__mpStream);
357         pa_stream_unref(__mpStream);
358         __mpStream = nullptr;
359     }
360
361     if (__mpContext) {
362         pa_context_disconnect(__mpContext);
363         pa_context_unref(__mpContext);
364         __mpContext = nullptr;
365     }
366
367     if (__mpMainloop) {
368         pa_threaded_mainloop_free(__mpMainloop);
369         __mpMainloop = nullptr;
370     }
371
372     if (__mpPropList) {
373         pa_proplist_free(__mpPropList);
374         __mpPropList = nullptr;
375     }
376 }
377
378 void CPulseAudioClient::initialize() {
379     if (__mIsInit)
380         return;
381
382     int ret = 0;
383     int err = 0;
384
385     try {
386         // Allocates PA proplist
387         __mpPropList = pa_proplist_new();
388         if (!__mpPropList)
389             THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_proplist_new()"); //LCOV_EXCL_LINE
390
391         // Adds values on proplist for delivery to PULSEAUDIO
392         pa_proplist_sets(__mpPropList, PA_PROP_MEDIA_ROLE, __mSpec.getAudioInfo().getConvertedStreamType());
393
394         int index = __mSpec.getAudioInfo().getAudioIndex();
395         if (index >= 0)
396             pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_PARENT_ID, "%u", (unsigned int) index);
397
398         // Adds latency on proplist for delivery to PULSEAUDIO
399         AUDIO_IO_LOGD("LATENCY : %s[%d]", __mSpec.getStreamLatencyToString(), static_cast<int>(__mSpec.getStreamLatency()));
400         pa_proplist_setf(__mpPropList, PA_PROP_MEDIA_TIZEN_AUDIO_LATENCY, "%s", __mSpec.getStreamLatencyToString());
401
402         // Allocates PA mainloop
403         __mpMainloop = pa_threaded_mainloop_new();
404         if (!__mpMainloop)
405             THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_threaded_mainloop_new()"); //LCOV_EXCL_LINE
406
407         // Allocates PA context
408         __mpContext = pa_context_new(pa_threaded_mainloop_get_api(__mpMainloop), CLIENT_NAME);
409         if (!__mpContext)
410             THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_context_new()"); //LCOV_EXCL_LINE
411
412         // Sets context state changed callback
413         pa_context_set_state_callback(__mpContext, __contextStateChangeCb, this);
414
415         // Connects this client with PA server
416         if (pa_context_connect(__mpContext, NULL, PA_CONTEXT_NOFLAGS, NULL) < 0)
417             THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pa_context_connect()"); //LCOV_EXCL_LINE
418
419         // LOCK for synchronous connection
420         CPulseThreadLocker locker{__mpMainloop};
421
422         // Start mainloop
423         if (pa_threaded_mainloop_start(__mpMainloop) < 0) {
424 //LCOV_EXCL_START
425             THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_threaded_mainloop_start()");
426 //LCOV_EXCL_STOP
427         }
428
429         // Connection process is asynchronously
430         // So, this function will be waited when occurred context state change event
431         // If I got a signal, do next processing
432         while (true) {
433             pa_context_state_t state;
434             state = pa_context_get_state(__mpContext);
435
436             if (state == PA_CONTEXT_READY)
437                 break;
438
439             if (!PA_CONTEXT_IS_GOOD(state)) {
440 //LCOV_EXCL_START
441                 err = pa_context_errno(__mpContext);
442                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION,
443                                        "pa_context's state is not good : err[%d]", err);
444 //LCOV_EXCL_STOP
445             }
446
447             /* Wait until the context is ready */
448             pa_threaded_mainloop_wait(__mpMainloop);
449         }
450
451         AUDIO_IO_LOGD("pa_context[%p] now ready", __mpContext);
452
453         // Allocates PA stream
454         pa_sample_spec ss   = __mSpec.getSampleSpec();
455         pa_channel_map map  = __mSpec.getChannelMap();
456
457         __mpStream = pa_stream_new_with_proplist(__mpContext, __mSpec.getStreamName(), &ss, &map, __mpPropList);
458         if (!__mpStream) {
459 //LCOV_EXCL_START
460             THROW_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_new_with_proplist()");
461 //LCOV_EXCL_STOP
462         }
463
464         // Sets stream callbacks
465         pa_stream_set_state_callback(__mpStream, __streamStateChangeCb, this);
466         pa_stream_set_read_callback(__mpStream, __streamCaptureCb, this);
467         pa_stream_set_write_callback(__mpStream, __streamPlaybackCb, this);
468         pa_stream_set_latency_update_callback(__mpStream, __streamLatencyUpdateCb, this);
469         pa_stream_set_event_callback(__mpStream, __streamEventCb, this);
470         if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
471             pa_stream_set_started_callback(__mpStream, __streamStartedCb, this);
472             pa_stream_set_underflow_callback(__mpStream, __streamUnderflowCb, this);
473         }
474
475         // Connect stream with PA Server
476
477         if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
478             auto flags = static_cast<pa_stream_flags_t>(
479                     PA_STREAM_INTERPOLATE_TIMING |
480                     PA_STREAM_ADJUST_LATENCY     |
481 #ifndef DISABLE_MOBILE_BACK_COMP
482                     PA_STREAM_START_CORKED       |
483 #endif
484                     PA_STREAM_AUTO_TIMING_UPDATE);
485
486             ret = pa_stream_connect_playback(__mpStream, NULL, NULL, flags, NULL, NULL);
487         } else {
488             auto flags = static_cast<pa_stream_flags_t>(
489                     PA_STREAM_INTERPOLATE_TIMING |
490                     PA_STREAM_ADJUST_LATENCY     |
491 #ifndef DISABLE_MOBILE_BACK_COMP
492                     PA_STREAM_START_CORKED       |
493 #endif
494                     PA_STREAM_AUTO_TIMING_UPDATE);
495
496             ret = pa_stream_connect_record(__mpStream, NULL, NULL, flags);
497         }
498         if (ret != 0) {
499 //LCOV_EXCL_START
500             err = pa_context_errno(__mpContext);
501             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
502                                    "Failed pa_stream_connect() : err[%d]", err);
503 //LCOV_EXCL_STOP
504         }
505
506         AUDIO_IO_LOGD("pa_stream[%p] now wait for stream ready...", __mpStream);
507
508         while (true) {
509             pa_stream_state_t state = pa_stream_get_state(__mpStream);
510             AUDIO_IO_LOGD("pa_stream[%p] current state[%d]", __mpStream, state);
511
512             if (state == PA_STREAM_READY)
513                 break;
514
515             if (!PA_STREAM_IS_GOOD(state)) {
516                 err = pa_context_errno(__mpContext);
517                 if (err == PA_ERR_ACCESS)
518                     THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_DEVICE_POLICY_RESTRICTION,
519                                            "pa_stream's state is not good : err[%d]", err);
520                 else
521                     THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION,   //LCOV_EXCL_LINE
522                                            "pa_stream's state is not good : err[%d]", err); //LCOV_EXCL_LINE
523             }
524
525             /* Wait until the stream is ready */
526             AUDIO_IO_LOGD("pa_mainloop[%p] signal wait...", __mpMainloop);
527             pa_threaded_mainloop_wait(__mpMainloop);
528             AUDIO_IO_LOGD("pa_mainloop[%p] signal wait done", __mpMainloop);
529         }
530         pa_threaded_mainloop_accept(__mpMainloop);
531
532         // __mIsInit = true;  // Moved to __streamStateChangeCb()
533     } catch (const CAudioError& e) {
534 //LCOV_EXCL_START
535         resetStreamCallbacks();
536         resetInternalObjects();
537         throw;
538 //LCOV_EXCL_END
539     }
540
541     AUDIO_IO_LOGD("Done : pa_context[%p], pa_mainloop[%p], pa_stream[%p]", __mpContext, __mpMainloop, __mpStream);
542 }
543
544 void CPulseAudioClient::finalize() {
545     AUDIO_IO_LOGD("pa_context[%p], pa_mainloop[%p], pa_stream[%p]", __mpContext, __mpMainloop, __mpStream);
546
547     if (!__mpMainloop)
548         return;
549
550     bool is_in_thread = isInThread();
551     if (!is_in_thread)
552         pa_threaded_mainloop_lock(__mpMainloop);
553
554     __mIsInit = false;
555
556     resetStreamCallbacks();
557
558     if (!is_in_thread)
559         pa_threaded_mainloop_unlock(__mpMainloop);
560
561     /* Wait for drain complete if draining before finalize */
562     if (__mIsDraining) {
563         unsigned int drain_wait_count = 0;
564         while (__mIsDraining && drain_wait_count++ < drain_wait_max_count)
565             usleep(drain_wait_interval);
566         AUDIO_IO_LOGD("wait for drain complete!!!! [%d * %d usec]",
567                       drain_wait_count, drain_wait_interval);
568     }
569
570     resetInternalObjects();
571
572     AUDIO_IO_LOGD("Done");
573 }
574
575 int CPulseAudioClient::read(void* buffer, size_t length) {
576     if (!__mIsInit)
577         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); //LCOV_EXCL_LINE
578
579     checkRunningState();
580
581     if (!buffer)
582         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "invalid parameter : buffer[%p]", buffer); //LCOV_EXCL_LINE
583
584     if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
585         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback client can't use this function"); //LCOV_EXCL_LINE
586
587     size_t lengthIter = length;
588     int ret = 0;
589
590     __mIsUsedSyncRead = true;
591
592     try {
593         CPulseThreadLocker locker{__mpMainloop};
594
595         while (lengthIter > 0) {
596             size_t l;
597
598             while (!__mpSyncReadDataPtr) {
599                 ret = pa_stream_peek(__mpStream, &__mpSyncReadDataPtr, &__mSyncReadLength);
600                 if (ret != 0)
601                     THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_peek() : ret[%d]", ret); //LCOV_EXCL_LINE
602
603                 if (__mSyncReadLength <= 0) {
604 #ifdef _AUDIO_IO_DEBUG_TIMING_
605                     AUDIO_IO_LOGD("readLength(%zu byte) is not valid. wait...", __mSyncReadLength);
606 #endif
607                     pa_threaded_mainloop_wait(__mpMainloop);
608                 } else if (!__mpSyncReadDataPtr) {
609 // LCOV_EXCL_START
610                     // Data peeked, but it doesn't have any data
611                     ret = pa_stream_drop(__mpStream);
612                     if (ret != 0)
613                         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_drop() : ret[%d]", ret);
614 //LCOV_EXCL_STOP
615                 } else {
616                     __mSyncReadIndex = 0;
617                 }
618             }
619
620             l = min(__mSyncReadLength, lengthIter);
621
622             // Copy partial pcm data on out parameter
623 #ifdef _AUDIO_IO_DEBUG_TIMING_
624             AUDIO_IO_LOGD("memcpy() that a peeked buffer[%p], index[%zu], length[%zu] on out buffer", (const uint8_t*)(__mpSyncReadDataPtr) + __mSyncReadIndex, __mSyncReadIndex, l);
625 #endif
626             memcpy(buffer, (const uint8_t*)__mpSyncReadDataPtr + __mSyncReadIndex, l);
627
628             // Move next position
629             buffer = (uint8_t*)buffer + l;
630             lengthIter -= l;
631
632             // Adjusts the rest length
633             __mSyncReadIndex  += l;
634             __mSyncReadLength -= l;
635
636             if (__mSyncReadLength == 0) {
637 #ifdef _AUDIO_IO_DEBUG_TIMING_
638                 AUDIO_IO_LOGD("__mSyncReadLength is zero, do drop()");
639 #endif
640                 ret = pa_stream_drop(__mpStream);
641                 if (ret != 0)
642                     THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, //LCOV_EXCL_LINE
643                                            "Failed pa_stream_drop() : ret[%d]", ret);     //LCOV_EXCL_LINE
644
645                 // Reset the internal pointer
646                 __mpSyncReadDataPtr = nullptr;
647                 __mSyncReadLength   = 0;
648                 __mSyncReadIndex    = 0;
649             }
650         }  // End of while (lengthIter > 0)
651
652         __mIsUsedSyncRead = false;
653     } catch (const CAudioError& e) {
654 // LCOV_EXCL_START
655         __mIsUsedSyncRead = false;
656         throw;
657 // LCOV_EXCL_STOP
658     }
659
660     return length;
661 }
662
663 int CPulseAudioClient::peek(const void** buffer, size_t* length) {
664     if (!__mIsInit)
665         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
666
667     checkRunningState();
668
669     if (!buffer || !length)
670         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT,                   // LCOV_EXCL_LINE
671                                "invalid parameter : buffer[%p], length[%p]", buffer, length); // LCOV_EXCL_LINE
672
673     if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
674         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
675
676     CPulseThreadLocker locker{__mpMainloop};
677
678     int ret = pa_stream_peek(__mpStream, buffer, length);
679
680
681 #ifdef _AUDIO_IO_DEBUG_TIMING_
682     AUDIO_IO_LOGD("buffer[%p], length[%zu]", *buffer, *length);
683 #endif
684
685     if (ret < 0)
686         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_peek() : err[%d]", ret); //LCOV_EXCL_LINE
687
688     return ret;
689 }
690
691 int CPulseAudioClient::drop() {
692     if (!__mIsInit)
693         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
694
695 #ifdef _AUDIO_IO_DEBUG_TIMING_
696     AUDIO_IO_LOGD("");
697 #endif
698
699     checkRunningState();
700
701     if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
702         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
703
704     CPulseThreadLocker locker{__mpMainloop};
705
706     int ret = pa_stream_drop(__mpStream);
707     if (ret < 0)
708         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_drop() : err[%d]", ret); //LCOV_EXCL_LINE
709
710     return ret;
711 }
712
713 int CPulseAudioClient::write(const void* data, size_t length) {
714     if (!data)
715         THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_ARGUMENT, "invalid parameter"); // LCOV_EXCL_LINE
716
717     if (__mDirection == EStreamDirection::STREAM_DIRECTION_RECORD)
718         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "playback can't use this function"); // LCOV_EXCL_LINE
719
720     int ret = 0;
721
722 #ifdef _AUDIO_IO_DEBUG_TIMING_
723     AUDIO_IO_LOGD("data[%p], length[%zu], First[%d]", data, length, __mIsFirstStream);
724 #endif
725
726     if (!isInThread()) {
727         CPulseThreadLocker locker{__mpMainloop};
728         if (pa_stream_is_corked(__mpStream)) {
729             AUDIO_IO_LOGW("stream is corked...do uncork here first!!!!");
730             pa_operation_unref(pa_stream_cork(__mpStream, 0, NULL, this));
731         }
732
733         ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
734     } else {
735 // LCOV_EXCL_START
736         if (pa_stream_is_corked(__mpStream)) {
737             AUDIO_IO_LOGW("stream is corked...do uncork here first!!!!");
738             pa_operation_unref(pa_stream_cork(__mpStream, 0, NULL, this));
739         }
740
741         if (__mIsFirstStream) {
742             const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
743             uint32_t prebuf = attr->prebuf;
744             // Compensate amount of prebuf in first stream callback when audio-io use prebuf(-1)
745             // Because a stream will never start when an application wrote less than prebuf at first
746             if (length < prebuf)
747                 __dummy_write(__mpStream, prebuf - length);
748
749             __mIsFirstStream = false;
750             AUDIO_IO_LOGW("FIRST STREAM CALLBACK : length[%zu], prebuf[%d], dummy[%zu]",
751                           length, prebuf, (length < prebuf) ? prebuf - length : 0);
752         }
753         ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
754 // LCOV_EXCL_STOP
755     }
756
757     if (ret < 0)
758         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_write() : err[%d]", ret); //LCOV_EXCL_LINE
759
760     return ret;
761 }
762
763 void CPulseAudioClient::cork(bool cork) {
764     AUDIO_IO_LOGD("cork[%d]", cork);
765
766     if (!__mIsInit)
767         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
768
769     if (isInThread())
770         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This operation is not supported in callback"); // LCOV_EXCL_LINE
771
772     checkRunningState();
773
774     // Set __mIsFirstStream flag when uncork(resume) stream, because prebuf will be enable again
775     if (!cork)
776         __mIsFirstStream = true;
777
778     CPulseThreadLocker locker{__mpMainloop};
779
780     /* FIXME: wait for completion like drain? */
781     pa_operation_unref(pa_stream_cork(__mpStream, static_cast<int>(cork), __successStreamCb, this));
782
783     AUDIO_IO_LOGD("cork[%d] done", cork);
784 }
785
786 bool CPulseAudioClient::isCorked() {
787     if (!__mIsInit)
788         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
789
790     checkRunningState();
791
792     CPulseThreadLocker locker{__mpMainloop};
793
794     int isCorked = pa_stream_is_corked(__mpStream);
795
796 #ifdef _AUDIO_IO_DEBUG_TIMING_
797     AUDIO_IO_LOGD("isCorked[%d]", isCorked);
798 #endif
799     return static_cast<bool>(isCorked);
800 }
801
802 bool CPulseAudioClient::drain() {
803     if (!__mIsInit)
804         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
805
806     checkRunningState();
807
808     if (isCorked()) {
809         AUDIO_IO_LOGW("Corked...");
810         return true;
811     }
812
813     if (__mIsDraining) {
814         AUDIO_IO_LOGW("already draining...");
815         return true;
816     }
817
818     if (!__mIsStarted) {
819         AUDIO_IO_LOGW("stream not started yet...skip drain");
820         return true;
821     }
822
823     if (!isInThread()) {
824         AUDIO_IO_LOGD("drain");
825         CPulseThreadLocker locker{__mpMainloop};
826
827         pa_operation* o = pa_stream_drain(__mpStream, __successDrainCb, this);
828         __mIsDraining = true;
829         while (pa_operation_get_state(o) == PA_OPERATION_RUNNING)
830             pa_threaded_mainloop_wait(__mpMainloop);
831         pa_operation_unref(o);
832
833         AUDIO_IO_LOGD("drain done");
834     } else {
835         AUDIO_IO_LOGD("drain in thread");
836         pa_operation_unref(pa_stream_drain(__mpStream, __successDrainCbInThread, this));
837         __mIsDraining = true;
838     }
839
840     return true;
841 }
842
843 bool CPulseAudioClient::flush() {
844     if (!__mIsInit)
845         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
846
847     checkRunningState();
848
849     CPulseThreadLocker locker{__mpMainloop};
850
851     /* FIXME: wait for completion like drain? */
852     pa_operation_unref(pa_stream_flush(__mpStream, __successStreamCb, this));
853
854     return true;
855 }
856
857 size_t CPulseAudioClient::getWritableSize() {
858     if (!__mIsInit)
859         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized"); // LCOV_EXCL_LINE
860
861     checkRunningState();
862
863     if (__mDirection != EStreamDirection::STREAM_DIRECTION_PLAYBACK)
864         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Playback"); // LCOV_EXCL_LINE
865
866     CPulseThreadLocker locker{__mpMainloop};
867
868     return pa_stream_writable_size(__mpStream);
869 }
870
871 void CPulseAudioClient::checkRunningState() {
872     if (!__mpContext || !PA_CONTEXT_IS_GOOD(pa_context_get_state(__mpContext)))
873         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED,                       // LCOV_EXCL_LINE
874                                "The context[%p] is not created or not good state", __mpContext); // LCOV_EXCL_LINE
875
876     if (!__mpStream || !PA_STREAM_IS_GOOD(pa_stream_get_state(__mpStream)))
877         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED,                     // LCOV_EXCL_LINE
878                                "The stream[%p] is not created or not good state", __mpStream); // LCOV_EXCL_LINE
879
880     if (pa_context_get_state(__mpContext) != PA_CONTEXT_READY || pa_stream_get_state(__mpStream) != PA_STREAM_READY)
881         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED,                                   // LCOV_EXCL_LINE
882                                "The context[%p] or stream[%p] state is not ready", __mpContext, __mpStream); // LCOV_EXCL_LINE
883
884 #ifdef _AUDIO_IO_DEBUG_TIMING_
885     AUDIO_IO_LOGD("This client is running");
886 #endif
887 }
888
889 bool CPulseAudioClient::isInThread() const {
890     if (!__mIsInit)
891         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "__mIsInit is null");
892
893     if (!__mpMainloop)
894         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "__mpMainloop is null");
895
896     int ret = pa_threaded_mainloop_in_thread(__mpMainloop);
897
898 #ifdef _AUDIO_IO_DEBUG_TIMING_
899     AUDIO_IO_LOGD("isInThread[%d]", ret);
900 #endif
901     return static_cast<bool>(ret);
902 }
903
904 //LCOV_EXCL_START
905 size_t CPulseAudioClient::getReadableSize() {
906     if (!__mIsInit)
907         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
908
909     checkRunningState();
910
911     if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD)
912         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Capture");
913
914     CPulseThreadLocker locker{__mpMainloop};
915
916     return pa_stream_readable_size(__mpStream);
917 }
918
919 size_t CPulseAudioClient::getBufferSize() {
920     if (!__mIsInit)
921         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
922
923     checkRunningState();
924
925     size_t buffer_size = 0;
926     CPulseThreadLocker locker{__mpMainloop};
927
928     const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
929     if (!attr)
930         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
931                                "Failed pa_stream_get_buffer_attr() : err[%d]", pa_context_errno(__mpContext));
932
933     if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
934         buffer_size = attr->tlength;
935         AUDIO_IO_LOGD("PLAYBACK buffer size[%zu]", buffer_size);
936     } else {
937         buffer_size = attr->fragsize;
938         AUDIO_IO_LOGD("RECORD buffer size[%zu]", buffer_size);
939     }
940
941     return buffer_size;
942 }
943
944 pa_usec_t CPulseAudioClient::getLatency() {
945     if (!__mIsInit)
946         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
947
948     checkRunningState();
949
950     pa_usec_t latency = 0;
951     int negative = 0;
952
953     if (!isInThread()) {
954         if (pa_stream_get_latency(__mpStream, &latency, &negative) < 0) {
955             int _err = pa_context_errno(__mpContext);
956             if (_err != PA_ERR_NODATA)
957                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
958                                        "Failed pa_stream_get_latency() : err[%d]", _err);
959         }
960         return negative ? 0 : latency;
961     }
962
963     CPulseThreadLocker locker{__mpMainloop};
964
965     while (pa_stream_get_latency(__mpStream, &latency, &negative) < 0) {
966         int _err = pa_context_errno(__mpContext);
967         if (_err != PA_ERR_NODATA)
968             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION,
969                                    "Failed pa_stream_get_latency() : err[%d]", _err);
970         /* Wait until latency data is available again */
971         pa_threaded_mainloop_wait(__mpMainloop);
972     }
973
974     return negative ? 0 : latency;
975 }
976
977 pa_usec_t CPulseAudioClient::getFinalLatency() {
978     if (!__mIsInit)
979         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
980
981     checkRunningState();
982
983     pa_usec_t latency = 0;
984
985     CPulseThreadLocker locker{__mpMainloop};
986
987     uint32_t ver = pa_context_get_server_protocol_version(__mpContext);
988     if (ver < 13)
989         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_SUPPORTED, "This version(ver.%d) is not supported", ver);
990
991     const pa_buffer_attr* buffer_attr = pa_stream_get_buffer_attr(__mpStream);
992     const pa_sample_spec* sample_spec = pa_stream_get_sample_spec(__mpStream);
993     const pa_timing_info* timing_info = pa_stream_get_timing_info(__mpStream);
994
995     if (!buffer_attr || !sample_spec || !timing_info)
996         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_OUT_OF_MEMORY,
997                 "Failed to get buffer_attr[%p] or sample_spec[%p] or timing_info[%p] from a pa_stream",
998                 buffer_attr, sample_spec, timing_info);
999
1000     if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
1001         latency = (pa_bytes_to_usec(buffer_attr->tlength, sample_spec) + timing_info->configured_sink_usec);
1002         AUDIO_IO_LOGD("FINAL PLAYBACK LATENCY[%" PRIu64 "]", latency);
1003     } else {
1004         latency = (pa_bytes_to_usec(buffer_attr->fragsize, sample_spec) + timing_info->configured_source_usec);
1005         AUDIO_IO_LOGD("FINAL RECORD LATENCY[%" PRIu64 "]", latency);
1006     }
1007
1008     return latency;
1009 }
1010 //LCOV_EXCL_STOP
1011
1012 void CPulseAudioClient::applyRecordVolume(double volume) {
1013
1014     if (!__mIsInit)
1015         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "CPulseAudioClient is not initialized");
1016
1017     checkRunningState();
1018
1019     if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD)
1020         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client can't use this function"); //LCOV_EXCL_LINE
1021
1022     CPulseThreadLocker locker{__mpMainloop};
1023
1024     pa_cvolume cv = { 0, };
1025     pa_volume_t v = PA_VOLUME_NORM * volume;
1026
1027     pa_cvolume_set(&cv, __mSpec.getChannelMap().channels, v);
1028
1029     pa_operation_unref(pa_context_set_source_output_volume(__mpContext,
1030             pa_stream_get_index(__mpStream), &cv, __successVolumeCb, NULL));
1031 }