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