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