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                 /* FIXME: Skip this codes due to the blocking of drain() function
240                 if (mpPulseAudioClient->getStreamDirection() == CPulseAudioClient::EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
241                     if (mpPulseAudioClient->drain() == false) {
242                         AUDIO_IO_LOGE("Failed CPulseAudioClient::drain()");
243                     }
244                 }
245                 */
246                 mpPulseAudioClient->cork(true);
247                 onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_PAUSED);
248             }
249             internalUnlock();
250
251             // Focus watch callback doesn't have focus handle, but it need to convert & report to application for convenience
252             state = FOCUS_IS_RELEASED;
253         }
254     } else {
255         ///////////////////////////////////////
256         // Triggered by 'focus callback'
257         ///////////////////////////////////////
258
259         if (pHandler->getId() != id) {
260             AUDIO_IO_LOGW("Id is different, why? [mId : %d]", pHandler->getId());
261         }
262
263         if (session_option & MM_SESSION_OPTION_UNINTERRUPTIBLE) {
264             AUDIO_IO_LOGD("Session option is uninterruptible, skip...");
265             return;
266         }
267
268         if (state == FOCUS_IS_RELEASED) {
269             // Focus handle(id) was released, do pause here
270             internalLock();
271             if (mpPulseAudioClient) {
272                 /* FIXME: Skip this codes due to the blocking of drain() function
273                 if (mpPulseAudioClient->getStreamDirection() == CPulseAudioClient::EStreamDirection::STREAM_DIRECTION_PLAYBACK) {
274                     if (mpPulseAudioClient->drain() == false) {
275                         AUDIO_IO_LOGE("Failed CPulseAudioClient::drain()");
276                     }
277                 }
278                 */
279                 mpPulseAudioClient->cork(true);
280                 onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_PAUSED);
281             }
282             internalUnlock();
283         } else if (state == FOCUS_IS_ACQUIRED) {
284             // Focus handle(id) was acquired again,
285             // check reason_for_change ("call-voice","call-video","voip","alarm","notification", ...)
286             // do resume here and call interrupt completed callback to application.
287             internalLock();
288             if (mpPulseAudioClient) {
289                 mpPulseAudioClient->cork(false);
290                 onStateChanged(CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING);
291             }
292             internalUnlock();
293         }
294     }
295
296     if (mInterruptCallback.onInterrupt != NULL) {
297         IAudioSessionEventListener::EInterruptCode e = IAudioSessionEventListener::EInterruptCode::INTERRUPT_COMPLETED;
298         e = IAudioSessionEventListener::convertInterruptedCode(state, reason_for_change);
299         mInterruptCallback.onInterrupt(e, mInterruptCallback.mUserData);
300     }
301 }
302
303 void CAudioIO::onSignal(CAudioSessionHandler* pHandler, mm_sound_signal_name_t signal, int value) {
304     assert(pHandler);
305
306     if (signal == MM_SOUND_SIGNAL_RELEASE_INTERNAL_FOCUS) {
307         if (value == 1 && pHandler->getSubscribeId() > 0) {
308             // Unregister focus watch callback & disable session handler
309             pHandler->disableSessionHandler();
310             AUDIO_IO_LOGD("Session handler disabled by signal");
311         } else if (value == 0) {
312             // Currently do nothing...
313         }
314     }
315 }
316
317 void CAudioIO::prepare() throw(CAudioError) {
318     if (__mIsInit == false) {
319         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
320     }
321
322     try {
323         AUDIO_IO_LOGD("------> prepare done");
324         /* Do nothing */
325     } catch (CAudioError e) {
326         throw e;
327     }
328 }
329
330 void CAudioIO::unprepare() throw(CAudioError) {
331     if (__mIsInit == false) {
332         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
333     }
334
335     try {
336         AUDIO_IO_LOGD("unprepare ----->");
337         /* Do nothing */
338     } catch (CAudioError e) {
339         throw e;
340     }
341 }
342
343 void CAudioIO::pause() throw(CAudioError) {
344     if (__mIsInit == false || IsReady() == false) {
345         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize or prepare CAudioIO");
346     }
347
348     try {
349         internalLock();
350         AUDIO_IO_LOGD("pause");
351         mpPulseAudioClient->cork(true);
352         internalUnlock();
353     } catch (CAudioError e) {
354         internalUnlock();
355         throw e;
356     }
357 }
358
359 void CAudioIO::resume() throw(CAudioError) {
360     if (__mIsInit == false || IsReady() == false) {
361         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize or prepare CAudioIO");
362     }
363
364     try {
365         internalLock();
366         AUDIO_IO_LOGD("resume");
367         mpPulseAudioClient->cork(false);
368         internalUnlock();
369     } catch (CAudioError e) {
370         internalUnlock();
371         throw e;
372     }
373 }
374
375 void CAudioIO::drain() throw(CAudioError) {
376     if (__mIsInit == false || IsReady() == false) {
377         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize or prepare CAudioIO");
378     }
379
380     try {
381         if (mpPulseAudioClient->isInThread()) {
382             mpPulseAudioClient->drain();
383         } else {
384             internalLock();
385             mpPulseAudioClient->drain();
386             internalUnlock();
387         }
388     } catch (CAudioError e) {
389         if (!mpPulseAudioClient->isInThread()) {
390             internalUnlock();
391         }
392         throw e;
393     }
394 }
395
396 void CAudioIO::flush() throw(CAudioError) {
397     if (__mIsInit == false || IsReady() == false) {
398         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Did not initialize or prepare CAudioIO");
399     }
400
401     try {
402         if (mpPulseAudioClient->isInThread()) {
403             mpPulseAudioClient->flush();
404         } else {
405             internalLock();
406             mpPulseAudioClient->flush();
407             internalUnlock();
408         }
409     } catch (CAudioError e) {
410         if (!mpPulseAudioClient->isInThread()) {
411             internalUnlock();
412         }
413         throw e;
414     }
415 }
416
417 CAudioInfo& CAudioIO::getAudioInfo() throw(CAudioError) {
418     if (__mIsInit == false) {
419         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
420     }
421
422     return mAudioInfo;
423 }
424
425 void CAudioIO::setStreamCallback(SStreamCallback callback) throw(CAudioError) {
426     if (__mIsInit == false) {
427         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
428     }
429
430     mStreamCallback = callback;
431 }
432
433 CAudioIO::SStreamCallback CAudioIO::getStreamCallback() throw(CAudioError) {
434     if (__mIsInit == false) {
435         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
436     }
437
438     return mStreamCallback;
439 }
440
441 void CAudioIO::setStateChangedCallback(SStateChangedCallback callback) throw(CAudioError) {
442     if (__mIsInit == false) {
443         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
444     }
445
446     mStateChangedCallback = callback;
447 }
448
449 CAudioIO::SStateChangedCallback CAudioIO::getStateChangedCallback() throw(CAudioError) {
450     if (__mIsInit == false) {
451         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
452     }
453
454     return mStateChangedCallback;
455 }
456
457 void CAudioIO::setInterruptCallback(SInterruptCallback callback) throw(CAudioError) {
458     if (__mIsInit == false) {
459         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
460     }
461
462     mInterruptCallback = callback;
463 }
464
465 CAudioIO::SInterruptCallback CAudioIO::getInterruptCallback() throw(CAudioError) {
466     if (__mIsInit == false) {
467         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
468     }
469
470     return mInterruptCallback;
471 }
472
473 void CAudioIO::ignoreSession() throw(CAudioError) {
474     if (__mIsInit == false)
475         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
476
477     try {
478         internalLock();
479
480         if (mpPulseAudioClient != NULL && mState == CAudioInfo::EAudioIOState::AUDIO_IO_STATE_RUNNING)
481             THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_OPERATION, "An Operation is not permitted while started");
482
483         abandonInternalFocus();
484
485         internalUnlock();
486     } catch (CAudioError e) {
487         internalUnlock();
488         throw e;
489     }
490 }
491
492 void CAudioIO::setStreamInfo(sound_stream_info_h stream_info) throw(CAudioError) {
493     if (stream_info == NULL)
494         THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_ARGUMENT, "stream_info is NULL");
495
496     if (__mIsInit == false)
497         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
498
499     try {
500         if (mState != CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE)
501             THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_STATE, "it is not permitted while started");
502
503         abandonInternalFocus();
504
505         int errorCode = SOUND_MANAGER_ERROR_NONE;
506         CAudioInfo::EAudioType audioType = CAudioInfo::EAudioType::AUDIO_IN_TYPE_MEDIA;
507         char *type = NULL;
508         int index = -1;
509         bool avail = false;
510
511         if ((errorCode = sound_manager_is_available_stream_information(stream_info, NATIVE_API_AUDIO_IO, &avail)) != SOUND_MANAGER_ERROR_NONE)
512             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "Parameter stream_info is invalid [ret:%d]", errorCode);
513
514         if (!avail)
515             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_NOT_SUPPORTED_TYPE, "Input stream is not supported");
516
517         if ((errorCode = sound_manager_get_type_from_stream_information(stream_info, &type)) != SOUND_MANAGER_ERROR_NONE)
518             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "Parameter stream_info->stream_type is invalid [ret:%d]", errorCode);
519
520         if (mDirection == CAudioInfo::EAudioDirection::AUDIO_DIRECTION_IN)
521             getAudioInfo().convertInputStreamType2AudioType(type, &audioType);
522         else
523             getAudioInfo().convertOutputStreamType2AudioType(type, &audioType);
524         getAudioInfo().setAudioType(audioType);
525
526         if ((errorCode = sound_manager_get_index_from_stream_information(stream_info, &index)) != SOUND_MANAGER_ERROR_NONE)
527             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_INVALID_ARGUMENT, "Parameter stream_info->index is invalid [ret:%d]", errorCode);
528
529         getAudioInfo().setAudioIndex(index);
530
531         AUDIO_IO_LOGD("stream info(%p) is set", stream_info);
532     } catch (CAudioError e) {
533         throw e;
534     }
535 }
536
537 void CAudioIO::setInternalStreamInfo() throw(CAudioError) {
538     if (__mIsInit == false)
539         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioIO");
540
541     try {
542         if (mState != CAudioInfo::EAudioIOState::AUDIO_IO_STATE_IDLE)
543             THROW_ERROR_MSG(CAudioError::EError::ERROR_INVALID_STATE, "it is not permitted while started");
544
545         if (mpAudioSessionHandler &&
546             mpAudioSessionHandler->getMultimediaSession() == MM_SESSION_TYPE_VOIP) {
547             sound_stream_info_h stream_info = NULL;
548             mpAudioSessionHandler->getInternalVoipStreamInfo(&stream_info);
549             AUDIO_IO_LOGD("get internal VOIP stream info(%p)", stream_info);
550             setStreamInfo(stream_info);
551         }
552     } catch (CAudioError e) {
553         throw e;
554     }
555 }
556
557 void CAudioIO::abandonInternalFocus() throw(CAudioError) {
558     bool isSkip = mpAudioSessionHandler->isSkipSession();
559     int id = mpAudioSessionHandler->getId();
560
561     try {
562         if (isSkip == false && id >= 0)
563             mpAudioSessionHandler->unregisterSound();
564
565         mpAudioSessionHandler->finalize();
566         __mForceIgnore = true;
567     } catch (CAudioError e) {
568         throw e;
569     }
570 }