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