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