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