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