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