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