07d3690813acb2232eab411c6f3cd8f41b2c38ce
[platform/core/api/audio-io.git] / src / cpp / CAudioSessionHandler.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 <unistd.h>
19 #include <mm_error.h>
20 #include "CAudioIODef.h"
21
22
23 using namespace std;
24 using namespace tizen_media_audio;
25
26
27 /**
28  * class CAudioSessionHandler
29  */
30 int CAudioSessionHandler::__sCaptureRef = 0;
31
32 int CAudioSessionHandler::__pcmCaptureCountInc() {
33     int actual;
34     do {
35         actual = __sCaptureRef;
36     } while (!__sync_bool_compare_and_swap(&__sCaptureRef, actual, actual + 1));
37     AUDIO_IO_LOGD("CaptureRefCount+1 > [%d]", __sCaptureRef);
38     return __sCaptureRef;
39 }
40
41 int CAudioSessionHandler::__pcmCaptureCountDec() {
42     int actual;
43     do {
44         actual = __sCaptureRef;
45     } while (!__sync_bool_compare_and_swap(&__sCaptureRef, actual, actual - 1));
46     AUDIO_IO_LOGD("CaptureRefCount-1 > [%d]", __sCaptureRef);
47     if (__sCaptureRef < 0) {
48         AUDIO_IO_LOGE("A CaptureRef[%d] is not valid! Something is wrong!", __sCaptureRef);
49         __sCaptureRef = 0;
50     }
51     return __sCaptureRef;
52 }
53
54 int CAudioSessionHandler::__pcmCaptureCountGet() {
55     AUDIO_IO_LOGD("CaptureRefCount > [%d]", __sCaptureRef);
56     return __sCaptureRef;
57 }
58
59 int CAudioSessionHandler::__sFocusRef = 0;
60
61 int CAudioSessionHandler::__focusIdCountInc() {
62     int actual;
63     do {
64         actual = __sFocusRef;
65     } while (!__sync_bool_compare_and_swap(&__sFocusRef, actual, actual + 1));
66     AUDIO_IO_LOGD("FocusRefCount+1 > [%d]", __sFocusRef);
67     return __sFocusRef;
68 }
69
70 int CAudioSessionHandler::__focusIdCountDec() {
71     int actual;
72     do {
73         actual = __sFocusRef;
74     } while (!__sync_bool_compare_and_swap(&__sFocusRef, actual, actual - 1));
75     AUDIO_IO_LOGD("FocusRefCount-1 > [%d]", __sFocusRef);
76     return __sFocusRef;
77 }
78
79 int CAudioSessionHandler::__focusIdCountGet() {
80     /* AUDIO_IO_LOGD("FocusRefCount > [%d]", __sFocusRef); */
81     return __sFocusRef;
82 }
83
84 CAudioSessionHandler::CAudioSessionHandler(EAudioSessionType sessionType, CAudioInfo& audioInfo, IAudioSessionEventListener* listener) :
85     __mId(-1),
86     __mOptions(0),
87     __mAudioSession(sessionType),
88     __mMultimediaSession(MM_SESSION_TYPE_MEDIA),
89     __mpEventListener(listener),
90     __mIsInit(false),
91     __mSubscribeId(-1),
92     __mUseFocus(false),
93     __mFocusType(FOCUS_NONE),
94     __mState(FOCUS_IS_RELEASED),
95     __mReasonForChange(NULL),
96     __mAdditionalInfo(NULL) {
97     __mAudioInfo = audioInfo;
98 }
99
100 CAudioSessionHandler::~CAudioSessionHandler() {
101 }
102
103 CAudioError CAudioSessionHandler::__convertStreamType(EAudioSessionType type1, MMSessionType type2, int *index) {
104     unsigned int i;
105     int idx = -1;
106
107     assert(index != NULL);
108
109     if (type1 == EAudioSessionType::AUDIO_SESSION_TYPE_CAPTURE) {
110         for (i = 0 ; i < sizeof(__STREAM_TYPE_TABLE_IN) / sizeof(__STREAM_TYPE_TABLE_IN[0]) ; i++) {
111             if (__STREAM_TYPE_TABLE_IN[i].type == type2) {
112                 idx = i;
113                 break;
114             }
115         }
116     } else {
117         for (i = 0 ; i < sizeof(__STREAM_TYPE_TABLE_OUT) / sizeof(__STREAM_TYPE_TABLE_OUT[0]) ; i++) {
118             if (__STREAM_TYPE_TABLE_OUT[i].type == type2) {
119                 idx = i;
120                 break;
121             }
122         }
123     }
124
125     if (idx < 0) {
126         RET_ERROR_MSG(CAudioError::EError::ERROR_NOT_SUPPORTED, "Does not support session type.");
127     }
128     *index = idx;
129     RET_ERROR(CAudioError::EError::ERROR_NONE);
130 }
131
132 CAudioError CAudioSessionHandler::__getAsmInformation(MMSessionType *type, int *options) {
133     assert(type != NULL);
134     assert(options != NULL);
135
136     MMSessionType currentSession = MM_SESSION_TYPE_MEDIA;
137     int           sessionOptions = 0;
138
139     /* Read session information */
140     int ret = 0;
141     if ((ret = _mm_session_util_read_information(-1, (int*)&currentSession, &sessionOptions)) < 0) {
142         if (ret == (int) MM_ERROR_INVALID_HANDLE) {
143             RET_ERROR_MSG(CAudioError::EError::ERROR_INVALID_HANDLE, "Failed _mm_session_util_read_information(). Invalid handle");
144         } else {
145             RET_ERROR_MSG(CAudioError::EError::ERROR_FAILED_OPERATION, "Failed _mm_session_util_read_information(). Not exist");
146         }
147     }
148
149     *type    = currentSession;
150     *options = sessionOptions;
151
152     RET_ERROR(CAudioError::EError::ERROR_NONE);
153 }
154
155 bool CAudioSessionHandler::__isFocusRequired(MMSessionType type, int options) {
156     if ((options & MM_SESSION_OPTION_PAUSE_OTHERS)
157         || ((type != MM_SESSION_TYPE_MEDIA) && (type != MM_SESSION_TYPE_MEDIA_RECORD)))
158         return true;
159     else
160         return false;
161 }
162
163 int CAudioSessionHandler::getId() {
164     return __mId;
165 }
166
167 int CAudioSessionHandler::getOptions() {
168     return __mOptions;
169 }
170
171 CAudioSessionHandler::EAudioSessionType CAudioSessionHandler::getAudioSession() {
172     return __mAudioSession;
173 }
174
175 MMSessionType CAudioSessionHandler::getMultimediaSession() {
176     return __mMultimediaSession;
177 }
178
179 int CAudioSessionHandler::getSubscribeId() {
180     return __mSubscribeId;
181 }
182
183 CAudioInfo CAudioSessionHandler::getAudioInfo() {
184     return __mAudioInfo;
185 }
186
187 void CAudioSessionHandler::__sound_pcm_signal_cb(mm_sound_signal_name_t signal, int value, void *user_data) {
188     assert(user_data);
189
190     AUDIO_IO_LOGD("[signal:%d], [value:%d], [user_data:0x%x]", signal, value, user_data);
191
192     CAudioSessionHandler* pHandler = static_cast<CAudioSessionHandler*>(user_data);
193     if (pHandler->__mpEventListener != NULL) {
194         pHandler->__mpEventListener->onSignal(pHandler, signal, value);
195     }
196 }
197
198 void CAudioSessionHandler::initialize() throw (CAudioError) {
199     AUDIO_IO_LOGD("");
200     if (__mIsInit == true) {
201         return;
202     }
203
204     MMSessionType currentSession = MM_SESSION_TYPE_MEDIA;
205     int           sessionOptions = 0;  // Mix with others by default
206
207     CAudioError err = __getAsmInformation(&currentSession, &sessionOptions);
208     if (err == CAudioError::EError::ERROR_NONE) {
209         // Session was configured before, use focus callback
210         __mUseFocus = true;
211         AUDIO_IO_LOGD("Use audio focus concept internally!");
212     } else {
213         if (err == CAudioError::EError::ERROR_INVALID_HANDLE) {
214             int value = 0;
215             unsigned int subscribe_id;
216
217             int errorCode = mm_sound_get_signal_value(MM_SOUND_SIGNAL_RELEASE_INTERNAL_FOCUS, &value);
218             if (errorCode != MM_ERROR_NONE) {
219                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_POLICY_BLOCKED, "Failed mm_sound_get_signal_value() err:0x%x", errorCode);
220             }
221
222             if (value == 1) {
223                 // stream_info was created or focus watch callback was configured before
224                 __mUseFocus = false;
225                 AUDIO_IO_LOGD("Skip audio focus concept!");
226             } else if (value == 0) {
227                 // No session, No stream_info, No focus watch callback before
228                 // Use focus watch callback with signal subscribe
229                 errorCode = mm_sound_subscribe_signal(MM_SOUND_SIGNAL_RELEASE_INTERNAL_FOCUS, &subscribe_id, __sound_pcm_signal_cb, static_cast<void*>(this));
230                 if (errorCode != MM_ERROR_NONE) {
231                     THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_POLICY_BLOCKED, "Failed mm_sound_get_signal_value() err:0x%x", errorCode);
232                 }
233
234                 __mSubscribeId = (int)subscribe_id;
235                 AUDIO_IO_LOGD("Subscribed mm_sound signal");
236
237                 sessionOptions = 0;  // Mix with others by default
238                 __mUseFocus = true;
239                 AUDIO_IO_LOGD("Use audio focus(watch) concept internally!");
240             }
241         } else {
242             __mUseFocus = false;
243             AUDIO_IO_LOGD("Skip audio focus concept!");
244         }
245
246         if (__mAudioSession == EAudioSessionType::AUDIO_SESSION_TYPE_CAPTURE) {
247             AUDIO_IO_LOGD("Set default \"Media_Record\" type");
248             currentSession = MM_SESSION_TYPE_MEDIA_RECORD;
249         } else {
250             AUDIO_IO_LOGD("Set default \"Media\" type");
251             currentSession = MM_SESSION_TYPE_MEDIA;
252         }
253     }
254
255     // Updates session information
256     __mMultimediaSession = currentSession;
257     __mOptions           = sessionOptions;
258
259     if (this->__mAudioSession == EAudioSessionType::AUDIO_SESSION_TYPE_CAPTURE) {
260         __pcmCaptureCountInc();
261     }
262
263     __mIsInit = true;
264 }
265
266 void CAudioSessionHandler::finalize() {
267     AUDIO_IO_LOGD("");
268     if (__mIsInit == false) {
269         return;
270     }
271
272     if (__mAudioSession == EAudioSessionType::AUDIO_SESSION_TYPE_CAPTURE) {
273         __pcmCaptureCountDec();
274     }
275
276     if (__mSubscribeId >= 0) {
277         mm_sound_unsubscribe_signal(__mSubscribeId);
278     }
279
280     __mIsInit = false;
281 }
282
283 bool CAudioSessionHandler::isSkipSessionEvent() throw (CAudioError) {
284     bool ret = false;
285
286     // To be regarded...
287 #if 0
288     /* Only Support below Event */
289     if (mEvent != ASM_EVENT_CALL              && mEvent != ASM_EVENT_VOIP              &&
290         mEvent != ASM_EVENT_VIDEOCALL         && mEvent != ASM_EVENT_VOICE_RECOGNITION &&
291         mEvent != ASM_EVENT_MMCAMCORDER_AUDIO && mEvent != ASM_EVENT_MMCAMCORDER_VIDEO) {
292
293         // Check AudioType
294         switch (__mAudioInfo.getAudioType()) {
295         case CAudioInfo::AUDIO_IN_TYPE_MEDIA:
296         case CAudioInfo::AUDIO_IN_TYPE_VOICECONTROL:
297             ret = false;
298             break;
299
300         case CAudioInfo::AUDIO_IN_TYPE_MIRRORING:
301         case CAudioInfo::AUDIO_IN_TYPE_LOOPBACK:
302             ret = true;
303             break;
304
305         default:
306             return false;
307         }
308
309         if (ret == true) {
310             int captureCount = CAudioSessionHandler::__pcmCaptureCountGet();
311             if (captureCount == 1) {/* If this is last one */
312                 /* Recover session information to MEDIA */
313                 int sessionResult = _mm_session_util_write_information(-1, MM_SESSION_TYPE_MEDIA, __mOptions);
314                 if (sessionResult != 0) {
315                     THROW_ERROR_MSG_FORMAT(CAudioError::ERROR_INTERNAL_OPERATION, "Failed _mm_session_util_write_information() ret:%d", sessionResult);
316                 }
317             }
318         }
319     }
320 #endif
321
322     return ret;
323 }
324
325 void CAudioSessionHandler::__sound_pcm_focus_cb(int id, mm_sound_focus_type_e focus_type, mm_sound_focus_state_e state, const char *reason_for_change, const char *additional_info, void *user_data) {
326     assert(user_data);
327
328     AUDIO_IO_LOGD("[id:%d], [focus_type:%d], [state:%d], [reason_for_change:%s], [additional_info:%s], [user_data:0x%x]", id, focus_type, state, reason_for_change, additional_info, user_data);
329
330     CAudioSessionHandler* pHandler = static_cast<CAudioSessionHandler*>(user_data);
331     pHandler->__mFocusType       = focus_type;
332     pHandler->__mState           = state;
333     pHandler->__mReasonForChange = (char *)reason_for_change;
334     pHandler->__mAdditionalInfo  = (char *)additional_info;
335
336     if (pHandler->__mpEventListener != NULL) {
337         pHandler->__mpEventListener->onInterrupt(pHandler, id, focus_type, state, reason_for_change, additional_info);
338     }
339
340     return;
341 }
342
343 void CAudioSessionHandler::__sound_pcm_focus_watch_cb(int id, mm_sound_focus_type_e focus_type, mm_sound_focus_state_e state, const char *reason_for_change, const char *additional_info, void *user_data) {
344     AUDIO_IO_LOGD("[id:%d], [focus_type:%d], [state:%d], [reason_for_change:%s], [additional_info:%s], [user_data:0x%x]", id, focus_type, state, reason_for_change, additional_info, user_data);
345
346     CAudioSessionHandler::__sound_pcm_focus_cb(-1, focus_type, state, reason_for_change, additional_info, user_data);
347
348     return;
349 }
350
351 void CAudioSessionHandler::registerSound() throw (CAudioError) {
352     if (__mIsInit == false) {
353         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioSessionHandler");
354     }
355
356     if (__mUseFocus == true) {
357         if (__mId >= 0) {
358             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_POLICY_BLOCKED, "Already registered [id:%d]", __mId);
359         }
360
361         int errorCode = 0;
362
363         if (__isFocusRequired(__mMultimediaSession, __mOptions)) {
364             int index = 0;
365             CAudioError err = __convertStreamType(__mAudioSession, __mMultimediaSession, &index);
366             if (err != CAudioError::EError::ERROR_NONE) {
367                 throw err;
368             }
369
370             errorCode = mm_sound_focus_get_id(&__mId);
371             if (errorCode != MM_ERROR_NONE) {
372                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_POLICY_BLOCKED, "Failed mm_sound_focus_get_id() err:0x%x", errorCode);
373             }
374
375             // Register focus callback
376             errorCode = mm_sound_register_focus_for_session(__mId,
377                                                 getpid(),
378                                                 __mAudioSession == EAudioSessionType::AUDIO_SESSION_TYPE_CAPTURE ? __STREAM_TYPE_TABLE_IN[index].name : __STREAM_TYPE_TABLE_OUT[index].name,
379                                                 __sound_pcm_focus_cb,
380                                                 static_cast<void*>(this));
381             if (errorCode != MM_ERROR_NONE) {
382                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_POLICY_BLOCKED, "Failed mm_sound_register_focus_for_session() err:0x%x", errorCode);
383             }
384
385             __focusIdCountInc();
386
387             AUDIO_IO_LOGD("Focus callback registered successfully [id:%d]", __mId);
388         } else if (!(__mOptions & MM_SESSION_OPTION_UNINTERRUPTIBLE)) {
389             // Register focus watch callback
390             errorCode = mm_sound_set_focus_watch_callback_for_session(getpid(), FOCUS_FOR_BOTH, __sound_pcm_focus_watch_cb, static_cast<void*>(this), &__mId);
391             if (errorCode < 0) {
392                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_POLICY_BLOCKED, "Failed mm_sound_set_focus_watch_callback_for_session() err:0x%x", errorCode);
393             }
394
395             __focusIdCountInc();
396
397             AUDIO_IO_LOGD("Focus watch callback registered successfully [id:%d]", __mId);
398         }
399     }
400 }
401
402 void CAudioSessionHandler::unregisterSound() throw (CAudioError) {
403     if (__mIsInit == false) {
404         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioSessionHandler");
405     }
406
407     if (__mUseFocus == true) {
408         if (__mId < 0) {
409             THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_POLICY_BLOCKED, "Did not register [id:%d]", __mId);
410         }
411
412         int errorCode = 0;
413
414         if (__isFocusRequired(__mMultimediaSession, __mOptions)) {
415             // Unregister focus callback
416             errorCode = mm_sound_unregister_focus(__mId);
417             if (errorCode != MM_ERROR_NONE) {
418                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_POLICY_BLOCKED, "Failed mm_sound_unregister_focus() err:0x%x", errorCode);
419             }
420
421             __focusIdCountDec();
422
423             AUDIO_IO_LOGD("Focus callback unregistered successfully [id:%d]", __mId);
424             __mId = -1;
425         } else if (!(__mOptions & MM_SESSION_OPTION_UNINTERRUPTIBLE)) {
426             // Unregister focus watch callback.
427             errorCode = mm_sound_unset_focus_watch_callback(__mId);
428             if (errorCode < 0) {
429                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_POLICY_BLOCKED, "Failed mm_sound_unset_focus_watch_callback() err:0x%x", errorCode);
430             }
431
432             __focusIdCountDec();
433
434             AUDIO_IO_LOGD("Focus watch callback unregistered successfully [id:%d]", __mId);
435             __mId = -1;
436         }
437     }
438 }
439
440 void CAudioSessionHandler::updatePlaying() throw (CAudioError) {
441     if (__mIsInit == false) {
442         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioSessionHandler");
443     }
444
445     if (__mUseFocus && __isFocusRequired(__mMultimediaSession, __mOptions)) {
446         if (__mId >= 0) {
447             int ret = mm_sound_acquire_focus(__mId, FOCUS_FOR_BOTH, "audio-io acquire focus");
448             if (ret != MM_ERROR_NONE) {
449                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_POLICY_BLOCKED, "Failed mm_sound_acquire_focus() err:0x%x", ret);
450             }
451             AUDIO_IO_LOGD("Focus acquired successfully [id:%d]", __mId);
452         }
453     }
454 }
455
456 void CAudioSessionHandler::updateStop() throw (CAudioError) {
457     if (__mIsInit == false) {
458         THROW_ERROR_MSG(CAudioError::EError::ERROR_NOT_INITIALIZED, "Doesn't initialize CAudioSessionHandler");
459     }
460
461     if (__mUseFocus && __isFocusRequired(__mMultimediaSession, __mOptions)) {
462         if (__mId >= 0) {
463             int ret = mm_sound_release_focus(__mId, FOCUS_FOR_BOTH, "audio-io release focus");
464             if (ret != MM_ERROR_NONE) {
465                 THROW_ERROR_MSG_FORMAT(CAudioError::EError::ERROR_POLICY_BLOCKED, "Failed mm_sound_release_focus() err:0x%x", ret);
466             }
467             AUDIO_IO_LOGD("Focus released successfully [id:%d]", __mId);
468         }
469     }
470 }
471
472 void CAudioSessionHandler::disableSessionHandler() throw (CAudioError) {
473     CAudioSessionHandler::updateStop();
474     CAudioSessionHandler::unregisterSound();
475
476     CAudioSessionHandler::__mUseFocus = false;
477 }
478
479 /**
480  * class IAudioSessionEventListener
481  */
482 IAudioSessionEventListener::EInterruptCode IAudioSessionEventListener::convertInterruptedCode(int code, const char *reason_for_change) {
483     EInterruptCode e = EInterruptCode::INTERRUPT_COMPLETED;
484
485     switch (code)
486     {
487     case FOCUS_IS_ACQUIRED:
488         e = EInterruptCode::INTERRUPT_COMPLETED;
489         break;
490
491     case FOCUS_IS_RELEASED:
492         if (!strcmp(reason_for_change, "media"))              e = EInterruptCode::INTERRUPT_BY_MEDIA;
493         if (!strcmp(reason_for_change, "radio"))              e = EInterruptCode::INTERRUPT_BY_MEDIA;
494         if (!strcmp(reason_for_change, "loopback"))           e = EInterruptCode::INTERRUPT_BY_MEDIA;
495         if (!strcmp(reason_for_change, "system"))             e = EInterruptCode::INTERRUPT_BY_MEDIA;
496         if (!strcmp(reason_for_change, "alarm"))              e = EInterruptCode::INTERRUPT_BY_ALARM;
497         if (!strcmp(reason_for_change, "notification"))       e = EInterruptCode::INTERRUPT_BY_NOTIFICATION;
498         if (!strcmp(reason_for_change, "emergency"))          e = EInterruptCode::INTERRUPT_BY_EMERGENCY;
499         if (!strcmp(reason_for_change, "voice-information"))  e = EInterruptCode::INTERRUPT_BY_MEDIA;  //for what?
500         if (!strcmp(reason_for_change, "voice-recognition"))  e = EInterruptCode::INTERRUPT_BY_MEDIA;  //for what?
501         if (!strcmp(reason_for_change, "ringtone-voip"))      e = EInterruptCode::INTERRUPT_BY_MEDIA;  //for what?
502         if (!strcmp(reason_for_change, "ringtone-call"))      e = EInterruptCode::INTERRUPT_BY_MEDIA;  //for what?
503         if (!strcmp(reason_for_change, "voip"))               e = EInterruptCode::INTERRUPT_BY_MEDIA;  //for what?
504         if (!strcmp(reason_for_change, "call-voice"))         e = EInterruptCode::INTERRUPT_BY_MEDIA;  //for what?
505         if (!strcmp(reason_for_change, "call-video"))         e = EInterruptCode::INTERRUPT_BY_MEDIA;  //for what?
506         break;
507     }
508
509     return e;
510 }