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