123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657 |
- /****************************************************************************
- Copyright (c) 2014-2017 Chukong Technologies Inc.
- http://www.cocos2d-x.org
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
- #define LOG_TAG "AudioEngine-inl.mm"
- #include "platform/CCPlatformConfig.h"
- #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC
- #include "audio/apple/AudioEngine-inl.h"
- #import <OpenAL/alc.h>
- #import <AVFoundation/AVFoundation.h>
- #include "audio/include/AudioEngine.h"
- #include "platform/CCFileUtils.h"
- #include "base/CCDirector.h"
- #include "base/CCScheduler.h"
- #include "base/ccUtils.h"
- using namespace cocos2d;
- using namespace cocos2d::experimental;
- static ALCdevice *s_ALDevice = nullptr;
- static ALCcontext *s_ALContext = nullptr;
- #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
- @interface AudioEngineSessionHandler : NSObject
- {
- }
- -(id) init;
- -(void)handleInterruption:(NSNotification*)notification;
- @end
- @implementation AudioEngineSessionHandler
- // only enable it on iOS. Disable it on tvOS
- #if !defined(CC_TARGET_OS_TVOS)
- void AudioEngineInterruptionListenerCallback(void* user_data, UInt32 interruption_state)
- {
- if (kAudioSessionBeginInterruption == interruption_state)
- {
- alcMakeContextCurrent(nullptr);
- }
- else if (kAudioSessionEndInterruption == interruption_state)
- {
- OSStatus result = AudioSessionSetActive(true);
- if (result) NSLog(@"Error setting audio session active! %d\n", static_cast<int>(result));
- alcMakeContextCurrent(s_ALContext);
- }
- }
- #endif
- -(id) init
- {
- if (self = [super init])
- {
- if ([[[UIDevice currentDevice] systemVersion] intValue] > 5) {
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:UIApplicationDidBecomeActiveNotification object:nil];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:UIApplicationWillResignActiveNotification object:nil];
- }
- // only enable it on iOS. Disable it on tvOS
- // AudioSessionInitialize removed from tvOS
- #if !defined(CC_TARGET_OS_TVOS)
- else {
- AudioSessionInitialize(NULL, NULL, AudioEngineInterruptionListenerCallback, self);
- }
- #endif
- }
- return self;
- }
- -(void)handleInterruption:(NSNotification*)notification
- {
- static bool isAudioSessionInterrupted = false;
- static bool resumeOnBecomingActive = false;
- static bool pauseOnResignActive = false;
- if ([notification.name isEqualToString:AVAudioSessionInterruptionNotification])
- {
- NSInteger reason = [[[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey] integerValue];
- if (reason == AVAudioSessionInterruptionTypeBegan)
- {
- isAudioSessionInterrupted = true;
- if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive)
- {
- ALOGD("AVAudioSessionInterruptionTypeBegan, application != UIApplicationStateActive, alcMakeContextCurrent(nullptr)");
- alcMakeContextCurrent(nullptr);
- }
- else
- {
- ALOGD("AVAudioSessionInterruptionTypeBegan, application == UIApplicationStateActive, pauseOnResignActive = true");
- pauseOnResignActive = true;
- }
- }
- if (reason == AVAudioSessionInterruptionTypeEnded)
- {
- isAudioSessionInterrupted = false;
- if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
- {
- ALOGD("AVAudioSessionInterruptionTypeEnded, application == UIApplicationStateActive, alcMakeContextCurrent(s_ALContext)");
- NSError *error = nil;
- [[AVAudioSession sharedInstance] setActive:YES error:&error];
- alcMakeContextCurrent(s_ALContext);
- if (Director::getInstance()->isPaused())
- {
- ALOGD("AVAudioSessionInterruptionTypeEnded, director was paused, try to resume it.");
- Director::getInstance()->resume();
- }
- }
- else
- {
- ALOGD("AVAudioSessionInterruptionTypeEnded, application != UIApplicationStateActive, resumeOnBecomingActive = true");
- resumeOnBecomingActive = true;
- }
- }
- }
- else if ([notification.name isEqualToString:UIApplicationWillResignActiveNotification])
- {
- ALOGD("UIApplicationWillResignActiveNotification");
- if (pauseOnResignActive)
- {
- pauseOnResignActive = false;
- ALOGD("UIApplicationWillResignActiveNotification, alcMakeContextCurrent(nullptr)");
- alcMakeContextCurrent(nullptr);
- }
- }
- else if ([notification.name isEqualToString:UIApplicationDidBecomeActiveNotification])
- {
- ALOGD("UIApplicationDidBecomeActiveNotification");
- if (resumeOnBecomingActive)
- {
- resumeOnBecomingActive = false;
- ALOGD("UIApplicationDidBecomeActiveNotification, alcMakeContextCurrent(s_ALContext)");
- NSError *error = nil;
- BOOL success = [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: &error];
- if (!success) {
- ALOGE("Fail to set audio session.");
- return;
- }
- [[AVAudioSession sharedInstance] setActive:YES error:&error];
- alcMakeContextCurrent(s_ALContext);
- }
- else if (isAudioSessionInterrupted)
- {
- ALOGD("Audio session is still interrupted, pause director!");
- Director::getInstance()->pause();
- }
- }
- }
- -(void) dealloc
- {
- [[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionInterruptionNotification object:nil];
- [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
- [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
- [super dealloc];
- }
- @end
- static id s_AudioEngineSessionHandler = nullptr;
- #endif
- AudioEngineImpl::AudioEngineImpl()
- : _lazyInitLoop(true)
- , _currentAudioID(0)
- , _scheduler(nullptr)
- {
- }
- AudioEngineImpl::~AudioEngineImpl()
- {
- if (_scheduler != nullptr)
- {
- _scheduler->unschedule(CC_SCHEDULE_SELECTOR(AudioEngineImpl::update), this);
- }
- if (s_ALContext) {
- alDeleteSources(MAX_AUDIOINSTANCES, _alSources);
- _audioCaches.clear();
- alcMakeContextCurrent(nullptr);
- alcDestroyContext(s_ALContext);
- }
- if (s_ALDevice) {
- alcCloseDevice(s_ALDevice);
- }
- #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
- [s_AudioEngineSessionHandler release];
- #endif
- }
- bool AudioEngineImpl::init()
- {
- bool ret = false;
- do{
- #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
- s_AudioEngineSessionHandler = [[AudioEngineSessionHandler alloc] init];
- #endif
- s_ALDevice = alcOpenDevice(nullptr);
- if (s_ALDevice) {
- s_ALContext = alcCreateContext(s_ALDevice, nullptr);
- alcMakeContextCurrent(s_ALContext);
- alGenSources(MAX_AUDIOINSTANCES, _alSources);
- auto alError = alGetError();
- if(alError != AL_NO_ERROR)
- {
- ALOGE("%s:generating sources failed! error = %x", __PRETTY_FUNCTION__, alError);
- break;
- }
- for (int i = 0; i < MAX_AUDIOINSTANCES; ++i) {
- _alSourceUsed[_alSources[i]] = false;
- }
- // fixed #16170: Random crash in alGenBuffers(AudioCache::readDataTask) at startup
- // Please note that, as we know the OpenAL operation is atomic (threadsafe),
- // 'alGenBuffers' may be invoked by different threads. But in current implementation of 'alGenBuffers',
- // When the first time it's invoked, application may crash!!!
- // Why? OpenAL is opensource by Apple and could be found at
- // http://opensource.apple.com/source/OpenAL/OpenAL-48.7/Source/OpenAL/oalImp.cpp .
- /*
- void InitializeBufferMap()
- {
- if (gOALBufferMap == NULL) // Position 1
- {
- gOALBufferMap = new OALBufferMap (); // Position 2
- // Position Gap
- gBufferMapLock = new CAGuard("OAL:BufferMapLock"); // Position 3
- gDeadOALBufferMap = new OALBufferMap ();
- OALBuffer *newBuffer = new OALBuffer (AL_NONE);
- gOALBufferMap->Add(AL_NONE, &newBuffer);
- }
- }
- AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *bids)
- {
- ...
- try {
- if (n < 0)
- throw ((OSStatus) AL_INVALID_VALUE);
- InitializeBufferMap();
- if (gOALBufferMap == NULL)
- throw ((OSStatus) AL_INVALID_OPERATION);
- CAGuard::Locker locked(*gBufferMapLock); // Position 4
- ...
- ...
- }
- */
- // 'gBufferMapLock' will be initialized in the 'InitializeBufferMap' function,
- // that's the problem. It means that 'InitializeBufferMap' may be invoked in different threads.
- // It will be very dangerous in multi-threads environment.
- // Imagine there're two threads (Thread A, Thread B), they call 'alGenBuffers' simultaneously.
- // While A goto 'Position Gap', 'gOALBufferMap' was assigned, then B goto 'Position 1' and find
- // that 'gOALBufferMap' isn't NULL, B just jump over 'InitialBufferMap' and goto 'Position 4'.
- // Meanwhile, A is still at 'Position Gap', B will crash at '*gBufferMapLock' since 'gBufferMapLock'
- // is still a null pointer. Oops, how could Apple implemented this method in this fucking way?
- // Workaround is do an unused invocation in the mainthread right after OpenAL is initialized successfully
- // as bellow.
- // ================ Workaround begin ================ //
- ALuint unusedAlBufferId = 0;
- alGenBuffers(1, &unusedAlBufferId);
- alDeleteBuffers(1, &unusedAlBufferId);
- // ================ Workaround end ================ //
- _scheduler = Director::getInstance()->getScheduler();
- ret = true;
- ALOGI("OpenAL was initialized successfully!");
- }
- }while (false);
- return ret;
- }
- AudioCache* AudioEngineImpl::preload(const std::string& filePath, std::function<void(bool)> callback)
- {
- AudioCache* audioCache = nullptr;
- auto it = _audioCaches.find(filePath);
- if (it == _audioCaches.end()) {
- audioCache = &_audioCaches[filePath];
- audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
- unsigned int cacheId = audioCache->_id;
- auto isCacheDestroyed = audioCache->_isDestroyed;
- AudioEngine::addTask([audioCache, cacheId, isCacheDestroyed](){
- if (*isCacheDestroyed)
- {
- ALOGV("AudioCache (id=%u) was destroyed, no need to launch readDataTask.", cacheId);
- audioCache->setSkipReadDataTask(true);
- return;
- }
- audioCache->readDataTask(cacheId);
- });
- }
- else {
- audioCache = &it->second;
- }
- if (audioCache && callback)
- {
- audioCache->addLoadCallback(callback);
- }
- return audioCache;
- }
- int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume)
- {
- if (s_ALDevice == nullptr) {
- return AudioEngine::INVALID_AUDIO_ID;
- }
- bool sourceFlag = false;
- ALuint alSource = 0;
- for (int i = 0; i < MAX_AUDIOINSTANCES; ++i) {
- alSource = _alSources[i];
- if ( !_alSourceUsed[alSource]) {
- sourceFlag = true;
- break;
- }
- }
- if(!sourceFlag){
- return AudioEngine::INVALID_AUDIO_ID;
- }
- auto player = new (std::nothrow) AudioPlayer;
- if (player == nullptr) {
- return AudioEngine::INVALID_AUDIO_ID;
- }
- player->_alSource = alSource;
- player->_loop = loop;
- player->_volume = volume;
- auto audioCache = preload(filePath, nullptr);
- if (audioCache == nullptr) {
- delete player;
- return AudioEngine::INVALID_AUDIO_ID;
- }
- player->setCache(audioCache);
- _threadMutex.lock();
- _audioPlayers[_currentAudioID] = player;
- _threadMutex.unlock();
- _alSourceUsed[alSource] = true;
- audioCache->addPlayCallback(std::bind(&AudioEngineImpl::_play2d,this,audioCache,_currentAudioID));
- if (_lazyInitLoop) {
- _lazyInitLoop = false;
- _scheduler->schedule(CC_SCHEDULE_SELECTOR(AudioEngineImpl::update), this, 0.05f, false);
- }
- return _currentAudioID++;
- }
- void AudioEngineImpl::_play2d(AudioCache *cache, int audioID)
- {
- //Note: It may bn in sub thread or main thread :(
- if (!*cache->_isDestroyed && cache->_state == AudioCache::State::READY)
- {
- _threadMutex.lock();
- auto playerIt = _audioPlayers.find(audioID);
- if (playerIt != _audioPlayers.end() && playerIt->second->play2d()) {
- _scheduler->performFunctionInCocosThread([audioID](){
- if (AudioEngine::_audioIDInfoMap.find(audioID) != AudioEngine::_audioIDInfoMap.end()) {
- AudioEngine::_audioIDInfoMap[audioID].state = AudioEngine::AudioState::PLAYING;
- }
- });
- }
- _threadMutex.unlock();
- }
- else
- {
- ALOGD("AudioEngineImpl::_play2d, cache was destroyed or not ready!");
- auto iter = _audioPlayers.find(audioID);
- if (iter != _audioPlayers.end())
- {
- iter->second->_removeByAudioEngine = true;
- }
- }
- }
- void AudioEngineImpl::setVolume(int audioID,float volume)
- {
- auto player = _audioPlayers[audioID];
- player->_volume = volume;
- if (player->_ready) {
- alSourcef(_audioPlayers[audioID]->_alSource, AL_GAIN, volume);
- auto error = alGetError();
- if (error != AL_NO_ERROR) {
- ALOGE("%s: audio id = %d, error = %x", __PRETTY_FUNCTION__,audioID,error);
- }
- }
- }
- void AudioEngineImpl::setLoop(int audioID, bool loop)
- {
- auto player = _audioPlayers[audioID];
- if (player->_ready) {
- if (player->_streamingSource) {
- player->setLoop(loop);
- } else {
- if (loop) {
- alSourcei(player->_alSource, AL_LOOPING, AL_TRUE);
- } else {
- alSourcei(player->_alSource, AL_LOOPING, AL_FALSE);
- }
- auto error = alGetError();
- if (error != AL_NO_ERROR) {
- ALOGE("%s: audio id = %d, error = %x", __PRETTY_FUNCTION__,audioID,error);
- }
- }
- }
- else {
- player->_loop = loop;
- }
- }
- bool AudioEngineImpl::pause(int audioID)
- {
- bool ret = true;
- alSourcePause(_audioPlayers[audioID]->_alSource);
- auto error = alGetError();
- if (error != AL_NO_ERROR) {
- ret = false;
- ALOGE("%s: audio id = %d, error = %x", __PRETTY_FUNCTION__,audioID,error);
- }
- return ret;
- }
- bool AudioEngineImpl::resume(int audioID)
- {
- bool ret = true;
- alSourcePlay(_audioPlayers[audioID]->_alSource);
- auto error = alGetError();
- if (error != AL_NO_ERROR) {
- ret = false;
- ALOGE("%s: audio id = %d, error = %x", __PRETTY_FUNCTION__,audioID,error);
- }
- return ret;
- }
- void AudioEngineImpl::stop(int audioID)
- {
- auto player = _audioPlayers[audioID];
- player->destroy();
- //Note: Don't set the flag to false here, it should be set in 'update' function.
- // Otherwise, the state got from alSourceState may be wrong
- // _alSourceUsed[player->_alSource] = false;
- }
- void AudioEngineImpl::stopAll()
- {
- for(auto&& player : _audioPlayers)
- {
- player.second->destroy();
- }
- //Note: Don't set the flag to false here, it should be set in 'update' function.
- // Otherwise, the state got from alSourceState may be wrong
- // for(int index = 0; index < MAX_AUDIOINSTANCES; ++index)
- // {
- // _alSourceUsed[_alSources[index]] = false;
- // }
- }
- float AudioEngineImpl::getDuration(int audioID)
- {
- auto player = _audioPlayers[audioID];
- if(player->_ready){
- return player->_audioCache->_duration;
- } else {
- return AudioEngine::TIME_UNKNOWN;
- }
- }
- float AudioEngineImpl::getCurrentTime(int audioID)
- {
- float ret = 0.0f;
- auto player = _audioPlayers[audioID];
- if(player->_ready){
- if (player->_streamingSource) {
- ret = player->getTime();
- } else {
- alGetSourcef(player->_alSource, AL_SEC_OFFSET, &ret);
- auto error = alGetError();
- if (error != AL_NO_ERROR) {
- ALOGE("%s, audio id:%d,error code:%x", __PRETTY_FUNCTION__,audioID,error);
- }
- }
- }
- return ret;
- }
- bool AudioEngineImpl::setCurrentTime(int audioID, float time)
- {
- bool ret = false;
- auto player = _audioPlayers[audioID];
- do {
- if (!player->_ready) {
- break;
- }
- if (player->_streamingSource) {
- ret = player->setTime(time);
- break;
- }
- else {
- if (player->_audioCache->_framesRead != player->_audioCache->_totalFrames &&
- (time * player->_audioCache->_sampleRate) > player->_audioCache->_framesRead) {
- ALOGE("%s: audio id = %d", __PRETTY_FUNCTION__,audioID);
- break;
- }
- alSourcef(player->_alSource, AL_SEC_OFFSET, time);
- auto error = alGetError();
- if (error != AL_NO_ERROR) {
- ALOGE("%s: audio id = %d, error = %x", __PRETTY_FUNCTION__,audioID,error);
- }
- ret = true;
- }
- } while (0);
- return ret;
- }
- void AudioEngineImpl::setFinishCallback(int audioID, const std::function<void (int, const std::string &)> &callback)
- {
- _audioPlayers[audioID]->_finishCallbak = callback;
- }
- void AudioEngineImpl::update(float dt)
- {
- ALint sourceState;
- int audioID;
- AudioPlayer* player;
- ALuint alSource;
- // ALOGV("AudioPlayer count: %d", (int)_audioPlayers.size());
- for (auto it = _audioPlayers.begin(); it != _audioPlayers.end(); ) {
- audioID = it->first;
- player = it->second;
- alSource = player->_alSource;
- alGetSourcei(alSource, AL_SOURCE_STATE, &sourceState);
- if (player->_removeByAudioEngine)
- {
- AudioEngine::remove(audioID);
- _threadMutex.lock();
- it = _audioPlayers.erase(it);
- _threadMutex.unlock();
- delete player;
- _alSourceUsed[alSource] = false;
- }
- else if (player->_ready && sourceState == AL_STOPPED) {
- std::string filePath;
- if (player->_finishCallbak) {
- auto& audioInfo = AudioEngine::_audioIDInfoMap[audioID];
- filePath = *audioInfo.filePath;
- }
- AudioEngine::remove(audioID);
- _threadMutex.lock();
- it = _audioPlayers.erase(it);
- _threadMutex.unlock();
- if (player->_finishCallbak) {
- player->_finishCallbak(audioID, filePath); //FIXME: callback will delay 50ms
- }
- delete player;
- _alSourceUsed[alSource] = false;
- }
- else{
- ++it;
- }
- }
- if(_audioPlayers.empty()){
- _lazyInitLoop = true;
- _scheduler->unschedule(CC_SCHEDULE_SELECTOR(AudioEngineImpl::update), this);
- }
- }
- void AudioEngineImpl::uncache(const std::string &filePath)
- {
- _audioCaches.erase(filePath);
- }
- void AudioEngineImpl::uncacheAll()
- {
- _audioCaches.clear();
- }
- #endif
|