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