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