Fix memory leak : valgrind
[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_operation_unref(o);
718         pa_threaded_mainloop_unlock(__mpMainloop);
719     } else {
720         AUDIO_IO_LOGD("drain in thread");
721         pa_operation_unref(pa_stream_drain(__mpStream, __successDrainCbInThread, this));
722         __mIsDraining = true;
723     }
724
725     return true;
726 }
727
728 bool CPulseAudioClient::flush() throw(CAudioError) {
729     if (__mIsInit == false) {
730         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
731     }
732
733     checkRunningState();
734
735     if (isInThread() == false) {
736         AUDIO_IO_LOGD("flush");
737         pa_threaded_mainloop_lock(__mpMainloop);
738         pa_operation_unref(pa_stream_flush(__mpStream, __successStreamCb, this));
739         pa_threaded_mainloop_unlock(__mpMainloop);
740     } else {
741         AUDIO_IO_LOGD("flush in thread");
742         pa_operation_unref(pa_stream_flush(__mpStream, __successStreamCb, this));
743     }
744
745     return true;
746 }
747
748 size_t CPulseAudioClient::getWritableSize() throw(CAudioError) {
749     if (__mIsInit == false) {
750         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
751     }
752
753     checkRunningState();
754
755     if (__mDirection != EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
756         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Playback");
757     }
758
759     size_t ret = 0;
760
761     if (isInThread() == false) {
762         pa_threaded_mainloop_lock(__mpMainloop);
763         ret = pa_stream_writable_size(__mpStream);
764         pa_threaded_mainloop_unlock(__mpMainloop);
765     } else {
766         ret = pa_stream_writable_size(__mpStream);
767     }
768
769     return ret;
770 }
771
772 void CPulseAudioClient::checkRunningState() throw(CAudioError) {
773     if (__mpContext == NULL || PA_CONTEXT_IS_GOOD(pa_context_get_state(__mpContext)) == 0) {
774         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, "The context[%p] is not created or not good state", __mpContext);
775     }
776     if (__mpStream == NULL || PA_STREAM_IS_GOOD(pa_stream_get_state(__mpStream)) == 0) {
777         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, "The stream[%p] is not created or not good state", __mpStream);
778     }
779     if (pa_context_get_state(__mpContext) != PA_CONTEXT_READY || pa_stream_get_state(__mpStream) != PA_STREAM_READY) {
780         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_INITIALIZED, "The context[%p] or stream[%p] state is not ready", __mpContext, __mpStream);
781     }
782
783 #ifdef _AUDIO_IO_DEBUG_TIMING_
784     AUDIO_IO_LOGD("This client is running");
785 #endif
786 }
787
788 bool CPulseAudioClient::isInThread() throw(CAudioError) {
789     int ret = pa_threaded_mainloop_in_thread(__mpMainloop);
790
791 #ifdef _AUDIO_IO_DEBUG_TIMING_
792     AUDIO_IO_LOGD("isInThread[%d]", ret);
793 #endif
794     return static_cast<bool>(ret);
795 }
796
797 size_t CPulseAudioClient::getReadableSize() throw(CAudioError) {
798     if (__mIsInit == false) {
799         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
800     }
801
802     checkRunningState();
803
804     if (__mDirection != EStreamDirection::STREAM_DIRECTION_RECORD) {
805         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "This client is used for Capture");
806     }
807
808     size_t ret = 0;
809
810     if (isInThread() == false) {
811         pa_threaded_mainloop_lock(__mpMainloop);
812         ret = pa_stream_writable_size(__mpStream);
813         pa_threaded_mainloop_unlock(__mpMainloop);
814     } else {
815         ret = pa_stream_writable_size(__mpStream);
816     }
817
818     return ret;
819 }
820
821 size_t CPulseAudioClient::getBufferSize() throw(CAudioError) {
822     if (__mIsInit == false) {
823         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
824     }
825
826     checkRunningState();
827
828     size_t ret = 0;
829
830     try {
831         if (isInThread() == false) {
832             pa_threaded_mainloop_lock(__mpMainloop);
833         }
834
835         const pa_buffer_attr* attr = pa_stream_get_buffer_attr(__mpStream);
836         if (attr == NULL) {
837             int _err = pa_context_errno(__mpContext);
838             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_buffer_attr() : err[%d]", _err);
839         }
840
841         if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
842             ret = attr->tlength;
843             AUDIO_IO_LOGD("PLAYBACK buffer size[%d]", ret);
844         } else {
845             ret = attr->fragsize;
846             AUDIO_IO_LOGD("RECORD buffer size[%d]", ret);
847         }
848     } catch (CAudioError err) {
849         if (isInThread() == false) {
850             pa_threaded_mainloop_unlock(__mpMainloop);
851         }
852         throw err;
853     }
854
855     if (isInThread() == false) {
856         pa_threaded_mainloop_unlock(__mpMainloop);
857     }
858
859     return ret;
860 }
861
862 pa_usec_t CPulseAudioClient::getLatency() throw(CAudioError) {
863     if (__mIsInit == false) {
864         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
865     }
866
867     checkRunningState();
868
869     pa_usec_t ret = 0;
870     int negative  = 0;
871
872     if (isInThread() == false) {
873         if (pa_stream_get_latency(__mpStream, &ret, &negative) < 0) {
874             int _err = pa_context_errno(__mpContext);
875             if (_err != PA_ERR_NODATA) {
876                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_latency() : err[%d]", _err);
877             }
878         }
879         return negative ? 0 : ret;
880     }
881
882     pa_threaded_mainloop_lock(__mpMainloop);
883
884     try {
885         while (true) {
886             if (pa_stream_get_latency(__mpStream, &ret, &negative) >= 0) {
887                 break;
888             }
889
890             int _err = pa_context_errno(__mpContext);
891             if (_err != PA_ERR_NODATA) {
892                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed pa_stream_get_latency() : err[%d]", _err);
893             }
894
895             /* Wait until latency data is available again */
896             pa_threaded_mainloop_wait(__mpMainloop);
897         }
898     } catch (CAudioError e) {
899         pa_threaded_mainloop_unlock(__mpMainloop);
900         throw e;
901     }
902
903     pa_threaded_mainloop_unlock(__mpMainloop);
904
905     return negative ? 0 : ret;
906 }
907
908 pa_usec_t CPulseAudioClient::getFinalLatency() throw(CAudioError) {
909     if (__mIsInit == false) {
910         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize CPulseAudioClient");
911     }
912
913     checkRunningState();
914
915     pa_usec_t ret = 0;
916     uint32_t  ver = 0;
917
918     try {
919         if (isInThread() == false) {
920             pa_threaded_mainloop_lock(__mpMainloop);
921         }
922
923         ver = pa_context_get_server_protocol_version(__mpContext);
924         if (ver >= 13) {
925             const pa_buffer_attr* buffer_attr = pa_stream_get_buffer_attr(__mpStream);
926             const pa_sample_spec* sample_spec = pa_stream_get_sample_spec(__mpStream);
927             const pa_timing_info* timing_info = pa_stream_get_timing_info(__mpStream);
928
929             if (buffer_attr == NULL || sample_spec == NULL || timing_info == NULL) {
930                 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",
931                         buffer_attr, sample_spec, timing_info);
932             }
933
934             if (__mDirection == EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
935                 ret = (pa_bytes_to_usec(buffer_attr->tlength, sample_spec) + timing_info->configured_sink_usec);
936                 AUDIO_IO_LOGD("FINAL PLAYBACK LATENCY[%d]", ret);
937             } else {
938                 ret = (pa_bytes_to_usec(buffer_attr->fragsize, sample_spec) + timing_info->configured_source_usec);
939                 AUDIO_IO_LOGD("FINAL RECORD LATENCY[%d]", ret);
940             }
941         } else {
942             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_SUPPORTED, "This version(ver.%d) is not supported", ver);
943         }
944
945         if (isInThread() == false) {
946             pa_threaded_mainloop_unlock(__mpMainloop);
947         }
948     } catch (CAudioError e) {
949         if (isInThread() == false) {
950             pa_threaded_mainloop_unlock(__mpMainloop);
951         }
952         throw e;
953     }
954
955     return ret;
956 }
957
958 CPulseAudioClient::EStreamDirection CPulseAudioClient::getStreamDirection() {
959     return __mDirection;
960 }
961
962 CPulseStreamSpec CPulseAudioClient::getStreamSpec() {
963     return __mSpec;
964 }