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