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