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