Revise CPulseAudioClient::finalize() to free all the resources which have been alread...
[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
450     if (__mpMainloop && isInThread() == false)
451         pa_threaded_mainloop_lock(__mpMainloop);
452
453     /* clear callbacks */
454     if (__mpStream) {
455         if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK)
456             pa_stream_set_write_callback(__mpStream, NULL, NULL);
457         else
458             pa_stream_set_read_callback(__mpStream, NULL, NULL);
459         pa_stream_set_latency_update_callback(__mpStream, NULL, NULL);
460         pa_stream_set_event_callback(__mpStream, NULL, NULL);
461     }
462
463     if (__mpMainloop && isInThread() == false)
464         pa_threaded_mainloop_unlock(__mpMainloop);
465
466     /* Wait for drain complete if draining before finalize */
467     if (__mIsDraining) {
468         unsigned int drain_wait_count = 0;
469         while (__mIsDraining && drain_wait_count++ < drain_wait_max_count) {
470             usleep(drain_wait_interval);
471         }
472         AUDIO_IO_LOGD("wait for drain complete!!!! [%d * %d usec]",
473                       drain_wait_count, drain_wait_interval);
474     }
475
476     if (__mpMainloop != NULL) {
477         pa_threaded_mainloop_stop(__mpMainloop);
478     }
479
480     if (__mpStream != NULL) {
481         pa_stream_disconnect(__mpStream);
482         pa_stream_unref(__mpStream);
483         __mpStream = NULL;
484     }
485
486     if (__mpContext != NULL) {
487         pa_context_disconnect(__mpContext);
488         pa_context_unref(__mpContext);
489         __mpContext = NULL;
490     }
491
492     if (__mpMainloop != NULL) {
493         pa_threaded_mainloop_free(__mpMainloop);
494         __mpMainloop = NULL;
495     }
496
497     if (__mpPropList != NULL) {
498         pa_proplist_free(__mpPropList);
499         __mpPropList = NULL;
500     }
501
502     __mIsInit = false;
503 }
504
505 int CPulseAudioClient::read(void* buffer, size_t length) {
506     if (__mIsInit == false) {
507         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
508     }
509
510     checkRunningState();
511
512     if (buffer == NULL) {
513         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "The parameter is invalid : buffer[%p]", buffer);
514     }
515
516     if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
517         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client couldn't use this function");
518     }
519
520     size_t lengthIter = length;
521     int ret = 0;
522
523     __mIsUsedSyncRead = true;
524
525     try {
526         pa_threaded_mainloop_lock(__mpMainloop);
527
528         while (lengthIter > 0) {
529             size_t l;
530
531             while (__mpSyncReadDataPtr == NULL) {
532                 ret = pa_stream_peek(__mpStream, &__mpSyncReadDataPtr, &__mSyncReadLength);
533                 if (ret != 0) {
534                     THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_peek() : ret[%d]", ret);
535                 }
536
537                 if (__mSyncReadLength <= 0) {
538 #ifdef _AUDIO_IO_DEBUG_TIMING_
539                     AUDIO_IO_LOGD("readLength(%d byte) is not valid. wait...", __mSyncReadLength);
540 #endif
541                     pa_threaded_mainloop_wait(__mpMainloop);
542                 } else if (__mpSyncReadDataPtr == NULL) {
543                     // Data peeked, but it doesn't have any data
544                     ret = pa_stream_drop(__mpStream);
545                     if (ret != 0) {
546                         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_drop() : ret[%d]", ret);
547                     }
548                 } else {
549                     __mSyncReadIndex = 0;
550                 }
551             }
552
553             if (__mSyncReadLength < lengthIter) {
554                 l = __mSyncReadLength;
555             } else {
556                 l = lengthIter;
557             }
558
559             // Copy partial pcm data on out parameter
560 #ifdef _AUDIO_IO_DEBUG_TIMING_
561             AUDIO_IO_LOGD("memcpy() that a peeked buffer[0x%x], index[%d], length[%d] on out buffer", (const uint8_t*)(__mpSyncReadDataPtr) + __mSyncReadIndex, __mSyncReadIndex, l);
562 #endif
563             memcpy(buffer, (const uint8_t*)__mpSyncReadDataPtr + __mSyncReadIndex, l);
564
565             // Move next position
566             buffer = (uint8_t*)buffer + l;
567             lengthIter -= l;
568
569             // Adjusts the rest length
570             __mSyncReadIndex  += l;
571             __mSyncReadLength -= l;
572
573             if (__mSyncReadLength == 0) {
574 #ifdef _AUDIO_IO_DEBUG_TIMING_
575                 AUDIO_IO_LOGD("__mSyncReadLength is zero, do drop()");
576 #endif
577                 ret = pa_stream_drop(__mpStream);
578                 if (ret != 0) {
579                     THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pa_stream_drop() : ret[%d]", ret);
580                 }
581
582                 // Reset the internal pointer
583                 __mpSyncReadDataPtr = NULL;
584                 __mSyncReadLength   = 0;
585                 __mSyncReadIndex    = 0;
586             }
587         }  // End of while (lengthIter > 0)
588
589         pa_threaded_mainloop_unlock(__mpMainloop);
590         __mIsUsedSyncRead = false;
591     } catch (CAudioError& e) {
592         pa_threaded_mainloop_unlock(__mpMainloop);
593         __mIsUsedSyncRead = false;
594         throw;
595     }
596
597     return length;
598 }
599
600 int CPulseAudioClient::peek(const void** buffer, size_t* length) {
601     if (__mIsInit == false) {
602         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
603     }
604
605     checkRunningState();
606
607     if (buffer == NULL || length == NULL) {
608         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "The parameter is invalid : buffer[%p], length[%p]", buffer, length);
609     }
610
611     if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
612         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client couldn't use this function");
613     }
614
615     int ret = 0;
616
617     if (isInThread() == false) {
618         pa_threaded_mainloop_lock(__mpMainloop);
619         ret = pa_stream_peek(__mpStream, buffer, length);
620         pa_threaded_mainloop_unlock(__mpMainloop);
621     } else {
622         ret = pa_stream_peek(__mpStream, buffer, length);
623     }
624
625 #ifdef _AUDIO_IO_DEBUG_TIMING_
626     AUDIO_IO_LOGD("buffer[%p], length[%d]", *buffer, *length);
627 #endif
628
629     if (ret < 0) {
630         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_peek() : err[%d]", ret);
631     }
632
633     return ret;
634 }
635
636 int CPulseAudioClient::drop() {
637     if (__mIsInit == false) {
638         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
639     }
640
641 #ifdef _AUDIO_IO_DEBUG_TIMING_
642     AUDIO_IO_LOGD("");
643 #endif
644
645     checkRunningState();
646
647     if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
648         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client couldn't use this function");
649     }
650
651     int ret = 0;
652
653     if (isInThread() == false) {
654         pa_threaded_mainloop_lock(__mpMainloop);
655         ret = pa_stream_drop(__mpStream);
656         pa_threaded_mainloop_unlock(__mpMainloop);
657     } else {
658         ret = pa_stream_drop(__mpStream);
659     }
660
661     if (ret < 0) {
662         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_drop() : err[%d]", ret);
663     }
664
665     return ret;
666 }
667
668 int CPulseAudioClient::write(const void* data, size_t length) {
669     if (data == NULL) {
670         THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_ARGUMENT, "The parameter is invalid");
671     }
672
673     if (__mDirection == EStreamDirection::STREAM_DIRECTION_RECORD) {
674         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "The Playback client couldn't use this function");
675     }
676
677     int ret = 0;
678
679 #ifdef _AUDIO_IO_DEBUG_TIMING_
680     AUDIO_IO_LOGD("data[%p], length[%d], First[%d]", data, length, __mIsFirstStream);
681 #endif
682     if (pa_stream_is_corked(__mpStream)) {
683         AUDIO_IO_LOGW("stream is corked...do uncork here first!!!!");
684         pa_operation_unref(pa_stream_cork(__mpStream, 0, NULL, this));
685     }
686
687     if (isInThread() == false) {
688         pa_threaded_mainloop_lock(__mpMainloop);
689         ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
690         pa_threaded_mainloop_unlock(__mpMainloop);
691     } else {
692         if (__mIsFirstStream) {
693             const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
694             uint32_t prebuf = attr->prebuf;
695             // Compensate amount of prebuf in first stream callback when audio-io use prebuf(-1)
696             // Because a stream will never start when an application wrote less than prebuf at first
697             if (length < prebuf) {
698                 char* dummy = new char[prebuf - length];
699                 memset(dummy, 0, prebuf - length);
700                 pa_stream_write(__mpStream, dummy, prebuf - length, NULL, 0LL, PA_SEEK_RELATIVE);
701                 delete [] dummy;
702             }
703             __mIsFirstStream = false;
704             AUDIO_IO_LOGW("FIRST STREAM CALLBACK : length[%d], prebuf[%d], dummy[%d]",
705                           length, prebuf, (length < prebuf) ? prebuf - length : 0);
706         }
707         ret = pa_stream_write(__mpStream, data, length, NULL, 0LL, PA_SEEK_RELATIVE);
708     }
709
710     if (ret < 0) {
711         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_write() : err[%d]", ret);
712     }
713
714     return ret;
715 }
716
717 void CPulseAudioClient::cork(bool cork) {
718     AUDIO_IO_LOGD("cork[%d]", cork);
719
720     if (__mIsInit == false) {
721         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
722     }
723
724     if (isInThread() == true) {
725         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This operation is not supported in callback");
726     }
727
728     checkRunningState();
729
730     // Set __mIsFirstStream flag when uncork(resume) stream, because prebuf will be enable again
731     if (cork == false)
732         __mIsFirstStream = true;
733
734     if (isInThread() == false) {
735         pa_threaded_mainloop_lock(__mpMainloop);
736         pa_operation_unref(pa_stream_cork(__mpStream, static_cast<int>(cork), __successStreamCb, this));
737         pa_threaded_mainloop_unlock(__mpMainloop);
738     } else {
739         pa_operation_unref(pa_stream_cork(__mpStream, static_cast<int>(cork), __successStreamCb, this));
740     }
741
742     return;
743 }
744
745 bool CPulseAudioClient::isCorked() {
746     if (__mIsInit == false) {
747         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
748     }
749
750     checkRunningState();
751
752     int isCork = 0;
753
754     if (isInThread() == false) {
755         pa_threaded_mainloop_lock(__mpMainloop);
756         isCork = pa_stream_is_corked(__mpStream);
757         pa_threaded_mainloop_unlock(__mpMainloop);
758     } else {
759         isCork = pa_stream_is_corked(__mpStream);
760     }
761
762 #ifdef _AUDIO_IO_DEBUG_TIMING_
763     AUDIO_IO_LOGD("isCork[%d]", isCork);
764 #endif
765     return static_cast<bool>(isCork);
766 }
767
768 bool CPulseAudioClient::drain() {
769     if (__mIsInit == false) {
770         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
771     }
772
773     checkRunningState();
774
775     if (isCorked()) {
776         AUDIO_IO_LOGW("Corked...");
777         return true;
778     }
779
780     if (__mIsDraining) {
781         AUDIO_IO_LOGW("already draining...");
782         return true;
783     }
784
785     if (isInThread() == false) {
786         AUDIO_IO_LOGD("drain");
787         pa_threaded_mainloop_lock(__mpMainloop);
788         pa_operation* o = pa_stream_drain(__mpStream, __successDrainCb, this);
789         __mIsDraining = true;
790         while (pa_operation_get_state(o) == PA_OPERATION_RUNNING) {
791             pa_threaded_mainloop_wait(__mpMainloop);
792         }
793         pa_operation_unref(o);
794         pa_threaded_mainloop_unlock(__mpMainloop);
795     } else {
796         AUDIO_IO_LOGD("drain in thread");
797         pa_operation_unref(pa_stream_drain(__mpStream, __successDrainCbInThread, this));
798         __mIsDraining = true;
799     }
800
801     return true;
802 }
803
804 bool CPulseAudioClient::flush() {
805     if (__mIsInit == false) {
806         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
807     }
808
809     checkRunningState();
810
811     if (isInThread() == false) {
812         AUDIO_IO_LOGD("flush");
813         pa_threaded_mainloop_lock(__mpMainloop);
814         pa_operation_unref(pa_stream_flush(__mpStream, __successStreamCb, this));
815         pa_threaded_mainloop_unlock(__mpMainloop);
816     } else {
817         AUDIO_IO_LOGD("flush in thread");
818         pa_operation_unref(pa_stream_flush(__mpStream, __successStreamCb, this));
819     }
820
821     return true;
822 }
823
824 size_t CPulseAudioClient::getWritableSize() {
825     if (__mIsInit == false) {
826         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
827     }
828
829     checkRunningState();
830
831     if (__mDirection != EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
832         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Playback");
833     }
834
835     size_t ret = 0;
836
837     if (isInThread() == false) {
838         pa_threaded_mainloop_lock(__mpMainloop);
839         ret = pa_stream_writable_size(__mpStream);
840         pa_threaded_mainloop_unlock(__mpMainloop);
841     } else {
842         ret = pa_stream_writable_size(__mpStream);
843     }
844
845     return ret;
846 }
847
848 void CPulseAudioClient::checkRunningState() {
849     if (__mpContext == NULL || PA_CONTEXT_IS_GOOD(pa_context_get_state(__mpContext)) == 0) {
850         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, "The context[%p] is not created or not good state", __mpContext);
851     }
852     if (__mpStream == NULL || PA_STREAM_IS_GOOD(pa_stream_get_state(__mpStream)) == 0) {
853         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, "The stream[%p] is not created or not good state", __mpStream);
854     }
855     if (pa_context_get_state(__mpContext) != PA_CONTEXT_READY || pa_stream_get_state(__mpStream) != PA_STREAM_READY) {
856         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, "The context[%p] or stream[%p] state is not ready", __mpContext, __mpStream);
857     }
858
859 #ifdef _AUDIO_IO_DEBUG_TIMING_
860     AUDIO_IO_LOGD("This client is running");
861 #endif
862 }
863
864 bool CPulseAudioClient::isInThread() {
865     int ret = pa_threaded_mainloop_in_thread(__mpMainloop);
866
867 #ifdef _AUDIO_IO_DEBUG_TIMING_
868     AUDIO_IO_LOGD("isInThread[%d]", ret);
869 #endif
870     return static_cast<bool>(ret);
871 }
872
873 size_t CPulseAudioClient::getReadableSize() {
874     if (__mIsInit == false) {
875         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
876     }
877
878     checkRunningState();
879
880     if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD) {
881         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Capture");
882     }
883
884     size_t ret = 0;
885
886     if (isInThread() == false) {
887         pa_threaded_mainloop_lock(__mpMainloop);
888         ret = pa_stream_writable_size(__mpStream);
889         pa_threaded_mainloop_unlock(__mpMainloop);
890     } else {
891         ret = pa_stream_writable_size(__mpStream);
892     }
893
894     return ret;
895 }
896
897 size_t CPulseAudioClient::getBufferSize() {
898     if (__mIsInit == false) {
899         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
900     }
901
902     checkRunningState();
903
904     size_t ret = 0;
905
906     try {
907         if (isInThread() == false) {
908             pa_threaded_mainloop_lock(__mpMainloop);
909         }
910
911         const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
912         if (attr == NULL) {
913             int _err = pa_context_errno(__mpContext);
914             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_buffer_attr() : err[%d]", _err);
915         }
916
917         if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
918             ret = attr->tlength;
919             AUDIO_IO_LOGD("PLAYBACK buffer size[%d]", ret);
920         } else {
921             ret = attr->fragsize;
922             AUDIO_IO_LOGD("RECORD buffer size[%d]", ret);
923         }
924     } catch (CAudioError& e) {
925         if (isInThread() == false) {
926             pa_threaded_mainloop_unlock(__mpMainloop);
927         }
928         throw;
929     }
930
931     if (isInThread() == false) {
932         pa_threaded_mainloop_unlock(__mpMainloop);
933     }
934
935     return ret;
936 }
937
938 pa_usec_t CPulseAudioClient::getLatency() {
939     if (__mIsInit == false) {
940         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
941     }
942
943     checkRunningState();
944
945     pa_usec_t ret = 0;
946     int negative  = 0;
947
948     if (isInThread() == false) {
949         if (pa_stream_get_latency(__mpStream, &ret, &negative) < 0) {
950             int _err = pa_context_errno(__mpContext);
951             if (_err != PA_ERR_NODATA) {
952                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_latency() : err[%d]", _err);
953             }
954         }
955         return negative ? 0 : ret;
956     }
957
958     pa_threaded_mainloop_lock(__mpMainloop);
959
960     try {
961         while (true) {
962             if (pa_stream_get_latency(__mpStream, &ret, &negative) >= 0) {
963                 break;
964             }
965
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             /* Wait until latency data is available again */
972             pa_threaded_mainloop_wait(__mpMainloop);
973         }
974     } catch (CAudioError& e) {
975         pa_threaded_mainloop_unlock(__mpMainloop);
976         throw;
977     }
978
979     pa_threaded_mainloop_unlock(__mpMainloop);
980
981     return negative ? 0 : ret;
982 }
983
984 pa_usec_t CPulseAudioClient::getFinalLatency() {
985     if (__mIsInit == false) {
986         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
987     }
988
989     checkRunningState();
990
991     pa_usec_t ret = 0;
992     uint32_t  ver = 0;
993
994     try {
995         if (isInThread() == false) {
996             pa_threaded_mainloop_lock(__mpMainloop);
997         }
998
999         ver = pa_context_get_server_protocol_version(__mpContext);
1000         if (ver >= 13) {
1001             const pa_buffer_attr* buffer_attr = pa_stream_get_buffer_attr(__mpStream);
1002             const pa_sample_spec* sample_spec = pa_stream_get_sample_spec(__mpStream);
1003             const pa_timing_info* timing_info = pa_stream_get_timing_info(__mpStream);
1004
1005             if (buffer_attr == NULL || sample_spec == NULL || timing_info == NULL) {
1006                 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",
1007                         buffer_attr, sample_spec, timing_info);
1008             }
1009
1010             if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
1011                 ret = (pa_bytes_to_usec(buffer_attr->tlength, sample_spec) + timing_info->configured_sink_usec);
1012                 AUDIO_IO_LOGD("FINAL PLAYBACK LATENCY[%" PRIu64 "]", ret);
1013             } else {
1014                 ret = (pa_bytes_to_usec(buffer_attr->fragsize, sample_spec) + timing_info->configured_source_usec);
1015                 AUDIO_IO_LOGD("FINAL RECORD LATENCY[%" PRIu64 "]", ret);
1016             }
1017         } else {
1018             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_SUPPORTED, "This version(ver.%d) is not supported", ver);
1019         }
1020
1021         if (isInThread() == false) {
1022             pa_threaded_mainloop_unlock(__mpMainloop);
1023         }
1024     } catch (CAudioError& e) {
1025         if (isInThread() == false) {
1026             pa_threaded_mainloop_unlock(__mpMainloop);
1027         }
1028         throw;
1029     }
1030
1031     return ret;
1032 }
1033
1034 CPulseAudioClient::EStreamDirection CPulseAudioClient::getStreamDirection() {
1035     return __mDirection;
1036 }
1037
1038 CPulseStreamSpec CPulseAudioClient::getStreamSpec() {
1039     return __mSpec;
1040 }