Add pa_threaded_mainloop_lock() in CPulseAudioClient::write()
[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
687     if (isInThread() == false) {
688         pa_threaded_mainloop_lock(__mpMainloop);
689         if (pa_stream_is_corked(__mpStream)) {
690             AUDIO_IO_LOGW("stream is corked...do uncork here first!!!!");
691             pa_operation_unref(pa_stream_cork(__mpStream, 0, NULL, this));
692         }
693
694         ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
695         pa_threaded_mainloop_unlock(__mpMainloop);
696     } else {
697         if (pa_stream_is_corked(__mpStream)) {
698             AUDIO_IO_LOGW("stream is corked...do uncork here first!!!!");
699             pa_operation_unref(pa_stream_cork(__mpStream, 0, NULL, this));
700         }
701
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 size_t CPulseAudioClient::getReadableSize() {
890     if (__mIsInit == false) {
891         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
892     }
893
894     checkRunningState();
895
896     if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD) {
897         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Capture");
898     }
899
900     size_t ret = 0;
901
902     if (isInThread() == false) {
903         pa_threaded_mainloop_lock(__mpMainloop);
904         ret = pa_stream_writable_size(__mpStream);
905         pa_threaded_mainloop_unlock(__mpMainloop);
906     } else {
907         ret = pa_stream_writable_size(__mpStream);
908     }
909
910     return ret;
911 }
912
913 size_t CPulseAudioClient::getBufferSize() {
914     if (__mIsInit == false) {
915         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
916     }
917
918     checkRunningState();
919
920     size_t ret = 0;
921
922     try {
923         if (isInThread() == false) {
924             pa_threaded_mainloop_lock(__mpMainloop);
925         }
926
927         const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
928         if (attr == NULL) {
929             int _err = pa_context_errno(__mpContext);
930             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_buffer_attr() : err[%d]", _err);
931         }
932
933         if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
934             ret = attr->tlength;
935             AUDIO_IO_LOGD("PLAYBACK buffer size[%d]", ret);
936         } else {
937             ret = attr->fragsize;
938             AUDIO_IO_LOGD("RECORD buffer size[%d]", ret);
939         }
940     } catch (CAudioError& e) {
941         if (isInThread() == false) {
942             pa_threaded_mainloop_unlock(__mpMainloop);
943         }
944         throw;
945     }
946
947     if (isInThread() == false) {
948         pa_threaded_mainloop_unlock(__mpMainloop);
949     }
950
951     return ret;
952 }
953
954 pa_usec_t CPulseAudioClient::getLatency() {
955     if (__mIsInit == false) {
956         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
957     }
958
959     checkRunningState();
960
961     pa_usec_t ret = 0;
962     int negative  = 0;
963
964     if (isInThread() == false) {
965         if (pa_stream_get_latency(__mpStream, &ret, &negative) < 0) {
966             int _err = pa_context_errno(__mpContext);
967             if (_err != PA_ERR_NODATA) {
968                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_latency() : err[%d]", _err);
969             }
970         }
971         return negative ? 0 : ret;
972     }
973
974     pa_threaded_mainloop_lock(__mpMainloop);
975
976     try {
977         while (true) {
978             if (pa_stream_get_latency(__mpStream, &ret, &negative) >= 0) {
979                 break;
980             }
981
982             int _err = pa_context_errno(__mpContext);
983             if (_err != PA_ERR_NODATA) {
984                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_latency() : err[%d]", _err);
985             }
986
987             /* Wait until latency data is available again */
988             pa_threaded_mainloop_wait(__mpMainloop);
989         }
990     } catch (CAudioError& e) {
991         pa_threaded_mainloop_unlock(__mpMainloop);
992         throw;
993     }
994
995     pa_threaded_mainloop_unlock(__mpMainloop);
996
997     return negative ? 0 : ret;
998 }
999
1000 pa_usec_t CPulseAudioClient::getFinalLatency() {
1001     if (__mIsInit == false) {
1002         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
1003     }
1004
1005     checkRunningState();
1006
1007     pa_usec_t ret = 0;
1008     uint32_t  ver = 0;
1009
1010     try {
1011         if (isInThread() == false) {
1012             pa_threaded_mainloop_lock(__mpMainloop);
1013         }
1014
1015         ver = pa_context_get_server_protocol_version(__mpContext);
1016         if (ver >= 13) {
1017             const pa_buffer_attr* buffer_attr = pa_stream_get_buffer_attr(__mpStream);
1018             const pa_sample_spec* sample_spec = pa_stream_get_sample_spec(__mpStream);
1019             const pa_timing_info* timing_info = pa_stream_get_timing_info(__mpStream);
1020
1021             if (buffer_attr == NULL || sample_spec == NULL || timing_info == NULL) {
1022                 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",
1023                         buffer_attr, sample_spec, timing_info);
1024             }
1025
1026             if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
1027                 ret = (pa_bytes_to_usec(buffer_attr->tlength, sample_spec) + timing_info->configured_sink_usec);
1028                 AUDIO_IO_LOGD("FINAL PLAYBACK LATENCY[%" PRIu64 "]", ret);
1029             } else {
1030                 ret = (pa_bytes_to_usec(buffer_attr->fragsize, sample_spec) + timing_info->configured_source_usec);
1031                 AUDIO_IO_LOGD("FINAL RECORD LATENCY[%" PRIu64 "]", ret);
1032             }
1033         } else {
1034             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_SUPPORTED, "This version(ver.%d) is not supported", ver);
1035         }
1036
1037         if (isInThread() == false) {
1038             pa_threaded_mainloop_unlock(__mpMainloop);
1039         }
1040     } catch (CAudioError& e) {
1041         if (isInThread() == false) {
1042             pa_threaded_mainloop_unlock(__mpMainloop);
1043         }
1044         throw;
1045     }
1046
1047     return ret;
1048 }
1049
1050 CPulseAudioClient::EStreamDirection CPulseAudioClient::getStreamDirection() {
1051     return __mDirection;
1052 }
1053
1054 CPulseStreamSpec CPulseAudioClient::getStreamSpec() {
1055     return __mSpec;
1056 }