Merge branch 'tizen_3.0' into tizen
[platform/core/api/audio-io.git] / src / cpp / CAudioIO.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 <pthread.h>
20 #include <assert.h>
21 #include "CAudioIODef.h"
22
23 using namespace std;
24 using namespace tizen_media_audio;
25
26
27 /**
28  * class CAudioIO
29  */
30 CAudioIO::CAudioIO() :
31     mpAudioSessionHandler(NULL),
32     mpPulseAudioClient(NULL),
33     __mMutex(PTHREAD_MUTEX_INITIALIZER),
34     __mCond(PTHREAD_COND_INITIALIZER),
35     __mIsInit(false),
36     __mForceIgnore(false) {
37     mDirection = CAudioInfo::EAudioDirection::AUDIO_DIRECTION_MAX;
38     mState = CAudioInfo::EAudioIOState::AUDIO_IO_STATE_NONE;
39     mStatePrev = CAudioInfo::EAudioIOState::AUDIO_IO_STATE_NONE;
40     mByPolicy = false;
41 }
42
43 CAudioIO::CAudioIO(CAudioInfo& audioInfo) :
44     mpAudioSessionHandler(NULL),
45     mpPulseAudioClient(NULL),
46     __mMutex(PTHREAD_MUTEX_INITIALIZER),
47     __mCond(PTHREAD_COND_INITIALIZER),
48     __mIsInit(false),
49     __mForceIgnore(false) {
50     mAudioInfo = audioInfo;
51     mDirection = CAudioInfo::EAudioDirection::AUDIO_DIRECTION_MAX;
52     mState = CAudioInfo::EAudioIOState::AUDIO_IO_STATE_NONE;
53     mStatePrev = CAudioInfo::EAudioIOState::AUDIO_IO_STATE_NONE;
54     mByPolicy = false;
55 }
56
57 CAudioIO::~CAudioIO() {
58 }
59
60 void CAudioIO::setInit(bool flag) {
61     __mIsInit = flag;
62 }
63
64 bool CAudioIO::isInit() {
65     return __mIsInit;
66 }
67
68 bool CAudioIO::IsReady() {
69     return ((mState == CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING || mState == CAudioInfo::EAudioIOState::AUDIO_IO_STATE_PAUSED)? true : false);
70 }
71
72 void CAudioIO::internalLock() throw(CAudioError) {
73     if (__mIsInit == false) {
74         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
75     }
76
77     if (pthread_mutex_lock(&__mMutex) != 0) {
78         THROW_ERROR_MSG(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pthread_mutex_lock()");
79     }
80 #ifdef _AUDIO_IO_DEBUG_TIMING_
81     AUDIO_IO_LOGD(COLOR_RED "LOCK" COLOR_END);
82 #endif
83 }
84
85 void CAudioIO::internalUnlock() throw(CAudioError) {
86     if (__mIsInit == false) {
87         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
88     }
89
90     if (pthread_mutex_unlock(&__mMutex) != 0) {
91         THROW_ERROR_MSG(CAudioError::EError::ERROR_INTERNAL_OPERATION, "Failed pthread_mutex_lock()");
92     }
93 #ifdef _AUDIO_IO_DEBUG_TIMING_
94     AUDIO_IO_LOGD(COLOR_GREEN "UNLOCK" COLOR_END);
95 #endif
96 }
97
98 void CAudioIO::internalWait() throw(CAudioError) {
99     if (__mIsInit == false) {
100         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
101     }
102
103 #ifdef _AUDIO_IO_DEBUG_TIMING_
104     AUDIO_IO_LOGD(COLOR_RED "WAIT" COLOR_END);
105 #endif
106
107     pthread_cond_wait(&__mCond, &__mMutex);
108 }
109
110 void CAudioIO::internalSignal() throw(CAudioError) {
111     if (__mIsInit == false) {
112         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
113     }
114
115 #ifdef _AUDIO_IO_DEBUG_TIMING_
116     AUDIO_IO_LOGD(COLOR_GREEN "SIGNAL" COLOR_END);
117 #endif
118
119     pthread_cond_signal(&__mCond);
120 }
121
122 bool CAudioIO::isForceIgnore() {
123     return __mForceIgnore;
124 }
125
126 void CAudioIO::initialize() throw(CAudioError) {
127     if (__mIsInit == true) {
128         return;
129     }
130
131     AUDIO_IO_LOGD("initialize");
132
133     int ret = pthread_mutex_init(&__mMutex, NULL);
134     if (ret != 0) {
135         THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pthread_mutex_init()");
136     }
137
138     ret = pthread_cond_init(&__mCond, NULL);
139     if (ret != 0) {
140         THROW_ERROR_MSG(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pthread_cond_init()");
141     }
142
143     __mIsInit = true;
144 }
145
146 void CAudioIO::finalize() {
147     if (__mIsInit == false) {
148         return;
149     }
150
151     AUDIO_IO_LOGD("finalize");
152
153     int ret = pthread_mutex_destroy(&__mMutex);
154     if (ret != 0) {
155         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pthread_mutex_destroy() ret:%d", ret);
156     }
157
158     ret = pthread_cond_destroy(&__mCond);
159     if (ret != 0) {
160         THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_OUT_OF_MEMORY, "Failed pthread_cond_destroy() ret:%d", ret);
161     }
162
163     __mIsInit = false;
164 }
165
166 void CAudioIO::onStream(CPulseAudioClient* pClient, size_t length) {
167     assert(__mIsInit == true);
168     assert(pClient != NULL);
169     assert(length > 0);
170
171 #ifdef _AUDIO_IO_DEBUG_TIMING_
172     AUDIO_IO_LOGD("mStreamCallback.onStream(%p), pClient(%p), length(%zu)", mStreamCallback.onStream, pClient, length);
173 #endif
174
175     if (mStreamCallback.onStream != NULL) {
176         mStreamCallback.onStream(length, mStreamCallback.mUserData);
177     }
178 }
179
180 void CAudioIO::onStateChanged(CAudioInfo::EAudioIOState state, bool byPolicy) {
181     assert(__mIsInit == true);
182     assert(state >= CAudioInfo::EAudioIOState::AUDIO_IO_STATE_NONE && state < CAudioInfo::EAudioIOState::AUDIO_IO_STATE_MAX);
183
184     mStatePrev = mState;
185     mState     = state;
186     mByPolicy  = byPolicy;
187
188     if (mState == mStatePrev)
189         return;
190
191     const char* state_string[] = { "NONE", "IDLE", "RUNNING", "PAUSED" };
192
193     AUDIO_IO_LOGD("previous(%s,%d) ===> current(%s,%d), by_policy(%d)",
194                   state_string[(int)mStatePrev], mStatePrev, state_string[(int)mState], mState, mByPolicy);
195
196     if (mStateChangedCallback.onStateChanged != NULL) {
197         mStateChangedCallback.onStateChanged(mState, mStatePrev, mByPolicy, mStateChangedCallback.mUserData);
198     }
199 }
200
201 void CAudioIO::onStateChanged(CAudioInfo::EAudioIOState state) {
202     onStateChanged(state, false);
203 }
204
205 CAudioInfo::EAudioIOState CAudioIO::getState() {
206     return mState;
207 }
208
209 void CAudioIO::onInterrupt(CAudioSessionHandler* pHandler, int id, mm_sound_focus_type_e focus_type, mm_sound_focus_state_e state, const char *reason_for_change, const char *additional_info) {
210     assert(pHandler);
211
212     int session_option = pHandler->getOptions();
213
214     if (id == -1) {
215         ///////////////////////////////////////
216         // Triggered by 'focus watch callback'
217         ///////////////////////////////////////
218
219         if (session_option & (MM_SESSION_OPTION_PAUSE_OTHERS | MM_SESSION_OPTION_UNINTERRUPTIBLE)) {
220             AUDIO_IO_LOGD("Session option is pausing others or uninterruptible, skip...");
221             return;
222         }
223
224         if (state == FOCUS_IS_RELEASED) {
225             // Focus handle(id) of the other application was released, do resume if possible
226             internalLock();
227             if (mpPulseAudioClient) {
228                 mpPulseAudioClient->cork(false);
229                 onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING);
230             }
231             internalUnlock();
232
233             // Focus watch callback doesn't have focus handle, but it need to convert & report to application for convenience
234             state = FOCUS_IS_ACQUIRED;
235         } else if (state == FOCUS_IS_ACQUIRED) {
236             // Focus handle(id) of the other application was acquired, do pause if possible
237             internalLock();
238             if (mpPulseAudioClient) {
239                 if (mpPulseAudioClient->getStreamDirection() == CPulseAudioClient::EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
240                     if (mpPulseAudioClient->drain() == false) {
241                         AUDIO_IO_LOGE("Failed CPulseAudioClient::drain()");
242                     }
243                 }
244                 mpPulseAudioClient->cork(true);
245                 onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_PAUSED);
246             }
247             internalUnlock();
248
249             // Focus watch callback doesn't have focus handle, but it need to convert & report to application for convenience
250             state = FOCUS_IS_RELEASED;
251         }
252     } else {
253         ///////////////////////////////////////
254         // Triggered by 'focus callback'
255         ///////////////////////////////////////
256
257         if (pHandler->getId() != id) {
258             AUDIO_IO_LOGW("Id is different, why? [mId : %d]", pHandler->getId());
259         }
260
261         if (session_option & MM_SESSION_OPTION_UNINTERRUPTIBLE) {
262             AUDIO_IO_LOGD("Session option is uninterruptible, skip...");
263             return;
264         }
265
266         if (state == FOCUS_IS_RELEASED) {
267             // Focus handle(id) was released, do pause here
268             internalLock();
269             if (mpPulseAudioClient) {
270                 if (mpPulseAudioClient->getStreamDirection() == CPulseAudioClient::EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
271                     if (mpPulseAudioClient->drain() == false) {
272                         AUDIO_IO_LOGE("Failed CPulseAudioClient::drain()");
273                     }
274                 }
275                 mpPulseAudioClient->cork(true);
276                 onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_PAUSED);
277             }
278             internalUnlock();
279         } else if (state == FOCUS_IS_ACQUIRED) {
280             // Focus handle(id) was acquired again,
281             // check reason_for_change ("call-voice","call-video","voip","alarm","notification", ...)
282             // do resume here and call interrupt completed callback to application.
283             internalLock();
284             if (mpPulseAudioClient) {
285                 mpPulseAudioClient->cork(false);
286                 onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING);
287             }
288             internalUnlock();
289         }
290     }
291
292     if (mInterruptCallback.onInterrupt != NULL) {
293         IAudioSessionEventListener::EInterruptCode e = IAudioSessionEventListener::EInterruptCode::INTERRUPT_COMPLETED;
294         e = IAudioSessionEventListener::convertInterruptedCode(state, reason_for_change);
295         mInterruptCallback.onInterrupt(e, mInterruptCallback.mUserData);
296     }
297 }
298
299 void CAudioIO::onSignal(CAudioSessionHandler* pHandler, mm_sound_signal_name_t signal, int value) {
300     assert(pHandler);
301
302     if (signal == MM_SOUND_SIGNAL_RELEASE_INTERNAL_FOCUS) {
303         if (value == 1 && pHandler->getSubscribeId() > 0) {
304             // Unregister focus watch callback & disable session handler
305             pHandler->disableSessionHandler();
306             AUDIO_IO_LOGD("Session handler disabled by signal");
307         } else if (value == 0) {
308             // Currently do nothing...
309         }
310     }
311 }
312
313 void CAudioIO::prepare() throw(CAudioError) {
314     if (__mIsInit == false) {
315         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
316     }
317
318     try {
319         AUDIO_IO_LOGD("------> prepare done");
320         /* Do nothing */
321     } catch (CAudioError e) {
322         throw e;
323     }
324 }
325
326 void CAudioIO::unprepare() throw(CAudioError) {
327     if (__mIsInit == false) {
328         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
329     }
330
331     try {
332         AUDIO_IO_LOGD("unprepare ----->");
333         /* Do nothing */
334     } catch (CAudioError e) {
335         throw e;
336     }
337 }
338
339 void CAudioIO::pause() throw(CAudioError) {
340     if (__mIsInit == false || IsReady() == false) {
341         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize or prepare CAudioIO");
342     }
343
344     try {
345         internalLock();
346         AUDIO_IO_LOGD("pause");
347         mpPulseAudioClient->cork(true);
348         internalUnlock();
349     } catch (CAudioError e) {
350         internalUnlock();
351         throw e;
352     }
353 }
354
355 void CAudioIO::resume() throw(CAudioError) {
356     if (__mIsInit == false || IsReady() == false) {
357         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize or prepare CAudioIO");
358     }
359
360     try {
361         internalLock();
362         AUDIO_IO_LOGD("resume");
363         mpPulseAudioClient->cork(false);
364         internalUnlock();
365     } catch (CAudioError e) {
366         internalUnlock();
367         throw e;
368     }
369 }
370
371 void CAudioIO::drain() throw(CAudioError) {
372     if (__mIsInit == false || IsReady() == false) {
373         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize or prepare CAudioIO");
374     }
375
376     try {
377         if (mpPulseAudioClient->isInThread()) {
378             mpPulseAudioClient->drain();
379         } else {
380             internalLock();
381             mpPulseAudioClient->drain();
382             internalUnlock();
383         }
384     } catch (CAudioError e) {
385         if (!mpPulseAudioClient->isInThread()) {
386             internalUnlock();
387         }
388         throw e;
389     }
390 }
391
392 void CAudioIO::flush() throw(CAudioError) {
393     if (__mIsInit == false || IsReady() == false) {
394         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize or prepare CAudioIO");
395     }
396
397     try {
398         if (mpPulseAudioClient->isInThread()) {
399             mpPulseAudioClient->flush();
400         } else {
401             internalLock();
402             mpPulseAudioClient->flush();
403             internalUnlock();
404         }
405     } catch (CAudioError e) {
406         if (!mpPulseAudioClient->isInThread()) {
407             internalUnlock();
408         }
409         throw e;
410     }
411 }
412
413 CAudioInfo& CAudioIO::getAudioInfo() throw(CAudioError) {
414     if (__mIsInit == false) {
415         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
416     }
417
418     return mAudioInfo;
419 }
420
421 void CAudioIO::setStreamCallback(SStreamCallback callback) throw(CAudioError) {
422     if (__mIsInit == false) {
423         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
424     }
425
426     mStreamCallback = callback;
427 }
428
429 CAudioIO::SStreamCallback CAudioIO::getStreamCallback() throw(CAudioError) {
430     if (__mIsInit == false) {
431         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
432     }
433
434     return mStreamCallback;
435 }
436
437 void CAudioIO::setStateChangedCallback(SStateChangedCallback callback) throw(CAudioError) {
438     if (__mIsInit == false) {
439         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
440     }
441
442     mStateChangedCallback = callback;
443 }
444
445 CAudioIO::SStateChangedCallback CAudioIO::getStateChangedCallback() throw(CAudioError) {
446     if (__mIsInit == false) {
447         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
448     }
449
450     return mStateChangedCallback;
451 }
452
453 void CAudioIO::setInterruptCallback(SInterruptCallback callback) throw(CAudioError) {
454     if (__mIsInit == false) {
455         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
456     }
457
458     mInterruptCallback = callback;
459 }
460
461 CAudioIO::SInterruptCallback CAudioIO::getInterruptCallback() throw(CAudioError) {
462     if (__mIsInit == false) {
463         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
464     }
465
466     return mInterruptCallback;
467 }
468
469 void CAudioIO::ignoreSession() throw(CAudioError) {
470     if (__mIsInit == false)
471         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
472
473     try {
474         internalLock();
475
476         if (mpPulseAudioClient != NULL && mState == CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING)
477             THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_OPERATION, "An Operation is not permitted while started");
478
479         bool isSkip = mpAudioSessionHandler->isSkipSession();
480         if (isSkip == false && mpAudioSessionHandler->getId() >= 0)
481             mpAudioSessionHandler->unregisterSound();
482
483         mpAudioSessionHandler->finalize();
484         __mForceIgnore = true;
485
486         internalUnlock();
487     } catch (CAudioError e) {
488         internalUnlock();
489         throw e;
490     }
491 }
492
493 void CAudioIO::setStreamInfo(sound_stream_info_h stream_info) throw(CAudioError) {
494     if (stream_info == NULL)
495         THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_ARGUMENT, "stream_info is NULL");
496
497     if (__mIsInit == false)
498         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
499
500     try {
501         if (mState != CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE)
502             THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_STATE, "it is not permitted while started");
503
504         int errorCode = SOUND_MANAGER_ERROR_NONE;
505         CAudioInfo::EAudioType audioType = CAudioInfo::EAudioType::AUDIO_IN_TYPE_MEDIA;
506         char *type = NULL;
507         int index = -1;
508         bool avail = false;
509
510         if ((errorCode = sound_manager_is_available_stream_information(stream_info, NATIVE_API_AUDIO_IO, &avail)) != SOUND_MANAGER_ERROR_NONE)
511             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "Parameter stream_info is invalid [ret:%d]", errorCode);
512
513         if (!avail)
514             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_SUPPORTED_TYPE, "Input stream is not supported");
515
516         if ((errorCode = sound_manager_get_type_from_stream_information(stream_info, &type)) != SOUND_MANAGER_ERROR_NONE)
517             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "Parameter stream_info->stream_type is invalid [ret:%d]", errorCode);
518
519         if (mDirection == CAudioInfo::EAudioDirection::AUDIO_DIRECTION_IN)
520             getAudioInfo().convertInputStreamType2AudioType(type, &audioType);
521         else
522             getAudioInfo().convertOutputStreamType2AudioType(type, &audioType);
523         getAudioInfo().setAudioType(audioType);
524
525         if ((errorCode = sound_manager_get_index_from_stream_information(stream_info, &index)) != SOUND_MANAGER_ERROR_NONE)
526             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "Parameter stream_info->index is invalid [ret:%d]", errorCode);
527
528         getAudioInfo().setAudioIndex(index);
529
530         AUDIO_IO_LOGD("stream info(%p) is set", stream_info);
531     } catch (CAudioError e) {
532         throw e;
533     }
534 }
535
536 void CAudioIO::setInternalStreamInfo() throw(CAudioError) {
537     if (__mIsInit == false)
538         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
539
540     try {
541         if (mState != CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE)
542             THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_STATE, "it is not permitted while started");
543
544         if (mpAudioSessionHandler &&
545             mpAudioSessionHandler->getMultimediaSession() == MM_SESSION_TYPE_VOIP) {
546             sound_stream_info_h stream_info = NULL;
547             mpAudioSessionHandler->getInternalVoipStreamInfo(&stream_info);
548             AUDIO_IO_LOGD("get internal VOIP stream info(%p)", stream_info);
549             setStreamInfo(stream_info);
550         }
551     } catch (CAudioError e) {
552         throw e;
553     }
554 }