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