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