From fc98b4bdc0cd4d05ebf85e2eb7b08f84cda41475 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 24 Apr 2017 10:49:02 +0800 Subject: [PATCH] Sync with cocos2d-x v3 branch ddb4dc8 commit. --- .../cocos2d_libs.xcodeproj/project.pbxproj | 12 + native/cocos/audio/AudioEngine.cpp | 81 +-- native/cocos/audio/android/Android.mk | 4 +- native/cocos/audio/android/AssetFd.cpp | 2 +- native/cocos/audio/android/AssetFd.h | 2 +- native/cocos/audio/android/AudioDecoder.cpp | 22 +- native/cocos/audio/android/AudioDecoder.h | 2 +- .../cocos/audio/android/AudioDecoderMp3.cpp | 54 +- .../cocos/audio/android/AudioDecoderOgg.cpp | 68 ++- .../audio/android/AudioDecoderProvider.cpp | 10 + .../cocos/audio/android/AudioDecoderSLES.cpp | 24 + .../cocos/audio/android/AudioDecoderWav.cpp | 111 ++++ native/cocos/audio/android/AudioDecoderWav.h | 46 ++ .../cocos/audio/android/AudioEngine-inl.cpp | 66 +- native/cocos/audio/android/AudioEngine-inl.h | 3 +- .../audio/android/AudioMixerController.cpp | 2 +- .../audio/android/AudioMixerController.h | 2 +- .../audio/android/AudioPlayerProvider.cpp | 24 +- .../cocos/audio/android/AudioPlayerProvider.h | 3 +- native/cocos/audio/android/CCThreadPool.cpp | 4 +- native/cocos/audio/android/CCThreadPool.h | 2 +- native/cocos/audio/android/IAudioPlayer.h | 4 +- .../cocos/audio/android/ICallerThreadUtils.h | 2 +- native/cocos/audio/android/IVolumeProvider.h | 2 +- native/cocos/audio/android/OpenSLHelper.h | 2 +- native/cocos/audio/android/PcmAudioPlayer.cpp | 7 +- native/cocos/audio/android/PcmAudioPlayer.h | 4 +- .../cocos/audio/android/PcmAudioService.cpp | 2 +- native/cocos/audio/android/PcmAudioService.h | 2 +- .../cocos/audio/android/PcmBufferProvider.cpp | 2 +- .../cocos/audio/android/PcmBufferProvider.h | 2 +- native/cocos/audio/android/PcmData.cpp | 2 +- native/cocos/audio/android/PcmData.h | 2 +- native/cocos/audio/android/Track.cpp | 12 +- native/cocos/audio/android/Track.h | 5 +- native/cocos/audio/android/UrlAudioPlayer.cpp | 35 +- native/cocos/audio/android/UrlAudioPlayer.h | 7 +- native/cocos/audio/android/audio.h | 2 +- .../cocos/audio/android/ccdandroidUtils.cpp | 2 +- native/cocos/audio/android/ccdandroidUtils.h | 2 +- .../audio/android/cddSimpleAudioEngine.cpp | 2 +- .../jni/cddandroidAndroidJavaEngine.cpp | 10 +- .../android/jni/cddandroidAndroidJavaEngine.h | 2 +- native/cocos/audio/android/mp3reader.cpp | 28 +- native/cocos/audio/android/tinysndfile.cpp | 518 ++++++++++++++++ native/cocos/audio/android/tinysndfile.h | 74 +++ native/cocos/audio/android/utils/Utils.cpp | 2 +- native/cocos/audio/android/utils/Utils.h | 2 +- native/cocos/audio/apple/AudioCache.h | 2 +- native/cocos/audio/apple/AudioCache.mm | 63 +- native/cocos/audio/apple/AudioDecoder.h | 2 +- native/cocos/audio/apple/AudioDecoder.mm | 4 +- native/cocos/audio/apple/AudioEngine-inl.h | 2 +- native/cocos/audio/apple/AudioEngine-inl.mm | 115 +++- native/cocos/audio/apple/AudioMacros.h | 2 +- native/cocos/audio/apple/AudioPlayer.h | 2 +- native/cocos/audio/apple/AudioPlayer.mm | 4 +- native/cocos/audio/include/AudioEngine.h | 112 ++-- native/cocos/audio/include/Export.h | 6 +- .../cocos/audio/include/SimpleAudioEngine.h | 19 +- native/cocos/audio/ios/CDAudioManager.h | 28 +- native/cocos/audio/ios/CDAudioManager.m | 334 +++++----- native/cocos/audio/ios/CDConfig.h | 18 +- native/cocos/audio/ios/CDOpenALSupport.h | 21 +- native/cocos/audio/ios/CDOpenALSupport.m | 80 +-- native/cocos/audio/ios/CocosDenshion.h | 69 ++- native/cocos/audio/ios/CocosDenshion.m | 519 ++++++++-------- native/cocos/audio/ios/SimpleAudioEngine.mm | 84 ++- .../cocos/audio/ios/SimpleAudioEngine_objc.h | 14 +- .../cocos/audio/ios/SimpleAudioEngine_objc.m | 38 +- native/cocos/audio/mac/CDAudioManager.h | 28 +- native/cocos/audio/mac/CDAudioManager.m | 342 +++++------ native/cocos/audio/mac/CDConfig.h | 19 +- native/cocos/audio/mac/CDOpenALSupport.h | 21 +- native/cocos/audio/mac/CDOpenALSupport.m | 80 +-- native/cocos/audio/mac/CDXMacOSXSupport.h | 99 ++- native/cocos/audio/mac/CDXMacOSXSupport.mm | 54 +- native/cocos/audio/mac/CocosDenshion.h | 69 ++- native/cocos/audio/mac/CocosDenshion.m | 531 ++++++++-------- native/cocos/audio/mac/SimpleAudioEngine.mm | 18 +- .../cocos/audio/mac/SimpleAudioEngine_objc.h | 14 +- .../cocos/audio/mac/SimpleAudioEngine_objc.m | 38 +- native/cocos/audio/win32/AudioCache.cpp | 570 +++++++++--------- native/cocos/audio/win32/AudioCache.h | 104 ++-- native/cocos/audio/win32/AudioDecoder.cpp | 91 +++ native/cocos/audio/win32/AudioDecoder.h | 119 ++++ .../cocos/audio/win32/AudioDecoderManager.cpp | 70 +++ .../cocos/audio/win32/AudioDecoderManager.h | 41 ++ native/cocos/audio/win32/AudioDecoderMp3.cpp | 183 ++++++ native/cocos/audio/win32/AudioDecoderMp3.h | 85 +++ native/cocos/audio/win32/AudioDecoderOgg.cpp | 86 +++ native/cocos/audio/win32/AudioDecoderOgg.h | 81 +++ .../cocos/audio/win32/AudioEngine-win32.cpp | 450 +++++++------- native/cocos/audio/win32/AudioEngine-win32.h | 18 +- native/cocos/audio/win32/AudioMacros.h | 71 +++ native/cocos/audio/win32/AudioPlayer.cpp | 499 +++++++-------- native/cocos/audio/win32/AudioPlayer.h | 39 +- native/cocos/audio/win32/MciPlayer.h | 11 +- .../cocos/audio/win32/SimpleAudioEngine.cpp | 25 +- native/cocos/network/Android.mk | 3 +- native/cocos/network/SocketIO.cpp | 179 +++--- native/cocos/network/SocketIO.h | 43 +- native/cocos/network/Uri.cpp | 377 ++++++++++++ native/cocos/network/Uri.h | 184 ++++++ native/cocos/network/WebSocket.cpp | 57 +- native/cocos/network/WebSocket.h | 6 +- .../org/cocos2dx/lib/Cocos2dxActivity.java | 3 + .../lib/Cocos2dxAudioFocusManager.java | 131 ++++ .../src/org/cocos2dx/lib/Cocos2dxHelper.java | 27 +- .../src/org/cocos2dx/lib/Cocos2dxMusic.java | 21 +- .../src/org/cocos2dx/lib/Cocos2dxSound.java | 177 +++--- .../platform/android/javaactivity-android.cpp | 39 +- .../manual/network/jsb_socketio.cpp | 69 ++- .../js-bindings/manual/network/jsb_socketio.h | 2 +- .../manual/network/jsb_websocket.cpp | 17 +- 115 files changed, 5389 insertions(+), 2620 deletions(-) create mode 100644 native/cocos/audio/android/AudioDecoderWav.cpp create mode 100644 native/cocos/audio/android/AudioDecoderWav.h create mode 100644 native/cocos/audio/android/tinysndfile.cpp create mode 100644 native/cocos/audio/android/tinysndfile.h create mode 100644 native/cocos/audio/win32/AudioDecoder.cpp create mode 100644 native/cocos/audio/win32/AudioDecoder.h create mode 100644 native/cocos/audio/win32/AudioDecoderManager.cpp create mode 100644 native/cocos/audio/win32/AudioDecoderManager.h create mode 100644 native/cocos/audio/win32/AudioDecoderMp3.cpp create mode 100644 native/cocos/audio/win32/AudioDecoderMp3.h create mode 100644 native/cocos/audio/win32/AudioDecoderOgg.cpp create mode 100644 native/cocos/audio/win32/AudioDecoderOgg.h create mode 100644 native/cocos/audio/win32/AudioMacros.h create mode 100644 native/cocos/network/Uri.cpp create mode 100644 native/cocos/network/Uri.h create mode 100644 native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxAudioFocusManager.java diff --git a/native/build/cocos2d_libs.xcodeproj/project.pbxproj b/native/build/cocos2d_libs.xcodeproj/project.pbxproj index 8b17c4e6b0..1c40d794b7 100644 --- a/native/build/cocos2d_libs.xcodeproj/project.pbxproj +++ b/native/build/cocos2d_libs.xcodeproj/project.pbxproj @@ -572,6 +572,10 @@ 1ABA68B11888D700007D1BB4 /* CCFontCharMap.h in Headers */ = {isa = PBXBuildFile; fileRef = 1ABA68AD1888D700007D1BB4 /* CCFontCharMap.h */; }; 1ACF6A3C1E4AFDC80033C137 /* libcrypto.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1ACF6A3A1E4AFDC80033C137 /* libcrypto.a */; }; 1ACF6A3D1E4AFDC80033C137 /* libssl.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1ACF6A3B1E4AFDC80033C137 /* libssl.a */; }; + 1AD473AC1EAD9A5200202582 /* Uri.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1AD473AA1EAD9A5200202582 /* Uri.cpp */; }; + 1AD473AD1EAD9A5300202582 /* Uri.h in Headers */ = {isa = PBXBuildFile; fileRef = 1AD473AB1EAD9A5200202582 /* Uri.h */; }; + 1AD473AE1EAD9A5600202582 /* Uri.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1AD473AA1EAD9A5200202582 /* Uri.cpp */; }; + 1AD473AF1EAD9A5900202582 /* Uri.h in Headers */ = {isa = PBXBuildFile; fileRef = 1AD473AB1EAD9A5200202582 /* Uri.h */; }; 291901431B05895600F8B4BA /* CCNinePatchImageParser.h in Headers */ = {isa = PBXBuildFile; fileRef = 291901411B05895600F8B4BA /* CCNinePatchImageParser.h */; }; 291901441B05895600F8B4BA /* CCNinePatchImageParser.h in Headers */ = {isa = PBXBuildFile; fileRef = 291901411B05895600F8B4BA /* CCNinePatchImageParser.h */; }; 291901451B05895600F8B4BA /* CCNinePatchImageParser.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 291901421B05895600F8B4BA /* CCNinePatchImageParser.cpp */; }; @@ -2080,6 +2084,8 @@ 1ABA68AD1888D700007D1BB4 /* CCFontCharMap.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCFontCharMap.h; sourceTree = ""; }; 1ACF6A3A1E4AFDC80033C137 /* libcrypto.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libcrypto.a; path = ../external/ios/libs/libcrypto.a; sourceTree = ""; }; 1ACF6A3B1E4AFDC80033C137 /* libssl.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libssl.a; path = ../external/ios/libs/libssl.a; sourceTree = ""; }; + 1AD473AA1EAD9A5200202582 /* Uri.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Uri.cpp; sourceTree = ""; }; + 1AD473AB1EAD9A5200202582 /* Uri.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Uri.h; sourceTree = ""; }; 1AD71CFA180E26E600808F54 /* CCBAnimationManager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCBAnimationManager.cpp; sourceTree = ""; }; 1AD71CFB180E26E600808F54 /* CCBAnimationManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCBAnimationManager.h; sourceTree = ""; }; 1AD71CFC180E26E600808F54 /* CCBFileLoader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCBFileLoader.cpp; sourceTree = ""; }; @@ -3535,6 +3541,8 @@ 1AAF5360180E3374000584C8 /* network */ = { isa = PBXGroup; children = ( + 1AD473AA1EAD9A5200202582 /* Uri.cpp */, + 1AD473AB1EAD9A5200202582 /* Uri.h */, 507003251B69820100E83DDD /* HttpClient */, 507003261B69820B00E83DDD /* SocketIO */, 507003271B69821300E83DDD /* WebSocket */, @@ -5298,6 +5306,7 @@ 50ABC0231926664800A911A9 /* CCGLViewImpl-desktop.h in Headers */, A63CF0081CD9CF3500A6971D /* CCUIPasswordTextField.h in Headers */, 15AE188D19AAD33D00C27E9E /* CCLabelBMFontLoader.h in Headers */, + 1AD473AD1EAD9A5300202582 /* Uri.h in Headers */, 4DED48521DFFA4AF0070C5C4 /* b2PolygonAndCircleContact.h in Headers */, 4DED48861DFFA4AF0070C5C4 /* b2WheelJoint.h in Headers */, 4DED485A1DFFA4AF0070C5C4 /* b2DistanceJoint.h in Headers */, @@ -5541,6 +5550,7 @@ 4DED48471DFFA4AF0070C5C4 /* b2ContactSolver.h in Headers */, 50ABBD3F1925AB0000A911A9 /* CCGeometry.h in Headers */, BAFF7CAB1D59E0DA0051B92F /* CCComBase.h in Headers */, + 1AD473AF1EAD9A5900202582 /* Uri.h in Headers */, BAFF7CBB1D59E0DB0051B92F /* CCDataReaderHelper.h in Headers */, BA68D7B51D62F66300B7A3F9 /* CCPass.h in Headers */, BAFF7C8D1D59E0DA0051B92F /* CCArmatureAnimation.h in Headers */, @@ -6103,6 +6113,7 @@ 1A5701B9180BCB5A0088DEC7 /* CCLabel.cpp in Sources */, 1A5701BD180BCB5A0088DEC7 /* CCLabelAtlas.cpp in Sources */, BA68D7B21D62F66300B7A3F9 /* CCPass.cpp in Sources */, + 1AD473AC1EAD9A5200202582 /* Uri.cpp in Sources */, 4DED48541DFFA4AF0070C5C4 /* b2PolygonContact.cpp in Sources */, BA68D78D1D62F4A500B7A3F9 /* sweep.cc in Sources */, 15AE1B5319AADA9900C27E9E /* UIRichText.cpp in Sources */, @@ -6555,6 +6566,7 @@ 1A57009F180BC5D20088DEC7 /* CCNode.cpp in Sources */, BA68D78A1D62F4A500B7A3F9 /* cdt.cc in Sources */, 1A57010F180BC8EE0088DEC7 /* CCDrawingPrimitives.cpp in Sources */, + 1AD473AE1EAD9A5600202582 /* Uri.cpp in Sources */, 1A570113180BC8EE0088DEC7 /* CCDrawNode.cpp in Sources */, 1A57011C180BC90D0088DEC7 /* CCGrabber.cpp in Sources */, 1A570120180BC90D0088DEC7 /* CCGrid.cpp in Sources */, diff --git a/native/cocos/audio/AudioEngine.cpp b/native/cocos/audio/AudioEngine.cpp index 7d3a76290f..2699c51bad 100644 --- a/native/cocos/audio/AudioEngine.cpp +++ b/native/cocos/audio/AudioEngine.cpp @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2014-2016 Chukong Technologies Inc. + Copyright (c) 2014-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -36,6 +36,12 @@ #include "audio/apple/AudioEngine-inl.h" #elif CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 #include "audio/win32/AudioEngine-win32.h" +#elif CC_TARGET_PLATFORM == CC_PLATFORM_WINRT +#include "audio/winrt/AudioEngine-winrt.h" +#elif CC_TARGET_PLATFORM == CC_PLATFORM_LINUX +#include "audio/linux/AudioEngine-linux.h" +#elif CC_TARGET_PLATFORM == CC_PLATFORM_TIZEN +#include "audio/tizen/AudioEngine-tizen.h" #endif #define TIME_DELAY_PRECISION 0.0001 @@ -61,20 +67,30 @@ AudioEngineImpl* AudioEngine::_audioEngineImpl = nullptr; AudioEngine::AudioEngineThreadPool* AudioEngine::s_threadPool = nullptr; +AudioEngine::AudioInfo::AudioInfo() +: filePath(nullptr) +, profileHelper(nullptr) +, volume(1.0f) +, loop(false) +, duration(TIME_UNKNOWN) +, state(AudioState::INITIALIZING) +{ + +} + +AudioEngine::AudioInfo::~AudioInfo() +{ +} + class AudioEngine::AudioEngineThreadPool { public: - AudioEngineThreadPool(bool detach, int threads = 4) - : _detach(detach) - , _stop(false) + AudioEngineThreadPool(int threads = 4) + : _stop(false) { for (int index = 0; index < threads; ++index) { _workers.emplace_back(std::thread(std::bind(&AudioEngineThreadPool::threadFunc, this))); - if (_detach) - { - _workers[index].detach(); - } } } @@ -92,11 +108,8 @@ public: _taskCondition.notify_all(); } - if (!_detach) - { - for (auto&& worker : _workers) { - worker.join(); - } + for (auto&& worker : _workers) { + worker.join(); } } @@ -132,7 +145,6 @@ private: std::mutex _queueMutex; std::condition_variable _taskCondition; - bool _detach; bool _stop; }; @@ -165,15 +177,10 @@ bool AudioEngine::lazyInit() } } -#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 +#if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) if (_audioEngineImpl && s_threadPool == nullptr) { - s_threadPool = new (std::nothrow) AudioEngineThreadPool(true); - } -#elif CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID - if (_audioEngineImpl && s_threadPool == nullptr) - { - s_threadPool = new (std::nothrow) AudioEngineThreadPool(false); + s_threadPool = new (std::nothrow) AudioEngineThreadPool(); } #endif @@ -199,7 +206,7 @@ int AudioEngine::play2d(const std::string& filePath, bool loop, float volume, co profileHelper = &_audioPathProfileHelperMap[profile->name]; profileHelper->profile = *profile; } - + if (_audioIDInfoMap.size() >= _maxInstances) { log("Fail to play %s cause by limited max instance of AudioEngine",filePath.c_str()); break; @@ -218,20 +225,20 @@ int AudioEngine::play2d(const std::string& filePath, bool loop, float volume, co } } } - + if (volume < 0.0f) { volume = 0.0f; } else if (volume > 1.0f){ volume = 1.0f; } - + ret = _audioEngineImpl->play2d(filePath, loop, volume); if (ret != INVALID_AUDIO_ID) { _audioPathIDMap[filePath].push_back(ret); auto it = _audioPathIDMap.find(filePath); - + auto& audioRef = _audioIDInfoMap[ret]; audioRef.volume = volume; audioRef.loop = loop; @@ -371,7 +378,7 @@ void AudioEngine::uncache(const std::string &filePath) for (int audioID : copiedIDs) { _audioEngineImpl->stop(audioID); - + auto itInfo = _audioIDInfoMap.find(audioID); if (itInfo != _audioIDInfoMap.end()) { @@ -385,15 +392,15 @@ void AudioEngine::uncache(const std::string &filePath) _audioPathIDMap.erase(filePath); } - if (_audioEngineImpl){ + if (_audioEngineImpl) + { _audioEngineImpl->uncache(filePath); } } void AudioEngine::uncacheAll() { - if (!_audioEngineImpl) - { + if(!_audioEngineImpl){ return; } stopAll(); @@ -403,7 +410,7 @@ void AudioEngine::uncacheAll() float AudioEngine::getDuration(int audioID) { auto it = _audioIDInfoMap.find(audioID); - if (it != _audioIDInfoMap.end() && it->second.state != AudioState::INITIALZING) + if (it != _audioIDInfoMap.end() && it->second.state != AudioState::INITIALIZING) { if (it->second.duration == TIME_UNKNOWN) { @@ -411,14 +418,14 @@ float AudioEngine::getDuration(int audioID) } return it->second.duration; } - + return TIME_UNKNOWN; } bool AudioEngine::setCurrentTime(int audioID, float time) { auto it = _audioIDInfoMap.find(audioID); - if (it != _audioIDInfoMap.end() && it->second.state != AudioState::INITIALZING){ + if (it != _audioIDInfoMap.end() && it->second.state != AudioState::INITIALIZING) { return _audioEngineImpl->setCurrentTime(audioID, time); } @@ -428,7 +435,7 @@ bool AudioEngine::setCurrentTime(int audioID, float time) float AudioEngine::getCurrentTime(int audioID) { auto it = _audioIDInfoMap.find(audioID); - if (it != _audioIDInfoMap.end() && it->second.state != AudioState::INITIALZING){ + if (it != _audioIDInfoMap.end() && it->second.state != AudioState::INITIALIZING) { return _audioEngineImpl->getCurrentTime(audioID); } return 0.0f; @@ -459,7 +466,7 @@ bool AudioEngine::isLoop(int audioID) { return tmpIterator->second.loop; } - + log("AudioEngine::isLoop-->The audio instance %d is non-existent", audioID); return false; } @@ -483,7 +490,7 @@ AudioEngine::AudioState AudioEngine::getState(int audioID) { return tmpIterator->second.state; } - + return AudioState::ERROR; } @@ -494,7 +501,7 @@ AudioProfile* AudioEngine::getProfile(int audioID) { return &it->second.profileHelper->profile; } - + return nullptr; } @@ -504,7 +511,7 @@ AudioProfile* AudioEngine::getDefaultProfile() { _defaultProfileHelper = new (std::nothrow) ProfileHelper(); } - + return &_defaultProfileHelper->profile; } diff --git a/native/cocos/audio/android/Android.mk b/native/cocos/audio/android/Android.mk index d5a4133ea1..cb048fdf84 100644 --- a/native/cocos/audio/android/Android.mk +++ b/native/cocos/audio/android/Android.mk @@ -16,6 +16,7 @@ LOCAL_SRC_FILES := AudioEngine-inl.cpp \ AudioDecoderSLES.cpp \ AudioDecoderOgg.cpp \ AudioDecoderMp3.cpp \ + AudioDecoderWav.cpp \ AudioPlayerProvider.cpp \ AudioResampler.cpp \ AudioResamplerCubic.cpp \ @@ -31,7 +32,8 @@ LOCAL_SRC_FILES := AudioEngine-inl.cpp \ audio_utils/minifloat.cpp \ audio_utils/primitives.c \ utils/Utils.cpp \ - mp3reader.cpp + mp3reader.cpp \ + tinysndfile.cpp LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../include diff --git a/native/cocos/audio/android/AssetFd.cpp b/native/cocos/audio/android/AssetFd.cpp index 88ab1bb857..ceb3fbd3a1 100644 --- a/native/cocos/audio/android/AssetFd.cpp +++ b/native/cocos/audio/android/AssetFd.cpp @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/android/AssetFd.h b/native/cocos/audio/android/AssetFd.h index 565568276a..f9d83d21d5 100644 --- a/native/cocos/audio/android/AssetFd.h +++ b/native/cocos/audio/android/AssetFd.h @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/android/AudioDecoder.cpp b/native/cocos/audio/android/AudioDecoder.cpp index e8e2bc96a1..b91432190f 100644 --- a/native/cocos/audio/android/AudioDecoder.cpp +++ b/native/cocos/audio/android/AudioDecoder.cpp @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -93,7 +93,7 @@ bool AudioDecoder::init(const std::string &url, int sampleRate) bool AudioDecoder::start() { auto oldTime = clockNow(); - + auto nowTime = oldTime; bool ret; do { @@ -103,23 +103,31 @@ bool AudioDecoder::start() ALOGE("decodeToPcm (%s) failed!", _url.c_str()); break; } + + nowTime = clockNow(); + ALOGD("Decoding (%s) to pcm data wasted %fms", _url.c_str(), intervalInMS(oldTime, nowTime)); + oldTime = nowTime; + ret = resample(); if (!ret) { ALOGE("resample (%s) failed!", _url.c_str()); break; } + + nowTime = clockNow(); + ALOGD("Resampling (%s) wasted %fms", _url.c_str(), intervalInMS(oldTime, nowTime)); + oldTime = nowTime; + ret = interleave(); if (!ret) { ALOGE("interleave (%s) failed!", _url.c_str()); break; } - - auto nowTime = clockNow(); - - ALOGV("Decoding (%s) to pcm data wasted %fms", _url.c_str(), - intervalInMS(oldTime, nowTime)); + + nowTime = clockNow(); + ALOGD("Interleave (%s) wasted %fms", _url.c_str(), intervalInMS(oldTime, nowTime)); } while(false); diff --git a/native/cocos/audio/android/AudioDecoder.h b/native/cocos/audio/android/AudioDecoder.h index d0024bf33b..23affd4961 100644 --- a/native/cocos/audio/android/AudioDecoder.h +++ b/native/cocos/audio/android/AudioDecoder.h @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/android/AudioDecoderMp3.cpp b/native/cocos/audio/android/AudioDecoderMp3.cpp index 6ac384f7fc..d88d2248df 100644 --- a/native/cocos/audio/android/AudioDecoderMp3.cpp +++ b/native/cocos/audio/android/AudioDecoderMp3.cpp @@ -1,3 +1,27 @@ +/**************************************************************************** +Copyright (c) 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 "AudioDecoderMp3" #include "audio/android/AudioDecoderMp3.h" @@ -33,20 +57,26 @@ bool AudioDecoderMp3::decodeToPcm() int numChannels = 0; int sampleRate = 0; int numFrames = 0; - decodeMP3(&callbacks, this, *_result.pcmBuffer, &numChannels, &sampleRate, &numFrames); + + if (EXIT_SUCCESS == decodeMP3(&callbacks, this, *_result.pcmBuffer, &numChannels, &sampleRate, &numFrames) + && numChannels > 0 && sampleRate > 0 && numFrames > 0) + { + _result.numChannels = numChannels; + _result.sampleRate = sampleRate; + _result.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; + _result.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; + _result.channelMask = numChannels == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT); + _result.endianness = SL_BYTEORDER_LITTLEENDIAN; + _result.numFrames = numFrames; + _result.duration = 1.0f * numFrames / sampleRate; - _result.numChannels = numChannels; - _result.sampleRate = sampleRate; - _result.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; - _result.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; - _result.channelMask = numChannels == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT); - _result.endianness = SL_BYTEORDER_LITTLEENDIAN; - _result.numFrames = numFrames; - _result.duration = 1.0f * numFrames / sampleRate; + std::string info = _result.toString(); + ALOGI("Original audio info: %s, total size: %d", info.c_str(), (int)_result.pcmBuffer->size()); + return true; + } - std::string info = _result.toString(); - ALOGI("Original audio info: %s, total size: %d", info.c_str(), (int)_result.pcmBuffer->size()); - return true; + ALOGE("Decode MP3 (%s) failed, channels: %d, rate: %d, frames: %d", _url.c_str(), numChannels, sampleRate, numFrames); + return false; } }} // namespace cocos2d { namespace experimental { \ No newline at end of file diff --git a/native/cocos/audio/android/AudioDecoderOgg.cpp b/native/cocos/audio/android/AudioDecoderOgg.cpp index 60e6b8e6fd..d928eb3a8c 100644 --- a/native/cocos/audio/android/AudioDecoderOgg.cpp +++ b/native/cocos/audio/android/AudioDecoderOgg.cpp @@ -1,3 +1,27 @@ +/**************************************************************************** +Copyright (c) 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 "AudioDecoderOgg" #include "audio/android/AudioDecoderOgg.h" @@ -46,35 +70,43 @@ bool AudioDecoderOgg::decodeToPcm() // header auto vi = ov_info(&vf, -1); - uint32_t uiPCMSamples = (uint32_t) ov_pcm_total(&vf, -1); + uint32_t pcmSamples = (uint32_t) ov_pcm_total(&vf, -1); - uint32_t bufferSize = uiPCMSamples * vi->channels * sizeof(short); - char* pvPCMBuffer = (char*)malloc(bufferSize); - memset(pvPCMBuffer, 0, bufferSize); + uint32_t bufferSize = pcmSamples * vi->channels * sizeof(short); + char* pcmBuffer = (char*)malloc(bufferSize); + memset(pcmBuffer, 0, bufferSize); int currentSection = 0; long curPos = 0; long readBytes = 0; - // decode - do { - readBytes = ov_read(&vf, pvPCMBuffer + curPos, 4096, ¤tSection); + + do + { + readBytes = ov_read(&vf, pcmBuffer + curPos, 4096, ¤tSection); curPos += readBytes; } while (readBytes > 0); - _result.pcmBuffer->insert(_result.pcmBuffer->end(), pvPCMBuffer, pvPCMBuffer + bufferSize); - _result.numChannels = vi->channels; - _result.sampleRate = vi->rate; - _result.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; - _result.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; - _result.channelMask = vi->channels == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT); - _result.endianness = SL_BYTEORDER_LITTLEENDIAN; - _result.numFrames = uiPCMSamples; - _result.duration = 1.0f * uiPCMSamples / vi->rate; + if (curPos > 0) + { + _result.pcmBuffer->insert(_result.pcmBuffer->end(), pcmBuffer, pcmBuffer + bufferSize); + _result.numChannels = vi->channels; + _result.sampleRate = vi->rate; + _result.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; + _result.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; + _result.channelMask = vi->channels == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT); + _result.endianness = SL_BYTEORDER_LITTLEENDIAN; + _result.numFrames = pcmSamples; + _result.duration = 1.0f * pcmSamples / vi->rate; + } + else + { + ALOGE("ov_read returns 0 byte!"); + } ov_clear(&vf); - free(pvPCMBuffer); + free(pcmBuffer); - return true; + return (curPos > 0); } }} // namespace cocos2d { namespace experimental { \ No newline at end of file diff --git a/native/cocos/audio/android/AudioDecoderProvider.cpp b/native/cocos/audio/android/AudioDecoderProvider.cpp index 606ac77ceb..56988cf07d 100644 --- a/native/cocos/audio/android/AudioDecoderProvider.cpp +++ b/native/cocos/audio/android/AudioDecoderProvider.cpp @@ -4,6 +4,7 @@ #include "audio/android/AudioDecoderSLES.h" #include "audio/android/AudioDecoderOgg.h" #include "audio/android/AudioDecoderMp3.h" +#include "audio/android/AudioDecoderWav.h" #include "platform/CCFileUtils.h" namespace cocos2d { namespace experimental { @@ -31,6 +32,15 @@ AudioDecoder* AudioDecoderProvider::createAudioDecoder(SLEngineItf engineItf, co decoder = nullptr; } } + else if (extension == ".wav") + { + decoder = new AudioDecoderWav(); + if (!decoder->init(url, sampleRate)) + { + delete decoder; + decoder = nullptr; + } + } else { auto slesDecoder = new AudioDecoderSLES(); diff --git a/native/cocos/audio/android/AudioDecoderSLES.cpp b/native/cocos/audio/android/AudioDecoderSLES.cpp index fcf8dd800d..b3c8e7630d 100644 --- a/native/cocos/audio/android/AudioDecoderSLES.cpp +++ b/native/cocos/audio/android/AudioDecoderSLES.cpp @@ -1,3 +1,27 @@ +/**************************************************************************** +Copyright (c) 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 "AudioDecoderSLES" #include "audio/android/AudioDecoderSLES.h" diff --git a/native/cocos/audio/android/AudioDecoderWav.cpp b/native/cocos/audio/android/AudioDecoderWav.cpp new file mode 100644 index 0000000000..37a7ceadc3 --- /dev/null +++ b/native/cocos/audio/android/AudioDecoderWav.cpp @@ -0,0 +1,111 @@ +/**************************************************************************** +Copyright (c) 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 "AudioDecoderWav" + +#include "audio/android/AudioDecoderWav.h" +#include "audio/android/tinysndfile.h" +#include "platform/CCFileUtils.h" + +namespace cocos2d { namespace experimental { + +AudioDecoderWav::AudioDecoderWav() +{ + ALOGV("Create AudioDecoderWav"); +} + +AudioDecoderWav::~AudioDecoderWav() +{ + +} + +void* AudioDecoderWav::onWavOpen(const char* path, void* user) +{ + return user; +} + +int AudioDecoderWav::onWavSeek(void* datasource, long offset, int whence) +{ + return AudioDecoder::fileSeek(datasource, (int64_t) offset, whence); +} + +int AudioDecoderWav::onWavClose(void* datasource) +{ +} + +bool AudioDecoderWav::decodeToPcm() +{ + _fileData = FileUtils::getInstance()->getDataFromFile(_url); + if (_fileData.isNull()) + { + return false; + } + + SF_INFO info; + + snd_callbacks cb; + cb.open = onWavOpen; + cb.read = AudioDecoder::fileRead; + cb.seek = onWavSeek; + cb.close = onWavClose; + cb.tell = AudioDecoder::fileTell; + + SNDFILE* handle = NULL; + bool ret = false; + do + { + handle = sf_open_read(_url.c_str(), &info, &cb, this); + if (handle == nullptr) + break; + + if (info.frames == 0) + break; + + ALOGD("wav info: frames: %d, samplerate: %d, channels: %d, format: %d", info.frames, info.samplerate, info.channels, info.format); + size_t bufSize = sizeof(short) * info.frames * info.channels; + unsigned char* buf = (unsigned char*)malloc(bufSize); + sf_count_t readFrames = sf_readf_short(handle, (short*)buf, info.frames); + assert(readFrames == info.frames); + + _result.pcmBuffer->insert(_result.pcmBuffer->end(), buf, buf + bufSize); + _result.numChannels = info.channels; + _result.sampleRate = info.samplerate; + _result.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; + _result.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; + _result.channelMask = _result.numChannels == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT); + _result.endianness = SL_BYTEORDER_LITTLEENDIAN; + _result.numFrames = info.frames; + _result.duration = 1.0f * info.frames / _result.sampleRate; + + free(buf); + ret = true; + } while (false); + + if (handle != NULL) + sf_close(handle); + + return ret; +} + +}} // namespace cocos2d { namespace experimental { \ No newline at end of file diff --git a/native/cocos/audio/android/AudioDecoderWav.h b/native/cocos/audio/android/AudioDecoderWav.h new file mode 100644 index 0000000000..328babd2ef --- /dev/null +++ b/native/cocos/audio/android/AudioDecoderWav.h @@ -0,0 +1,46 @@ +/**************************************************************************** +Copyright (c) 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. +****************************************************************************/ + +#pragma once + +#include "audio/android/AudioDecoder.h" + +namespace cocos2d { namespace experimental { + +class AudioDecoderWav : public AudioDecoder +{ +protected: + AudioDecoderWav(); + virtual ~AudioDecoderWav(); + + virtual bool decodeToPcm() override; + + static void* onWavOpen(const char* path, void* user); + static int onWavSeek(void* datasource, long offset, int whence); + static int onWavClose(void* datasource); + + friend class AudioDecoderProvider; +}; + +}} // namespace cocos2d { namespace experimental { \ No newline at end of file diff --git a/native/cocos/audio/android/AudioEngine-inl.cpp b/native/cocos/audio/android/AudioEngine-inl.cpp index 22a1da2a69..56622bdf30 100644 --- a/native/cocos/audio/android/AudioEngine-inl.cpp +++ b/native/cocos/audio/android/AudioEngine-inl.cpp @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2014-2016 Chukong Technologies Inc. + Copyright (c) 2014-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -23,8 +23,6 @@ ****************************************************************************/ #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID -#define LOG_TAG "cocos2d-x debug info" - #include "audio/android/AudioEngine-inl.h" #include @@ -43,6 +41,7 @@ #include "base/CCEventDispatcher.h" #include "base/CCEventType.h" #include "base/CCEventListenerCustom.h" +#include "base/ccUTF8.h" #include "platform/android/CCFileUtils-android.h" #include "platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h" @@ -55,8 +54,14 @@ using namespace cocos2d; using namespace cocos2d::experimental; -#define DELAY_TIME_TO_REMOVE 0.5f +// Audio focus values synchronized with which in cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java +static const int AUDIOFOCUS_GAIN = 0; +static const int AUDIOFOCUS_LOST = 1; +static const int AUDIOFOCUS_LOST_TRANSIENT = 2; +static const int AUDIOFOCUS_LOST_TRANSIENT_CAN_DUCK = 3; +static int __currentAudioFocus = AUDIOFOCUS_GAIN; +static AudioEngineImpl* __impl = nullptr; class CallerThreadUtils : public ICallerThreadUtils { @@ -107,16 +112,17 @@ static int fdGetter(const std::string& url, off_t* start, off_t* length) //==================================================== AudioEngineImpl::AudioEngineImpl() - : _audioIDIndex(0) - , _engineObject(nullptr) + : _engineObject(nullptr) , _engineEngine(nullptr) , _outputMixObject(nullptr) - , _lazyInitLoop(true) , _audioPlayerProvider(nullptr) , _onPauseListener(nullptr) , _onResumeListener(nullptr) + , _audioIDIndex(0) + , _lazyInitLoop(true) { __callerThreadUtils.setCallerThreadId(std::this_thread::get_id()); + __impl = this; } AudioEngineImpl::~AudioEngineImpl() @@ -145,6 +151,8 @@ AudioEngineImpl::~AudioEngineImpl() { Director::getInstance()->getEventDispatcher()->removeEventListener(_onResumeListener); } + + __impl = nullptr; } bool AudioEngineImpl::init() @@ -225,6 +233,14 @@ void AudioEngineImpl::onEnterForeground(EventCustom* event) _urlAudioPlayersNeedResume.clear(); } +void AudioEngineImpl::setAudioFocusForAllPlayers(bool isFocus) +{ + for (const auto& e : _audioPlayers) + { + e.second->setAudioFocus(isFocus); + } +} + int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume) { ALOGV("play2d, _audioPlayers.size=%d", (int)_audioPlayers.size()); @@ -254,24 +270,27 @@ int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume } int id = player->getId(); + std::string filePath = *AudioEngine::_audioIDInfoMap[id].filePath; ALOGV("Removing player id=%d, state:%d", id, (int)state); + AudioEngine::remove(id); + _audioPlayers.erase(id); + auto iter = _callbackMap.find(id); if (iter != _callbackMap.end()) { if (state == IAudioPlayer::State::OVER) { - iter->second(id, *AudioEngine::_audioIDInfoMap[id].filePath); + iter->second(id, filePath); } _callbackMap.erase(iter); } - AudioEngine::remove(id); - _audioPlayers.erase(id); }); player->setLoop(loop); player->setVolume(volume); + player->setAudioFocus(__currentAudioFocus == AUDIOFOCUS_GAIN); player->play(); } else @@ -437,4 +456,31 @@ void AudioEngineImpl::uncacheAll() } } +// It's invoked from javaactivity-android.cpp +void cocos_audioengine_focus_change(int focusChange) +{ + if (focusChange < AUDIOFOCUS_GAIN || focusChange > AUDIOFOCUS_LOST_TRANSIENT_CAN_DUCK) + { + CCLOGERROR("cocos_audioengine_focus_change: unknown value: %d", focusChange); + return; + } + CCLOG("cocos_audioengine_focus_change: %d", focusChange); + __currentAudioFocus = focusChange; + + if (__impl == nullptr) + { + CCLOGWARN("cocos_audioengine_focus_change: AudioEngineImpl isn't ready!"); + return; + } + + if (__currentAudioFocus == AUDIOFOCUS_GAIN) + { + __impl->setAudioFocusForAllPlayers(true); + } + else + { + __impl->setAudioFocusForAllPlayers(false); + } +} + #endif diff --git a/native/cocos/audio/android/AudioEngine-inl.h b/native/cocos/audio/android/AudioEngine-inl.h index 620f1fbe30..bec699dbae 100644 --- a/native/cocos/audio/android/AudioEngine-inl.h +++ b/native/cocos/audio/android/AudioEngine-inl.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2014-2016 Chukong Technologies Inc. + Copyright (c) 2014-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -72,6 +72,7 @@ public: void uncacheAll(); void preload(const std::string& filePath, const std::function& callback); + void setAudioFocusForAllPlayers(bool isFocus); private: void onEnterBackground(EventCustom* event); diff --git a/native/cocos/audio/android/AudioMixerController.cpp b/native/cocos/audio/android/AudioMixerController.cpp index 1e46af338d..40aeed4ec0 100644 --- a/native/cocos/audio/android/AudioMixerController.cpp +++ b/native/cocos/audio/android/AudioMixerController.cpp @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/android/AudioMixerController.h b/native/cocos/audio/android/AudioMixerController.h index bb4915641b..290b688c36 100644 --- a/native/cocos/audio/android/AudioMixerController.h +++ b/native/cocos/audio/android/AudioMixerController.h @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/android/AudioPlayerProvider.cpp b/native/cocos/audio/android/AudioPlayerProvider.cpp index 5a750594eb..0027cdf2af 100644 --- a/native/cocos/audio/android/AudioPlayerProvider.cpp +++ b/native/cocos/audio/android/AudioPlayerProvider.cpp @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -147,21 +147,23 @@ IAudioPlayer *AudioPlayerProvider::getAudioPlayer(const std::string &audioFilePa auto pcmData = std::make_shared(); auto isSucceed = std::make_shared(false); auto isReturnFromCache = std::make_shared(false); + auto isPreloadFinished = std::make_shared(false); std::thread::id threadId = std::this_thread::get_id(); void* infoPtr = &info; std::string url = info.url; - preloadEffect(info, [infoPtr, url, threadId, pcmData, isSucceed, isReturnFromCache](bool succeed, PcmData data){ + preloadEffect(info, [infoPtr, url, threadId, pcmData, isSucceed, isReturnFromCache, isPreloadFinished](bool succeed, PcmData data){ // If the callback is in the same thread as caller's, it means that we found it // in the cache *isReturnFromCache = std::this_thread::get_id() == threadId; *pcmData = data; *isSucceed = succeed; + *isPreloadFinished = true; ALOGV("FileInfo (%p), Set isSucceed flag: %d, path: %s", infoPtr, succeed, url.c_str()); }, true); - if (!*isReturnFromCache) + if (!*isReturnFromCache && !*isPreloadFinished) { std::unique_lock lk(_preloadWaitMutex); // Wait for 2 seconds for the decoding in sub thread finishes. @@ -272,11 +274,12 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload ALOGV("audio (%s) is being preloaded, add to callback vector!", audioFilePath.c_str()); PreloadCallbackParam param; param.callback = cb; + param.isPreloadInPlay2d = isPreloadInPlay2d; preloadIter->second.push_back(std::move(param)); return; } - // 3. Check it in cache again. If it has been removed from map just now, the file is in + // 3. Check it in cache again. If it has been removed from map just now, the file is in // the cache absolutely. _pcmCacheMutex.lock(); auto&& iter = _pcmCache.find(audioFilePath); @@ -289,15 +292,15 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload } _pcmCacheMutex.unlock(); - PreloadCallbackParam param; param.callback = cb; + param.isPreloadInPlay2d = isPreloadInPlay2d; std::vector callbacks; callbacks.push_back(std::move(param)); _preloadCallbackMap.insert(std::make_pair(audioFilePath, std::move(callbacks))); } - _threadPool->pushTask([this, audioFilePath, isPreloadInPlay2d](int tid) { + _threadPool->pushTask([this, audioFilePath](int tid) { ALOGV("AudioPlayerProvider::preloadEffect: (%s)", audioFilePath.c_str()); PcmData d; AudioDecoder* decoder = AudioDecoderProvider::createAudioDecoder(_engineItf, audioFilePath, _bufferSizeInFrames, _deviceSampleRate, _fdGetterCallback); @@ -325,13 +328,12 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload for (auto&& param : params) { param.callback(ret, result); + if (param.isPreloadInPlay2d) + { + _preloadWaitCond.notify_one(); + } } _preloadCallbackMap.erase(preloadIter); - - if (isPreloadInPlay2d) - { - _preloadWaitCond.notify_one(); - } } AudioDecoderProvider::destroyAudioDecoder(&decoder); diff --git a/native/cocos/audio/android/AudioPlayerProvider.h b/native/cocos/audio/android/AudioPlayerProvider.h index 2392a069e5..ae5e0d6872 100644 --- a/native/cocos/audio/android/AudioPlayerProvider.h +++ b/native/cocos/audio/android/AudioPlayerProvider.h @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -108,6 +108,7 @@ private: struct PreloadCallbackParam { PreloadCallback callback; + bool isPreloadInPlay2d; }; std::unordered_map> _preloadCallbackMap; diff --git a/native/cocos/audio/android/CCThreadPool.cpp b/native/cocos/audio/android/CCThreadPool.cpp index 23c483787c..6f5cbe6895 100644 --- a/native/cocos/audio/android/CCThreadPool.cpp +++ b/native/cocos/audio/android/CCThreadPool.cpp @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2016 Chukong Technologies Inc. + Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -102,7 +102,7 @@ ThreadPool *ThreadPool::newSingleThreadPool() } ThreadPool::ThreadPool(int minNum, int maxNum) - : _isStop(false), _isDone(false), _idleThreadNum(0), _minThreadNum(minNum), + : _isDone(false), _isStop(false), _idleThreadNum(0), _minThreadNum(minNum), _maxThreadNum(maxNum), _initedThreadNum(0), _shrinkInterval(DEFAULT_SHRINK_INTERVAL), _shrinkStep(DEFAULT_SHRINK_STEP), _stretchStep(DEFAULT_STRETCH_STEP), _isFixedSize(false) diff --git a/native/cocos/audio/android/CCThreadPool.h b/native/cocos/audio/android/CCThreadPool.h index 143e1c8791..5498bbfd9f 100644 --- a/native/cocos/audio/android/CCThreadPool.h +++ b/native/cocos/audio/android/CCThreadPool.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2016 Chukong Technologies Inc. + Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/android/IAudioPlayer.h b/native/cocos/audio/android/IAudioPlayer.h index fc3cec37b5..d5cd1cca24 100644 --- a/native/cocos/audio/android/IAudioPlayer.h +++ b/native/cocos/audio/android/IAudioPlayer.h @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -68,6 +68,8 @@ public: virtual float getVolume() const = 0; + virtual void setAudioFocus(bool isFocus) = 0; + virtual void setLoop(bool isLoop) = 0; virtual bool isLoop() const = 0; diff --git a/native/cocos/audio/android/ICallerThreadUtils.h b/native/cocos/audio/android/ICallerThreadUtils.h index 0df795c762..cec4f62516 100644 --- a/native/cocos/audio/android/ICallerThreadUtils.h +++ b/native/cocos/audio/android/ICallerThreadUtils.h @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/android/IVolumeProvider.h b/native/cocos/audio/android/IVolumeProvider.h index a4b246858e..e76c6c48df 100644 --- a/native/cocos/audio/android/IVolumeProvider.h +++ b/native/cocos/audio/android/IVolumeProvider.h @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/android/OpenSLHelper.h b/native/cocos/audio/android/OpenSLHelper.h index e02a598c99..aec8513b19 100644 --- a/native/cocos/audio/android/OpenSLHelper.h +++ b/native/cocos/audio/android/OpenSLHelper.h @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/android/PcmAudioPlayer.cpp b/native/cocos/audio/android/PcmAudioPlayer.cpp index dd39707a60..30ae4c5522 100644 --- a/native/cocos/audio/android/PcmAudioPlayer.cpp +++ b/native/cocos/audio/android/PcmAudioPlayer.cpp @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -110,6 +110,11 @@ float PcmAudioPlayer::getVolume() const return _track->getVolume(); } +void PcmAudioPlayer::setAudioFocus(bool isFocus) +{ + _track->setAudioFocus(isFocus); +} + void PcmAudioPlayer::setLoop(bool isLoop) { _track->setLoop(isLoop); diff --git a/native/cocos/audio/android/PcmAudioPlayer.h b/native/cocos/audio/android/PcmAudioPlayer.h index 0a25e22ced..b55f6dc51d 100644 --- a/native/cocos/audio/android/PcmAudioPlayer.h +++ b/native/cocos/audio/android/PcmAudioPlayer.h @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -62,6 +62,8 @@ public: virtual float getVolume() const override; + virtual void setAudioFocus(bool isFocus) override; + virtual void setLoop(bool isLoop) override; virtual bool isLoop() const override; diff --git a/native/cocos/audio/android/PcmAudioService.cpp b/native/cocos/audio/android/PcmAudioService.cpp index 2c63a6c731..25afef5f04 100644 --- a/native/cocos/audio/android/PcmAudioService.cpp +++ b/native/cocos/audio/android/PcmAudioService.cpp @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/android/PcmAudioService.h b/native/cocos/audio/android/PcmAudioService.h index 4b1af44427..2e83e26650 100644 --- a/native/cocos/audio/android/PcmAudioService.h +++ b/native/cocos/audio/android/PcmAudioService.h @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/android/PcmBufferProvider.cpp b/native/cocos/audio/android/PcmBufferProvider.cpp index c2174d6543..a5f55b8162 100644 --- a/native/cocos/audio/android/PcmBufferProvider.cpp +++ b/native/cocos/audio/android/PcmBufferProvider.cpp @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/android/PcmBufferProvider.h b/native/cocos/audio/android/PcmBufferProvider.h index 2caaea93e0..45bbe93f5a 100644 --- a/native/cocos/audio/android/PcmBufferProvider.h +++ b/native/cocos/audio/android/PcmBufferProvider.h @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/android/PcmData.cpp b/native/cocos/audio/android/PcmData.cpp index fc5be4462e..add468e436 100644 --- a/native/cocos/audio/android/PcmData.cpp +++ b/native/cocos/audio/android/PcmData.cpp @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/android/PcmData.h b/native/cocos/audio/android/PcmData.h index 89c7207838..4457b8d31c 100644 --- a/native/cocos/audio/android/PcmData.h +++ b/native/cocos/audio/android/PcmData.h @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/android/Track.cpp b/native/cocos/audio/android/Track.cpp index da06da5df9..f94faec578 100644 --- a/native/cocos/audio/android/Track.cpp +++ b/native/cocos/audio/android/Track.cpp @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -41,6 +41,7 @@ Track::Track(const PcmData &pcmData) , _isVolumeDirty(true) , _isLoop(false) , _isInitialized(false) + , _isAudioFocus(true) { init(_pcmData.pcmBuffer->data(), _pcmData.numFrames, _pcmData.bitsPerSample / 8 * _pcmData.numChannels); } @@ -52,7 +53,8 @@ Track::~Track() gain_minifloat_packed_t Track::getVolumeLR() { - gain_minifloat_t v = gain_from_float(_volume); + float volume = _isAudioFocus ? _volume : 0.0f; + gain_minifloat_t v = gain_from_float(volume); return gain_minifloat_pack(v, v); } @@ -83,6 +85,12 @@ float Track::getVolume() const return _volume; } +void Track::setAudioFocus(bool isFocus) +{ + _isAudioFocus = isFocus; + setVolumeDirty(true); +} + void Track::setState(State state) { std::lock_guard lk(_stateMutex); diff --git a/native/cocos/audio/android/Track.h b/native/cocos/audio/android/Track.h index 9d69b91c70..c9a559fd57 100644 --- a/native/cocos/audio/android/Track.h +++ b/native/cocos/audio/android/Track.h @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -62,6 +62,8 @@ public: void setVolume(float volume); float getVolume() const; + void setAudioFocus(bool isFocus); + bool setPosition(float pos); float getPosition() const; @@ -96,6 +98,7 @@ private: std::mutex _volumeDirtyMutex; bool _isLoop; bool _isInitialized; + bool _isAudioFocus; friend class AudioMixerController; }; diff --git a/native/cocos/audio/android/UrlAudioPlayer.cpp b/native/cocos/audio/android/UrlAudioPlayer.cpp index 54bbafc1f1..c6f01b826c 100644 --- a/native/cocos/audio/android/UrlAudioPlayer.cpp +++ b/native/cocos/audio/android/UrlAudioPlayer.cpp @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -60,7 +60,7 @@ UrlAudioPlayer::UrlAudioPlayer(SLEngineItf engineItf, SLObjectItf outputMixObjec : _engineItf(engineItf), _outputMixObj(outputMixObject), _callerThreadUtils(callerThreadUtils), _id(-1), _assetFd(nullptr), _playObj(nullptr), _playItf(nullptr), _seekItf(nullptr), _volumeItf(nullptr), - _volume(0.0f), _duration(0.0f), _isLoop(false), _state(State::INVALID), + _volume(0.0f), _duration(0.0f), _isLoop(false), _isAudioFocus(true), _state(State::INVALID), _playEventCallback(nullptr), _isDestroyed(std::make_shared(false)) { std::call_once(__onceFlag, [](){ @@ -215,16 +215,36 @@ void UrlAudioPlayer::play() } } -void UrlAudioPlayer::setVolume(float volume) +void UrlAudioPlayer::setVolumeToSLPlayer(float volume) { - _volume = volume; int dbVolume = 2000 * log10(volume); if (dbVolume < SL_MILLIBEL_MIN) { dbVolume = SL_MILLIBEL_MIN; } SLresult r = (*_volumeItf)->SetVolumeLevel(_volumeItf, dbVolume); - SL_RETURN_IF_FAILED(r, "UrlAudioPlayer::setVolume %d failed", dbVolume); + SL_RETURN_IF_FAILED(r, "UrlAudioPlayer::setVolumeToSLPlayer %d failed", dbVolume); +} + +void UrlAudioPlayer::setVolume(float volume) +{ + _volume = volume; + if (_isAudioFocus) + { + setVolumeToSLPlayer(_volume); + } +} + +float UrlAudioPlayer::getVolume() const +{ + return _volume; +} + +void UrlAudioPlayer::setAudioFocus(bool isFocus) +{ + _isAudioFocus = isFocus; + float volume = _isAudioFocus ? _volume : 0.0f; + setVolumeToSLPlayer(volume); } float UrlAudioPlayer::getDuration() const @@ -362,11 +382,6 @@ void UrlAudioPlayer::rewind() // Not supported currently. since cocos audio engine will new -> prepare -> play again. } -float UrlAudioPlayer::getVolume() const -{ - return _volume; -} - void UrlAudioPlayer::setLoop(bool isLoop) { _isLoop = isLoop; diff --git a/native/cocos/audio/android/UrlAudioPlayer.h b/native/cocos/audio/android/UrlAudioPlayer.h index bf91772c4f..0ac1ca8907 100644 --- a/native/cocos/audio/android/UrlAudioPlayer.h +++ b/native/cocos/audio/android/UrlAudioPlayer.h @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -68,6 +68,8 @@ public: virtual float getVolume() const override; + virtual void setAudioFocus(bool isFocus) override; + virtual void setLoop(bool isLoop) override; virtual bool isLoop() const override; @@ -97,6 +99,8 @@ private: void playEventCallback(SLPlayItf caller, SLuint32 playEvent); + void setVolumeToSLPlayer(float volume); + private: SLEngineItf _engineItf; SLObjectItf _outputMixObj; @@ -115,6 +119,7 @@ private: float _volume; float _duration; bool _isLoop; + bool _isAudioFocus; State _state; PlayEventCallback _playEventCallback; diff --git a/native/cocos/audio/android/audio.h b/native/cocos/audio/android/audio.h index bc6219902c..d0be20d861 100644 --- a/native/cocos/audio/android/audio.h +++ b/native/cocos/audio/android/audio.h @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/android/ccdandroidUtils.cpp b/native/cocos/audio/android/ccdandroidUtils.cpp index e01ad51586..1bcd0a2d8a 100644 --- a/native/cocos/audio/android/ccdandroidUtils.cpp +++ b/native/cocos/audio/android/ccdandroidUtils.cpp @@ -1,6 +1,6 @@ /**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2013-2016 Chukong Technologies Inc. +Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/android/ccdandroidUtils.h b/native/cocos/audio/android/ccdandroidUtils.h index 79106952f4..1424f2e449 100644 --- a/native/cocos/audio/android/ccdandroidUtils.h +++ b/native/cocos/audio/android/ccdandroidUtils.h @@ -1,6 +1,6 @@ /**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2013-2016 Chukong Technologies Inc. +Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/android/cddSimpleAudioEngine.cpp b/native/cocos/audio/android/cddSimpleAudioEngine.cpp index 169338099f..d4cbb12bb9 100644 --- a/native/cocos/audio/android/cddSimpleAudioEngine.cpp +++ b/native/cocos/audio/android/cddSimpleAudioEngine.cpp @@ -1,6 +1,6 @@ /**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2013-2016 Chukong Technologies Inc. +Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/android/jni/cddandroidAndroidJavaEngine.cpp b/native/cocos/audio/android/jni/cddandroidAndroidJavaEngine.cpp index 6333f629ce..4fbd5b1459 100644 --- a/native/cocos/audio/android/jni/cddandroidAndroidJavaEngine.cpp +++ b/native/cocos/audio/android/jni/cddandroidAndroidJavaEngine.cpp @@ -1,6 +1,6 @@ /**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2013-2016 Chukong Technologies Inc. +Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -271,6 +271,10 @@ void AndroidJavaEngine::preloadEffect(const char* filePath) std::string fullPath = CocosDenshion::android::getFullPathWithoutAssetsPrefix(filePath); JniHelper::callStaticVoidMethod(helperClassName, "preloadEffect", fullPath); } + else + { + AudioEngine::preload(filePath); + } } void AndroidJavaEngine::unloadEffect(const char* filePath) @@ -280,4 +284,8 @@ void AndroidJavaEngine::unloadEffect(const char* filePath) std::string fullPath = CocosDenshion::android::getFullPathWithoutAssetsPrefix(filePath); JniHelper::callStaticVoidMethod(helperClassName, "unloadEffect", fullPath); } + else + { + AudioEngine::uncache(filePath); + } } diff --git a/native/cocos/audio/android/jni/cddandroidAndroidJavaEngine.h b/native/cocos/audio/android/jni/cddandroidAndroidJavaEngine.h index 8329002595..76869d6edc 100644 --- a/native/cocos/audio/android/jni/cddandroidAndroidJavaEngine.h +++ b/native/cocos/audio/android/jni/cddandroidAndroidJavaEngine.h @@ -1,6 +1,6 @@ /**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2013-2016 Chukong Technologies Inc. +Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/android/mp3reader.cpp b/native/cocos/audio/android/mp3reader.cpp index eacee02c17..9388d843d8 100644 --- a/native/cocos/audio/android/mp3reader.cpp +++ b/native/cocos/audio/android/mp3reader.cpp @@ -26,6 +26,8 @@ * SUCH DAMAGE. */ +#define LOG_TAG "mp3reader" + #include #include #include @@ -34,7 +36,7 @@ #include "audio/android/cutils/log.h" #include "pvmp3decoder_api.h" -#include "mp3reader.h" +#include "audio/android/mp3reader.h" using namespace std; @@ -239,6 +241,9 @@ static bool resync( len += 10; *inout_pos += len; + + ALOGV("skipped ID3 tag, new starting offset is %lld (0x%016llx)", + (long long)*inout_pos, (long long)*inout_pos); } } @@ -256,8 +261,9 @@ static bool resync( uint8_t *tmp = buf; do { - if (pos >= *inout_pos + kMaxBytesChecked) { + if (pos >= (off64_t)(*inout_pos + kMaxBytesChecked)) { // Don't scan forever. + ALOGV("giving up at offset %lld", (long long)pos); break; } @@ -306,6 +312,7 @@ static bool resync( continue; } + // ALOGV("found possible 1st frame at %lld (header = 0x%08x)", (long long)pos, header); // We found what looks like a valid frame, // now find its successors. @@ -323,6 +330,8 @@ static bool resync( uint32_t test_header = U32_AT(tmp); + ALOGV("subsequent header is %08x", test_header); + if ((test_header & kMask) != (header & kMask)) { valid = false; break; @@ -334,6 +343,7 @@ static bool resync( break; } + ALOGV("found subsequent frame #%d at %lld", j + 2, (long long)test_pos); test_pos += test_frame_size; } @@ -343,6 +353,8 @@ static bool resync( if (out_header != NULL) { *out_header = header; } + } else { + ALOGV("no dice, no valid sequence of frames found."); } ++pos; @@ -369,7 +381,11 @@ bool Mp3Reader::init(mp3_callbacks *callback, void* source) { off64_t pos = 0; uint32_t header; bool success = resync(callback, source, 0 /*match_header*/, &pos, &header); - if (success == false) return false; + if (!success) + { + ALOGE("%s, resync failed", __FUNCTION__); + return false; + } mCurrentPos = pos; mFixedHeader = header; @@ -455,7 +471,7 @@ int decodeMP3(mp3_callbacks* cb, void* source, std::vector& pcmBuffer, int Mp3Reader mp3Reader; bool success = mp3Reader.init(cb, source); if (!success) { - fprintf(stderr, "Encountered error reading\n"); + ALOGE("mp3Reader.init: Encountered error reading\n"); free(decoderBuf); return EXIT_FAILURE; } @@ -468,7 +484,7 @@ int decodeMP3(mp3_callbacks* cb, void* source, std::vector& pcmBuffer, int // sfInfo.samplerate = mp3Reader.getSampleRate(); // SNDFILE *handle = sf_open(argv[2], SFM_WRITE, &sfInfo); // if (handle == NULL) { - // fprintf(stderr, "Encountered error writing %s\n", argv[2]); + // ALOGE("Encountered error writing %s\n", argv[2]); // mp3Reader.close(); // free(decoderBuf); // return EXIT_FAILURE; @@ -504,7 +520,7 @@ int decodeMP3(mp3_callbacks* cb, void* source, std::vector& pcmBuffer, int ERROR_CODE decoderErr; decoderErr = pvmp3_framedecoder(&config, decoderBuf); if (decoderErr != NO_DECODING_ERROR) { - fprintf(stderr, "Decoder encountered error\n"); + ALOGE("Decoder encountered error=%d", decoderErr); retVal = EXIT_FAILURE; break; } diff --git a/native/cocos/audio/android/tinysndfile.cpp b/native/cocos/audio/android/tinysndfile.cpp new file mode 100644 index 0000000000..a7b66300f0 --- /dev/null +++ b/native/cocos/audio/android/tinysndfile.cpp @@ -0,0 +1,518 @@ +/* + * Copyright (C) 2012 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define LOG_TAG "tinysndfile" + +#include "audio/android/tinysndfile.h" +#include "audio/android/audio_utils/include/audio_utils/primitives.h" +#include "audio/android/cutils/log.h" + +// #ifdef HAVE_STDERR +// #include +// #endif + +#include +#include + +#ifndef HAVE_STDERR +#define HAVE_STDERR +#endif + +#define WAVE_FORMAT_PCM 1 +#define WAVE_FORMAT_IEEE_FLOAT 3 +#define WAVE_FORMAT_EXTENSIBLE 0xFFFE + +static snd_callbacks __defaultCallback; +static int __inited = 0; + +struct SNDFILE_ { + uint8_t *temp; // realloc buffer used for shrinking 16 bits to 8 bits and byte-swapping + void *stream; + size_t bytesPerFrame; + size_t remaining; // frames unread for SFM_READ, frames written for SFM_WRITE + SF_INFO info; + snd_callbacks callback; +}; + +static unsigned little2u(unsigned char *ptr) +{ + return (ptr[1] << 8) + ptr[0]; +} + +static unsigned little4u(unsigned char *ptr) +{ + return (ptr[3] << 24) + (ptr[2] << 16) + (ptr[1] << 8) + ptr[0]; +} + +static int isLittleEndian(void) +{ + static const short one = 1; + return *((const char *) &one) == 1; +} + +// "swab" conflicts with OS X +static void my_swab(short *ptr, size_t numToSwap) +{ + while (numToSwap > 0) { + *ptr = little2u((unsigned char *) ptr); + --numToSwap; + ++ptr; + } +} + +static void* open_func(const char* path, void* user) +{ + return fopen(path, "rb"); +} + +static size_t read_func(void *ptr, size_t size, size_t nmemb, void* datasource) +{ + return fread(ptr, size, nmemb, (FILE*)datasource); +} + +static int seek_func(void* datasource, long offset, int whence) +{ + return fseek((FILE*)datasource, offset, whence); +} + +static int close_func(void* datasource) +{ + return fclose((FILE*)datasource); +} + +static long tell_func(void* datasource) +{ + return ftell((FILE*)datasource); +} + +static void lazyInit() +{ + if (__inited == 0) + { + __defaultCallback.open = open_func; + __defaultCallback.read = read_func; + __defaultCallback.seek = seek_func; + __defaultCallback.close = close_func; + __defaultCallback.tell = tell_func; + __inited = 1; + } +} + +SNDFILE *sf_open_read(const char *path, SF_INFO *info, snd_callbacks* cb, void* user) +{ + lazyInit(); + + if (path == NULL || info == NULL) { +#ifdef HAVE_STDERR + ALOGE("path=%p info=%p\n", path, info); +#endif + return NULL; + } + + SNDFILE *handle = (SNDFILE *) malloc(sizeof(SNDFILE)); + handle->temp = NULL; + + handle->info.format = SF_FORMAT_WAV; + if (cb != NULL) { + handle->callback = *cb; + } else { + handle->callback = __defaultCallback; + } + + void* stream = handle->callback.open(path, user); + if (stream == NULL) { +#ifdef HAVE_STDERR + ALOGE("fopen %s failed errno %d\n", path, errno); +#endif + free(handle); + return NULL; + } + handle->stream = stream; + + // don't attempt to parse all valid forms, just the most common ones + unsigned char wav[12]; + size_t actual; + unsigned riffSize; + size_t remaining; + int hadFmt = 0; + int hadData = 0; + long dataTell = 0L; + + actual = handle->callback.read(wav, sizeof(char), sizeof(wav), stream); + if (actual < 12) { +#ifdef HAVE_STDERR + ALOGE("actual %zu < 44\n", actual); +#endif + goto close; + } + if (memcmp(wav, "RIFF", 4)) { +#ifdef HAVE_STDERR + ALOGE("wav != RIFF\n"); +#endif + goto close; + } + riffSize = little4u(&wav[4]); + if (riffSize < 4) { +#ifdef HAVE_STDERR + ALOGE("riffSize %u < 4\n", riffSize); +#endif + goto close; + } + if (memcmp(&wav[8], "WAVE", 4)) { +#ifdef HAVE_STDERR + ALOGE("missing WAVE\n"); +#endif + goto close; + } + remaining = riffSize - 4; + + while (remaining >= 8) { + unsigned char chunk[8]; + actual = handle->callback.read(chunk, sizeof(char), sizeof(chunk), stream); + if (actual != sizeof(chunk)) { +#ifdef HAVE_STDERR + ALOGE("actual %zu != %zu\n", actual, sizeof(chunk)); +#endif + goto close; + } + remaining -= 8; + unsigned chunkSize = little4u(&chunk[4]); + if (chunkSize > remaining) { +#ifdef HAVE_STDERR + ALOGE("chunkSize %u > remaining %zu\n", chunkSize, remaining); +#endif + goto close; + } + if (!memcmp(&chunk[0], "fmt ", 4)) { + if (hadFmt) { +#ifdef HAVE_STDERR + ALOGE("multiple fmt\n"); +#endif + goto close; + } + if (chunkSize < 2) { +#ifdef HAVE_STDERR + ALOGE("chunkSize %u < 2\n", chunkSize); +#endif + goto close; + } + unsigned char fmt[40]; + actual = handle->callback.read(fmt, sizeof(char), 2, stream); + if (actual != 2) { +#ifdef HAVE_STDERR + ALOGE("actual %zu != 2\n", actual); +#endif + goto close; + } + unsigned format = little2u(&fmt[0]); + size_t minSize = 0; + switch (format) { + case WAVE_FORMAT_PCM: + case WAVE_FORMAT_IEEE_FLOAT: + minSize = 16; + break; + case WAVE_FORMAT_EXTENSIBLE: + minSize = 40; + break; + default: +#ifdef HAVE_STDERR + ALOGE("unsupported format %u\n", format); +#endif + goto close; + } + if (chunkSize < minSize) { +#ifdef HAVE_STDERR + ALOGE("chunkSize %u < minSize %zu\n", chunkSize, minSize); +#endif + goto close; + } + actual = handle->callback.read(&fmt[2], sizeof(char), minSize - 2, stream); + if (actual != minSize - 2) { +#ifdef HAVE_STDERR + ALOGE("actual %zu != %zu\n", actual, minSize - 16); +#endif + goto close; + } + if (chunkSize > minSize) { + handle->callback.seek(stream, (long) (chunkSize - minSize), SEEK_CUR); + } + unsigned channels = little2u(&fmt[2]); + // FIXME FCC_8 + if (channels != 1 && channels != 2 && channels != 4 && channels != 6 && channels != 8) { +#ifdef HAVE_STDERR + ALOGE("unsupported channels %u\n", channels); +#endif + goto close; + } + unsigned samplerate = little4u(&fmt[4]); + if (samplerate == 0) { +#ifdef HAVE_STDERR + ALOGE("samplerate %u == 0\n", samplerate); +#endif + goto close; + } + // ignore byte rate + // ignore block alignment + unsigned bitsPerSample = little2u(&fmt[14]); + if (bitsPerSample != 8 && bitsPerSample != 16 && bitsPerSample != 24 && + bitsPerSample != 32) { +#ifdef HAVE_STDERR + ALOGE("bitsPerSample %u != 8 or 16 or 24 or 32\n", bitsPerSample); +#endif + goto close; + } + unsigned bytesPerFrame = (bitsPerSample >> 3) * channels; + handle->bytesPerFrame = bytesPerFrame; + handle->info.samplerate = samplerate; + handle->info.channels = channels; + switch (bitsPerSample) { + case 8: + handle->info.format |= SF_FORMAT_PCM_U8; + break; + case 16: + handle->info.format |= SF_FORMAT_PCM_16; + break; + case 24: + handle->info.format |= SF_FORMAT_PCM_24; + break; + case 32: + if (format == WAVE_FORMAT_IEEE_FLOAT) + handle->info.format |= SF_FORMAT_FLOAT; + else + handle->info.format |= SF_FORMAT_PCM_32; + break; + } + hadFmt = 1; + } else if (!memcmp(&chunk[0], "data", 4)) { + if (!hadFmt) { +#ifdef HAVE_STDERR + ALOGE("data not preceded by fmt\n"); +#endif + goto close; + } + if (hadData) { +#ifdef HAVE_STDERR + ALOGE("multiple data\n"); +#endif + goto close; + } + handle->remaining = chunkSize / handle->bytesPerFrame; + handle->info.frames = handle->remaining; + dataTell = handle->callback.tell(stream); + if (chunkSize > 0) { + handle->callback.seek(stream, (long) chunkSize, SEEK_CUR); + } + hadData = 1; + } else if (!memcmp(&chunk[0], "fact", 4)) { + // ignore fact + if (chunkSize > 0) { + handle->callback.seek(stream, (long) chunkSize, SEEK_CUR); + } + } else { + // ignore unknown chunk +#ifdef HAVE_STDERR + ALOGE("ignoring unknown chunk %c%c%c%c\n", + chunk[0], chunk[1], chunk[2], chunk[3]); +#endif + if (chunkSize > 0) { + handle->callback.seek(stream, (long) chunkSize, SEEK_CUR); + } + } + remaining -= chunkSize; + } + if (remaining > 0) { +#ifdef HAVE_STDERR + ALOGE("partial chunk at end of RIFF, remaining %zu\n", remaining); +#endif + goto close; + } + if (!hadData) { +#ifdef HAVE_STDERR + ALOGE("missing data\n"); +#endif + goto close; + } + (void) handle->callback.seek(stream, dataTell, SEEK_SET); + *info = handle->info; + return handle; + +close: + free(handle); + handle->callback.close(stream); + return NULL; +} + +void sf_close(SNDFILE *handle) +{ + if (handle == NULL) + return; + free(handle->temp); + (void) handle->callback.close(handle->stream); + free(handle); +} + +sf_count_t sf_readf_short(SNDFILE *handle, short *ptr, sf_count_t desiredFrames) +{ + if (handle == NULL || ptr == NULL || !handle->remaining || + desiredFrames <= 0) { + return 0; + } + if (handle->remaining < (size_t) desiredFrames) { + desiredFrames = handle->remaining; + } + // does not check for numeric overflow + size_t desiredBytes = desiredFrames * handle->bytesPerFrame; + size_t actualBytes; + void *temp = NULL; + unsigned format = handle->info.format & SF_FORMAT_SUBMASK; + if (format == SF_FORMAT_PCM_32 || format == SF_FORMAT_FLOAT || format == SF_FORMAT_PCM_24) { + temp = malloc(desiredBytes); + actualBytes = handle->callback.read(temp, sizeof(char), desiredBytes, handle->stream); + } else { + actualBytes = handle->callback.read(ptr, sizeof(char), desiredBytes, handle->stream); + } + size_t actualFrames = actualBytes / handle->bytesPerFrame; + handle->remaining -= actualFrames; + switch (format) { + case SF_FORMAT_PCM_U8: + memcpy_to_i16_from_u8(ptr, (unsigned char *) ptr, actualFrames * handle->info.channels); + break; + case SF_FORMAT_PCM_16: + if (!isLittleEndian()) + my_swab(ptr, actualFrames * handle->info.channels); + break; + case SF_FORMAT_PCM_32: + memcpy_to_i16_from_i32(ptr, (const int *) temp, actualFrames * handle->info.channels); + free(temp); + break; + case SF_FORMAT_FLOAT: + memcpy_to_i16_from_float(ptr, (const float *) temp, actualFrames * handle->info.channels); + free(temp); + break; + case SF_FORMAT_PCM_24: + memcpy_to_i16_from_p24(ptr, (const uint8_t *) temp, actualFrames * handle->info.channels); + free(temp); + break; + default: + memset(ptr, 0, actualFrames * handle->info.channels * sizeof(short)); + break; + } + return actualFrames; +} + +/* +sf_count_t sf_readf_float(SNDFILE *handle, float *ptr, sf_count_t desiredFrames) +{ + if (handle == NULL || ptr == NULL || !handle->remaining || + desiredFrames <= 0) { + return 0; + } + if (handle->remaining < (size_t) desiredFrames) { + desiredFrames = handle->remaining; + } + // does not check for numeric overflow + size_t desiredBytes = desiredFrames * handle->bytesPerFrame; + size_t actualBytes; + void *temp = NULL; + unsigned format = handle->info.format & SF_FORMAT_SUBMASK; + if (format == SF_FORMAT_PCM_16 || format == SF_FORMAT_PCM_U8 || format == SF_FORMAT_PCM_24) { + temp = malloc(desiredBytes); + actualBytes = handle->callback.read(temp, sizeof(char), desiredBytes, handle->stream); + } else { + actualBytes = handle->callback.read(ptr, sizeof(char), desiredBytes, handle->stream); + } + size_t actualFrames = actualBytes / handle->bytesPerFrame; + handle->remaining -= actualFrames; + switch (format) { + case SF_FORMAT_PCM_U8: +#if 0 + // TODO - implement + memcpy_to_float_from_u8(ptr, (const unsigned char *) temp, + actualFrames * handle->info.channels); +#endif + free(temp); + break; + case SF_FORMAT_PCM_16: + memcpy_to_float_from_i16(ptr, (const short *) temp, actualFrames * handle->info.channels); + free(temp); + break; + case SF_FORMAT_PCM_32: + memcpy_to_float_from_i32(ptr, (const int *) ptr, actualFrames * handle->info.channels); + break; + case SF_FORMAT_FLOAT: + break; + case SF_FORMAT_PCM_24: + memcpy_to_float_from_p24(ptr, (const uint8_t *) temp, actualFrames * handle->info.channels); + free(temp); + break; + default: + memset(ptr, 0, actualFrames * handle->info.channels * sizeof(float)); + break; + } + return actualFrames; +} + +sf_count_t sf_readf_int(SNDFILE *handle, int *ptr, sf_count_t desiredFrames) +{ + if (handle == NULL || ptr == NULL || !handle->remaining || + desiredFrames <= 0) { + return 0; + } + if (handle->remaining < (size_t) desiredFrames) { + desiredFrames = handle->remaining; + } + // does not check for numeric overflow + size_t desiredBytes = desiredFrames * handle->bytesPerFrame; + void *temp = NULL; + unsigned format = handle->info.format & SF_FORMAT_SUBMASK; + size_t actualBytes; + if (format == SF_FORMAT_PCM_16 || format == SF_FORMAT_PCM_U8 || format == SF_FORMAT_PCM_24) { + temp = malloc(desiredBytes); + actualBytes = handle->callback.read(temp, sizeof(char), desiredBytes, handle->stream); + } else { + actualBytes = handle->callback.read(ptr, sizeof(char), desiredBytes, handle->stream); + } + size_t actualFrames = actualBytes / handle->bytesPerFrame; + handle->remaining -= actualFrames; + switch (format) { + case SF_FORMAT_PCM_U8: +#if 0 + // TODO - implement + memcpy_to_i32_from_u8(ptr, (const unsigned char *) temp, + actualFrames * handle->info.channels); +#endif + free(temp); + break; + case SF_FORMAT_PCM_16: + memcpy_to_i32_from_i16(ptr, (const short *) temp, actualFrames * handle->info.channels); + free(temp); + break; + case SF_FORMAT_PCM_32: + break; + case SF_FORMAT_FLOAT: + memcpy_to_i32_from_float(ptr, (const float *) ptr, actualFrames * handle->info.channels); + break; + case SF_FORMAT_PCM_24: + memcpy_to_i32_from_p24(ptr, (const uint8_t *) temp, actualFrames * handle->info.channels); + free(temp); + break; + default: + memset(ptr, 0, actualFrames * handle->info.channels * sizeof(int)); + break; + } + return actualFrames; +} + */ diff --git a/native/cocos/audio/android/tinysndfile.h b/native/cocos/audio/android/tinysndfile.h new file mode 100644 index 0000000000..ca7e765131 --- /dev/null +++ b/native/cocos/audio/android/tinysndfile.h @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2012 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +// This is a C library for reading and writing PCM .wav files. It is +// influenced by other libraries such as libsndfile and audiofile, except is +// much smaller and has an Apache 2.0 license. +// The API should be familiar to clients of similar libraries, but there is +// no guarantee that it will stay exactly source-code compatible with other libraries. + +#include +#include + +__BEGIN_DECLS + +// visible to clients +typedef int sf_count_t; + +typedef struct { + sf_count_t frames; + int samplerate; + int channels; + int format; +} SF_INFO; + +// opaque to clients +typedef struct SNDFILE_ SNDFILE; + +// Format +#define SF_FORMAT_TYPEMASK 1 +#define SF_FORMAT_WAV 1 +#define SF_FORMAT_SUBMASK 14 +#define SF_FORMAT_PCM_16 2 +#define SF_FORMAT_PCM_U8 4 +#define SF_FORMAT_FLOAT 6 +#define SF_FORMAT_PCM_32 8 +#define SF_FORMAT_PCM_24 10 + +typedef struct { + void* (*open)(const char* path, void* user); + size_t (*read) (void* ptr, size_t size, size_t nmemb, void* datasource); + int (*seek) (void* datasource, long offset, int whence); + int (*close) (void* datasource); + long (*tell) (void* datasource); +} snd_callbacks; + +// Open stream +SNDFILE *sf_open_read(const char *path, SF_INFO *info, snd_callbacks* cb, void* user); + +// Close stream +void sf_close(SNDFILE *handle); + +// Read interleaved frames and return actual number of frames read +sf_count_t sf_readf_short(SNDFILE *handle, short *ptr, sf_count_t desired); +/* +sf_count_t sf_readf_float(SNDFILE *handle, float *ptr, sf_count_t desired); +sf_count_t sf_readf_int(SNDFILE *handle, int *ptr, sf_count_t desired); +*/ + +__END_DECLS diff --git a/native/cocos/audio/android/utils/Utils.cpp b/native/cocos/audio/android/utils/Utils.cpp index 6f7dc34a2d..0ef5771be5 100644 --- a/native/cocos/audio/android/utils/Utils.cpp +++ b/native/cocos/audio/android/utils/Utils.cpp @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/android/utils/Utils.h b/native/cocos/audio/android/utils/Utils.h index d4d2415321..8979bb39da 100644 --- a/native/cocos/audio/android/utils/Utils.h +++ b/native/cocos/audio/android/utils/Utils.h @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2016 Chukong Technologies Inc. +Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/apple/AudioCache.h b/native/cocos/audio/apple/AudioCache.h index 4c313c096b..8c7c3a8e4f 100644 --- a/native/cocos/audio/apple/AudioCache.h +++ b/native/cocos/audio/apple/AudioCache.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2014-2016 Chukong Technologies Inc. + Copyright (c) 2014-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/apple/AudioCache.mm b/native/cocos/audio/apple/AudioCache.mm index b5491a0690..a38875a79e 100644 --- a/native/cocos/audio/apple/AudioCache.mm +++ b/native/cocos/audio/apple/AudioCache.mm @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2014-2016 Chukong Technologies Inc. + Copyright (c) 2014-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -66,14 +66,57 @@ static ALvoid alBufferDataStaticProc(const ALint bid, ALenum format, ALvoid* da return; } + +@interface NSTimerWrapper : NSObject +{ + std::function _timeoutCallback; +} + +@end + +@implementation NSTimerWrapper + +-(id) initWithTimeInterval:(double) seconds callback:(const std::function&) cb +{ + if (self = [super init]) + { + _timeoutCallback = cb; + NSTimer* timer = [NSTimer timerWithTimeInterval:seconds target: self selector:@selector(onTimeoutCallback:) userInfo:nil repeats:NO]; + [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode]; + } + + return self; +} + +-(void) onTimeoutCallback: (NSTimer*) timer +{ + if (_timeoutCallback != nullptr) + { + _timeoutCallback(); + _timeoutCallback = nullptr; + } +} + +-(void) dealloc +{ + [super dealloc]; +} + +@end + +static void setTimeout(double seconds, const std::function& cb) +{ + [[[NSTimerWrapper alloc] initWithTimeInterval:seconds callback:cb] autorelease]; +} + using namespace cocos2d; using namespace cocos2d::experimental; AudioCache::AudioCache() -: _totalFrames(0) -, _framesRead(0) -, _format(-1) +: _format(-1) , _duration(0.0f) +, _totalFrames(0) +, _framesRead(0) , _alBufferId(INVALID_AL_BUFFER_ID) , _pcmData(nullptr) , _queBufferFrames(0) @@ -125,7 +168,17 @@ AudioCache::~AudioCache() ALOGW("AudioCache (%p), id=%u, buffer isn't ready, state=%d", this, _id, _state); } - free(_pcmData); + // fixed #17494: CrashIfClientProvidedBogusAudioBufferList + // We're using 'alBufferDataStaticProc' for speeding up + // the performance of playing audio without preload, but we need to manage the memory by ourself carefully. + // It's probably that '_pcmData' is freed before OpenAL finishes the audio render task, + // then 'CrashIfClientProvidedBogusAudioBufferList' may be triggered. + // 'cpp-tests/NewAudioEngineTest/AudioSwitchStateTest' can reproduce this issue without the following fix. + // The workaround is delaying 200ms to free pcm data. + char* data = _pcmData; + setTimeout(0.2, [data](){ + free(data); + }); } if (_queBufferFrames > 0) diff --git a/native/cocos/audio/apple/AudioDecoder.h b/native/cocos/audio/apple/AudioDecoder.h index a19f2723c0..c0547faf8b 100644 --- a/native/cocos/audio/apple/AudioDecoder.h +++ b/native/cocos/audio/apple/AudioDecoder.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2016 Chukong Technologies Inc. + Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/apple/AudioDecoder.mm b/native/cocos/audio/apple/AudioDecoder.mm index 8794a24145..3862f7d7a7 100644 --- a/native/cocos/audio/apple/AudioDecoder.mm +++ b/native/cocos/audio/apple/AudioDecoder.mm @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2016 Chukong Technologies Inc. + Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -25,6 +25,8 @@ #include "audio/apple/AudioDecoder.h" #include "audio/apple/AudioMacros.h" +#import + #define LOG_TAG "AudioDecoder" namespace cocos2d { namespace experimental { diff --git a/native/cocos/audio/apple/AudioEngine-inl.h b/native/cocos/audio/apple/AudioEngine-inl.h index 5bde49a43f..3c88ee7071 100644 --- a/native/cocos/audio/apple/AudioEngine-inl.h +++ b/native/cocos/audio/apple/AudioEngine-inl.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2014-2016 Chukong Technologies Inc. + Copyright (c) 2014-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/apple/AudioEngine-inl.mm b/native/cocos/audio/apple/AudioEngine-inl.mm index 22899e2c36..72936d1684 100644 --- a/native/cocos/audio/apple/AudioEngine-inl.mm +++ b/native/cocos/audio/apple/AudioEngine-inl.mm @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2014-2016 Chukong Technologies Inc. + Copyright (c) 2014-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -79,8 +79,9 @@ void AudioEngineInterruptionListenerCallback(void* user_data, UInt32 interruptio 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: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 @@ -95,37 +96,83 @@ void AudioEngineInterruptionListenerCallback(void* user_data, UInt32 interruptio -(void)handleInterruption:(NSNotification*)notification { + static bool isAudioSessionInterrupted = false; static bool resumeOnBecomingActive = false; + static bool pauseOnResignActive = false; - if ([notification.name isEqualToString:AVAudioSessionInterruptionNotification]) { + if ([notification.name isEqualToString:AVAudioSessionInterruptionNotification]) + { NSInteger reason = [[[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey] integerValue]; - if (reason == AVAudioSessionInterruptionTypeBegan) { - alcMakeContextCurrent(NULL); + 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) { - if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) { + 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); - } else { + 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; } } } - - if ([notification.name isEqualToString:UIApplicationDidBecomeActiveNotification] && resumeOnBecomingActive) { - resumeOnBecomingActive = false; - NSError *error = nil; - BOOL success = [[AVAudioSession sharedInstance] - setCategory: AVAudioSessionCategoryAmbient - error: &error]; - if (!success) { - ALOGE("Fail to set audio session."); - return; + 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(); } - [[AVAudioSession sharedInstance] setActive:YES error:&error]; - alcMakeContextCurrent(s_ALContext); } } @@ -133,6 +180,7 @@ void AudioEngineInterruptionListenerCallback(void* user_data, UInt32 interruptio { [[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]; } @@ -144,12 +192,18 @@ static id s_AudioEngineSessionHandler = nullptr; 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); @@ -540,37 +594,44 @@ 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; - alGetSourcei(player->_alSource, AL_SOURCE_STATE, &sourceState); + alSource = player->_alSource; + alGetSourcei(alSource, AL_SOURCE_STATE, &sourceState); if (player->_removeByAudioEngine) { - _alSourceUsed[player->_alSource] = false; - AudioEngine::remove(audioID); _threadMutex.lock(); it = _audioPlayers.erase(it); _threadMutex.unlock(); delete player; + _alSourceUsed[alSource] = false; } else if (player->_ready && sourceState == AL_STOPPED) { - _alSourceUsed[player->_alSource] = false; + std::string filePath; if (player->_finishCallbak) { auto& audioInfo = AudioEngine::_audioIDInfoMap[audioID]; - player->_finishCallbak(audioID, *audioInfo.filePath); //FIXME: callback will delay 50ms + filePath = *audioInfo.filePath; } AudioEngine::remove(audioID); - delete player; _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; diff --git a/native/cocos/audio/apple/AudioMacros.h b/native/cocos/audio/apple/AudioMacros.h index b74fd6dced..9d890c181a 100644 --- a/native/cocos/audio/apple/AudioMacros.h +++ b/native/cocos/audio/apple/AudioMacros.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2016 Chukong Technologies Inc. + Copyright (c) 2016-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/apple/AudioPlayer.h b/native/cocos/audio/apple/AudioPlayer.h index f79be14f7a..b21a4ccfb8 100644 --- a/native/cocos/audio/apple/AudioPlayer.h +++ b/native/cocos/audio/apple/AudioPlayer.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2014-2016 Chukong Technologies Inc. + Copyright (c) 2014-2017 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/native/cocos/audio/apple/AudioPlayer.mm b/native/cocos/audio/apple/AudioPlayer.mm index a90146fc06..22409143ea 100644 --- a/native/cocos/audio/apple/AudioPlayer.mm +++ b/native/cocos/audio/apple/AudioPlayer.mm @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2014-2016 Chukong Technologies Inc. + Copyright (c) 2014-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -128,7 +128,7 @@ void AudioPlayer::destroy() ALOGVV("Before alSourceStop"); alSourceStop(_alSource); CHECK_AL_ERROR_DEBUG(); ALOGVV("Before alSourcei"); - alSourcei(_alSource, AL_BUFFER, NULL); CHECK_AL_ERROR_DEBUG(); + alSourcei(_alSource, AL_BUFFER, 0); CHECK_AL_ERROR_DEBUG(); _removeByAudioEngine = true; diff --git a/native/cocos/audio/include/AudioEngine.h b/native/cocos/audio/include/AudioEngine.h index 02d8f8676e..77399f3751 100644 --- a/native/cocos/audio/include/AudioEngine.h +++ b/native/cocos/audio/include/AudioEngine.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2014-2016 Chukong Technologies Inc. + Copyright (c) 2014-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -22,19 +22,17 @@ THE SOFTWARE. ****************************************************************************/ -#include "platform/CCPlatformConfig.h" +#pragma once -#ifndef __AUDIO_ENGINE_H_ -#define __AUDIO_ENGINE_H_ +#include "platform/CCPlatformConfig.h" +#include "platform/CCPlatformMacros.h" +#include "audio/include/Export.h" #include #include #include #include -#include "platform/CCPlatformMacros.h" -#include "audio/include/Export.h" - #ifdef ERROR #undef ERROR #endif // ERROR @@ -45,7 +43,7 @@ */ NS_CC_BEGIN - namespace experimental{ +namespace experimental { /** * @class AudioProfile @@ -60,10 +58,10 @@ public: std::string name; //The maximum number of simultaneous audio instance. unsigned int maxInstances; - + /* Minimum delay in between sounds */ double minDelay; - + /** * Default constructor * @@ -73,7 +71,7 @@ public: : maxInstances(0) , minDelay(0.0) { - + } }; @@ -95,11 +93,11 @@ public: enum class AudioState { ERROR = -1, - INITIALZING, + INITIALIZING, PLAYING, PAUSED }; - + static const int INVALID_AUDIO_ID; static const float TIME_UNKNOWN; @@ -113,15 +111,15 @@ public: * @lua endToLua */ static void end(); - - /** + + /** * Gets the default profile of audio instances. * * @return The default profile of audio instances. */ static AudioProfile* getDefaultProfile(); - - /** + + /** * Play 2d sound. * * @param filePath The path of an audio file. @@ -133,8 +131,8 @@ public: * @see `AudioProfile` */ static int play2d(const std::string& filePath, bool loop = false, float volume = 1.0f, const AudioProfile *profile = nullptr); - - /** + + /** * Sets whether an audio instance loop or not. * * @param audioID An audioID returned by the play2d function. @@ -142,7 +140,7 @@ public: */ static void setLoop(int audioID, bool loop); - /** + /** * Checks whether an audio instance is loop. * * @param audioID An audioID returned by the play2d function. @@ -150,7 +148,7 @@ public: */ static bool isLoop(int audioID); - /** + /** * Sets volume for an audio instance. * * @param audioID An audioID returned by the play2d function. @@ -158,7 +156,7 @@ public: */ static void setVolume(int audioID, float volume); - /** + /** * Gets the volume value of an audio instance. * * @param audioID An audioID returned by the play2d function. @@ -166,7 +164,7 @@ public: */ static float getVolume(int audioID); - /** + /** * Pause an audio instance. * * @param audioID An audioID returned by the play2d function. @@ -176,7 +174,7 @@ public: /** Pause all playing audio instances. */ static void pauseAll(); - /** + /** * Resume an audio instance. * * @param audioID An audioID returned by the play2d function. @@ -186,7 +184,7 @@ public: /** Resume all suspended audio instances. */ static void resumeAll(); - /** + /** * Stop an audio instance. * * @param audioID An audioID returned by the play2d function. @@ -201,11 +199,11 @@ public: * * @param audioID An audioID returned by the play2d function. * @param sec The offset in seconds from the start to seek to. - * @return + * @return */ static bool setCurrentTime(int audioID, float sec); - /** + /** * Gets the current playback position of an audio instance. * * @param audioID An audioID returned by the play2d function. @@ -213,7 +211,7 @@ public: */ static float getCurrentTime(int audioID); - /** + /** * Gets the duration of an audio instance. * * @param audioID An audioID returned by the play2d function. @@ -221,7 +219,7 @@ public: */ static float getDuration(int audioID); - /** + /** * Returns the state of an audio instance. * * @param audioID An audioID returned by the play2d function. @@ -229,27 +227,27 @@ public: */ static AudioState getState(int audioID); - /** + /** * Register a callback to be invoked when an audio instance has completed playing. * * @param audioID An audioID returned by the play2d function. * @param callback */ static void setFinishCallback(int audioID, const std::function& callback); - + /** * Gets the maximum number of simultaneous audio instance of AudioEngine. */ static int getMaxAudioInstance() {return _maxInstances;} - + /** * Sets the maximum number of simultaneous audio instance for AudioEngine. * * @param maxInstances The maximum number of simultaneous audio instance. */ static bool setMaxAudioInstance(int maxInstances); - - /** + + /** * Uncache the audio data from internal buffer. * AudioEngine cache audio data on ios,mac, and win32 platform. * @@ -257,15 +255,15 @@ public: * @param filePath Audio file path. */ static void uncache(const std::string& filePath); - - /** + + /** * Uncache all audio data from internal buffer. * * @warning All audio will be stopped first. */ static void uncacheAll(); - - /** + + /** * Gets the audio profile by id of audio instance. * * @param audioID An audioID returned by the play2d function. @@ -273,7 +271,7 @@ public: */ static AudioProfile* getProfile(int audioID); - /** + /** * Gets an audio profile by name. * * @param profileName A name of audio profile. @@ -297,7 +295,7 @@ public: protected: static void addTask(const std::function& task); static void remove(int audioID); - + struct ProfileHelper { AudioProfile profile; @@ -312,51 +310,49 @@ protected: } }; - + struct AudioInfo { const std::string* filePath; ProfileHelper* profileHelper; - + float volume; bool loop; float duration; AudioState state; - AudioInfo() - : profileHelper(nullptr) - , duration(TIME_UNKNOWN) - , state(AudioState::INITIALZING) - { - - } + AudioInfo(); + ~AudioInfo(); + private: + AudioInfo(const AudioInfo& info); + AudioInfo(AudioInfo&& info); + AudioInfo& operator=(const AudioInfo& info); + AudioInfo& operator=(AudioInfo&& info); }; //audioID,audioAttribute static std::unordered_map _audioIDInfoMap; - + //audio file path,audio IDs static std::unordered_map> _audioPathIDMap; - + //profileName,ProfileHelper static std::unordered_map _audioPathProfileHelperMap; - + static unsigned int _maxInstances; - + static ProfileHelper* _defaultProfileHelper; - + static AudioEngineImpl* _audioEngineImpl; class AudioEngineThreadPool; static AudioEngineThreadPool* s_threadPool; - + friend class AudioEngineImpl; }; -} +} // namespace experimental { NS_CC_END // end group /// @} - -#endif // __AUDIO_ENGINE_H_ diff --git a/native/cocos/audio/include/Export.h b/native/cocos/audio/include/Export.h index 3f5c4d37e7..bd057292bf 100644 --- a/native/cocos/audio/include/Export.h +++ b/native/cocos/audio/include/Export.h @@ -1,6 +1,6 @@ /**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2013-2016 Chukong Technologies Inc. +Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -33,7 +33,7 @@ THE SOFTWARE. #define EXPORT_DLL #else #if defined(_EXPORT_DLL_) - #define EXPORT_DLL __declspec(dllexport) + #define EXPORT_DLL __declspec(dllexport) #else /* use a DLL library */ #define EXPORT_DLL __declspec(dllimport) #endif @@ -46,6 +46,6 @@ THE SOFTWARE. #else #define EXPORT_DLL #endif -#endif +#endif #endif // end of __EXPORT_COMMON__ diff --git a/native/cocos/audio/include/SimpleAudioEngine.h b/native/cocos/audio/include/SimpleAudioEngine.h index 46cdc30089..482c1c35da 100644 --- a/native/cocos/audio/include/SimpleAudioEngine.h +++ b/native/cocos/audio/include/SimpleAudioEngine.h @@ -1,7 +1,7 @@ /**************************************************************************** Copyright (c) 2010 Steve Oldmeadow Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2013-2016 Chukong Technologies Inc. +Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -62,6 +62,13 @@ public: */ static SimpleAudioEngine* getInstance(); + /** + * @deprecated Use `getInstance` instead. + * @js NA + * @lua NA + */ + CC_DEPRECATED_ATTRIBUTE static SimpleAudioEngine* sharedEngine() { return SimpleAudioEngine::getInstance(); } + /** * Release the shared Engine object. * @@ -78,10 +85,10 @@ public: * @lua preloadMusic */ virtual void preloadBackgroundMusic(const char* filePath); - + /** * Play background music. - * + * * @param filePath The path of the background music file,or the FileName of T_SoundResInfo. * @param loop Whether the background music loop or not. * @js playMusic @@ -137,7 +144,7 @@ public: */ virtual bool isBackgroundMusicPlaying(); - // + // // properties // @@ -169,7 +176,7 @@ public: */ virtual void setEffectsVolume(float volume); - // + // // for sound effects /** @@ -181,7 +188,7 @@ public: * @param pan Stereo effect, in the range of [-1..1] where -1 enables only left channel. * @param gain Volume, in the range of [0..1]. The normal value is 1. * @return The sound id. - * + * * @note Full support is under development, now there are limitations: * - no pitch effect on Samsung Galaxy S2 with OpenSL backend enabled; * - no pitch/pan/gain on win32. diff --git a/native/cocos/audio/ios/CDAudioManager.h b/native/cocos/audio/ios/CDAudioManager.h index bef283918d..ea62321b49 100644 --- a/native/cocos/audio/ios/CDAudioManager.h +++ b/native/cocos/audio/ios/CDAudioManager.h @@ -1,16 +1,16 @@ /* Copyright (c) 2010 Steve Oldmeadow - + 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 @@ -18,7 +18,7 @@ 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. - + $Id$ */ @@ -54,14 +54,14 @@ typedef enum { /** Notifications */ extern NSString * const kCDN_AudioManagerInitialised; -@interface CDAsynchInitialiser : NSOperation {} +@interface CDAsynchInitialiser : NSOperation {} @end /** CDAudioManager supports two long audio source channels called left and right*/ typedef enum { kASC_Left = 0, kASC_Right = 1 -} tAudioSourceChannel; +} tAudioSourceChannel; typedef enum { kLAS_Init, @@ -94,19 +94,19 @@ typedef enum { NSString *audioSourceFilePath; NSInteger numberOfLoops; float volume; - id delegate; + id delegate; BOOL mute; BOOL enabled_; BOOL backgroundMusic; // whether background music is paused BOOL paused; BOOL stopped; -@public +@public BOOL systemPaused;//Used for auto resign handling NSTimeInterval systemPauseLocation;//Used for auto resign handling @protected tLongAudioSourceState state; -} +} @property (readonly) AVAudioPlayer *audioSourcePlayer; @property (readonly) NSString *audioSourceFilePath; @property (readwrite, nonatomic) NSInteger numberOfLoops; @@ -120,7 +120,7 @@ typedef enum { -(void) load:(NSString*) filePath; /** Plays the audio source */ -(void) play; -/** Stops playing the audio soruce */ +/** Stops playing the audio source */ -(void) stop; /** Pauses the audio source */ -(void) pause; @@ -133,15 +133,15 @@ typedef enum { @end -/** +/** CDAudioManager manages audio requirements for a game. It provides access to a CDSoundEngine object for playing sound effects. It provides access to two CDLongAudioSource object (left and right channel) for playing long duration audio such as background music and narration tracks. Additionally it manages the audio session to take care of things like audio session interruption and interacting with the audio of other apps that are running on the device. - + Requirements: - - Firmware: OS 2.2 or greater + - Firmware: OS 2.2 or greater - Files: CDAudioManager.*, CocosDenshion.* - Frameworks: OpenAL, AudioToolbox, AVFoundation @since v0.8 @@ -167,7 +167,7 @@ typedef enum { BOOL _interrupted; BOOL _audioSessionActive; BOOL enabled_; - + //For handling resign/become active BOOL _isObservingAppEvents; tAudioManagerResignBehavior _resignBehavior; diff --git a/native/cocos/audio/ios/CDAudioManager.m b/native/cocos/audio/ios/CDAudioManager.m index 0406437c22..c0b41f2ebc 100644 --- a/native/cocos/audio/ios/CDAudioManager.m +++ b/native/cocos/audio/ios/CDAudioManager.m @@ -1,16 +1,16 @@ /* Copyright (c) 2010 Steve Oldmeadow - + 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 @@ -18,7 +18,7 @@ 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. - + $Id$ */ @@ -27,13 +27,13 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised"; -//NSOperation object used to asynchronously initialise +//NSOperation object used to asynchronously initialise @implementation CDAsynchInitialiser -(void) main { [super main]; [CDAudioManager sharedManager]; -} +} @end @@ -58,10 +58,10 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised"; [audioSourcePlayer release]; [audioSourceFilePath release]; [super dealloc]; -} +} -(void) load:(NSString*) filePath { - //We have alread loaded a file previously, check if we are being asked to load the same file + //We have already loaded a file previously, check if we are being asked to load the same file if (state == kLAS_Init || ![filePath isEqualToString:audioSourceFilePath]) { CDLOGINFO(@"Denshion::CDLongAudioSource - Loading new audio source %@",filePath); //New file @@ -79,10 +79,10 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised"; if (delegate && [delegate respondsToSelector:@selector(cdAudioSourceFileDidChange:)]) { //Tell our delegate the file has changed [delegate cdAudioSourceFileDidChange:self]; - } + } } else { CDLOG(@"Denshion::CDLongAudioSource - Error initialising audio player: %@",error); - } + } } else { //Same file - just return it to a consistent state [self pause]; @@ -91,7 +91,7 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised"; audioSourcePlayer.volume = volume; audioSourcePlayer.numberOfLoops = numberOfLoops; state = kLAS_Loaded; -} +} -(void) play { if (enabled_) { @@ -101,19 +101,19 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised"; [audioSourcePlayer play]; } else { CDLOGINFO(@"Denshion::CDLongAudioSource long audio source didn't play because it is disabled"); - } -} + } +} -(void) stop { paused = NO; stopped = YES; [audioSourcePlayer stop]; -} +} -(void) pause { paused = YES; [audioSourcePlayer pause]; -} +} -(void) rewind { paused = NO; @@ -142,10 +142,10 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised"; volume = newVolume; if (state != kLAS_Init && !mute) { audioSourcePlayer.volume = newVolume; - } + } } --(float) volume +-(float) volume { return volume; } @@ -154,9 +154,9 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised"; -(BOOL) mute { return mute; -} +} --(void) setMute:(BOOL) muteValue +-(void) setMute:(BOOL) muteValue { if (mute != muteValue) { if (mute) { @@ -166,15 +166,15 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised"; audioSourcePlayer.volume = 0.0f; } mute = muteValue; - } -} + } +} --(BOOL) enabled +-(BOOL) enabled { return enabled_; -} +} --(void) setEnabled:(BOOL)enabledValue +-(void) setEnabled:(BOOL)enabledValue { if (enabledValue != enabled_) { enabled_ = enabledValue; @@ -182,25 +182,25 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised"; //"Stop" the sounds [self pause]; [self rewind]; - } - } -} + } + } +} -(NSInteger) numberOfLoops { return numberOfLoops; -} +} -(void) setNumberOfLoops:(NSInteger) loopCount { audioSourcePlayer.numberOfLoops = loopCount; numberOfLoops = loopCount; -} +} - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag { CDLOGINFO(@"Denshion::CDLongAudioSource - audio player finished"); -#if TARGET_IPHONE_SIMULATOR +#if TARGET_IPHONE_SIMULATOR CDLOGINFO(@"Denshion::CDLongAudioSource - workaround for OpenAL clobbered audio issue"); - //This is a workaround for an issue in all simulators (tested to 3.1.2). Problem is + //This is a workaround for an issue in all simulators (tested to 3.1.2). Problem is //that OpenAL audio playback is clobbered when an AVAudioPlayer stops. Workaround //is to keep the player playing on an endless loop with 0 volume and then when //it is played again reset the volume and set loop count appropriately. @@ -208,11 +208,11 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised"; player.numberOfLoops = -1; player.volume = 0; [player play]; -#endif +#endif if (delegate && [delegate respondsToSelector:@selector(cdAudioSourceDidFinishPlaying:)]) { [delegate cdAudioSourceDidFinishPlaying:self]; - } -} + } +} -(void)audioPlayerBeginInterruption:(AVAudioPlayer *)player { CDLOGINFO(@"Denshion::CDLongAudioSource - audio player interrupted"); @@ -221,16 +221,16 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised"; -(void)audioPlayerEndInterruption:(AVAudioPlayer *)player { CDLOGINFO(@"Denshion::CDLongAudioSource - audio player resumed"); if (self.backgroundMusic) { - //Check if background music can play as rules may have changed during + //Check if background music can play as rules may have changed during //the interruption. This is to address a specific issue in 4.x when //fast task switching if([CDAudioManager sharedManager].willPlayBackgroundMusic) { [player play]; - } + } } else { [player play]; - } -} + } +} @end @@ -255,26 +255,26 @@ static BOOL configured = FALSE; NSError *activationError = nil; if ([[AVAudioSession sharedInstance] setActive:active error:&activationError]) { _audioSessionActive = active; - CDLOGINFO(@"Denshion::CDAudioManager - Audio session set active %i succeeded", active); + CDLOGINFO(@"Denshion::CDAudioManager - Audio session set active %i succeeded", active); return YES; } else { //Failed - CDLOG(@"Denshion::CDAudioManager - Audio session set active %i failed with error %@", active, activationError); + CDLOG(@"Denshion::CDAudioManager - Audio session set active %i failed with error %@", active, activationError); return NO; - } -} + } +} -(BOOL) audioSessionSetCategory:(NSString*) category { NSError *categoryError = nil; if ([[AVAudioSession sharedInstance] setCategory:category error:&categoryError]) { - CDLOGINFO(@"Denshion::CDAudioManager - Audio session set category %@ succeeded", category); + CDLOGINFO(@"Denshion::CDAudioManager - Audio session set category %@ succeeded", category); return YES; } else { //Failed - CDLOG(@"Denshion::CDAudioManager - Audio session set category %@ failed with error %@", category, categoryError); + CDLOG(@"Denshion::CDAudioManager - Audio session set category %@ failed with error %@", category, categoryError); return NO; - } -} + } +} // Init + (CDAudioManager *) sharedManager @@ -288,14 +288,14 @@ static BOOL configured = FALSE; sharedManager = [[CDAudioManager alloc] init:configuredMode]; _sharedManagerState = kAMStateInitialised;//This is only really relevant when using asynchronous initialisation [[NSNotificationCenter defaultCenter] postNotificationName:kCDN_AudioManagerInitialised object:nil]; - } + } } return sharedManager; } + (tAudioManagerState) sharedManagerState { return _sharedManagerState; -} +} /** * Call this to set up audio manager asynchronously. Initialisation is finished when sharedManagerState == kAMStateInitialised @@ -308,9 +308,9 @@ static BOOL configured = FALSE; CDAsynchInitialiser *initOp = [[[CDAsynchInitialiser alloc] init] autorelease]; NSOperationQueue *opQ = [[[NSOperationQueue alloc] init] autorelease]; [opQ addOperation:initOp]; - } + } } -} +} + (id) alloc { @@ -327,7 +327,7 @@ static BOOL configured = FALSE; + (void) configure: (tAudioManagerMode) mode { configuredMode = mode; configured = TRUE; -} +} -(BOOL) isOtherAudioPlaying { @@ -346,7 +346,7 @@ static BOOL configured = FALSE; _mode = mode; switch (_mode) { - + case kAMM_FxOnly: //Share audio with other app CDLOGINFO(@"Denshion::CDAudioManager - Audio will be shared"); @@ -354,7 +354,7 @@ static BOOL configured = FALSE; _audioSessionCategory = AVAudioSessionCategoryAmbient; willPlayBackgroundMusic = NO; break; - + case kAMM_FxPlusMusic: //Use audio exclusively - if other audio is playing it will be stopped CDLOGINFO(@"Denshion::CDAudioManager - Audio will be exclusive"); @@ -362,7 +362,7 @@ static BOOL configured = FALSE; _audioSessionCategory = AVAudioSessionCategorySoloAmbient; willPlayBackgroundMusic = YES; break; - + case kAMM_MediaPlayback: //Use audio exclusively, ignore mute switch and sleep CDLOGINFO(@"Denshion::CDAudioManager - Media playback mode, audio will be exclusive"); @@ -370,7 +370,7 @@ static BOOL configured = FALSE; _audioSessionCategory = AVAudioSessionCategoryPlayback; willPlayBackgroundMusic = YES; break; - + case kAMM_PlayAndRecord: //Use audio exclusively, ignore mute switch and sleep, has inputs and outputs CDLOGINFO(@"Denshion::CDAudioManager - Play and record mode, audio will be exclusive"); @@ -378,7 +378,7 @@ static BOOL configured = FALSE; _audioSessionCategory = AVAudioSessionCategoryPlayAndRecord; willPlayBackgroundMusic = YES; break; - + default: //kAudioManagerFxPlusMusicIfNoOtherAudio if ([self isOtherAudioPlaying]) { @@ -391,18 +391,18 @@ static BOOL configured = FALSE; //_audioSessionCategory = kAudioSessionCategory_SoloAmbientSound; _audioSessionCategory = AVAudioSessionCategorySoloAmbient; willPlayBackgroundMusic = YES; - } - + } + break; } - + [self audioSessionSetCategory:_audioSessionCategory]; - -} + +} /** - * This method is used to work around various bugs introduced in 4.x OS versions. In some circumstances the - * audio session is interrupted but never resumed, this results in the loss of OpenAL audio when following + * This method is used to work around various bugs introduced in 4.x OS versions. In some circumstances the + * audio session is interrupted but never resumed, this results in the loss of OpenAL audio when following * standard practices. If we detect this situation then we will attempt to resume the audio session ourselves. * Known triggers: lock the device then unlock it (iOS 4.2 gm), playback a song using MPMediaPlayer (iOS 4.0) */ @@ -410,8 +410,8 @@ static BOOL configured = FALSE; if (_interrupted && alcGetCurrentContext() == NULL) { CDLOG(@"Denshion::CDAudioManager - bad OpenAL context detected, attempting to resume audio session"); [self audioSessionResumed]; - } -} + } +} - (id) init: (tAudioManagerMode) mode { if ((self = [super init])) { @@ -433,27 +433,27 @@ static BOOL configured = FALSE; _audioSessionActive = NO; [self setMode:mode]; soundEngine = [[CDSoundEngine alloc] init]; - + //Set up audioSource channels audioSourceChannels = [[NSMutableArray alloc] init]; CDLongAudioSource *leftChannel = [[CDLongAudioSource alloc] init]; leftChannel.backgroundMusic = YES; CDLongAudioSource *rightChannel = [[CDLongAudioSource alloc] init]; rightChannel.backgroundMusic = NO; - [audioSourceChannels insertObject:leftChannel atIndex:kASC_Left]; + [audioSourceChannels insertObject:leftChannel atIndex:kASC_Left]; [audioSourceChannels insertObject:rightChannel atIndex:kASC_Right]; [leftChannel release]; [rightChannel release]; //Used to support legacy APIs backgroundMusic = [self audioSourceForChannel:BACKGROUND_MUSIC_CHANNEL]; backgroundMusic.delegate = self; - + //Add handler for bad al context messages, these are posted by the sound engine. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(badAlContextHandler) name:kCDN_BadAlContext object:nil]; - } - return self; -} + } + return self; +} -(void) dealloc { CDLOGINFO(@"Denshion::CDAudioManager - deallocating"); @@ -463,13 +463,13 @@ static BOOL configured = FALSE; [self audioSessionSetActive:NO]; [audioSourceChannels release]; [super dealloc]; -} +} /** Retrieves the audio source for the specified channel */ --(CDLongAudioSource*) audioSourceForChannel:(tAudioSourceChannel) channel +-(CDLongAudioSource*) audioSourceForChannel:(tAudioSourceChannel) channel { return (CDLongAudioSource*)[audioSourceChannels objectAtIndex:channel]; -} +} /** Loads the data from the specified file path to the channel's audio source */ -(CDLongAudioSource*) audioSourceLoad:(NSString*) filePath channel:(tAudioSourceChannel) channel @@ -479,14 +479,14 @@ static BOOL configured = FALSE; [audioSource load:filePath]; } return audioSource; -} +} -(BOOL) isBackgroundMusicPlaying { return [self.backgroundMusic isPlaying]; -} +} //NB: originally I tried using a route change listener and intended to store the current route, -//however, on a 3gs running 3.1.2 no route change is generated when the user switches the +//however, on a 3gs running 3.1.2 no route change is generated when the user switches the //ringer mute switch to off (i.e. enables sound) therefore polling is the only reliable way to //determine ringer switch state -(BOOL) isDeviceMuted { @@ -494,36 +494,36 @@ static BOOL configured = FALSE; #if TARGET_IPHONE_SIMULATOR || defined(CC_TARGET_OS_TVOS) //Calling audio route stuff on the simulator causes problems return NO; -#else +#else CFStringRef newAudioRoute; UInt32 propertySize = sizeof (CFStringRef); - + AudioSessionGetProperty ( kAudioSessionProperty_AudioRoute, &propertySize, &newAudioRoute ); - + if (newAudioRoute == NULL) { //Don't expect this to happen but playing safe otherwise a null in the CFStringCompare will cause a crash return YES; - } else { + } else { CFComparisonResult newDeviceIsMuted = CFStringCompare ( newAudioRoute, (CFStringRef) @"", 0 ); - + return (newDeviceIsMuted == kCFCompareEqualTo); - } + } #endif -} +} #pragma mark Audio Interrupt Protocol -(BOOL) mute { return _mute; -} +} -(void) setMute:(BOOL) muteValue { if (muteValue != _mute) { @@ -531,13 +531,13 @@ static BOOL configured = FALSE; [soundEngine setMute:muteValue]; for( CDLongAudioSource *audioSource in audioSourceChannels) { audioSource.mute = muteValue; - } - } + } + } } -(BOOL) enabled { return enabled_; -} +} -(void) setEnabled:(BOOL) enabledValue { if (enabledValue != enabled_) { @@ -545,20 +545,20 @@ static BOOL configured = FALSE; [soundEngine setEnabled:enabled_]; for( CDLongAudioSource *audioSource in audioSourceChannels) { audioSource.enabled = enabled_; - } - } + } + } } -(CDLongAudioSource*) backgroundMusic { return backgroundMusic; -} +} //Load background music ready for playing -(void) preloadBackgroundMusic:(NSString*) filePath { - [self.backgroundMusic load:filePath]; -} + [self.backgroundMusic load:filePath]; +} -(void) playBackgroundMusic:(NSString*) filePath loop:(BOOL) loop { @@ -586,7 +586,7 @@ static BOOL configured = FALSE; -(void) pauseBackgroundMusic { [self.backgroundMusic pause]; -} +} -(void) resumeBackgroundMusic { @@ -594,35 +594,35 @@ static BOOL configured = FALSE; CDLOGINFO(@"Denshion::CDAudioManager - resume bgm aborted because audio is not exclusive or sound is muted"); return; } - + if (![self.backgroundMusic paused]) { return; } - + [self.backgroundMusic resume]; -} +} -(void) rewindBackgroundMusic { [self.backgroundMusic rewind]; -} +} -(void) setBackgroundMusicCompletionListener:(id) listener selector:(SEL) selector { backgroundMusicCompletionListener = listener; backgroundMusicCompletionSelector = selector; -} +} /* * Call this method to have the audio manager automatically handle application resign and * become active. Pass a tAudioManagerResignBehavior to indicate the desired behavior * for resigning and becoming active again. * - * If autohandle is YES then the applicationWillResignActive and applicationDidBecomActive + * If autohandle is YES then the applicationWillResignActive and applicationDidBecomActive * methods are automatically called, otherwise you must call them yourself at the appropriate time. * * Based on idea of Dominique Bongard */ --(void) setResignBehavior:(tAudioManagerResignBehavior) resignBehavior autoHandle:(BOOL) autoHandle { +-(void) setResignBehavior:(tAudioManagerResignBehavior) resignBehavior autoHandle:(BOOL) autoHandle { if (!_isObservingAppEvents && autoHandle) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:@"UIApplicationWillResignActiveNotification" object:nil]; @@ -631,18 +631,18 @@ static BOOL configured = FALSE; _isObservingAppEvents = TRUE; } _resignBehavior = resignBehavior; -} +} - (void) applicationWillResignActive { _resigned = YES; - - //Set the audio sesssion to one that allows sharing so that other audio won't be clobbered on resume + + //Set the audio session to one that allows sharing so that other audio won't be clobbered on resume [self audioSessionSetCategory:AVAudioSessionCategoryAmbient]; - + switch (_resignBehavior) { - + case kAMRBStopPlay: - + for( CDLongAudioSource *audioSource in audioSourceChannels) { if (!audioSource->systemPaused) { if (audioSource.isPlaying) { @@ -658,18 +658,18 @@ static BOOL configured = FALSE; } } break; - + case kAMRBStop: //Stop music regardless of whether it is playing or not because if it was paused //then the OS would resume it for( CDLongAudioSource *audioSource in audioSourceChannels) { [audioSource stop]; - } - + } + default: break; - - } + + } CDLOGINFO(@"Denshion::CDAudioManager - handled resign active"); } @@ -677,18 +677,18 @@ static BOOL configured = FALSE; - (void) applicationWillResignActive:(NSNotification *) notification { [self applicationWillResignActive]; -} +} - (void) applicationDidBecomeActive { - + if (_resigned) { _resigned = NO; //Reset the mode incase something changed with audio while we were inactive [self setMode:_mode]; switch (_resignBehavior) { - + case kAMRBStopPlay: - + //Music had been stopped but stop maintains current time //so playing again will continue from where music was before resign active. //We check if music can be played because while we were inactive the user might have @@ -702,10 +702,10 @@ static BOOL configured = FALSE; } } break; - + default: break; - + } CDLOGINFO(@"Denshion::CDAudioManager - audio manager handled become active"); } @@ -717,7 +717,7 @@ static BOOL configured = FALSE; [self applicationDidBecomeActive]; } -//Called when application terminates only if setResignBehavior has been called +//Called when application terminates only if setResignBehavior has been called - (void) applicationWillTerminate:(NSNotification *) notification { CDLOGINFO(@"Denshion::CDAudioManager - audio manager handling terminate"); @@ -729,8 +729,8 @@ static BOOL configured = FALSE; CDLOGINFO(@"Denshion::CDAudioManager - audio manager got told background music finished"); if (backgroundMusicCompletionSelector != nil) { [backgroundMusicCompletionListener performSelector:backgroundMusicCompletionSelector]; - } -} + } +} -(void) beginInterruption { CDLOGINFO(@"Denshion::CDAudioManager - begin interruption"); @@ -747,78 +747,78 @@ static BOOL configured = FALSE; CDLOGINFO(@"Denshion::CDAudioManager - interruption ended with flags %i",flags); if (flags == AVAudioSessionInterruptionFlags_ShouldResume) { [self audioSessionResumed]; - } + } } #endif --(void)audioSessionInterrupted -{ +-(void)audioSessionInterrupted +{ if (!_interrupted) { - CDLOGINFO(@"Denshion::CDAudioManager - Audio session interrupted"); + CDLOGINFO(@"Denshion::CDAudioManager - Audio session interrupted"); _interrupted = YES; - // Deactivate the current audio session + // Deactivate the current audio session [self audioSessionSetActive:NO]; - + if (alcGetCurrentContext() != NULL) { - CDLOGINFO(@"Denshion::CDAudioManager - Setting OpenAL context to NULL"); + CDLOGINFO(@"Denshion::CDAudioManager - Setting OpenAL context to NULL"); ALenum error = AL_NO_ERROR; - // set the current context to NULL will 'shutdown' openAL - alcMakeContextCurrent(NULL); - + // set the current context to NULL will 'shutdown' openAL + alcMakeContextCurrent(NULL); + if((error = alGetError()) != AL_NO_ERROR) { CDLOG(@"Denshion::CDAudioManager - Error making context current %x\n", error); - } + } #pragma unused(error) } - } -} + } +} --(void)audioSessionResumed -{ +-(void)audioSessionResumed +{ if (_interrupted) { - CDLOGINFO(@"Denshion::CDAudioManager - Audio session resumed"); + CDLOGINFO(@"Denshion::CDAudioManager - Audio session resumed"); _interrupted = NO; - + BOOL activationResult = NO; // Reactivate the current audio session - activationResult = [self audioSessionSetActive:YES]; - + activationResult = [self audioSessionSetActive:YES]; + //This code is to handle a problem with iOS 4.0 and 4.01 where reactivating the session can fail if //task switching is performed too rapidly. A test case that reliably reproduces the issue is to call the //iPhone and then hang up after two rings (timing may vary ;)) //Basically we keep waiting and trying to let the OS catch up with itself but the number of tries is //limited. if (!activationResult) { - CDLOG(@"Denshion::CDAudioManager - Failure reactivating audio session, will try wait-try cycle"); + CDLOG(@"Denshion::CDAudioManager - Failure reactivating audio session, will try wait-try cycle"); int activateCount = 0; while (!activationResult && activateCount < 10) { [NSThread sleepForTimeInterval:0.5]; - activationResult = [self audioSessionSetActive:YES]; + activationResult = [self audioSessionSetActive:YES]; activateCount++; - CDLOGINFO(@"Denshion::CDAudioManager - Reactivation attempt %i status = %i",activateCount,activationResult); - } + CDLOGINFO(@"Denshion::CDAudioManager - Reactivation attempt %i status = %i",activateCount,activationResult); + } } - + if (alcGetCurrentContext() == NULL) { - CDLOGINFO(@"Denshion::CDAudioManager - Restoring OpenAL context"); + CDLOGINFO(@"Denshion::CDAudioManager - Restoring OpenAL context"); ALenum error = AL_NO_ERROR; - // Restore open al context - alcMakeContextCurrent([soundEngine openALContext]); + // Restore open al context + alcMakeContextCurrent([soundEngine openALContext]); if((error = alGetError()) != AL_NO_ERROR) { CDLOG(@"Denshion::CDAudioManager - Error making context current%x\n", error); - } + } #pragma unused(error) - } - } + } + } } +(void) end { [sharedManager release]; sharedManager = nil; -} +} @end @@ -827,7 +827,7 @@ static BOOL configured = FALSE; -(void) _setTargetProperty:(float) newVal { ((CDLongAudioSource*)target).volume = newVal; -} +} -(float) _getTargetProperty { return ((CDLongAudioSource*)target).volume; @@ -840,7 +840,7 @@ static BOOL configured = FALSE; -(Class) _allowableType { return [CDLongAudioSource class]; -} +} @end /////////////////////////////////////////////////////////////////////////////////////// @@ -852,18 +852,18 @@ static BOOL configured = FALSE; loadedBuffers = [[NSMutableDictionary alloc] initWithCapacity:CD_BUFFERS_START]; freedBuffers = [[NSMutableArray alloc] init]; nextBufferId = 0; - } + } return self; -} +} -(void) dealloc { [loadedBuffers release]; [freedBuffers release]; [super dealloc]; -} +} -(int) bufferForFile:(NSString*) filePath create:(BOOL) create { - + NSNumber* soundId = (NSNumber*)[loadedBuffers objectForKey:filePath]; if(soundId == nil) { @@ -872,7 +872,7 @@ static BOOL configured = FALSE; //First try to get a buffer from the free buffers if ([freedBuffers count] > 0) { bufferId = [[[freedBuffers lastObject] retain] autorelease]; - [freedBuffers removeLastObject]; + [freedBuffers removeLastObject]; CDLOGINFO(@"Denshion::CDBufferManager reusing buffer id %i",[bufferId intValue]); } else { bufferId = [[NSNumber alloc] initWithInt:nextBufferId]; @@ -880,7 +880,7 @@ static BOOL configured = FALSE; CDLOGINFO(@"Denshion::CDBufferManager generating new buffer id %i",[bufferId intValue]); nextBufferId++; } - + if ([soundEngine loadBuffer:[bufferId intValue] filePath:filePath]) { //File successfully loaded CDLOGINFO(@"Denshion::CDBufferManager buffer loaded %@ %@",bufferId,filePath); @@ -890,15 +890,15 @@ static BOOL configured = FALSE; //File didn't load, put buffer id on free list [freedBuffers addObject:bufferId]; return kCDNoBuffer; - } + } } else { //No matching buffer was found return kCDNoBuffer; - } + } } else { return [soundId intValue]; - } -} + } +} -(void) releaseBufferForFile:(NSString *) filePath { int bufferId = [self bufferForFile:filePath create:NO]; @@ -908,7 +908,9 @@ static BOOL configured = FALSE; NSNumber *freedBufferId = [[NSNumber alloc] initWithInt:bufferId]; [freedBufferId autorelease]; [freedBuffers addObject:freedBufferId]; - } -} + } +} @end + + diff --git a/native/cocos/audio/ios/CDConfig.h b/native/cocos/audio/ios/CDConfig.h index b258a1fd9d..2bd8f760c1 100644 --- a/native/cocos/audio/ios/CDConfig.h +++ b/native/cocos/audio/ios/CDConfig.h @@ -1,16 +1,16 @@ /* Copyright (c) 2010 Steve Oldmeadow - + 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 @@ -18,7 +18,7 @@ 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. - + $Id$ */ #define COCOSDENSHION_VERSION "Aphex.rc" @@ -35,22 +35,22 @@ */ //Number of buffers slots that will be initially created #define CD_BUFFERS_START 64 -//Number of buffers that will be added +//Number of buffers that will be added #define CD_BUFFERS_INCREMENT 16 /** If enabled, OpenAL code will use static buffers. When static buffers are used the audio - data is managed outside of OpenAL, this eliminates a memcpy operation which leads to + data is managed outside of OpenAL, this eliminates a memcpy operation which leads to higher performance when loading sounds. - + However, the downside is that when the audio data is freed you must be certain that it is no longer being accessed otherwise your app will crash. Testing on OS 2.2.1 and 3.1.2 has shown that this may occur if a buffer is being used by a source with state = AL_PLAYING when the buffer is deleted. If the data is freed too quickly after the source is stopped then a crash will occur. The implemented workaround is that when static buffers are used the unloadBuffer code will wait for - any playing sources to finish playing before the associated buffer and data are deleted, however, this delay may negate any + any playing sources to finish playing before the associated buffer and data are deleted, however, this delay may negate any performance gains that are achieved during loading. - + Performance tests on a 1st gen iPod running OS 2.2.1 loading the CocosDenshionDemo sounds were ~0.14 seconds without static buffers and ~0.12 seconds when using static buffers. diff --git a/native/cocos/audio/ios/CDOpenALSupport.h b/native/cocos/audio/ios/CDOpenALSupport.h index 49631cc686..aeac861c96 100644 --- a/native/cocos/audio/ios/CDOpenALSupport.h +++ b/native/cocos/audio/ios/CDOpenALSupport.h @@ -1,12 +1,12 @@ /* - + Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. - + In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the @@ -22,13 +22,13 @@ or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. - + The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - + IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS @@ -37,9 +37,9 @@ AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - + Copyright (C) 2009 Apple Inc. All Rights Reserved. - + $Id$ */ @@ -55,8 +55,8 @@ #ifdef __cplusplus extern "C" { -#endif - +#endif + #import #import @@ -67,10 +67,11 @@ extern "C" { void* CDloadWaveAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate); void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate); void* CDGetOpenALAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate); - + #ifdef __cplusplus } #endif -#endif +#endif + diff --git a/native/cocos/audio/ios/CDOpenALSupport.m b/native/cocos/audio/ios/CDOpenALSupport.m index 1d4b1e96ca..16ae51571a 100644 --- a/native/cocos/audio/ios/CDOpenALSupport.m +++ b/native/cocos/audio/ios/CDOpenALSupport.m @@ -1,12 +1,12 @@ /* - + Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. - + In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the @@ -22,13 +22,13 @@ or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. - + The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - + IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS @@ -37,9 +37,9 @@ AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - + Copyright (C) 2009 Apple Inc. All Rights Reserved. - + $Id: CDOpenALSupport.h 16 2010-03-11 06:22:10Z steveoldmeadow $ */ @@ -51,38 +51,38 @@ //Taken from oalTouch MyOpenALSupport 1.1 void* CDloadWaveAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate) { - OSStatus err = noErr; + OSStatus err = noErr; UInt64 fileDataSize = 0; AudioStreamBasicDescription theFileFormat; UInt32 thePropertySize = sizeof(theFileFormat); AudioFileID afid = 0; void* theData = NULL; - + // Open a file with ExtAudioFileOpen() err = AudioFileOpenURL(inFileURL, kAudioFileReadPermission, 0, &afid); if(err) { CDLOG(@"MyGetOpenALAudioData: AudioFileOpenURL FAILED, Error = %ld\n", err); goto Exit; } - + // Get the audio data format err = AudioFileGetProperty(afid, kAudioFilePropertyDataFormat, &thePropertySize, &theFileFormat); if(err) { CDLOG(@"MyGetOpenALAudioData: AudioFileGetProperty(kAudioFileProperty_DataFormat) FAILED, Error = %ld\n", err); goto Exit; } - - if (theFileFormat.mChannelsPerFrame > 2) { + + if (theFileFormat.mChannelsPerFrame > 2) { CDLOG(@"MyGetOpenALAudioData - Unsupported Format, channel count is greater than stereo\n"); goto Exit; } - - if ((theFileFormat.mFormatID != kAudioFormatLinearPCM) || (!TestAudioFormatNativeEndian(theFileFormat))) { + + if ((theFileFormat.mFormatID != kAudioFormatLinearPCM) || (!TestAudioFormatNativeEndian(theFileFormat))) { CDLOG(@"MyGetOpenALAudioData - Unsupported Format, must be little-endian PCM\n"); goto Exit; } - - if ((theFileFormat.mBitsPerChannel != 8) && (theFileFormat.mBitsPerChannel != 16)) { + + if ((theFileFormat.mBitsPerChannel != 8) && (theFileFormat.mBitsPerChannel != 16)) { CDLOG(@"MyGetOpenALAudioData - Unsupported Format, must be 8 or 16 bit PCM\n"); goto Exit; } - - + + thePropertySize = sizeof(fileDataSize); err = AudioFileGetProperty(afid, kAudioFilePropertyAudioDataByteCount, &thePropertySize, &fileDataSize); if(err) { CDLOG(@"MyGetOpenALAudioData: AudioFileGetProperty(kAudioFilePropertyAudioDataByteCount) FAILED, Error = %ld\n", err); goto Exit; } - + // Read all the data into memory UInt32 dataSize = (UInt32)fileDataSize; theData = malloc(dataSize); @@ -95,22 +95,22 @@ void* CDloadWaveAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outD // success *outDataSize = (ALsizei)dataSize; //This fix was added by me, however, 8 bit sounds have a clipping sound at the end so aren't really usable (SO) - if (theFileFormat.mBitsPerChannel == 16) { + if (theFileFormat.mBitsPerChannel == 16) { *outDataFormat = (theFileFormat.mChannelsPerFrame > 1) ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16; } else { - *outDataFormat = (theFileFormat.mChannelsPerFrame > 1) ? AL_FORMAT_STEREO8 : AL_FORMAT_MONO8; - } + *outDataFormat = (theFileFormat.mChannelsPerFrame > 1) ? AL_FORMAT_STEREO8 : AL_FORMAT_MONO8; + } *outSampleRate = (ALsizei)theFileFormat.mSampleRate; } - else - { + else + { // failure free (theData); theData = NULL; // make sure to return NULL CDLOG(@"MyGetOpenALAudioData: ExtAudioFileRead FAILED, Error = %ld\n", err); goto Exit; - } + } } - + Exit: // Dispose the ExtAudioFileRef, it is no longer needed if (afid) AudioFileClose(afid); @@ -129,7 +129,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa void* theData = NULL; AudioStreamBasicDescription theOutputFormat; UInt32 dataSize = 0; - + // Open a file with ExtAudioFileOpen() status = ExtAudioFileOpenURL(inFileURL, &extRef); if (status != noErr) @@ -139,7 +139,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa } if (abort) goto Exit; - + // Get the audio data format status = ExtAudioFileGetProperty(extRef, kExtAudioFileProperty_FileDataFormat, &thePropertySize, &theFileFormat); if (status != noErr) @@ -149,7 +149,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa } if (abort) goto Exit; - + if (theFileFormat.mChannelsPerFrame > 2) { CDLOG(@"MyGetOpenALAudioData - Unsupported Format, channel count is greater than stereo\n"); @@ -157,19 +157,19 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa } if (abort) goto Exit; - + // Set the client format to 16 bit signed integer (native-endian) data // Maintain the channel count and sample rate of the original source format theOutputFormat.mSampleRate = theFileFormat.mSampleRate; theOutputFormat.mChannelsPerFrame = theFileFormat.mChannelsPerFrame; - + theOutputFormat.mFormatID = kAudioFormatLinearPCM; theOutputFormat.mBytesPerPacket = 2 * theOutputFormat.mChannelsPerFrame; theOutputFormat.mFramesPerPacket = 1; theOutputFormat.mBytesPerFrame = 2 * theOutputFormat.mChannelsPerFrame; theOutputFormat.mBitsPerChannel = 16; theOutputFormat.mFormatFlags = kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked | kAudioFormatFlagIsSignedInteger; - + // Set the desired client (output) data format status = ExtAudioFileSetProperty(extRef, kExtAudioFileProperty_ClientDataFormat, sizeof(theOutputFormat), &theOutputFormat); if (status != noErr) @@ -179,7 +179,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa } if (abort) goto Exit; - + // Get the total frame count thePropertySize = sizeof(theFileLengthInFrames); status = ExtAudioFileGetProperty(extRef, kExtAudioFileProperty_FileLengthFrames, &thePropertySize, &theFileLengthInFrames); @@ -190,7 +190,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa } if (abort) goto Exit; - + // Read all the data into memory dataSize = (UInt32) theFileLengthInFrames * theOutputFormat.mBytesPerFrame; theData = malloc(dataSize); @@ -202,7 +202,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa theDataBuffer.mBuffers[0].mDataByteSize = dataSize; theDataBuffer.mBuffers[0].mNumberChannels = theOutputFormat.mChannelsPerFrame; theDataBuffer.mBuffers[0].mData = theData; - + // Read the data into an AudioBufferList status = ExtAudioFileRead(extRef, (UInt32*)&theFileLengthInFrames, &theDataBuffer); if(status == noErr) @@ -223,7 +223,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa } if (abort) goto Exit; - + Exit: // Dispose the ExtAudioFileRef, it is no longer needed if (extRef) ExtAudioFileDispose(extRef); @@ -231,18 +231,18 @@ Exit: } void* CDGetOpenALAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate) { - + CFStringRef extension = CFURLCopyPathExtension(inFileURL); CFComparisonResult isWavFile = 0; if (extension != NULL) { isWavFile = CFStringCompare (extension,(CFStringRef)@"wav", kCFCompareCaseInsensitive); CFRelease(extension); - } - + } + if (isWavFile == kCFCompareEqualTo) { - return CDloadWaveAudioData(inFileURL, outDataSize, outDataFormat, outSampleRate); + return CDloadWaveAudioData(inFileURL, outDataSize, outDataFormat, outSampleRate); } else { - return CDloadCafAudioData(inFileURL, outDataSize, outDataFormat, outSampleRate); + return CDloadCafAudioData(inFileURL, outDataSize, outDataFormat, outSampleRate); } } diff --git a/native/cocos/audio/ios/CocosDenshion.h b/native/cocos/audio/ios/CocosDenshion.h index 3e97a39733..60232b4ab7 100644 --- a/native/cocos/audio/ios/CocosDenshion.h +++ b/native/cocos/audio/ios/CocosDenshion.h @@ -1,16 +1,16 @@ /* Copyright (c) 2010 Steve Oldmeadow - + 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 @@ -18,16 +18,16 @@ 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. - + $Id$ */ -/** +/** @file @b IMPORTANT -There are 3 different ways of using CocosDenshion. Depending on which you choose you +There are 3 different ways of using CocosDenshion. Depending on which you choose you will need to include different files and frameworks. @par SimpleAudioEngine @@ -36,36 +36,36 @@ and some background music and have no interest in learning the lower level worki this is the interface to use. Requirements: - - Firmware: OS 2.2 or greater + - Firmware: OS 2.2 or greater - Files: SimpleAudioEngine.*, CocosDenshion.* - Frameworks: OpenAL, AudioToolbox, AVFoundation - + @par CDAudioManager CDAudioManager is basically a thin wrapper around an AVAudioPlayer object used for playing background music and a CDSoundEngine object used for playing sound effects. It manages the audio session for you deals with audio session interruption. It is fairly low level and it -is expected you have some understanding of the underlying technologies. For example, for +is expected you have some understanding of the underlying technologies. For example, for many use cases regarding background music it is expected you will work directly with the backgroundMusic AVAudioPlayer which is exposed as a property. - + Requirements: - - Firmware: OS 2.2 or greater + - Firmware: OS 2.2 or greater - Files: CDAudioManager.*, CocosDenshion.* - Frameworks: OpenAL, AudioToolbox, AVFoundation @par CDSoundEngine -CDSoundEngine is a sound engine built upon OpenAL and derived from Apple's oalTouch +CDSoundEngine is a sound engine built upon OpenAL and derived from Apple's oalTouch example. It can playback up to 32 sounds simultaneously with control over pitch, pan -and gain. It can be set up to handle audio session interruption automatically. You +and gain. It can be set up to handle audio session interruption automatically. You may decide to use CDSoundEngine directly instead of CDAudioManager or SimpleAudioEngine because you require OS 2.0 compatibility. - + Requirements: - - Firmware: OS 2.0 or greater + - Firmware: OS 2.0 or greater - Files: CocosDenshion.* - Frameworks: OpenAL, AudioToolbox - -*/ + +*/ #import #import @@ -136,13 +136,13 @@ typedef struct _bufferInfo { ALenum format; ALsizei sizeInBytes; ALsizei frequencyInHertz; -} bufferInfo; +} bufferInfo; typedef struct _sourceInfo { bool usable; ALuint sourceId; ALuint attachedBufferId; -} sourceInfo; +} sourceInfo; #pragma mark CDAudioTransportProtocol @@ -176,7 +176,7 @@ typedef struct _sourceInfo { */ @interface CDUtilities : NSObject { -} +} /** Fundamentally the same as the corresponding method is FileUtils but added to break binding to cocos2d */ +(NSString*) fullPathFromRelativePath:(NSString*) relPath; @@ -187,22 +187,22 @@ typedef struct _sourceInfo { #pragma mark CDSoundEngine /** CDSoundEngine is built upon OpenAL and works with SDK 2.0. - CDSoundEngine is a sound engine built upon OpenAL and derived from Apple's oalTouch + CDSoundEngine is a sound engine built upon OpenAL and derived from Apple's oalTouch example. It can playback up to 32 sounds simultaneously with control over pitch, pan - and gain. It can be set up to handle audio session interruption automatically. You + and gain. It can be set up to handle audio session interruption automatically. You may decide to use CDSoundEngine directly instead of CDAudioManager or SimpleAudioEngine because you require OS 2.0 compatibility. - + Requirements: - - Firmware: OS 2.0 or greater + - Firmware: OS 2.0 or greater - Files: CocosDenshion.* - Frameworks: OpenAL, AudioToolbox - + @since v0.8 */ @class CDSoundSource; @interface CDSoundEngine : NSObject { - + bufferInfo *_buffers; sourceInfo *_sources; sourceGroup *_sourceGroups; @@ -219,11 +219,11 @@ typedef struct _sourceInfo { BOOL functioning_; float asynchLoadProgress_; BOOL getGainWorks_; - + //For managing dynamic allocation of sources and buffers int sourceTotal_; int bufferTotal; - + } @property (readwrite, nonatomic) ALfloat masterGain; @@ -288,10 +288,10 @@ typedef struct _sourceInfo { #pragma mark CDSoundSource /** CDSoundSource is a wrapper around an OpenAL sound source. - It allows you to manipulate properties such as pitch, gain, pan and looping while the + It allows you to manipulate properties such as pitch, gain, pan and looping while the sound is playing. CDSoundSource is based on the old CDSourceWrapper class but with much added functionality. - + @since v1.0 */ @interface CDSoundSource : NSObject { @@ -324,7 +324,7 @@ typedef struct _sourceInfo { #pragma mark CDAudioInterruptTargetGroup /** Container for objects that implement audio interrupt protocol i.e. they can be muted and enabled. - Setting mute and enabled for the group propagates to all children. + Setting mute and enabled for the group propagates to all children. Designed to be used with your CDSoundSource objects to get them to comply with global enabled and mute settings if that is what you want to do.*/ @interface CDAudioInterruptTargetGroup : NSObject { @@ -343,7 +343,7 @@ typedef struct _sourceInfo { @interface CDAsynchBufferLoader : NSOperation { NSArray *_loadRequests; CDSoundEngine *_soundEngine; -} +} -(id) init:(NSArray *)loadRequests soundEngine:(CDSoundEngine *) theSoundEngine; @@ -401,7 +401,7 @@ typedef enum { float endValue; id target; BOOL stopTargetWhenComplete; - + } @property (readwrite, nonatomic) BOOL stopTargetWhenComplete; @property (readwrite, nonatomic) float startValue; @@ -443,3 +443,6 @@ typedef enum { @interface CDSoundEngineFader : CDPropertyModifier{} @end + + + diff --git a/native/cocos/audio/ios/CocosDenshion.m b/native/cocos/audio/ios/CocosDenshion.m index d0a51a6a76..298c9c16b7 100644 --- a/native/cocos/audio/ios/CocosDenshion.m +++ b/native/cocos/audio/ios/CocosDenshion.m @@ -1,16 +1,16 @@ /* Copyright (c) 2010 Steve Oldmeadow - + 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 @@ -18,7 +18,7 @@ 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. - + $Id$ */ @@ -32,14 +32,14 @@ typedef ALvoid AL_APIENTRY (*alBufferDataStaticProcPtr) (const ALint bid, ALvoid alBufferDataStaticProc(const ALint bid, ALenum format, ALvoid* data, ALsizei size, ALsizei freq) { static alBufferDataStaticProcPtr proc = NULL; - + if (proc == NULL) { proc = (alBufferDataStaticProcPtr) alcGetProcAddress(NULL, (const ALCchar*) "alBufferDataStatic"); } - + if (proc) proc(bid, format, data, size, freq); - + return; } @@ -47,14 +47,14 @@ typedef ALvoid AL_APIENTRY (*alcMacOSXMixerOutputRateProcPtr) (const ALdou ALvoid alcMacOSXMixerOutputRateProc(const ALdouble value) { static alcMacOSXMixerOutputRateProcPtr proc = NULL; - + if (proc == NULL) { proc = (alcMacOSXMixerOutputRateProcPtr) alcGetProcAddress(NULL, (const ALCchar*) "alcMacOSXMixerOutputRate"); } - + if (proc) proc(value); - + return; } @@ -74,7 +74,7 @@ float const kCD_GainDefault = 1.0f; -(void) _dumpSourceGroupsInfo; -(void) _getSourceIndexForSourceGroup; -(void) _freeSourceGroups; --(BOOL) _setUpSourceGroups:(int[]) definitions total:(NSUInteger) total; +-(BOOL) _setUpSourceGroups:(int[]) definitions total:(NSUInteger) total; @end #pragma mark - CDUtilities @@ -88,18 +88,18 @@ float const kCD_GainDefault = 1.0f; { return relPath; } - + NSMutableArray *imagePathComponents = [NSMutableArray arrayWithArray:[relPath pathComponents]]; NSString *file = [imagePathComponents lastObject]; - + [imagePathComponents removeLastObject]; NSString *imageDirectory = [NSString pathWithComponents:imagePathComponents]; - + NSString *fullpath = [[NSBundle mainBundle] pathForResource:file ofType:nil inDirectory:imageDirectory]; if (fullpath == nil) fullpath = relPath; - - return fullpath; + + return fullpath; } @end @@ -121,7 +121,7 @@ static BOOL _mixerRateSet = NO; + (void) setMixerSampleRate:(Float32) sampleRate { _mixerRateSet = YES; _mixerSampleRate = sampleRate; -} +} - (void) _testGetGain { float testValue = 0.7f; @@ -135,7 +135,7 @@ static BOOL _mixerRateSet = NO; //Generate sources one at a time until we fail -(void) _generateSources { - + _sources = (sourceInfo*)malloc( sizeof(_sources[0]) * CD_SOURCE_LIMIT); BOOL hasFailed = NO; sourceTotal_ = 0; @@ -146,21 +146,21 @@ static BOOL _mixerRateSet = NO; //Now try attaching source to null buffer alSourcei(_sources[sourceTotal_].sourceId, AL_BUFFER, 0); if (alGetError() == AL_NO_ERROR) { - _sources[sourceTotal_].usable = true; + _sources[sourceTotal_].usable = true; sourceTotal_++; } else { hasFailed = YES; - } + } } else { _sources[sourceTotal_].usable = false; hasFailed = YES; - } + } } //Mark the rest of the sources as not usable for (int i=sourceTotal_; i < CD_SOURCE_LIMIT; i++) { _sources[i].usable = false; - } -} + } +} -(void) _generateBuffers:(int) startIndex endIndex:(int) endIndex { if (_buffers) { @@ -173,9 +173,9 @@ static BOOL _mixerRateSet = NO; } else { _buffers[i].bufferState = CD_BS_FAILED; CDLOG(@"Denshion::CDSoundEngine - buffer creation failed %i",i); - } + } } - } + } } /** @@ -193,44 +193,44 @@ static BOOL _mixerRateSet = NO; } alcMacOSXMixerOutputRateProc(_mixerSampleRate); CDLOGINFO(@"Denshion::CDSoundEngine - mixer output rate set to %0.2f",_mixerSampleRate); - + // Create a new OpenAL Device // Pass NULL to specify the system's default output device newDevice = alcOpenDevice(NULL); if (newDevice != NULL) { // Create a new OpenAL Context - // The new context will render to the OpenAL Device just created + // The new context will render to the OpenAL Device just created context = alcCreateContext(newDevice, 0); if (context != NULL) { // Make the new context the Current OpenAL Context alcMakeContextCurrent(context); - + // Create some OpenAL Buffer Objects [self _generateBuffers:0 endIndex:bufferTotal-1]; - + // Create some OpenAL Source Objects [self _generateSources]; - + } } else { return FALSE;//No device - } + } alGetError();//Clear error return TRUE; } - (void) dealloc { - + ALCcontext *currentContext = NULL; ALCdevice *device = NULL; - + [self stopAllSounds]; CDLOGINFO(@"Denshion::CDSoundEngine - Deallocing sound engine."); [self _freeSourceGroups]; - + // Delete the Sources CDLOGINFO(@"Denshion::CDSoundEngine - deleting sources."); for (int i=0; i < sourceTotal_; i++) { @@ -238,8 +238,8 @@ static BOOL _mixerRateSet = NO; alDeleteSources(1, &(_sources[i].sourceId)); if((lastErrorCode_ = alGetError()) != AL_NO_ERROR) { CDLOG(@"Denshion::CDSoundEngine - Error deleting source! %x\n", lastErrorCode_); - } - } + } + } // Delete the Buffers CDLOGINFO(@"Denshion::CDSoundEngine - deleting buffers."); @@ -248,9 +248,9 @@ static BOOL _mixerRateSet = NO; #ifdef CD_USE_STATIC_BUFFERS if (_buffers[i].bufferData) { free(_buffers[i].bufferData); - } -#endif - } + } +#endif + } CDLOGINFO(@"Denshion::CDSoundEngine - free buffers."); free(_buffers); currentContext = alcGetCurrentContext(); @@ -265,18 +265,18 @@ static BOOL _mixerRateSet = NO; alcCloseDevice(device); CDLOGINFO(@"Denshion::CDSoundEngine - free sources."); free(_sources); - + //Release mutexes [_mutexBufferLoad release]; - + [super dealloc]; -} +} -(NSUInteger) sourceGroupTotal { return _sourceGroupTotal; -} +} --(void) _freeSourceGroups +-(void) _freeSourceGroups { CDLOGINFO(@"Denshion::CDSoundEngine freeing source groups"); if(_sourceGroups) { @@ -284,11 +284,11 @@ static BOOL _mixerRateSet = NO; if (_sourceGroups[i].sourceStatuses) { free(_sourceGroups[i].sourceStatuses); CDLOGINFO(@"Denshion::CDSoundEngine freed source statuses %i",i); - } + } } free(_sourceGroups); - } -} + } +} -(BOOL) _redefineSourceGroups:(int[]) definitions total:(NSUInteger) total { @@ -299,20 +299,20 @@ static BOOL _mixerRateSet = NO; [self _freeSourceGroups]; } return [self _setUpSourceGroups:definitions total:total]; -} +} --(BOOL) _setUpSourceGroups:(int[]) definitions total:(NSUInteger) total +-(BOOL) _setUpSourceGroups:(int[]) definitions total:(NSUInteger) total { _sourceGroups = (sourceGroup *)malloc( sizeof(_sourceGroups[0]) * total); if(!_sourceGroups) { CDLOG(@"Denshion::CDSoundEngine - source groups memory allocation failed"); return NO; } - + _sourceGroupTotal = total; int sourceCount = 0; for (int i=0; i < _sourceGroupTotal; i++) { - + _sourceGroups[i].startIndex = 0; _sourceGroups[i].currentIndex = _sourceGroups[i].startIndex; _sourceGroups[i].enabled = false; @@ -322,9 +322,9 @@ static BOOL _mixerRateSet = NO; if (_sourceGroups[i].sourceStatuses) { for (int j=0; j < _sourceGroups[i].totalSources; j++) { //First bit is used to indicate whether source is locked, index is shifted back 1 bit - _sourceGroups[i].sourceStatuses[j] = (sourceCount + j) << 1; - } - } + _sourceGroups[i].sourceStatuses[j] = (sourceCount + j) << 1; + } + } sourceCount += definitions[i]; } return YES; @@ -346,12 +346,12 @@ static BOOL _mixerRateSet = NO; } else { CDLOG(@"Denshion::CDSoundEngine - warning, did not understand source definition."); defs[currentIndex] = 0; - } + } currentIndex++; } [self _redefineSourceGroups:defs total:totalDefs]; free(defs); -} +} - (void) _lazyInitOpenAL { @@ -401,20 +401,20 @@ static BOOL _mixerRateSet = NO; * Delete the buffer identified by soundId * @return true if buffer deleted successfully, otherwise false */ -- (BOOL) unloadBuffer:(int) soundId +- (BOOL) unloadBuffer:(int) soundId { //Ensure soundId is within array bounds otherwise memory corruption will occur if (soundId < 0 || soundId >= bufferTotal) { CDLOG(@"Denshion::CDSoundEngine - soundId is outside array bounds, maybe you need to increase CD_MAX_BUFFERS"); return FALSE; - } - + } + //Before a buffer can be deleted any sources that are attached to it must be stopped for (int i=0; i < sourceTotal_; i++) { //Note: tried getting the AL_BUFFER attribute of the source instead but doesn't //appear to work on a device - just returned zero. if (_buffers[soundId].bufferId == _sources[i].attachedBufferId) { - + CDLOG(@"Denshion::CDSoundEngine - Found attached source %i %i %i",i,_buffers[soundId].bufferId,_sources[i].sourceId); #ifdef CD_USE_STATIC_BUFFERS //When using static buffers a crash may occur if a source is playing with a buffer that is about @@ -422,34 +422,34 @@ static BOOL _mixerRateSet = NO; //on 2.2.1 and 3.1.2, however, it will only occur if a source is used rapidly after having its prior //data deleted. To avoid any possibility of the crash we wait for the source to finish playing. ALint state; - + alGetSourcei(_sources[i].sourceId, AL_SOURCE_STATE, &state); - + if (state == AL_PLAYING) { - CDLOG(@"Denshion::CDSoundEngine - waiting for source to complete playing before removing buffer data"); + CDLOG(@"Denshion::CDSoundEngine - waiting for source to complete playing before removing buffer data"); alSourcei(_sources[i].sourceId, AL_LOOPING, FALSE);//Turn off looping otherwise loops will never end while (state == AL_PLAYING) { alGetSourcei(_sources[i].sourceId, AL_SOURCE_STATE, &state); usleep(10000); } } -#endif +#endif //Stop source and detach - alSourceStop(_sources[i].sourceId); + alSourceStop(_sources[i].sourceId); if((lastErrorCode_ = alGetError()) != AL_NO_ERROR) { CDLOG(@"Denshion::CDSoundEngine - error stopping source: %x\n", lastErrorCode_); - } - + } + alSourcei(_sources[i].sourceId, AL_BUFFER, 0);//Attach to "NULL" buffer to detach if((lastErrorCode_ = alGetError()) != AL_NO_ERROR) { CDLOG(@"Denshion::CDSoundEngine - error detaching buffer: %x\n", lastErrorCode_); } else { //Record that source is now attached to nothing _sources[i].attachedBufferId = 0; - } - } - } - + } + } + } + alDeleteBuffers(1, &_buffers[soundId].bufferId); if((lastErrorCode_ = alGetError()) != AL_NO_ERROR) { CDLOG(@"Denshion::CDSoundEngine - error deleting buffer: %x\n", lastErrorCode_); @@ -457,15 +457,15 @@ static BOOL _mixerRateSet = NO; return FALSE; } else { #ifdef CD_USE_STATIC_BUFFERS - //Free previous data, if alDeleteBuffer has returned without error then no + //Free previous data, if alDeleteBuffer has returned without error then no if (_buffers[soundId].bufferData) { CDLOGINFO(@"Denshion::CDSoundEngine - freeing static data for soundId %i @ %i",soundId,_buffers[soundId].bufferData); free(_buffers[soundId].bufferData);//Free the old data _buffers[soundId].bufferData = NULL; } -#endif - } - +#endif + } + alGenBuffers(1, &_buffers[soundId].bufferId); if((lastErrorCode_ = alGetError()) != AL_NO_ERROR) { CDLOG(@"Denshion::CDSoundEngine - error regenerating buffer: %x\n", lastErrorCode_); @@ -476,11 +476,11 @@ static BOOL _mixerRateSet = NO; _buffers[soundId].bufferState = CD_BS_EMPTY; CDLOGINFO(@"Denshion::CDSoundEngine - buffer %i successfully unloaded\n",soundId); return TRUE; - } -} + } +} /** - * Load buffers asynchronously + * Load buffers asynchronously * Check asynchLoadProgress for progress. asynchLoadProgress represents fraction of completion. When it equals 1.0 loading * is complete. NB: asynchLoadProgress is simply based on the number of load requests, it does not take into account * file sizes. @@ -493,12 +493,12 @@ static BOOL _mixerRateSet = NO; NSOperationQueue *opQ = [[[NSOperationQueue alloc] init] autorelease]; [opQ addOperation:loaderOp]; } -} +} -(BOOL) _resizeBuffers:(int) increment { - + void * tmpBufferInfos = realloc( _buffers, sizeof(_buffers[0]) * (bufferTotal + increment) ); - + if(!tmpBufferInfos) { free(tmpBufferInfos); return NO; @@ -508,8 +508,8 @@ static BOOL _mixerRateSet = NO; bufferTotal = bufferTotal + increment; [self _generateBuffers:oldBufferTotal endIndex:bufferTotal-1]; return YES; - } -} + } +} -(BOOL) loadBufferFromData:(int) soundId soundData:(ALvoid*) soundData format:(ALenum) format size:(ALsizei) size freq:(ALsizei) freq { @@ -522,13 +522,13 @@ static BOOL _mixerRateSet = NO; CDLOG(@"Denshion::CDSoundEngine - Loading buffer failed because sound engine state != functioning"); return FALSE; } - + //Ensure soundId is within array bounds otherwise memory corruption will occur if (soundId < 0) { CDLOG(@"Denshion::CDSoundEngine - soundId is negative"); return FALSE; } - + if (soundId >= bufferTotal) { //Need to resize the buffers int requiredIncrement = CD_BUFFERS_INCREMENT; @@ -539,9 +539,9 @@ static BOOL _mixerRateSet = NO; if (![self _resizeBuffers:requiredIncrement]) { CDLOG(@"Denshion::CDSoundEngine - buffer resize failed"); return FALSE; - } - } - + } + } + if (soundData) { if (_buffers[soundId].bufferState != CD_BS_EMPTY) { @@ -549,33 +549,33 @@ static BOOL _mixerRateSet = NO; if (![self unloadBuffer:soundId]) { //Deletion of buffer failed, delete buffer routine has set buffer state and lastErrorCode return NO; - } - } - + } + } + #ifdef CD_DEBUG //Check that sample rate matches mixer rate and warn if they do not if (freq != (int)_mixerSampleRate) { CDLOGINFO(@"Denshion::CDSoundEngine - WARNING sample rate does not match mixer sample rate performance may not be optimal."); - } -#endif - + } +#endif + #ifdef CD_USE_STATIC_BUFFERS alBufferDataStaticProc(_buffers[soundId].bufferId, format, soundData, size, freq); - _buffers[soundId].bufferData = data;//Save the pointer to the new data -#else + _buffers[soundId].bufferData = soundData;//Save the pointer to the new data +#else alBufferData(_buffers[soundId].bufferId, format, soundData, size, freq); #endif if((lastErrorCode_ = alGetError()) != AL_NO_ERROR) { CDLOG(@"Denshion::CDSoundEngine - error attaching audio to buffer: %x", lastErrorCode_); _buffers[soundId].bufferState = CD_BS_FAILED; return FALSE; - } + } } else { CDLOG(@"Denshion::CDSoundEngine Buffer data is null!"); _buffers[soundId].bufferState = CD_BS_FAILED; return FALSE; - } - + } + _buffers[soundId].format = format; _buffers[soundId].sizeInBytes = size; _buffers[soundId].frequencyInHertz = freq; @@ -583,7 +583,7 @@ static BOOL _mixerRateSet = NO; CDLOGINFO(@"Denshion::CDSoundEngine Buffer %i loaded format:%i freq:%i size:%i",soundId,format,freq,size); return TRUE; }//end mutex -} +} /** * Load sound data for later play back. @@ -596,9 +596,9 @@ static BOOL _mixerRateSet = NO; ALenum format; ALsizei size; ALsizei freq; - + CDLOGINFO(@"Denshion::CDSoundEngine - Loading openAL buffer %i %@", soundId, filePath); - + CFURLRef fileURL = nil; NSString *path = [CDUtilities fullPathFromRelativePath:filePath]; if (path) { @@ -611,14 +611,14 @@ static BOOL _mixerRateSet = NO; CFRelease(fileURL); BOOL result = [self loadBufferFromData:soundId soundData:data format:format size:size freq:freq]; #ifndef CD_USE_STATIC_BUFFERS - free(data);//Data can be freed here because alBufferData performs a memcpy + free(data);//Data can be freed here because alBufferData performs a memcpy #endif return result; } else { CDLOG(@"Denshion::CDSoundEngine Could not find file!\n"); - //Don't change buffer state here as it will be the same as before method was called + //Don't change buffer state here as it will be the same as before method was called return FALSE; - } + } } -(BOOL) validateBufferId:(int) soundId { @@ -630,8 +630,8 @@ static BOOL _mixerRateSet = NO; return NO; } else { return YES; - } -} + } +} -(float) bufferDurationInSeconds:(int) soundId { if ([self validateBufferId:soundId]) { @@ -649,39 +649,39 @@ static BOOL _mixerRateSet = NO; case AL_FORMAT_STEREO16: factor = 0.25f; break; - } + } return (float)_buffers[soundId].sizeInBytes/(float)_buffers[soundId].frequencyInHertz * factor; } else { return -1.0f; - } -} + } +} -(ALsizei) bufferSizeInBytes:(int) soundId { if ([self validateBufferId:soundId]) { return _buffers[soundId].sizeInBytes; } else { return -1.0f; - } -} + } +} -(ALsizei) bufferFrequencyInHertz:(int) soundId { if ([self validateBufferId:soundId]) { return _buffers[soundId].frequencyInHertz; } else { return -1.0f; - } -} + } +} - (ALfloat) masterGain { if (mute_) { //When mute the real gain will always be 0 therefore return the preMuteGain value return _preMuteGain; - } else { + } else { ALfloat gain; alGetListenerf(AL_GAIN, &gain); return gain; - } -} + } +} /** * Overall gain setting multiplier. e.g 0.5 is half the gain. @@ -689,25 +689,25 @@ static BOOL _mixerRateSet = NO; - (void) setMasterGain:(ALfloat) newGainValue { if (mute_) { _preMuteGain = newGainValue; - } else { + } else { alListenerf(AL_GAIN, newGainValue); - } + } } #pragma mark CDSoundEngine AudioInterrupt protocol - (BOOL) mute { return mute_; -} +} /** * Setting mute silences all sounds but playing sounds continue to advance playback */ - (void) setMute:(BOOL) newMuteValue { - + if (newMuteValue == mute_) { return; } - + mute_ = newMuteValue; if (mute_) { //Remember what the gain was @@ -717,7 +717,7 @@ static BOOL _mixerRateSet = NO; } else { //Restore gain to what it was before being muted self.masterGain = _preMuteGain; - } + } } - (BOOL) enabled { @@ -728,12 +728,12 @@ static BOOL _mixerRateSet = NO; { if (enabled_ == enabledValue) { return; - } + } enabled_ = enabledValue; if (enabled_ == NO) { [self stopAllSounds]; - } -} + } +} -(void) _lockSource:(int) sourceIndex lock:(BOOL) lock { BOOL found = NO; @@ -747,22 +747,22 @@ static BOOL _mixerRateSet = NO; _sourceGroups[i].sourceStatuses[j] |= 1; } else { //Unset first bit to unlock this source - _sourceGroups[i].sourceStatuses[j] &= ~1; - } + _sourceGroups[i].sourceStatuses[j] &= ~1; + } found = YES; - } - } - } + } + } + } } -} +} --(int) _getSourceIndexForSourceGroup:(int)sourceGroupId +-(int) _getSourceIndexForSourceGroup:(int)sourceGroupId { //Ensure source group id is valid to prevent memory corruption if (sourceGroupId < 0 || sourceGroupId >= _sourceGroupTotal) { CDLOG(@"Denshion::CDSoundEngine invalid source group id %i",sourceGroupId); return CD_NO_SOURCE; - } + } int sourceIndex = -1;//Using -1 to indicate no source found BOOL complete = NO; @@ -784,49 +784,49 @@ static BOOL _mixerRateSet = NO; break; } else { sourceIndex = -1;//The source index was no good because the source was playing - } - } else { + } + } else { //complete = YES; //Set start index so next search starts at the next position thisSourceGroup->startIndex = thisSourceGroup->currentIndex + 1; break; - } + } } thisSourceGroup->currentIndex++; if (thisSourceGroup->currentIndex >= thisSourceGroup->totalSources) { //Reset to the beginning - thisSourceGroup->currentIndex = 0; - } + thisSourceGroup->currentIndex = 0; + } if (thisSourceGroup->currentIndex == thisSourceGroup->startIndex) { //We have looped around and got back to the start complete = YES; - } + } } //Reset start index to beginning if beyond bounds if (thisSourceGroup->startIndex >= thisSourceGroup->totalSources) { - thisSourceGroup->startIndex = 0; - } - + thisSourceGroup->startIndex = 0; + } + if (sourceIndex >= 0) { return sourceIndex; - } else { + } else { return CD_NO_SOURCE; - } - -} + } + +} /** * Play a sound. * @param soundId the id of the sound to play (buffer id). * @param SourceGroupId the source group that will be used to play the sound. - * @param pitch pitch multiplier. e.g 1.0 is unaltered, 0.5 is 1 octave lower. + * @param pitch pitch multiplier. e.g 1.0 is unaltered, 0.5 is 1 octave lower. * @param pan stereo position. -1 is fully left, 0 is centre and 1 is fully right. * @param gain gain multiplier. e.g. 1.0 is unaltered, 0.5 is half the gain * @param loop should the sound be looped or one shot. - * @return the id of the source being used to play the sound or CD_MUTE if the sound engine is muted or non functioning + * @return the id of the source being used to play the sound or CD_MUTE if the sound engine is muted or non functioning * or CD_NO_SOURCE if a problem occurs setting up the source - * + * */ - (ALuint)playSound:(int) soundId sourceGroupId:(int)sourceGroupId pitch:(float) pitch pan:(float) pan gain:(float) gain loop:(BOOL) loop { @@ -847,22 +847,22 @@ static BOOL _mixerRateSet = NO; CDLOGINFO(@"Denshion::CDSoundEngine - sound playback aborted because sound engine is not functioning"); } else if (_buffers[soundId].bufferState != CD_BS_LOADED) { CDLOGINFO(@"Denshion::CDSoundEngine - sound playback aborted because buffer %i is not loaded", soundId); - } -#endif + } +#endif return CD_MUTE; - } + } int sourceIndex = [self _getSourceIndexForSourceGroup:sourceGroupId];//This method ensures sourceIndex is valid - + if (sourceIndex != CD_NO_SOURCE) { ALint state; ALuint source = _sources[sourceIndex].sourceId; ALuint buffer = _buffers[soundId].bufferId; - alGetError();//Clear the error code + alGetError();//Clear the error code alGetSourcei(source, AL_SOURCE_STATE, &state); if (state == AL_PLAYING) { alSourceStop(source); - } + } alSourcei(source, AL_BUFFER, buffer);//Attach to sound alSourcef(source, AL_PITCH, pitch);//Set pitch alSourcei(source, AL_LOOPING, loop);//Set looping @@ -879,12 +879,12 @@ static BOOL _mixerRateSet = NO; if (alcGetCurrentContext() == NULL) { CDLOGINFO(@"Denshion::CDSoundEngine - posting bad OpenAL context message"); [[NSNotificationCenter defaultCenter] postNotificationName:kCDN_BadAlContext object:nil]; - } + } return CD_NO_SOURCE; - } - } else { + } + } else { return CD_NO_SOURCE; - } + } } -(BOOL) _soundSourceAttachToBuffer:(CDSoundSource*) soundSource soundId:(int) soundId { @@ -896,7 +896,7 @@ static BOOL _mixerRateSet = NO; if (state == AL_PLAYING) { alSourceStop(source); } - alGetError();//Clear the error code + alGetError();//Clear the error code alSourcei(source, AL_BUFFER, buffer);//Attach to sound data if((lastErrorCode_ = alGetError()) == AL_NO_ERROR) { _sources[soundSource->_sourceIndex].attachedBufferId = buffer; @@ -905,20 +905,20 @@ static BOOL _mixerRateSet = NO; return YES; } else { return NO; - } -} + } +} /** * Get a sound source for the specified sound in the specified source group */ --(CDSoundSource *) soundSourceForSound:(int) soundId sourceGroupId:(int) sourceGroupId +-(CDSoundSource *) soundSourceForSound:(int) soundId sourceGroupId:(int) sourceGroupId { if (!functioning_) { return nil; - } + } //Check if a source is available int sourceIndex = [self _getSourceIndexForSourceGroup:sourceGroupId]; - if (sourceIndex != CD_NO_SOURCE) { + if (sourceIndex != CD_NO_SOURCE) { CDSoundSource *result = [[CDSoundSource alloc] init:_sources[sourceIndex].sourceId sourceIndex:sourceIndex soundEngine:self]; [self _lockSource:sourceIndex lock:YES]; //Try to attach to the buffer @@ -933,34 +933,34 @@ static BOOL _mixerRateSet = NO; //Release the sound source we just created, this will also unlock the source [result release]; return nil; - } + } } else { //No available source within that source group return nil; } -} +} -(void) _soundSourcePreRelease:(CDSoundSource *) soundSource { CDLOGINFO(@"Denshion::CDSoundEngine _soundSourcePreRelease %i",soundSource->_sourceIndex); //Unlock the sound source's source [self _lockSource:soundSource->_sourceIndex lock:NO]; -} +} /** * Stop all sounds playing within a source group */ - (void) stopSourceGroup:(int) sourceGroupId { - + if (!functioning_ || sourceGroupId >= _sourceGroupTotal || sourceGroupId < 0) { return; - } + } int sourceCount = _sourceGroups[sourceGroupId].totalSources; for (int i=0; i < sourceCount; i++) { int sourceIndex = _sourceGroups[sourceGroupId].sourceStatuses[i] >> 1; alSourceStop(_sources[sourceIndex].sourceId); } alGetError();//Clear error in case we stopped any sounds that couldn't be stopped -} +} /** * Stop a sound playing. @@ -969,7 +969,7 @@ static BOOL _mixerRateSet = NO; - (void)stopSound:(ALuint) sourceId { if (!functioning_) { return; - } + } alSourceStop(sourceId); alGetError();//Clear error in case we stopped any sounds that couldn't be stopped } @@ -977,9 +977,9 @@ static BOOL _mixerRateSet = NO; - (void) stopAllSounds { for (int i=0; i < sourceTotal_; i++) { alSourceStop(_sources[i].sourceId); - } + } alGetError();//Clear error in case we stopped any sounds that couldn't be stopped -} +} - (void) pauseSound:(ALuint) sourceId { if (!functioning_) { @@ -1000,7 +1000,7 @@ static BOOL _mixerRateSet = NO; if (!functioning_) { return; } - + // only resume a sound id that is paused ALint state; alGetSourcei(soundId, AL_SOURCE_STATE, &state); @@ -1008,7 +1008,7 @@ static BOOL _mixerRateSet = NO; { return; } - + alSourcePlay(soundId); alGetError();//Clear error in case we stopped any sounds that couldn't be resumed } @@ -1030,19 +1030,19 @@ static BOOL _mixerRateSet = NO; if (sourceGroupId < 0 || sourceGroupId >= _sourceGroupTotal) { CDLOG(@"Denshion::CDSoundEngine setSourceGroupNonInterruptible invalid source group id %i",sourceGroupId); return; - } - + } + if (isNonInterruptible) { _sourceGroups[sourceGroupId].nonInterruptible = true; } else { _sourceGroups[sourceGroupId].nonInterruptible = false; - } + } } /** * Set the mute property for a source group. If mute is turned on any sounds in that source group * will be stopped and further sounds in that source group will play. However, turning mute off - * will not restart any sounds that were playing when mute was turned on. Also the mute setting + * will not restart any sounds that were playing when mute was turned on. Also the mute setting * for the sound engine must be taken into account. If the sound engine is mute no sounds will play * no matter what the source group mute setting is. */ @@ -1051,14 +1051,14 @@ static BOOL _mixerRateSet = NO; if (sourceGroupId < 0 || sourceGroupId >= _sourceGroupTotal) { CDLOG(@"Denshion::CDSoundEngine setSourceGroupEnabled invalid source group id %i",sourceGroupId); return; - } - + } + if (enabled) { _sourceGroups[sourceGroupId].enabled = true; [self stopSourceGroup:sourceGroupId]; } else { - _sourceGroups[sourceGroupId].enabled = false; - } + _sourceGroups[sourceGroupId].enabled = false; + } } /** @@ -1070,10 +1070,10 @@ static BOOL _mixerRateSet = NO; -(ALCcontext *) openALContext { return context; -} +} - (void) _dumpSourceGroupsInfo { -#ifdef CD_DEBUG +#ifdef CD_DEBUG CDLOGINFO(@"-------------- source Group Info --------------"); for (int i=0; i < _sourceGroupTotal; i++) { CDLOGINFO(@"Group: %i start:%i total:%i",i,_sourceGroups[i].startIndex, _sourceGroups[i].totalSources); @@ -1081,10 +1081,10 @@ static BOOL _mixerRateSet = NO; CDLOGINFO(@"----- Source statuses ----"); for (int j=0; j < _sourceGroups[i].totalSources; j++) { CDLOGINFO(@"Source status:%i index=%i locked=%i",j,_sourceGroups[i].sourceStatuses[j] >> 1, _sourceGroups[i].sourceStatuses[j] & 1); - } - } -#endif -} + } + } +#endif +} @end @@ -1105,7 +1105,7 @@ static BOOL _mixerRateSet = NO; enabled_ = YES; mute_ = NO; _preMuteGain = self.gain; - } + } return self; } @@ -1116,19 +1116,19 @@ static BOOL _mixerRateSet = NO; //Notify sound engine we are about to release [_engine _soundSourcePreRelease:self]; [super dealloc]; -} +} - (void) setPitch:(float) newPitchValue { alSourcef(_sourceId, AL_PITCH, newPitchValue); CDSOUNDSOURCE_UPDATE_LAST_ERROR; -} +} - (void) setGain:(float) newGainValue { if (!mute_) { - alSourcef(_sourceId, AL_GAIN, newGainValue); + alSourcef(_sourceId, AL_GAIN, newGainValue); } else { _preMuteGain = newGainValue; - } + } CDSOUNDSOURCE_UPDATE_LAST_ERROR; } @@ -1150,7 +1150,7 @@ static BOOL _mixerRateSet = NO; alGetSourcei(_sourceId, AL_SOURCE_STATE, &state); CDSOUNDSOURCE_UPDATE_LAST_ERROR; return (state == AL_PLAYING); -} +} - (float) pitch { ALfloat pitchVal; @@ -1174,8 +1174,8 @@ static BOOL _mixerRateSet = NO; return val; } else { return _preMuteGain; - } -} + } +} - (BOOL) looping { ALfloat val; @@ -1187,7 +1187,7 @@ static BOOL _mixerRateSet = NO; -(BOOL) stop { alSourceStop(_sourceId); return CDSOUNDSOURCE_ERROR_HANDLER; -} +} -(BOOL) play { if (enabled_) { @@ -1197,15 +1197,15 @@ static BOOL _mixerRateSet = NO; if (alcGetCurrentContext() == NULL) { CDLOGINFO(@"Denshion::CDSoundSource - posting bad OpenAL context message"); [[NSNotificationCenter defaultCenter] postNotificationName:kCDN_BadAlContext object:nil]; - } + } return NO; } else { return YES; - } + } } else { return NO; } -} +} -(BOOL) pause { alSourcePause(_sourceId); @@ -1223,26 +1223,26 @@ static BOOL _mixerRateSet = NO; -(int) soundId { return _soundId; -} +} -(float) durationInSeconds { return [_engine bufferDurationInSeconds:_soundId]; -} +} #pragma mark CDSoundSource AudioInterrupt protocol - (BOOL) mute { return mute_; -} +} /** * Setting mute silences all sounds but playing sounds continue to advance playback */ - (void) setMute:(BOOL) newMuteValue { - + if (newMuteValue == mute_) { return; } - + if (newMuteValue) { //Remember what the gain was _preMuteGain = self.gain; @@ -1252,7 +1252,7 @@ static BOOL _mixerRateSet = NO; //Restore gain to what it was before being muted mute_ = newMuteValue; self.gain = _preMuteGain; - } + } } - (BOOL) enabled { @@ -1263,12 +1263,12 @@ static BOOL _mixerRateSet = NO; { if (enabled_ == enabledValue) { return; - } + } enabled_ = enabledValue; if (enabled_ == NO) { [self stop]; - } -} + } +} @end @@ -1284,35 +1284,35 @@ static BOOL _mixerRateSet = NO; mute_ = NO; } return self; -} +} -(void) addAudioInterruptTarget:(NSObject*) interruptibleTarget { //Synchronize child with group settings; [interruptibleTarget setMute:mute_]; [interruptibleTarget setEnabled:enabled_]; [children_ addObject:interruptibleTarget]; -} +} -(void) removeAudioInterruptTarget:(NSObject*) interruptibleTarget { [children_ removeObjectIdenticalTo:interruptibleTarget]; -} +} - (BOOL) mute { return mute_; -} +} /** * Setting mute silences all sounds but playing sounds continue to advance playback */ - (void) setMute:(BOOL) newMuteValue { - + if (newMuteValue == mute_) { return; } - + for (NSObject* target in children_) { [target setMute:newMuteValue]; - } + } } - (BOOL) enabled { @@ -1324,11 +1324,11 @@ static BOOL _mixerRateSet = NO; if (enabledValue == enabled_) { return; } - + for (NSObject* target in children_) { [target setEnabled:enabledValue]; - } -} + } +} @end @@ -1346,9 +1346,9 @@ static BOOL _mixerRateSet = NO; [_loadRequests retain]; _soundEngine = theSoundEngine; [_soundEngine retain]; - } + } return self; -} +} -(void) main { CDLOGINFO(@"Denshion::CDAsynchBufferLoader - loading buffers"); @@ -1361,20 +1361,20 @@ static BOOL _mixerRateSet = NO; for (CDBufferLoadRequest *loadRequest in _loadRequests) { [_soundEngine loadBuffer:loadRequest.soundId filePath:loadRequest.filePath]; _soundEngine.asynchLoadProgress += increment; - } - } - + } + } + //Completed _soundEngine.asynchLoadProgress = 1.0f; [[NSNotificationCenter defaultCenter] postNotificationName:kCDN_AsynchLoadComplete object:nil]; - -} + +} -(void) dealloc { [_loadRequests release]; [_soundEngine release]; [super dealloc]; -} +} @end @@ -1408,18 +1408,18 @@ static BOOL _mixerRateSet = NO; @synthesize start,end,interpolationType; -(float) interpolate:(float) t { - + if (t < 1.0f) { switch (interpolationType) { case kIT_Linear: //Linear interpolation return ((end - start) * t) + start; - + case kIT_SCurve: //Cubic s curve t^2 * (3 - 2t) return ((float)(t * t * (3.0 - (2.0 * t))) * (end - start)) + start; - - case kIT_Exponential: + + case kIT_Exponential: //Formulas taken from EaseAction if (end > start) { //Fade in @@ -1435,7 +1435,7 @@ static BOOL _mixerRateSet = NO; } } else { return end; - } + } } -(id) init:(tCDInterpolationType) type startVal:(float) startVal endVal:(float) endVal { @@ -1443,7 +1443,7 @@ static BOOL _mixerRateSet = NO; start = startVal; end = endVal; interpolationType = type; - } + } return self; } @@ -1461,7 +1461,7 @@ static BOOL _mixerRateSet = NO; if (target) { //Release the previous target if there is one [target release]; - } + } target = theTarget; #if CD_DEBUG //Check target is of the required type @@ -1469,26 +1469,26 @@ static BOOL _mixerRateSet = NO; CDLOG(@"Denshion::CDPropertyModifier target is not of type %@",[self _allowableType]); NSAssert([theTarget isKindOfClass:[CDSoundEngine class]], @"CDPropertyModifier target not of required type"); } -#endif +#endif [target retain]; startValue = startVal; endValue = endVal; if (interpolator) { //Release previous interpolator if there is one [interpolator release]; - } + } interpolator = [[CDFloatInterpolator alloc] init:type startVal:startVal endVal:endVal]; stopTargetWhenComplete = NO; } return self; -} +} -(void) dealloc { CDLOGINFO(@"Denshion::CDPropertyModifier deallocated %@",self); [target release]; [interpolator release]; [super dealloc]; -} +} -(void) modify:(float) t { if (t < 1.0) { @@ -1498,9 +1498,9 @@ static BOOL _mixerRateSet = NO; [self _setTargetProperty:endValue]; if (stopTargetWhenComplete) { [self _stopTarget]; - } - } -} + } + } +} -(float) startValue { return startValue; @@ -1510,7 +1510,7 @@ static BOOL _mixerRateSet = NO; { startValue = startVal; interpolator.start = startVal; -} +} -(float) endValue { return startValue; @@ -1520,7 +1520,7 @@ static BOOL _mixerRateSet = NO; { endValue = endVal; interpolator.end = endVal; -} +} -(tCDInterpolationType) interpolationType { return interpolator.interpolationType; @@ -1528,23 +1528,23 @@ static BOOL _mixerRateSet = NO; -(void) setInterpolationType:(tCDInterpolationType) interpolationType { interpolator.interpolationType = interpolationType; -} +} -(void) _setTargetProperty:(float) newVal { -} +} -(float) _getTargetProperty { return 0.0f; -} +} -(void) _stopTarget { -} +} -(Class) _allowableType { return [NSObject class]; -} +} @end /////////////////////////////////////////////////////////////////////////////////////// @@ -1554,7 +1554,7 @@ static BOOL _mixerRateSet = NO; -(void) _setTargetProperty:(float) newVal { ((CDSoundSource*)target).gain = newVal; -} +} -(float) _getTargetProperty { return ((CDSoundSource*)target).gain; @@ -1566,7 +1566,7 @@ static BOOL _mixerRateSet = NO; -(Class) _allowableType { return [CDSoundSource class]; -} +} @end @@ -1577,7 +1577,7 @@ static BOOL _mixerRateSet = NO; -(void) _setTargetProperty:(float) newVal { ((CDSoundSource*)target).pan = newVal; -} +} -(float) _getTargetProperty { return ((CDSoundSource*)target).pan; @@ -1589,7 +1589,7 @@ static BOOL _mixerRateSet = NO; -(Class) _allowableType { return [CDSoundSource class]; -} +} @end @@ -1600,7 +1600,7 @@ static BOOL _mixerRateSet = NO; -(void) _setTargetProperty:(float) newVal { ((CDSoundSource*)target).pitch = newVal; -} +} -(float) _getTargetProperty { return ((CDSoundSource*)target).pitch; @@ -1612,7 +1612,7 @@ static BOOL _mixerRateSet = NO; -(Class) _allowableType { return [CDSoundSource class]; -} +} @end @@ -1623,7 +1623,7 @@ static BOOL _mixerRateSet = NO; -(void) _setTargetProperty:(float) newVal { ((CDSoundEngine*)target).masterGain = newVal; -} +} -(float) _getTargetProperty { return ((CDSoundEngine*)target).masterGain; @@ -1635,7 +1635,8 @@ static BOOL _mixerRateSet = NO; -(Class) _allowableType { return [CDSoundEngine class]; -} +} @end + diff --git a/native/cocos/audio/ios/SimpleAudioEngine.mm b/native/cocos/audio/ios/SimpleAudioEngine.mm index e5beeb7e16..7d95c9c44e 100644 --- a/native/cocos/audio/ios/SimpleAudioEngine.mm +++ b/native/cocos/audio/ios/SimpleAudioEngine.mm @@ -28,121 +28,183 @@ THE SOFTWARE. USING_NS_CC; +static bool __isAudioPreloadOrPlayed = false; + static void static_end() { - [SimpleAudioEngine end]; + if (__isAudioPreloadOrPlayed) + { + [SimpleAudioEngine end]; + } + + __isAudioPreloadOrPlayed = false; } static void static_preloadBackgroundMusic(const char* pszFilePath) { + __isAudioPreloadOrPlayed = true; [[SimpleAudioEngine sharedEngine] preloadBackgroundMusic: [NSString stringWithUTF8String: pszFilePath]]; } static void static_playBackgroundMusic(const char* pszFilePath, bool bLoop) { + __isAudioPreloadOrPlayed = true; [[SimpleAudioEngine sharedEngine] playBackgroundMusic: [NSString stringWithUTF8String: pszFilePath] loop: bLoop]; } static void static_stopBackgroundMusic() { + if (!__isAudioPreloadOrPlayed) + return; + [[SimpleAudioEngine sharedEngine] stopBackgroundMusic]; } static void static_pauseBackgroundMusic() { + if (!__isAudioPreloadOrPlayed) + return; + [[SimpleAudioEngine sharedEngine] pauseBackgroundMusic]; } static void static_resumeBackgroundMusic() { + if (!__isAudioPreloadOrPlayed) + return; + [[SimpleAudioEngine sharedEngine] resumeBackgroundMusic]; -} +} static void static_rewindBackgroundMusic() { + if (!__isAudioPreloadOrPlayed) + return; + [[SimpleAudioEngine sharedEngine] rewindBackgroundMusic]; } static bool static_willPlayBackgroundMusic() { + if (!__isAudioPreloadOrPlayed) + return false; + return [[SimpleAudioEngine sharedEngine] willPlayBackgroundMusic]; } static bool static_isBackgroundMusicPlaying() { + if (!__isAudioPreloadOrPlayed) + return false; + return [[SimpleAudioEngine sharedEngine] isBackgroundMusicPlaying]; } static float static_getBackgroundMusicVolume() { + if (!__isAudioPreloadOrPlayed) + return 0.0f; + return [[SimpleAudioEngine sharedEngine] backgroundMusicVolume]; } static void static_setBackgroundMusicVolume(float volume) { + if (!__isAudioPreloadOrPlayed) + return; + volume = MAX( MIN(volume, 1.0), 0 ); [SimpleAudioEngine sharedEngine].backgroundMusicVolume = volume; } - + static float static_getEffectsVolume() { + if (!__isAudioPreloadOrPlayed) + return 0.0f; + return [[SimpleAudioEngine sharedEngine] effectsVolume]; } - + static void static_setEffectsVolume(float volume) { + if (!__isAudioPreloadOrPlayed) + return; + volume = MAX( MIN(volume, 1.0), 0 ); [SimpleAudioEngine sharedEngine].effectsVolume = volume; } static unsigned int static_playEffect(const char* pszFilePath, bool bLoop, Float32 pszPitch, Float32 pszPan, Float32 pszGain) { + __isAudioPreloadOrPlayed = true; return [[SimpleAudioEngine sharedEngine] playEffect:[NSString stringWithUTF8String: pszFilePath] loop:bLoop pitch:pszPitch pan: pszPan gain:pszGain]; } - + static void static_stopEffect(int nSoundId) { + if (!__isAudioPreloadOrPlayed) + return; + [[SimpleAudioEngine sharedEngine] stopEffect: nSoundId]; } - + static void static_preloadEffect(const char* pszFilePath) { + __isAudioPreloadOrPlayed = true; [[SimpleAudioEngine sharedEngine] preloadEffect: [NSString stringWithUTF8String: pszFilePath]]; } - + static void static_unloadEffect(const char* pszFilePath) { + if (!__isAudioPreloadOrPlayed) + return; + [[SimpleAudioEngine sharedEngine] unloadEffect: [NSString stringWithUTF8String: pszFilePath]]; } static void static_pauseEffect(unsigned int uSoundId) { + if (!__isAudioPreloadOrPlayed) + return; + [[SimpleAudioEngine sharedEngine] pauseEffect: uSoundId]; } static void static_pauseAllEffects() { + if (!__isAudioPreloadOrPlayed) + return; + [[SimpleAudioEngine sharedEngine] pauseAllEffects]; } static void static_resumeEffect(unsigned int uSoundId) { + if (!__isAudioPreloadOrPlayed) + return; + [[SimpleAudioEngine sharedEngine] resumeEffect: uSoundId]; } static void static_resumeAllEffects() { + if (!__isAudioPreloadOrPlayed) + return; + [[SimpleAudioEngine sharedEngine] resumeAllEffects]; } static void static_stopAllEffects() { + if (!__isAudioPreloadOrPlayed) + return; + [[SimpleAudioEngine sharedEngine] stopAllEffects]; } namespace CocosDenshion { -static SimpleAudioEngine *s_pEngine; +static SimpleAudioEngine *s_pEngine = nullptr; SimpleAudioEngine::SimpleAudioEngine() { @@ -160,7 +222,7 @@ SimpleAudioEngine* SimpleAudioEngine::getInstance() { s_pEngine = new (std::nothrow) SimpleAudioEngine(); } - + return s_pEngine; } @@ -171,7 +233,7 @@ void SimpleAudioEngine::end() delete s_pEngine; s_pEngine = nullptr; } - + static_end(); } @@ -202,7 +264,7 @@ void SimpleAudioEngine::pauseBackgroundMusic() void SimpleAudioEngine::resumeBackgroundMusic() { static_resumeBackgroundMusic(); -} +} void SimpleAudioEngine::rewindBackgroundMusic() { diff --git a/native/cocos/audio/ios/SimpleAudioEngine_objc.h b/native/cocos/audio/ios/SimpleAudioEngine_objc.h index 40ea380ce6..bfceac2862 100644 --- a/native/cocos/audio/ios/SimpleAudioEngine_objc.h +++ b/native/cocos/audio/ios/SimpleAudioEngine_objc.h @@ -1,16 +1,16 @@ /* Copyright (c) 2010 Steve Oldmeadow - + 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 @@ -18,7 +18,7 @@ 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. - + $Id$ */ @@ -30,15 +30,15 @@ This is recommended for basic audio requirements. If you just want to play some sound fx and some background music and have no interest in learning the lower level workings then this is the interface to use. - + Requirements: - - Firmware: OS 2.2 or greater + - Firmware: OS 2.2 or greater - Files: SimpleAudioEngine.*, CocosDenshion.* - Frameworks: OpenAL, AudioToolbox, AVFoundation @since v0.8 */ @interface SimpleAudioEngine : NSObject { - + BOOL mute_; BOOL enabled_; } diff --git a/native/cocos/audio/ios/SimpleAudioEngine_objc.m b/native/cocos/audio/ios/SimpleAudioEngine_objc.m index c224ed924a..2c4cec0c97 100644 --- a/native/cocos/audio/ios/SimpleAudioEngine_objc.m +++ b/native/cocos/audio/ios/SimpleAudioEngine_objc.m @@ -1,16 +1,16 @@ /* Copyright (c) 2010 Steve Oldmeadow - + 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 @@ -18,7 +18,7 @@ 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. - + $Id$ */ @@ -71,14 +71,14 @@ static CDBufferManager *bufferManager = nil; [super dealloc]; } -+(void) end ++(void) end { am = nil; [CDAudioManager end]; [bufferManager release]; [sharedEngine release]; sharedEngine = nil; -} +} #pragma mark SimpleAudioEngine - background music @@ -103,11 +103,11 @@ static CDBufferManager *bufferManager = nil; -(void) pauseBackgroundMusic { [am pauseBackgroundMusic]; -} +} -(void) resumeBackgroundMusic { [am resumeBackgroundMusic]; -} +} -(void) rewindBackgroundMusic { [am rewindBackgroundMusic]; @@ -115,7 +115,7 @@ static CDBufferManager *bufferManager = nil; -(BOOL) isBackgroundMusicPlaying { return [am isBackgroundMusicPlaying]; -} +} -(BOOL) willPlayBackgroundMusic { return [am willPlayBackgroundMusic]; @@ -135,12 +135,12 @@ static CDBufferManager *bufferManager = nil; return [soundEngine playSound:soundId sourceGroupId:0 pitch:pitch pan:pan gain:gain loop:loop]; } else { return CD_MUTE; - } + } } -(void) stopEffect:(ALuint) soundId { [soundEngine stopSound:soundId]; -} +} -(void) pauseEffect:(ALuint) soundId { [soundEngine pauseSound: soundId]; @@ -187,7 +187,7 @@ static CDBufferManager *bufferManager = nil; if (mute_ != muteValue) { mute_ = muteValue; am.mute = mute_; - } + } } -(BOOL) enabled @@ -200,7 +200,7 @@ static CDBufferManager *bufferManager = nil; if (enabled_ != enabledValue) { enabled_ = enabledValue; am.enabled = enabled_; - } + } } @@ -208,23 +208,23 @@ static CDBufferManager *bufferManager = nil; -(float) backgroundMusicVolume { return am.backgroundMusic.volume; -} +} -(void) setBackgroundMusicVolume:(float) volume { am.backgroundMusic.volume = volume; -} +} #pragma mark SimpleAudioEngine - EffectsVolume -(float) effectsVolume { return am.soundEngine.masterGain; -} +} -(void) setEffectsVolume:(float) volume { am.soundEngine.masterGain = volume; -} +} -(CDSoundSource *) soundSourceForFile:(NSString*) filePath { int soundId = [bufferManager bufferForFile:filePath create:YES]; @@ -234,7 +234,7 @@ static CDBufferManager *bufferManager = nil; return result; } else { return nil; - } -} + } +} @end diff --git a/native/cocos/audio/mac/CDAudioManager.h b/native/cocos/audio/mac/CDAudioManager.h index 36e1e695dc..bfc07a04f5 100644 --- a/native/cocos/audio/mac/CDAudioManager.h +++ b/native/cocos/audio/mac/CDAudioManager.h @@ -1,16 +1,16 @@ /* Copyright (c) 2010 Steve Oldmeadow - + 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 @@ -18,7 +18,7 @@ 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. - + $Id$ */ @@ -54,14 +54,14 @@ typedef enum { /** Notifications */ extern NSString * const kCDN_AudioManagerInitialised; -@interface CDAsynchInitialiser : NSOperation {} +@interface CDAsynchInitialiser : NSOperation {} @end /** CDAudioManager supports two long audio source channels called left and right*/ typedef enum { kASC_Left = 0, kASC_Right = 1 -} tAudioSourceChannel; +} tAudioSourceChannel; typedef enum { kLAS_Init, @@ -94,18 +94,18 @@ typedef enum { NSString *audioSourceFilePath; NSInteger numberOfLoops; float volume; - id delegate; + id delegate; BOOL mute; BOOL enabled_; BOOL backgroundMusic; // whether background music is paused BOOL paused; -@public +@public BOOL systemPaused;//Used for auto resign handling NSTimeInterval systemPauseLocation;//Used for auto resign handling @protected tLongAudioSourceState state; -} +} @property (readonly) CCAudioPlayer *audioSourcePlayer; @property (readonly) NSString *audioSourceFilePath; @property (readwrite, nonatomic) NSInteger numberOfLoops; @@ -119,7 +119,7 @@ typedef enum { -(void) load:(NSString*) filePath; /** Plays the audio source */ -(void) play; -/** Stops playing the audio soruce */ +/** Stops playing the audio source */ -(void) stop; /** Pauses the audio source */ -(void) pause; @@ -132,15 +132,15 @@ typedef enum { @end -/** +/** CDAudioManager manages audio requirements for a game. It provides access to a CDSoundEngine object for playing sound effects. It provides access to two CDLongAudioSource object (left and right channel) for playing long duration audio such as background music and narration tracks. Additionally it manages the audio session to take care of things like audio session interruption and interacting with the audio of other apps that are running on the device. - + Requirements: - - Firmware: OS 2.2 or greater + - Firmware: OS 2.2 or greater - Files: CDAudioManager.*, CocosDenshion.* - Frameworks: OpenAL, AudioToolbox, AVFoundation @since v0.8 @@ -160,7 +160,7 @@ typedef enum { BOOL _interrupted; BOOL _audioSessionActive; BOOL enabled_; - + //For handling resign/become active BOOL _isObservingAppEvents; tAudioManagerResignBehavior _resignBehavior; diff --git a/native/cocos/audio/mac/CDAudioManager.m b/native/cocos/audio/mac/CDAudioManager.m index 418bca66d5..ced152e4e9 100644 --- a/native/cocos/audio/mac/CDAudioManager.m +++ b/native/cocos/audio/mac/CDAudioManager.m @@ -1,16 +1,16 @@ /* Copyright (c) 2010 Steve Oldmeadow - + 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 @@ -18,7 +18,7 @@ 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. - + $Id$ */ @@ -27,13 +27,13 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised"; -//NSOperation object used to asynchronously initialise +//NSOperation object used to asynchronously initialise @implementation CDAsynchInitialiser -(void) main { [super main]; [CDAudioManager sharedManager]; -} +} @end @@ -57,10 +57,10 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised"; [audioSourcePlayer release]; [audioSourceFilePath release]; [super dealloc]; -} +} -(void) load:(NSString*) filePath { - //We have alread loaded a file previously, check if we are being asked to load the same file + //We have already loaded a file previously, check if we are being asked to load the same file if (state == kLAS_Init || ![filePath isEqualToString:audioSourceFilePath]) { CDLOGINFO(@"Denshion::CDLongAudioSource - Loading new audio source %@",filePath); //New file @@ -78,10 +78,10 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised"; if (delegate && [delegate respondsToSelector:@selector(cdAudioSourceFileDidChange:)]) { //Tell our delegate the file has changed [delegate cdAudioSourceFileDidChange:self]; - } + } } else { CDLOG(@"Denshion::CDLongAudioSource - Error initialising audio player: %@",error); - } + } } else { //Same file - just return it to a consistent state [self pause]; @@ -90,7 +90,7 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised"; audioSourcePlayer.volume = volume; audioSourcePlayer.numberOfLoops = numberOfLoops; state = kLAS_Loaded; -} +} -(void) play { if (enabled_) { @@ -99,18 +99,18 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised"; [audioSourcePlayer play]; } else { CDLOGINFO(@"Denshion::CDLongAudioSource long audio source didn't play because it is disabled"); - } -} + } +} -(void) stop { paused = NO; [audioSourcePlayer stop]; -} +} -(void) pause { paused = YES; [audioSourcePlayer pause]; -} +} -(void) rewind { paused = NO; @@ -121,7 +121,7 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised"; -(void) resume { paused = NO; [audioSourcePlayer resume]; -} +} -(BOOL) isPlaying { if (state != kLAS_Init) { @@ -136,10 +136,10 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised"; volume = newVolume; if (state != kLAS_Init && !mute) { audioSourcePlayer.volume = newVolume; - } + } } --(float) volume +-(float) volume { return volume; } @@ -148,9 +148,9 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised"; -(BOOL) mute { return mute; -} +} --(void) setMute:(BOOL) muteValue +-(void) setMute:(BOOL) muteValue { if (mute != muteValue) { if (mute) { @@ -160,15 +160,15 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised"; audioSourcePlayer.volume = 0.0f; } mute = muteValue; - } -} + } +} --(BOOL) enabled +-(BOOL) enabled { return enabled_; -} +} --(void) setEnabled:(BOOL)enabledValue +-(void) setEnabled:(BOOL)enabledValue { if (enabledValue != enabled_) { enabled_ = enabledValue; @@ -176,25 +176,25 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised"; //"Stop" the sounds [self pause]; [self rewind]; - } - } -} + } + } +} -(NSInteger) numberOfLoops { return numberOfLoops; -} +} -(void) setNumberOfLoops:(NSInteger) loopCount { audioSourcePlayer.numberOfLoops = loopCount; numberOfLoops = loopCount; -} +} - (void)audioPlayerDidFinishPlaying:(CCAudioPlayer *)player successfully:(BOOL)flag { CDLOGINFO(@"Denshion::CDLongAudioSource - audio player finished"); -#if TARGET_IPHONE_SIMULATOR +#if TARGET_IPHONE_SIMULATOR CDLOGINFO(@"Denshion::CDLongAudioSource - workaround for OpenAL clobbered audio issue"); - //This is a workaround for an issue in all simulators (tested to 3.1.2). Problem is + //This is a workaround for an issue in all simulators (tested to 3.1.2). Problem is //that OpenAL audio playback is clobbered when an CCAudioPlayer stops. Workaround //is to keep the player playing on an endless loop with 0 volume and then when //it is played again reset the volume and set loop count appropriately. @@ -202,11 +202,11 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised"; player.numberOfLoops = -1; player.volume = 0; [player play]; -#endif +#endif if (delegate && [delegate respondsToSelector:@selector(cdAudioSourceDidFinishPlaying:)]) { [delegate cdAudioSourceDidFinishPlaying:self]; - } -} + } +} -(void)audioPlayerBeginInterruption:(CCAudioPlayer *)player { CDLOGINFO(@"Denshion::CDLongAudioSource - audio player interrupted"); @@ -215,16 +215,16 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised"; -(void)audioPlayerEndInterruption:(CCAudioPlayer *)player { CDLOGINFO(@"Denshion::CDLongAudioSource - audio player resumed"); if (self.backgroundMusic) { - //Check if background music can play as rules may have changed during + //Check if background music can play as rules may have changed during //the interruption. This is to address a specific issue in 4.x when //fast task switching if([CDAudioManager sharedManager].willPlayBackgroundMusic) { [player play]; - } + } } else { [player play]; - } -} + } +} @end @@ -249,26 +249,26 @@ static BOOL configured = FALSE; NSError *activationError = nil; if ([[AVAudioSession sharedInstance] setActive:active error:&activationError]) { _audioSessionActive = active; - CDLOGINFO(@"Denshion::CDAudioManager - Audio session set active %i succeeded", active); + CDLOGINFO(@"Denshion::CDAudioManager - Audio session set active %i succeeded", active); return YES; } else { //Failed - CDLOG(@"Denshion::CDAudioManager - Audio session set active %i failed with error %@", active, activationError); + CDLOG(@"Denshion::CDAudioManager - Audio session set active %i failed with error %@", active, activationError); return NO; - } -} + } +} -(BOOL) audioSessionSetCategory:(NSString*) category { NSError *categoryError = nil; if ([[AVAudioSession sharedInstance] setCategory:category error:&categoryError]) { - CDLOGINFO(@"Denshion::CDAudioManager - Audio session set category %@ succeeded", category); + CDLOGINFO(@"Denshion::CDAudioManager - Audio session set category %@ succeeded", category); return YES; } else { //Failed - CDLOG(@"Denshion::CDAudioManager - Audio session set category %@ failed with error %@", category, categoryError); + CDLOG(@"Denshion::CDAudioManager - Audio session set category %@ failed with error %@", category, categoryError); return NO; - } -} + } +} // Init + (CDAudioManager *) sharedManager @@ -282,14 +282,14 @@ static BOOL configured = FALSE; sharedManager = [[CDAudioManager alloc] init:configuredMode]; _sharedManagerState = kAMStateInitialised;//This is only really relevant when using asynchronous initialisation [[NSNotificationCenter defaultCenter] postNotificationName:kCDN_AudioManagerInitialised object:nil]; - } + } } return sharedManager; } + (tAudioManagerState) sharedManagerState { return _sharedManagerState; -} +} /** * Call this to set up audio manager asynchronously. Initialisation is finished when sharedManagerState == kAMStateInitialised @@ -302,9 +302,9 @@ static BOOL configured = FALSE; CDAsynchInitialiser *initOp = [[[CDAsynchInitialiser alloc] init] autorelease]; NSOperationQueue *opQ = [[[NSOperationQueue alloc] init] autorelease]; [opQ addOperation:initOp]; - } + } } -} +} + (id) alloc { @@ -321,7 +321,7 @@ static BOOL configured = FALSE; + (void) configure: (tAudioManagerMode) mode { configuredMode = mode; configured = TRUE; -} +} -(BOOL) isOtherAudioPlaying { UInt32 isPlaying = 0; @@ -334,7 +334,7 @@ static BOOL configured = FALSE; _mode = mode; switch (_mode) { - + case kAMM_FxOnly: //Share audio with other app CDLOGINFO(@"Denshion::CDAudioManager - Audio will be shared"); @@ -342,7 +342,7 @@ static BOOL configured = FALSE; _audioSessionCategory = AVAudioSessionCategoryAmbient; willPlayBackgroundMusic = NO; break; - + case kAMM_FxPlusMusic: //Use audio exclusively - if other audio is playing it will be stopped CDLOGINFO(@"Denshion::CDAudioManager - Audio will be exclusive"); @@ -350,7 +350,7 @@ static BOOL configured = FALSE; _audioSessionCategory = AVAudioSessionCategorySoloAmbient; willPlayBackgroundMusic = YES; break; - + case kAMM_MediaPlayback: //Use audio exclusively, ignore mute switch and sleep CDLOGINFO(@"Denshion::CDAudioManager - Media playback mode, audio will be exclusive"); @@ -358,7 +358,7 @@ static BOOL configured = FALSE; _audioSessionCategory = AVAudioSessionCategoryPlayback; willPlayBackgroundMusic = YES; break; - + case kAMM_PlayAndRecord: //Use audio exclusively, ignore mute switch and sleep, has inputs and outputs CDLOGINFO(@"Denshion::CDAudioManager - Play and record mode, audio will be exclusive"); @@ -366,7 +366,7 @@ static BOOL configured = FALSE; _audioSessionCategory = AVAudioSessionCategoryPlayAndRecord; willPlayBackgroundMusic = YES; break; - + default: //kAudioManagerFxPlusMusicIfNoOtherAudio if ([self isOtherAudioPlaying]) { @@ -379,18 +379,18 @@ static BOOL configured = FALSE; //_audioSessionCategory = kAudioSessionCategory_SoloAmbientSound; _audioSessionCategory = AVAudioSessionCategorySoloAmbient; willPlayBackgroundMusic = YES; - } - + } + break; } - + [self audioSessionSetCategory:_audioSessionCategory]; - -} + +} /** - * This method is used to work around various bugs introduced in 4.x OS versions. In some circumstances the - * audio session is interrupted but never resumed, this results in the loss of OpenAL audio when following + * This method is used to work around various bugs introduced in 4.x OS versions. In some circumstances the + * audio session is interrupted but never resumed, this results in the loss of OpenAL audio when following * standard practices. If we detect this situation then we will attempt to resume the audio session ourselves. * Known triggers: lock the device then unlock it (iOS 4.2 gm), playback a song using MPMediaPlayer (iOS 4.0) */ @@ -398,16 +398,16 @@ static BOOL configured = FALSE; if (_interrupted && alcGetCurrentContext() == NULL) { CDLOG(@"Denshion::CDAudioManager - bad OpenAL context detected, attempting to resume audio session"); [self audioSessionResumed]; - } -} + } +} - (id) init: (tAudioManagerMode) mode { if ((self = [super init])) { - - //Initialise the audio session + + //Initialise the audio session AVAudioSession* session = [AVAudioSession sharedInstance]; session.delegate = self; - + _mode = mode; backgroundMusicCompletionSelector = nil; _isObservingAppEvents = FALSE; @@ -418,27 +418,27 @@ static BOOL configured = FALSE; _audioSessionActive = NO; [self setMode:mode]; soundEngine = [[CDSoundEngine alloc] init]; - + //Set up audioSource channels audioSourceChannels = [[NSMutableArray alloc] init]; CDLongAudioSource *leftChannel = [[CDLongAudioSource alloc] init]; leftChannel.backgroundMusic = YES; CDLongAudioSource *rightChannel = [[CDLongAudioSource alloc] init]; rightChannel.backgroundMusic = NO; - [audioSourceChannels insertObject:leftChannel atIndex:kASC_Left]; + [audioSourceChannels insertObject:leftChannel atIndex:kASC_Left]; [audioSourceChannels insertObject:rightChannel atIndex:kASC_Right]; [leftChannel release]; [rightChannel release]; //Used to support legacy APIs backgroundMusic = [self audioSourceForChannel:BACKGROUND_MUSIC_CHANNEL]; backgroundMusic.delegate = self; - + //Add handler for bad al context messages, these are posted by the sound engine. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(badAlContextHandler) name:kCDN_BadAlContext object:nil]; - } - return self; -} + } + return self; +} -(void) dealloc { CDLOGINFO(@"Denshion::CDAudioManager - deallocating"); @@ -448,13 +448,13 @@ static BOOL configured = FALSE; [self audioSessionSetActive:NO]; [audioSourceChannels release]; [super dealloc]; -} +} /** Retrieves the audio source for the specified channel */ --(CDLongAudioSource*) audioSourceForChannel:(tAudioSourceChannel) channel +-(CDLongAudioSource*) audioSourceForChannel:(tAudioSourceChannel) channel { return (CDLongAudioSource*)[audioSourceChannels objectAtIndex:channel]; -} +} /** Loads the data from the specified file path to the channel's audio source */ -(CDLongAudioSource*) audioSourceLoad:(NSString*) filePath channel:(tAudioSourceChannel) channel @@ -464,14 +464,14 @@ static BOOL configured = FALSE; [audioSource load:filePath]; } return audioSource; -} +} -(BOOL) isBackgroundMusicPlaying { return [self.backgroundMusic isPlaying]; -} +} //NB: originally I tried using a route change listener and intended to store the current route, -//however, on a 3gs running 3.1.2 no route change is generated when the user switches the +//however, on a 3gs running 3.1.2 no route change is generated when the user switches the //ringer mute switch to off (i.e. enables sound) therefore polling is the only reliable way to //determine ringer switch state -(BOOL) isDeviceMuted { @@ -479,36 +479,36 @@ static BOOL configured = FALSE; #if TARGET_IPHONE_SIMULATOR //Calling audio route stuff on the simulator causes problems return NO; -#else +#else CFStringRef newAudioRoute; UInt32 propertySize = sizeof (CFStringRef); - + AudioSessionGetProperty ( kAudioSessionProperty_AudioRoute, &propertySize, &newAudioRoute ); - + if (newAudioRoute == NULL) { //Don't expect this to happen but playing safe otherwise a null in the CFStringCompare will cause a crash return YES; - } else { + } else { CFComparisonResult newDeviceIsMuted = CFStringCompare ( newAudioRoute, (CFStringRef) @"", 0 ); - + return (newDeviceIsMuted == kCFCompareEqualTo); - } + } #endif -} +} #pragma mark Audio Interrupt Protocol -(BOOL) mute { return _mute; -} +} -(void) setMute:(BOOL) muteValue { if (muteValue != _mute) { @@ -516,13 +516,13 @@ static BOOL configured = FALSE; [soundEngine setMute:muteValue]; for( CDLongAudioSource *audioSource in audioSourceChannels) { audioSource.mute = muteValue; - } - } + } + } } -(BOOL) enabled { return enabled_; -} +} -(void) setEnabled:(BOOL) enabledValue { if (enabledValue != enabled_) { @@ -530,20 +530,20 @@ static BOOL configured = FALSE; [soundEngine setEnabled:enabled_]; for( CDLongAudioSource *audioSource in audioSourceChannels) { audioSource.enabled = enabled_; - } - } + } + } } -(CDLongAudioSource*) backgroundMusic { return backgroundMusic; -} +} //Load background music ready for playing -(void) preloadBackgroundMusic:(NSString*) filePath { - [self.backgroundMusic load:filePath]; -} + [self.backgroundMusic load:filePath]; +} -(void) playBackgroundMusic:(NSString*) filePath loop:(BOOL) loop { @@ -571,7 +571,7 @@ static BOOL configured = FALSE; -(void) pauseBackgroundMusic { [self.backgroundMusic pause]; -} +} -(void) resumeBackgroundMusic { @@ -579,35 +579,35 @@ static BOOL configured = FALSE; CDLOGINFO(@"Denshion::CDAudioManager - resume bgm aborted because audio is not exclusive or sound is muted"); return; } - + if (![self.backgroundMusic paused]) { return; } - + [self.backgroundMusic resume]; -} +} -(void) rewindBackgroundMusic { [self.backgroundMusic rewind]; -} +} -(void) setBackgroundMusicCompletionListener:(id) listener selector:(SEL) selector { backgroundMusicCompletionListener = listener; backgroundMusicCompletionSelector = selector; -} +} /* * Call this method to have the audio manager automatically handle application resign and * become active. Pass a tAudioManagerResignBehavior to indicate the desired behavior * for resigning and becoming active again. * - * If autohandle is YES then the applicationWillResignActive and applicationDidBecomActive + * If autohandle is YES then the applicationWillResignActive and applicationDidBecomActive * methods are automatically called, otherwise you must call them yourself at the appropriate time. * * Based on idea of Dominique Bongard */ --(void) setResignBehavior:(tAudioManagerResignBehavior) resignBehavior autoHandle:(BOOL) autoHandle { +-(void) setResignBehavior:(tAudioManagerResignBehavior) resignBehavior autoHandle:(BOOL) autoHandle { if (!_isObservingAppEvents && autoHandle) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:@"UIApplicationWillResignActiveNotification" object:nil]; @@ -616,18 +616,18 @@ static BOOL configured = FALSE; _isObservingAppEvents = TRUE; } _resignBehavior = resignBehavior; -} +} - (void) applicationWillResignActive { _resigned = YES; - - //Set the audio sesssion to one that allows sharing so that other audio won't be clobbered on resume + + //Set the audio session to one that allows sharing so that other audio won't be clobbered on resume [self audioSessionSetCategory:AVAudioSessionCategoryAmbient]; - + switch (_resignBehavior) { - + case kAMRBStopPlay: - + for( CDLongAudioSource *audioSource in audioSourceChannels) { if (audioSource.isPlaying) { audioSource->systemPaused = YES; @@ -641,18 +641,18 @@ static BOOL configured = FALSE; } } break; - + case kAMRBStop: //Stop music regardless of whether it is playing or not because if it was paused //then the OS would resume it for( CDLongAudioSource *audioSource in audioSourceChannels) { [audioSource stop]; - } - + } + default: break; - - } + + } CDLOGINFO(@"Denshion::CDAudioManager - handled resign active"); } @@ -660,18 +660,18 @@ static BOOL configured = FALSE; - (void) applicationWillResignActive:(NSNotification *) notification { [self applicationWillResignActive]; -} +} - (void) applicationDidBecomeActive { - + if (_resigned) { _resigned = NO; //Reset the mode incase something changed with audio while we were inactive [self setMode:_mode]; switch (_resignBehavior) { - + case kAMRBStopPlay: - + //Music had been stopped but stop maintains current time //so playing again will continue from where music was before resign active. //We check if music can be played because while we were inactive the user might have @@ -685,10 +685,10 @@ static BOOL configured = FALSE; } } break; - + default: break; - + } CDLOGINFO(@"Denshion::CDAudioManager - audio manager handled become active"); } @@ -700,7 +700,7 @@ static BOOL configured = FALSE; [self applicationDidBecomeActive]; } -//Called when application terminates only if setResignBehavior has been called +//Called when application terminates only if setResignBehavior has been called - (void) applicationWillTerminate:(NSNotification *) notification { CDLOGINFO(@"Denshion::CDAudioManager - audio manager handling terminate"); @@ -712,8 +712,8 @@ static BOOL configured = FALSE; CDLOGINFO(@"Denshion::CDAudioManager - audio manager got told background music finished"); if (backgroundMusicCompletionSelector != nil) { [backgroundMusicCompletionListener performSelector:backgroundMusicCompletionSelector]; - } -} + } +} -(void) beginInterruption { CDLOGINFO(@"Denshion::CDAudioManager - begin interruption"); @@ -730,78 +730,78 @@ static BOOL configured = FALSE; CDLOGINFO(@"Denshion::CDAudioManager - interruption ended with flags %i",flags); if (flags == AVAudioSessionInterruptionFlags_ShouldResume) { [self audioSessionResumed]; - } + } } #endif --(void)audioSessionInterrupted -{ +-(void)audioSessionInterrupted +{ if (!_interrupted) { - CDLOGINFO(@"Denshion::CDAudioManager - Audio session interrupted"); + CDLOGINFO(@"Denshion::CDAudioManager - Audio session interrupted"); _interrupted = YES; - // Deactivate the current audio session + // Deactivate the current audio session [self audioSessionSetActive:NO]; - + if (alcGetCurrentContext() != NULL) { - CDLOGINFO(@"Denshion::CDAudioManager - Setting OpenAL context to NULL"); + CDLOGINFO(@"Denshion::CDAudioManager - Setting OpenAL context to NULL"); ALenum error = AL_NO_ERROR; - // set the current context to NULL will 'shutdown' openAL - alcMakeContextCurrent(NULL); - + // set the current context to NULL will 'shutdown' openAL + alcMakeContextCurrent(NULL); + if((error = alGetError()) != AL_NO_ERROR) { CDLOG(@"Denshion::CDAudioManager - Error making context current %x\n", error); - } + } #pragma unused(error) } - } -} + } +} --(void)audioSessionResumed -{ +-(void)audioSessionResumed +{ if (_interrupted) { - CDLOGINFO(@"Denshion::CDAudioManager - Audio session resumed"); + CDLOGINFO(@"Denshion::CDAudioManager - Audio session resumed"); _interrupted = NO; - + BOOL activationResult = NO; // Reactivate the current audio session - activationResult = [self audioSessionSetActive:YES]; - + activationResult = [self audioSessionSetActive:YES]; + //This code is to handle a problem with iOS 4.0 and 4.01 where reactivating the session can fail if //task switching is performed too rapidly. A test case that reliably reproduces the issue is to call the //iPhone and then hang up after two rings (timing may vary ;)) //Basically we keep waiting and trying to let the OS catch up with itself but the number of tries is //limited. if (!activationResult) { - CDLOG(@"Denshion::CDAudioManager - Failure reactivating audio session, will try wait-try cycle"); + CDLOG(@"Denshion::CDAudioManager - Failure reactivating audio session, will try wait-try cycle"); int activateCount = 0; while (!activationResult && activateCount < 10) { [NSThread sleepForTimeInterval:0.5]; - activationResult = [self audioSessionSetActive:YES]; + activationResult = [self audioSessionSetActive:YES]; activateCount++; - CDLOGINFO(@"Denshion::CDAudioManager - Reactivation attempt %i status = %i",activateCount,activationResult); - } + CDLOGINFO(@"Denshion::CDAudioManager - Reactivation attempt %i status = %i",activateCount,activationResult); + } } - + if (alcGetCurrentContext() == NULL) { - CDLOGINFO(@"Denshion::CDAudioManager - Restoring OpenAL context"); + CDLOGINFO(@"Denshion::CDAudioManager - Restoring OpenAL context"); ALenum error = AL_NO_ERROR; - // Restore open al context - alcMakeContextCurrent([soundEngine openALContext]); + // Restore open al context + alcMakeContextCurrent([soundEngine openALContext]); if((error = alGetError()) != AL_NO_ERROR) { CDLOG(@"Denshion::CDAudioManager - Error making context current%x\n", error); - } + } #pragma unused(error) - } - } + } + } } +(void) end { [sharedManager release]; sharedManager = nil; -} +} @end @@ -810,7 +810,7 @@ static BOOL configured = FALSE; -(void) _setTargetProperty:(float) newVal { ((CDLongAudioSource*)target).volume = newVal; -} +} -(float) _getTargetProperty { return ((CDLongAudioSource*)target).volume; @@ -823,7 +823,7 @@ static BOOL configured = FALSE; -(Class) _allowableType { return [CDLongAudioSource class]; -} +} @end /////////////////////////////////////////////////////////////////////////////////////// @@ -835,18 +835,18 @@ static BOOL configured = FALSE; loadedBuffers = [[NSMutableDictionary alloc] initWithCapacity:CD_BUFFERS_START]; freedBuffers = [[NSMutableArray alloc] init]; nextBufferId = 0; - } + } return self; -} +} -(void) dealloc { [loadedBuffers release]; [freedBuffers release]; [super dealloc]; -} +} -(int) bufferForFile:(NSString*) filePath create:(BOOL) create { - + NSNumber* soundId = (NSNumber*)[loadedBuffers objectForKey:filePath]; if(soundId == nil) { @@ -855,7 +855,7 @@ static BOOL configured = FALSE; //First try to get a buffer from the free buffers if ([freedBuffers count] > 0) { bufferId = [[[freedBuffers lastObject] retain] autorelease]; - [freedBuffers removeLastObject]; + [freedBuffers removeLastObject]; CDLOGINFO(@"Denshion::CDBufferManager reusing buffer id %i",[bufferId intValue]); } else { bufferId = [[NSNumber alloc] initWithInt:nextBufferId]; @@ -863,7 +863,7 @@ static BOOL configured = FALSE; CDLOGINFO(@"Denshion::CDBufferManager generating new buffer id %i",[bufferId intValue]); nextBufferId++; } - + if ([soundEngine loadBuffer:[bufferId intValue] filePath:filePath]) { //File successfully loaded CDLOGINFO(@"Denshion::CDBufferManager buffer loaded %@ %@",bufferId,filePath); @@ -873,15 +873,15 @@ static BOOL configured = FALSE; //File didn't load, put buffer id on free list [freedBuffers addObject:bufferId]; return kCDNoBuffer; - } + } } else { //No matching buffer was found return kCDNoBuffer; - } + } } else { return [soundId intValue]; - } -} + } +} -(void) releaseBufferForFile:(NSString *) filePath { int bufferId = [self bufferForFile:filePath create:NO]; @@ -891,7 +891,9 @@ static BOOL configured = FALSE; NSNumber *freedBufferId = [[NSNumber alloc] initWithInt:bufferId]; [freedBufferId autorelease]; [freedBuffers addObject:freedBufferId]; - } -} + } +} @end + + diff --git a/native/cocos/audio/mac/CDConfig.h b/native/cocos/audio/mac/CDConfig.h index fccadb83da..2bd8f760c1 100644 --- a/native/cocos/audio/mac/CDConfig.h +++ b/native/cocos/audio/mac/CDConfig.h @@ -1,16 +1,16 @@ /* Copyright (c) 2010 Steve Oldmeadow - + 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 @@ -18,7 +18,7 @@ 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. - + $Id$ */ #define COCOSDENSHION_VERSION "Aphex.rc" @@ -35,25 +35,26 @@ */ //Number of buffers slots that will be initially created #define CD_BUFFERS_START 64 -//Number of buffers that will be added +//Number of buffers that will be added #define CD_BUFFERS_INCREMENT 16 /** If enabled, OpenAL code will use static buffers. When static buffers are used the audio - data is managed outside of OpenAL, this eliminates a memcpy operation which leads to + data is managed outside of OpenAL, this eliminates a memcpy operation which leads to higher performance when loading sounds. - + However, the downside is that when the audio data is freed you must be certain that it is no longer being accessed otherwise your app will crash. Testing on OS 2.2.1 and 3.1.2 has shown that this may occur if a buffer is being used by a source with state = AL_PLAYING when the buffer is deleted. If the data is freed too quickly after the source is stopped then a crash will occur. The implemented workaround is that when static buffers are used the unloadBuffer code will wait for - any playing sources to finish playing before the associated buffer and data are deleted, however, this delay may negate any + any playing sources to finish playing before the associated buffer and data are deleted, however, this delay may negate any performance gains that are achieved during loading. - + Performance tests on a 1st gen iPod running OS 2.2.1 loading the CocosDenshionDemo sounds were ~0.14 seconds without static buffers and ~0.12 seconds when using static buffers. */ //#define CD_USE_STATIC_BUFFERS 1 + diff --git a/native/cocos/audio/mac/CDOpenALSupport.h b/native/cocos/audio/mac/CDOpenALSupport.h index 49631cc686..aeac861c96 100644 --- a/native/cocos/audio/mac/CDOpenALSupport.h +++ b/native/cocos/audio/mac/CDOpenALSupport.h @@ -1,12 +1,12 @@ /* - + Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. - + In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the @@ -22,13 +22,13 @@ or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. - + The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - + IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS @@ -37,9 +37,9 @@ AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - + Copyright (C) 2009 Apple Inc. All Rights Reserved. - + $Id$ */ @@ -55,8 +55,8 @@ #ifdef __cplusplus extern "C" { -#endif - +#endif + #import #import @@ -67,10 +67,11 @@ extern "C" { void* CDloadWaveAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate); void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate); void* CDGetOpenALAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate); - + #ifdef __cplusplus } #endif -#endif +#endif + diff --git a/native/cocos/audio/mac/CDOpenALSupport.m b/native/cocos/audio/mac/CDOpenALSupport.m index 55b2d9cdde..5603c9da28 100644 --- a/native/cocos/audio/mac/CDOpenALSupport.m +++ b/native/cocos/audio/mac/CDOpenALSupport.m @@ -1,12 +1,12 @@ /* - + Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. - + In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the @@ -22,13 +22,13 @@ or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. - + The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. - + IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS @@ -37,9 +37,9 @@ AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - + Copyright (C) 2009 Apple Inc. All Rights Reserved. - + $Id: CDOpenALSupport.h 16 2010-03-11 06:22:10Z steveoldmeadow $ */ @@ -51,38 +51,38 @@ //Taken from oalTouch MyOpenALSupport 1.1 void* CDloadWaveAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate) { - OSStatus err = noErr; + OSStatus err = noErr; UInt64 fileDataSize = 0; AudioStreamBasicDescription theFileFormat; UInt32 thePropertySize = sizeof(theFileFormat); AudioFileID afid = 0; void* theData = NULL; - + // Open a file with ExtAudioFileOpen() err = AudioFileOpenURL(inFileURL, kAudioFileReadPermission, 0, &afid); if(err) { CDLOG(@"MyGetOpenALAudioData: AudioFileOpenURL FAILED, Error = %ld\n", err); goto Exit; } - + // Get the audio data format err = AudioFileGetProperty(afid, kAudioFilePropertyDataFormat, &thePropertySize, &theFileFormat); if(err) { CDLOG(@"MyGetOpenALAudioData: AudioFileGetProperty(kAudioFileProperty_DataFormat) FAILED, Error = %ld\n", err); goto Exit; } - - if (theFileFormat.mChannelsPerFrame > 2) { + + if (theFileFormat.mChannelsPerFrame > 2) { CDLOG(@"MyGetOpenALAudioData - Unsupported Format, channel count is greater than stereo\n"); goto Exit; } - - if ((theFileFormat.mFormatID != kAudioFormatLinearPCM) || (!TestAudioFormatNativeEndian(theFileFormat))) { + + if ((theFileFormat.mFormatID != kAudioFormatLinearPCM) || (!TestAudioFormatNativeEndian(theFileFormat))) { CDLOG(@"MyGetOpenALAudioData - Unsupported Format, must be little-endian PCM\n"); goto Exit; } - - if ((theFileFormat.mBitsPerChannel != 8) && (theFileFormat.mBitsPerChannel != 16)) { + + if ((theFileFormat.mBitsPerChannel != 8) && (theFileFormat.mBitsPerChannel != 16)) { CDLOG(@"MyGetOpenALAudioData - Unsupported Format, must be 8 or 16 bit PCM\n"); goto Exit; } - - + + thePropertySize = sizeof(fileDataSize); err = AudioFileGetProperty(afid, kAudioFilePropertyAudioDataByteCount, &thePropertySize, &fileDataSize); if(err) { CDLOG(@"MyGetOpenALAudioData: AudioFileGetProperty(kAudioFilePropertyAudioDataByteCount) FAILED, Error = %ld\n", err); goto Exit; } - + // Read all the data into memory UInt32 dataSize = (UInt32)fileDataSize; theData = malloc(dataSize); @@ -95,22 +95,22 @@ void* CDloadWaveAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outD // success *outDataSize = (ALsizei)dataSize; //This fix was added by me, however, 8 bit sounds have a clipping sound at the end so aren't really usable (SO) - if (theFileFormat.mBitsPerChannel == 16) { + if (theFileFormat.mBitsPerChannel == 16) { *outDataFormat = (theFileFormat.mChannelsPerFrame > 1) ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16; } else { - *outDataFormat = (theFileFormat.mChannelsPerFrame > 1) ? AL_FORMAT_STEREO8 : AL_FORMAT_MONO8; - } + *outDataFormat = (theFileFormat.mChannelsPerFrame > 1) ? AL_FORMAT_STEREO8 : AL_FORMAT_MONO8; + } *outSampleRate = (ALsizei)theFileFormat.mSampleRate; } - else - { + else + { // failure free (theData); theData = NULL; // make sure to return NULL CDLOG(@"MyGetOpenALAudioData: ExtAudioFileRead FAILED, Error = %ld\n", err); goto Exit; - } + } } - + Exit: // Dispose the ExtAudioFileRef, it is no longer needed if (afid) AudioFileClose(afid); @@ -129,7 +129,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa void* theData = NULL; AudioStreamBasicDescription theOutputFormat; UInt32 dataSize = 0; - + // Open a file with ExtAudioFileOpen() status = ExtAudioFileOpenURL(inFileURL, &extRef); if (status != noErr) @@ -139,7 +139,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa } if (abort) goto Exit; - + // Get the audio data format status = ExtAudioFileGetProperty(extRef, kExtAudioFileProperty_FileDataFormat, &thePropertySize, &theFileFormat); if (status != noErr) @@ -149,7 +149,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa } if (abort) goto Exit; - + if (theFileFormat.mChannelsPerFrame > 2) { CDLOG(@"MyGetOpenALAudioData - Unsupported Format, channel count is greater than stereo\n"); @@ -157,19 +157,19 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa } if (abort) goto Exit; - + // Set the client format to 16 bit signed integer (native-endian) data // Maintain the channel count and sample rate of the original source format theOutputFormat.mSampleRate = theFileFormat.mSampleRate; theOutputFormat.mChannelsPerFrame = theFileFormat.mChannelsPerFrame; - + theOutputFormat.mFormatID = kAudioFormatLinearPCM; theOutputFormat.mBytesPerPacket = 2 * theOutputFormat.mChannelsPerFrame; theOutputFormat.mFramesPerPacket = 1; theOutputFormat.mBytesPerFrame = 2 * theOutputFormat.mChannelsPerFrame; theOutputFormat.mBitsPerChannel = 16; theOutputFormat.mFormatFlags = kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked | kAudioFormatFlagIsSignedInteger; - + // Set the desired client (output) data format status = ExtAudioFileSetProperty(extRef, kExtAudioFileProperty_ClientDataFormat, sizeof(theOutputFormat), &theOutputFormat); if (status != noErr) @@ -179,7 +179,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa } if (abort) goto Exit; - + // Get the total frame count thePropertySize = sizeof(theFileLengthInFrames); status = ExtAudioFileGetProperty(extRef, kExtAudioFileProperty_FileLengthFrames, &thePropertySize, &theFileLengthInFrames); @@ -190,7 +190,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa } if (abort) goto Exit; - + // Read all the data into memory dataSize = (UInt32) theFileLengthInFrames * theOutputFormat.mBytesPerFrame; theData = malloc(dataSize); @@ -202,7 +202,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa theDataBuffer.mBuffers[0].mDataByteSize = dataSize; theDataBuffer.mBuffers[0].mNumberChannels = theOutputFormat.mChannelsPerFrame; theDataBuffer.mBuffers[0].mData = theData; - + // Read the data into an AudioBufferList status = ExtAudioFileRead(extRef, (UInt32*)&theFileLengthInFrames, &theDataBuffer); if(status == noErr) @@ -223,7 +223,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa } if (abort) goto Exit; - + Exit: // Dispose the ExtAudioFileRef, it is no longer needed if (extRef) ExtAudioFileDispose(extRef); @@ -231,18 +231,18 @@ Exit: } void* CDGetOpenALAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate) { - + CFStringRef extension = CFURLCopyPathExtension(inFileURL); CFComparisonResult isWavFile = 0; if (extension != NULL) { isWavFile = CFStringCompare (extension,(CFStringRef)@"wav", kCFCompareCaseInsensitive); CFRelease(extension); - } - + } + if (isWavFile == kCFCompareEqualTo) { - return CDloadWaveAudioData(inFileURL, outDataSize, outDataFormat, outSampleRate); + return CDloadWaveAudioData(inFileURL, outDataSize, outDataFormat, outSampleRate); } else { - return CDloadCafAudioData(inFileURL, outDataSize, outDataFormat, outSampleRate); + return CDloadCafAudioData(inFileURL, outDataSize, outDataFormat, outSampleRate); } } diff --git a/native/cocos/audio/mac/CDXMacOSXSupport.h b/native/cocos/audio/mac/CDXMacOSXSupport.h index e7e13a9b9f..eaa97f2e34 100644 --- a/native/cocos/audio/mac/CDXMacOSXSupport.h +++ b/native/cocos/audio/mac/CDXMacOSXSupport.h @@ -1,16 +1,16 @@ /* Copyright (c) 2010 Steve Oldmeadow - + 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 @@ -18,14 +18,14 @@ 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. - + $Id$ */ /** A set of proxy classes to allow iOS audio code to run on MacOS X. CCAudioPlayer is implemented using NSSound. AVAudioSession is a "do nothing" class as it isn't really relevant on MacOS X. - + Limitations: CCAudioPlayer numberOfLoops not correctly supported. Looping is either on or off, can not specify a specific number of loops. CCAudioPlayer panning not supported. @@ -41,14 +41,14 @@ #import enum AudioSessionProperties { - kAudioSessionProperty_OtherAudioIsPlaying, - kAudioSessionProperty_AudioRoute + kAudioSessionProperty_OtherAudioIsPlaying, + kAudioSessionProperty_AudioRoute }; #ifdef __cplusplus extern "C" { -#endif - -extern OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *outData); +#endif + +extern OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *outData); #ifdef __cplusplus } @@ -61,21 +61,21 @@ extern OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *o /* This class is available with iPhone 2.2 or later */ @interface CCAudioPlayer : NSObject { - - // properties - id delegate; - NSUInteger numberOfChannels; - BOOL playing; - NSTimeInterval duration; - NSURL *url; - NSData *data; - float pan; - float volume; - NSTimeInterval currentTime; - NSTimeInterval deviceCurrentTime; - NSInteger numberOfLoops; - BOOL meteringEnabled; - + + // properties + id delegate; + NSUInteger numberOfChannels; + BOOL playing; + NSTimeInterval duration; + NSURL *url; + NSData *data; + float pan; + float volume; + NSTimeInterval currentTime; + NSTimeInterval deviceCurrentTime; + NSInteger numberOfLoops; + BOOL meteringEnabled; + @private NSSound* _player; @@ -91,11 +91,11 @@ extern OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *o /* transport control */ /* methods that return BOOL return YES on success and NO on failure. */ -- (BOOL)prepareToPlay; /* get ready to play the sound. happens automatically on play. */ -- (BOOL)play; /* sound is played asynchronously. */ +- (BOOL)prepareToPlay; /* get ready to play the sound. happens automatically on play. */ +- (BOOL)play; /* sound is played asynchronously. */ - (BOOL)playAtTime:(NSTimeInterval) time; /* play a sound some time in the future. time should be greater than deviceCurrentTime. */ -- (void)pause; /* pauses playback, but remains ready to play. */ -- (void)stop; /* stops playback. no longer ready to play. */ +- (void)pause; /* pauses playback, but remains ready to play. */ +- (void)stop; /* stops playback. no longer ready to play. */ - (BOOL) resume; /* properties */ @@ -105,7 +105,7 @@ extern OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *o @property(readonly) NSUInteger numberOfChannels; @property(readonly) NSTimeInterval duration; /* the duration of the sound. */ -@property(assign) id delegate; /* the delegate will be sent playerDidFinishPlaying */ +@property(assign) id delegate; /* the delegate will be sent playerDidFinishPlaying */ /* one of these three properties will be non-nil based on the init... method used */ @property(readonly) NSURL *url; /* returns nil if object was not created with a URL */ @@ -113,14 +113,14 @@ extern OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *o @property float pan; /* set panning. -1.0 is left, 0.0 is center, 1.0 is right. */ @property float volume; /* The volume for the sound. The nominal range is from 0.0 to 1.0. */ -/* If the sound is playing, currentTime is the offset into the sound of the current playback position. +/* If the sound is playing, currentTime is the offset into the sound of the current playback position. If the sound is not playing, currentTime is the offset into the sound where playing would start. */ @property NSTimeInterval currentTime; /* returns the current time associated with the output device */ -@property(readonly) NSTimeInterval deviceCurrentTime; +@property(readonly) NSTimeInterval deviceCurrentTime; -/* "numberOfLoops" is the number of times that the sound will return to the beginning upon reaching the end. +/* "numberOfLoops" is the number of times that the sound will return to the beginning upon reaching the end. A value of zero means to play the sound just once. A value of one will result in playing the sound twice, and so on.. Any negative number will loop indefinitely until stopped. @@ -139,7 +139,7 @@ extern OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *o /* A protocol for delegates of CCAudioPlayer */ @protocol AVAudioPlayerDelegate -@optional +@optional /* audioPlayerDidFinishPlaying:successfully: is called when a sound has finished playing. This method is NOT called if the player is stopped due to an interruption. */ - (void)audioPlayerDidFinishPlaying:(CCAudioPlayer *)player successfully:(BOOL)flag; @@ -175,25 +175,25 @@ extern NSString *const AVAudioSessionCategoryPlayAndRecord; extern NSString *const AVAudioSessionCategoryAudioProcessing; enum { - AVAudioSessionInterruptionFlags_ShouldResume = 1 + AVAudioSessionInterruptionFlags_ShouldResume = 1 }; -enum { - AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation = 1 +enum { + AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation = 1 }; @interface AVAudioSession : NSObject { - - // properties - NSString* category; - double preferredHardwareSampleRate; - NSTimeInterval preferredIOBufferDuration; - - BOOL inputIsAvailable; - double currentHardwareSampleRate; - NSInteger currentHardwareInputNumberOfChannels; - NSInteger currentHardwareOutputNumberOfChannels; - id delegate; + + // properties + NSString* category; + double preferredHardwareSampleRate; + NSTimeInterval preferredIOBufferDuration; + + BOOL inputIsAvailable; + double currentHardwareSampleRate; + NSInteger currentHardwareInputNumberOfChannels; + NSInteger currentHardwareOutputNumberOfChannels; + id delegate; @private __strong void *_impl; @@ -225,7 +225,7 @@ enum { /* A protocol for delegates of AVAudioSession */ @protocol AVAudioSessionDelegate -@optional +@optional - (void)beginInterruption; @@ -237,4 +237,3 @@ enum { @end #endif - diff --git a/native/cocos/audio/mac/CDXMacOSXSupport.mm b/native/cocos/audio/mac/CDXMacOSXSupport.mm index e339c7069d..8799eb90df 100644 --- a/native/cocos/audio/mac/CDXMacOSXSupport.mm +++ b/native/cocos/audio/mac/CDXMacOSXSupport.mm @@ -1,16 +1,16 @@ /* Copyright (c) 2010 Steve Oldmeadow - + 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 @@ -18,7 +18,7 @@ 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. - + $Id$ */ @@ -40,7 +40,7 @@ NSString *const AVAudioSessionCategoryAudioProcessing = @"AVAudioSessionCategory OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *outData) { //TODO: set outData appropriately return 0; -} +} @implementation CCAudioPlayer @@ -52,18 +52,18 @@ OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *outData) if (_player != nil) { _player.delegate = self; CDLOG(@"Denshion::CDXMacOSXSupport - NSSound allocated for %@", theUrl); - } + } } return self; } -- (id)initWithData:(NSData *)theData error:(NSError **)outError { +- (id)initWithData:(NSData *)theData error:(NSError **)outError { if ((self = [super init])) { _player = [[NSSound alloc] initWithData:theData]; if (_player != nil) { _player.delegate = self; CDLOG(@"Denshion::CDXMacOSXSupport - NSSound allocated for %@", theData); - } + } } return self; } @@ -72,21 +72,21 @@ OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *outData) -(void) dealloc { [_player release]; [super dealloc]; -} +} - (void)sound:(NSSound *)sound didFinishPlaying:(BOOL)finished { if (self.delegate && [self.delegate respondsToSelector:@selector(audioPlayerDidFinishPlaying:successfully:)]) { [self.delegate audioPlayerDidFinishPlaying:self successfully:finished]; - } -} + } +} - (BOOL)play { BOOL result; result = [_player play]; if (!result) { - //May be paused, try resuming instead + //May be paused, try resuming instead result = [_player resume]; - } + } return result; } @@ -98,15 +98,15 @@ OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *outData) -(void) pause { [_player pause]; -} +} -(void) stop { [_player stop]; -} +} -(BOOL) isPlaying { return [_player isPlaying]; -} +} -(void) setVolume:(float) vol { [_player setVolume:vol]; @@ -114,23 +114,23 @@ OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *outData) -(float) volume { return [_player volume]; -} +} -(void) setNumberOfLoops:(NSInteger) nOfLoops { if (nOfLoops < 0) { [_player setLoops:YES]; } else { [_player setLoops:NO]; - } -} + } +} -(NSInteger) numberOfLoops { if (_player.loops) { return -1; } else { return 0; - } -} + } +} -(void) setCurrentTime:(NSTimeInterval) aCurrentTime { [_player setCurrentTime:aCurrentTime]; @@ -147,17 +147,17 @@ OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *outData) #pragma mark unsupported - (BOOL)prepareToPlay { return YES; -} +} -(BOOL)playAtTime:(NSTimeInterval)time { return YES; -} +} -(void) setMeteringEnabled:(BOOL) enabled { -} +} -(BOOL) isMeteringEnabled { return NO; -} +} - (void)updateMeters{} -- (float)peakPowerForChannel:(NSUInteger)channelNumber{return 0.0f;} +- (float)peakPowerForChannel:(NSUInteger)channelNumber{return 0.0f;} - (float)averagePowerForChannel:(NSUInteger)channelNumber{return 0.0f;} @end @@ -170,7 +170,7 @@ OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *outData) + (id)sharedInstance { return nil; -} +} - (BOOL)setActive:(BOOL)beActive error:(NSError**)outError {return YES;} - (BOOL)setActive:(BOOL)beActive withFlags:(NSInteger)flags error:(NSError**)outError {return YES;} diff --git a/native/cocos/audio/mac/CocosDenshion.h b/native/cocos/audio/mac/CocosDenshion.h index e19257265e..ed25c32e9c 100644 --- a/native/cocos/audio/mac/CocosDenshion.h +++ b/native/cocos/audio/mac/CocosDenshion.h @@ -1,16 +1,16 @@ /* Copyright (c) 2010 Steve Oldmeadow - + 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 @@ -18,16 +18,16 @@ 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. - + $Id$ */ -/** +/** @file @b IMPORTANT -There are 3 different ways of using CocosDenshion. Depending on which you choose you +There are 3 different ways of using CocosDenshion. Depending on which you choose you will need to include different files and frameworks. @par SimpleAudioEngine @@ -36,36 +36,36 @@ and some background music and have no interest in learning the lower level worki this is the interface to use. Requirements: - - Firmware: OS 2.2 or greater + - Firmware: OS 2.2 or greater - Files: SimpleAudioEngine.*, CocosDenshion.* - Frameworks: OpenAL, AudioToolbox, AVFoundation - + @par CDAudioManager CDAudioManager is basically a thin wrapper around an CCAudioPlayer object used for playing background music and a CDSoundEngine object used for playing sound effects. It manages the audio session for you deals with audio session interruption. It is fairly low level and it -is expected you have some understanding of the underlying technologies. For example, for +is expected you have some understanding of the underlying technologies. For example, for many use cases regarding background music it is expected you will work directly with the backgroundMusic CCAudioPlayer which is exposed as a property. - + Requirements: - - Firmware: OS 2.2 or greater + - Firmware: OS 2.2 or greater - Files: CDAudioManager.*, CocosDenshion.* - Frameworks: OpenAL, AudioToolbox, AVFoundation @par CDSoundEngine -CDSoundEngine is a sound engine built upon OpenAL and derived from Apple's oalTouch +CDSoundEngine is a sound engine built upon OpenAL and derived from Apple's oalTouch example. It can playback up to 32 sounds simultaneously with control over pitch, pan -and gain. It can be set up to handle audio session interruption automatically. You +and gain. It can be set up to handle audio session interruption automatically. You may decide to use CDSoundEngine directly instead of CDAudioManager or SimpleAudioEngine because you require OS 2.0 compatibility. - + Requirements: - - Firmware: OS 2.0 or greater + - Firmware: OS 2.0 or greater - Files: CocosDenshion.* - Frameworks: OpenAL, AudioToolbox - -*/ + +*/ #import #import @@ -136,13 +136,13 @@ typedef struct _bufferInfo { ALenum format; ALsizei sizeInBytes; ALsizei frequencyInHertz; -} bufferInfo; +} bufferInfo; typedef struct _sourceInfo { bool usable; ALuint sourceId; ALuint attachedBufferId; -} sourceInfo; +} sourceInfo; #pragma mark CDAudioTransportProtocol @@ -176,7 +176,7 @@ typedef struct _sourceInfo { */ @interface CDUtilities : NSObject { -} +} /** Fundamentally the same as the corresponding method is FileUtils but added to break binding to cocos2d */ +(NSString*) fullPathFromRelativePath:(NSString*) relPath; @@ -187,22 +187,22 @@ typedef struct _sourceInfo { #pragma mark CDSoundEngine /** CDSoundEngine is built upon OpenAL and works with SDK 2.0. - CDSoundEngine is a sound engine built upon OpenAL and derived from Apple's oalTouch + CDSoundEngine is a sound engine built upon OpenAL and derived from Apple's oalTouch example. It can playback up to 32 sounds simultaneously with control over pitch, pan - and gain. It can be set up to handle audio session interruption automatically. You + and gain. It can be set up to handle audio session interruption automatically. You may decide to use CDSoundEngine directly instead of CDAudioManager or SimpleAudioEngine because you require OS 2.0 compatibility. - + Requirements: - - Firmware: OS 2.0 or greater + - Firmware: OS 2.0 or greater - Files: CocosDenshion.* - Frameworks: OpenAL, AudioToolbox - + @since v0.8 */ @class CDSoundSource; @interface CDSoundEngine : NSObject { - + bufferInfo *_buffers; sourceInfo *_sources; sourceGroup *_sourceGroups; @@ -219,11 +219,11 @@ typedef struct _sourceInfo { BOOL functioning_; float asynchLoadProgress_; BOOL getGainWorks_; - + //For managing dynamic allocation of sources and buffers int sourceTotal_; int bufferTotal; - + } @property (readwrite, nonatomic) ALfloat masterGain; @@ -288,10 +288,10 @@ typedef struct _sourceInfo { #pragma mark CDSoundSource /** CDSoundSource is a wrapper around an OpenAL sound source. - It allows you to manipulate properties such as pitch, gain, pan and looping while the + It allows you to manipulate properties such as pitch, gain, pan and looping while the sound is playing. CDSoundSource is based on the old CDSourceWrapper class but with much added functionality. - + @since v1.0 */ @interface CDSoundSource : NSObject { @@ -324,7 +324,7 @@ typedef struct _sourceInfo { #pragma mark CDAudioInterruptTargetGroup /** Container for objects that implement audio interrupt protocol i.e. they can be muted and enabled. - Setting mute and enabled for the group propagates to all children. + Setting mute and enabled for the group propagates to all children. Designed to be used with your CDSoundSource objects to get them to comply with global enabled and mute settings if that is what you want to do.*/ @interface CDAudioInterruptTargetGroup : NSObject { @@ -343,7 +343,7 @@ typedef struct _sourceInfo { @interface CDAsynchBufferLoader : NSOperation { NSArray *_loadRequests; CDSoundEngine *_soundEngine; -} +} -(id) init:(NSArray *)loadRequests soundEngine:(CDSoundEngine *) theSoundEngine; @@ -401,7 +401,7 @@ typedef enum { float endValue; id target; BOOL stopTargetWhenComplete; - + } @property (readwrite, nonatomic) BOOL stopTargetWhenComplete; @property (readwrite, nonatomic) float startValue; @@ -443,3 +443,6 @@ typedef enum { @interface CDSoundEngineFader : CDPropertyModifier{} @end + + + diff --git a/native/cocos/audio/mac/CocosDenshion.m b/native/cocos/audio/mac/CocosDenshion.m index 0aae5174eb..df3d8c7cc8 100644 --- a/native/cocos/audio/mac/CocosDenshion.m +++ b/native/cocos/audio/mac/CocosDenshion.m @@ -1,16 +1,16 @@ /* Copyright (c) 2010 Steve Oldmeadow - + 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 @@ -18,7 +18,7 @@ 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. - + $Id$ */ @@ -32,14 +32,14 @@ typedef ALvoid AL_APIENTRY (*alBufferDataStaticProcPtr) (const ALint bid, ALvoid alBufferDataStaticProc(const ALint bid, ALenum format, ALvoid* data, ALsizei size, ALsizei freq) { static alBufferDataStaticProcPtr proc = NULL; - + if (proc == NULL) { proc = (alBufferDataStaticProcPtr) alcGetProcAddress(NULL, (const ALCchar*) "alBufferDataStatic"); } - + if (proc) proc(bid, format, data, size, freq); - + return; } @@ -47,14 +47,14 @@ typedef ALvoid AL_APIENTRY (*alcMacOSXMixerOutputRateProcPtr) (const ALdou ALvoid alcMacOSXMixerOutputRateProc(const ALdouble value) { static alcMacOSXMixerOutputRateProcPtr proc = NULL; - + if (proc == NULL) { proc = (alcMacOSXMixerOutputRateProcPtr) alcGetProcAddress(NULL, (const ALCchar*) "alcMacOSXMixerOutputRate"); } - + if (proc) proc(value); - + return; } @@ -74,7 +74,7 @@ float const kCD_GainDefault = 1.0f; -(void) _dumpSourceGroupsInfo; -(void) _getSourceIndexForSourceGroup; -(void) _freeSourceGroups; --(BOOL) _setUpSourceGroups:(int[]) definitions total:(NSUInteger) total; +-(BOOL) _setUpSourceGroups:(int[]) definitions total:(NSUInteger) total; @end #pragma mark - @@ -89,18 +89,18 @@ float const kCD_GainDefault = 1.0f; { return relPath; } - + NSMutableArray *imagePathComponents = [NSMutableArray arrayWithArray:[relPath pathComponents]]; NSString *file = [imagePathComponents lastObject]; - + [imagePathComponents removeLastObject]; NSString *imageDirectory = [NSString pathWithComponents:imagePathComponents]; - + NSString *fullpath = [[NSBundle mainBundle] pathForResource:file ofType:nil inDirectory:imageDirectory]; if (fullpath == nil) fullpath = relPath; - - return fullpath; + + return fullpath; } @end @@ -122,7 +122,7 @@ static BOOL _mixerRateSet = NO; + (void) setMixerSampleRate:(Float32) sampleRate { _mixerRateSet = YES; _mixerSampleRate = sampleRate; -} +} - (void) _testGetGain { float testValue = 0.7f; @@ -136,7 +136,7 @@ static BOOL _mixerRateSet = NO; //Generate sources one at a time until we fail -(void) _generateSources { - + _sources = (sourceInfo*)malloc( sizeof(_sources[0]) * CD_SOURCE_LIMIT); BOOL hasFailed = NO; sourceTotal_ = 0; @@ -147,21 +147,21 @@ static BOOL _mixerRateSet = NO; //Now try attaching source to null buffer alSourcei(_sources[sourceTotal_].sourceId, AL_BUFFER, 0); if (alGetError() == AL_NO_ERROR) { - _sources[sourceTotal_].usable = true; + _sources[sourceTotal_].usable = true; sourceTotal_++; } else { hasFailed = YES; - } + } } else { _sources[sourceTotal_].usable = false; hasFailed = YES; - } + } } //Mark the rest of the sources as not usable for (int i=sourceTotal_; i < CD_SOURCE_LIMIT; i++) { _sources[i].usable = false; - } -} + } +} -(void) _generateBuffers:(int) startIndex endIndex:(int) endIndex { if (_buffers) { @@ -174,9 +174,9 @@ static BOOL _mixerRateSet = NO; } else { _buffers[i].bufferState = CD_BS_FAILED; CDLOG(@"Denshion::CDSoundEngine - buffer creation failed %i",i); - } + } } - } + } } /** @@ -194,44 +194,44 @@ static BOOL _mixerRateSet = NO; } alcMacOSXMixerOutputRateProc(_mixerSampleRate); CDLOGINFO(@"Denshion::CDSoundEngine - mixer output rate set to %0.2f",_mixerSampleRate); - + // Create a new OpenAL Device // Pass NULL to specify the system's default output device newDevice = alcOpenDevice(NULL); if (newDevice != NULL) { // Create a new OpenAL Context - // The new context will render to the OpenAL Device just created + // The new context will render to the OpenAL Device just created context = alcCreateContext(newDevice, 0); if (context != NULL) { // Make the new context the Current OpenAL Context alcMakeContextCurrent(context); - + // Create some OpenAL Buffer Objects [self _generateBuffers:0 endIndex:bufferTotal-1]; - + // Create some OpenAL Source Objects [self _generateSources]; - + } } else { return FALSE;//No device - } + } alGetError();//Clear error return TRUE; } - (void) dealloc { - + ALCcontext *currentContext = NULL; ALCdevice *device = NULL; - + [self stopAllSounds]; CDLOGINFO(@"Denshion::CDSoundEngine - Deallocing sound engine."); [self _freeSourceGroups]; - + // Delete the Sources CDLOGINFO(@"Denshion::CDSoundEngine - deleting sources."); for (int i=0; i < sourceTotal_; i++) { @@ -239,8 +239,8 @@ static BOOL _mixerRateSet = NO; alDeleteSources(1, &(_sources[i].sourceId)); if((lastErrorCode_ = alGetError()) != AL_NO_ERROR) { CDLOG(@"Denshion::CDSoundEngine - Error deleting source! %x\n", lastErrorCode_); - } - } + } + } // Delete the Buffers CDLOGINFO(@"Denshion::CDSoundEngine - deleting buffers."); @@ -249,9 +249,9 @@ static BOOL _mixerRateSet = NO; #ifdef CD_USE_STATIC_BUFFERS if (_buffers[i].bufferData) { free(_buffers[i].bufferData); - } -#endif - } + } +#endif + } CDLOGINFO(@"Denshion::CDSoundEngine - free buffers."); free(_buffers); currentContext = alcGetCurrentContext(); @@ -266,18 +266,18 @@ static BOOL _mixerRateSet = NO; alcCloseDevice(device); CDLOGINFO(@"Denshion::CDSoundEngine - free sources."); free(_sources); - + //Release mutexes [_mutexBufferLoad release]; - + [super dealloc]; -} +} -(NSUInteger) sourceGroupTotal { return _sourceGroupTotal; -} +} --(void) _freeSourceGroups +-(void) _freeSourceGroups { CDLOGINFO(@"Denshion::CDSoundEngine freeing source groups"); if(_sourceGroups) { @@ -285,11 +285,11 @@ static BOOL _mixerRateSet = NO; if (_sourceGroups[i].sourceStatuses) { free(_sourceGroups[i].sourceStatuses); CDLOGINFO(@"Denshion::CDSoundEngine freed source statuses %i",i); - } + } } free(_sourceGroups); - } -} + } +} -(BOOL) _redefineSourceGroups:(int[]) definitions total:(NSUInteger) total { @@ -300,20 +300,20 @@ static BOOL _mixerRateSet = NO; [self _freeSourceGroups]; } return [self _setUpSourceGroups:definitions total:total]; -} +} --(BOOL) _setUpSourceGroups:(int[]) definitions total:(NSUInteger) total +-(BOOL) _setUpSourceGroups:(int[]) definitions total:(NSUInteger) total { _sourceGroups = (sourceGroup *)malloc( sizeof(_sourceGroups[0]) * total); if(!_sourceGroups) { CDLOG(@"Denshion::CDSoundEngine - source groups memory allocation failed"); return NO; } - + _sourceGroupTotal = total; int sourceCount = 0; for (int i=0; i < _sourceGroupTotal; i++) { - + _sourceGroups[i].startIndex = 0; _sourceGroups[i].currentIndex = _sourceGroups[i].startIndex; _sourceGroups[i].enabled = false; @@ -323,9 +323,9 @@ static BOOL _mixerRateSet = NO; if (_sourceGroups[i].sourceStatuses) { for (int j=0; j < _sourceGroups[i].totalSources; j++) { //First bit is used to indicate whether source is locked, index is shifted back 1 bit - _sourceGroups[i].sourceStatuses[j] = (sourceCount + j) << 1; - } - } + _sourceGroups[i].sourceStatuses[j] = (sourceCount + j) << 1; + } + } sourceCount += definitions[i]; } return YES; @@ -347,25 +347,25 @@ static BOOL _mixerRateSet = NO; } else { CDLOG(@"Denshion::CDSoundEngine - warning, did not understand source definition."); defs[currentIndex] = 0; - } + } currentIndex++; } [self _redefineSourceGroups:defs total:totalDefs]; free(defs); -} +} - (id)init -{ +{ if ((self = [super init])) { - + //Create mutexes _mutexBufferLoad = [[NSObject alloc] init]; - + asynchLoadProgress_ = 0.0f; - + bufferTotal = CD_BUFFERS_START; _buffers = (bufferInfo *)malloc( sizeof(_buffers[0]) * bufferTotal); - + // Initialize our OpenAL environment if ([self _initOpenAL]) { //Set up the default source group - a single group that contains all the sources @@ -385,7 +385,7 @@ static BOOL _mixerRateSet = NO; functioning_ = NO; } } - + return self; } @@ -393,20 +393,20 @@ static BOOL _mixerRateSet = NO; * Delete the buffer identified by soundId * @return true if buffer deleted successfully, otherwise false */ -- (BOOL) unloadBuffer:(int) soundId +- (BOOL) unloadBuffer:(int) soundId { //Ensure soundId is within array bounds otherwise memory corruption will occur if (soundId < 0 || soundId >= bufferTotal) { CDLOG(@"Denshion::CDSoundEngine - soundId is outside array bounds, maybe you need to increase CD_MAX_BUFFERS"); return FALSE; - } - + } + //Before a buffer can be deleted any sources that are attached to it must be stopped for (int i=0; i < sourceTotal_; i++) { //Note: tried getting the AL_BUFFER attribute of the source instead but doesn't //appear to work on a device - just returned zero. if (_buffers[soundId].bufferId == _sources[i].attachedBufferId) { - + CDLOG(@"Denshion::CDSoundEngine - Found attached source %i %i %i",i,_buffers[soundId].bufferId,_sources[i].sourceId); #ifdef CD_USE_STATIC_BUFFERS //When using static buffers a crash may occur if a source is playing with a buffer that is about @@ -414,34 +414,34 @@ static BOOL _mixerRateSet = NO; //on 2.2.1 and 3.1.2, however, it will only occur if a source is used rapidly after having its prior //data deleted. To avoid any possibility of the crash we wait for the source to finish playing. ALint state; - + alGetSourcei(_sources[i].sourceId, AL_SOURCE_STATE, &state); - + if (state == AL_PLAYING) { - CDLOG(@"Denshion::CDSoundEngine - waiting for source to complete playing before removing buffer data"); + CDLOG(@"Denshion::CDSoundEngine - waiting for source to complete playing before removing buffer data"); alSourcei(_sources[i].sourceId, AL_LOOPING, FALSE);//Turn off looping otherwise loops will never end while (state == AL_PLAYING) { alGetSourcei(_sources[i].sourceId, AL_SOURCE_STATE, &state); usleep(10000); } } -#endif +#endif //Stop source and detach - alSourceStop(_sources[i].sourceId); + alSourceStop(_sources[i].sourceId); if((lastErrorCode_ = alGetError()) != AL_NO_ERROR) { CDLOG(@"Denshion::CDSoundEngine - error stopping source: %x\n", lastErrorCode_); - } - + } + alSourcei(_sources[i].sourceId, AL_BUFFER, 0);//Attach to "NULL" buffer to detach if((lastErrorCode_ = alGetError()) != AL_NO_ERROR) { CDLOG(@"Denshion::CDSoundEngine - error detaching buffer: %x\n", lastErrorCode_); } else { //Record that source is now attached to nothing _sources[i].attachedBufferId = 0; - } - } - } - + } + } + } + alDeleteBuffers(1, &_buffers[soundId].bufferId); if((lastErrorCode_ = alGetError()) != AL_NO_ERROR) { CDLOG(@"Denshion::CDSoundEngine - error deleting buffer: %x\n", lastErrorCode_); @@ -449,15 +449,15 @@ static BOOL _mixerRateSet = NO; return FALSE; } else { #ifdef CD_USE_STATIC_BUFFERS - //Free previous data, if alDeleteBuffer has returned without error then no + //Free previous data, if alDeleteBuffer has returned without error then no if (_buffers[soundId].bufferData) { CDLOGINFO(@"Denshion::CDSoundEngine - freeing static data for soundId %i @ %i",soundId,_buffers[soundId].bufferData); free(_buffers[soundId].bufferData);//Free the old data _buffers[soundId].bufferData = NULL; } -#endif - } - +#endif + } + alGenBuffers(1, &_buffers[soundId].bufferId); if((lastErrorCode_ = alGetError()) != AL_NO_ERROR) { CDLOG(@"Denshion::CDSoundEngine - error regenerating buffer: %x\n", lastErrorCode_); @@ -468,11 +468,11 @@ static BOOL _mixerRateSet = NO; _buffers[soundId].bufferState = CD_BS_EMPTY; CDLOGINFO(@"Denshion::CDSoundEngine - buffer %i successfully unloaded\n",soundId); return TRUE; - } -} + } +} /** - * Load buffers asynchronously + * Load buffers asynchronously * Check asynchLoadProgress for progress. asynchLoadProgress represents fraction of completion. When it equals 1.0 loading * is complete. NB: asynchLoadProgress is simply based on the number of load requests, it does not take into account * file sizes. @@ -485,12 +485,12 @@ static BOOL _mixerRateSet = NO; NSOperationQueue *opQ = [[[NSOperationQueue alloc] init] autorelease]; [opQ addOperation:loaderOp]; } -} +} -(BOOL) _resizeBuffers:(int) increment { - + void * tmpBufferInfos = realloc( _buffers, sizeof(_buffers[0]) * (bufferTotal + increment) ); - + if(!tmpBufferInfos) { free(tmpBufferInfos); return NO; @@ -500,25 +500,25 @@ static BOOL _mixerRateSet = NO; bufferTotal = bufferTotal + increment; [self _generateBuffers:oldBufferTotal endIndex:bufferTotal-1]; return YES; - } -} + } +} -(BOOL) loadBufferFromData:(int) soundId soundData:(ALvoid*) soundData format:(ALenum) format size:(ALsizei) size freq:(ALsizei) freq { @synchronized(_mutexBufferLoad) { - + if (!functioning_) { //OpenAL initialisation has previously failed CDLOG(@"Denshion::CDSoundEngine - Loading buffer failed because sound engine state != functioning"); return FALSE; } - + //Ensure soundId is within array bounds otherwise memory corruption will occur if (soundId < 0) { CDLOG(@"Denshion::CDSoundEngine - soundId is negative"); return FALSE; } - + if (soundId >= bufferTotal) { //Need to resize the buffers int requiredIncrement = CD_BUFFERS_INCREMENT; @@ -529,9 +529,9 @@ static BOOL _mixerRateSet = NO; if (![self _resizeBuffers:requiredIncrement]) { CDLOG(@"Denshion::CDSoundEngine - buffer resize failed"); return FALSE; - } - } - + } + } + if (soundData) { if (_buffers[soundId].bufferState != CD_BS_EMPTY) { @@ -539,33 +539,33 @@ static BOOL _mixerRateSet = NO; if (![self unloadBuffer:soundId]) { //Deletion of buffer failed, delete buffer routine has set buffer state and lastErrorCode return NO; - } - } - + } + } + #ifdef CD_DEBUG //Check that sample rate matches mixer rate and warn if they do not if (freq != (int)_mixerSampleRate) { CDLOGINFO(@"Denshion::CDSoundEngine - WARNING sample rate does not match mixer sample rate performance may not be optimal."); - } -#endif - + } +#endif + #ifdef CD_USE_STATIC_BUFFERS alBufferDataStaticProc(_buffers[soundId].bufferId, format, soundData, size, freq); - _buffers[soundId].bufferData = data;//Save the pointer to the new data -#else + _buffers[soundId].bufferData = soundData;//Save the pointer to the new data +#else alBufferData(_buffers[soundId].bufferId, format, soundData, size, freq); #endif if((lastErrorCode_ = alGetError()) != AL_NO_ERROR) { CDLOG(@"Denshion::CDSoundEngine - error attaching audio to buffer: %x", lastErrorCode_); _buffers[soundId].bufferState = CD_BS_FAILED; return FALSE; - } + } } else { CDLOG(@"Denshion::CDSoundEngine Buffer data is null!"); _buffers[soundId].bufferState = CD_BS_FAILED; return FALSE; - } - + } + _buffers[soundId].format = format; _buffers[soundId].sizeInBytes = size; _buffers[soundId].frequencyInHertz = freq; @@ -573,7 +573,7 @@ static BOOL _mixerRateSet = NO; CDLOGINFO(@"Denshion::CDSoundEngine Buffer %i loaded format:%i freq:%i size:%i",soundId,format,freq,size); return TRUE; }//end mutex -} +} /** * Load sound data for later play back. @@ -586,9 +586,9 @@ static BOOL _mixerRateSet = NO; ALenum format; ALsizei size; ALsizei freq; - + CDLOGINFO(@"Denshion::CDSoundEngine - Loading openAL buffer %i %@", soundId, filePath); - + CFURLRef fileURL = nil; NSString *path = [CDUtilities fullPathFromRelativePath:filePath]; if (path) { @@ -601,14 +601,14 @@ static BOOL _mixerRateSet = NO; CFRelease(fileURL); BOOL result = [self loadBufferFromData:soundId soundData:data format:format size:size freq:freq]; #ifndef CD_USE_STATIC_BUFFERS - free(data);//Data can be freed here because alBufferData performs a memcpy + free(data);//Data can be freed here because alBufferData performs a memcpy #endif return result; } else { CDLOG(@"Denshion::CDSoundEngine Could not find file!\n"); - //Don't change buffer state here as it will be the same as before method was called + //Don't change buffer state here as it will be the same as before method was called return FALSE; - } + } } -(BOOL) validateBufferId:(int) soundId { @@ -620,8 +620,8 @@ static BOOL _mixerRateSet = NO; return NO; } else { return YES; - } -} + } +} -(float) bufferDurationInSeconds:(int) soundId { if ([self validateBufferId:soundId]) { @@ -639,39 +639,39 @@ static BOOL _mixerRateSet = NO; case AL_FORMAT_STEREO16: factor = 0.25f; break; - } + } return (float)_buffers[soundId].sizeInBytes/(float)_buffers[soundId].frequencyInHertz * factor; } else { return -1.0f; - } -} + } +} -(ALsizei) bufferSizeInBytes:(int) soundId { if ([self validateBufferId:soundId]) { return _buffers[soundId].sizeInBytes; } else { return -1.0f; - } -} + } +} -(ALsizei) bufferFrequencyInHertz:(int) soundId { if ([self validateBufferId:soundId]) { return _buffers[soundId].frequencyInHertz; } else { return -1.0f; - } -} + } +} - (ALfloat) masterGain { if (mute_) { //When mute the real gain will always be 0 therefore return the preMuteGain value return _preMuteGain; - } else { + } else { ALfloat gain; alGetListenerf(AL_GAIN, &gain); return gain; - } -} + } +} /** * Overall gain setting multiplier. e.g 0.5 is half the gain. @@ -679,25 +679,25 @@ static BOOL _mixerRateSet = NO; - (void) setMasterGain:(ALfloat) newGainValue { if (mute_) { _preMuteGain = newGainValue; - } else { + } else { alListenerf(AL_GAIN, newGainValue); - } + } } #pragma mark CDSoundEngine AudioInterrupt protocol - (BOOL) mute { return mute_; -} +} /** * Setting mute silences all sounds but playing sounds continue to advance playback */ - (void) setMute:(BOOL) newMuteValue { - + if (newMuteValue == mute_) { return; } - + mute_ = newMuteValue; if (mute_) { //Remember what the gain was @@ -707,7 +707,7 @@ static BOOL _mixerRateSet = NO; } else { //Restore gain to what it was before being muted self.masterGain = _preMuteGain; - } + } } - (BOOL) enabled { @@ -718,12 +718,12 @@ static BOOL _mixerRateSet = NO; { if (enabled_ == enabledValue) { return; - } + } enabled_ = enabledValue; if (enabled_ == NO) { [self stopAllSounds]; - } -} + } +} -(void) _lockSource:(int) sourceIndex lock:(BOOL) lock { BOOL found = NO; @@ -737,22 +737,22 @@ static BOOL _mixerRateSet = NO; _sourceGroups[i].sourceStatuses[j] |= 1; } else { //Unset first bit to unlock this source - _sourceGroups[i].sourceStatuses[j] &= ~1; - } + _sourceGroups[i].sourceStatuses[j] &= ~1; + } found = YES; - } - } - } + } + } + } } -} +} --(int) _getSourceIndexForSourceGroup:(int)sourceGroupId +-(int) _getSourceIndexForSourceGroup:(int)sourceGroupId { //Ensure source group id is valid to prevent memory corruption if (sourceGroupId < 0 || sourceGroupId >= _sourceGroupTotal) { CDLOG(@"Denshion::CDSoundEngine invalid source group id %i",sourceGroupId); return CD_NO_SOURCE; - } + } int sourceIndex = -1;//Using -1 to indicate no source found BOOL complete = NO; @@ -774,49 +774,49 @@ static BOOL _mixerRateSet = NO; break; } else { sourceIndex = -1;//The source index was no good because the source was playing - } - } else { + } + } else { //complete = YES; //Set start index so next search starts at the next position thisSourceGroup->startIndex = thisSourceGroup->currentIndex + 1; break; - } + } } thisSourceGroup->currentIndex++; if (thisSourceGroup->currentIndex >= thisSourceGroup->totalSources) { //Reset to the beginning - thisSourceGroup->currentIndex = 0; - } + thisSourceGroup->currentIndex = 0; + } if (thisSourceGroup->currentIndex == thisSourceGroup->startIndex) { //We have looped around and got back to the start complete = YES; - } + } } //Reset start index to beginning if beyond bounds if (thisSourceGroup->startIndex >= thisSourceGroup->totalSources) { - thisSourceGroup->startIndex = 0; - } - + thisSourceGroup->startIndex = 0; + } + if (sourceIndex >= 0) { return sourceIndex; - } else { + } else { return CD_NO_SOURCE; - } - -} + } + +} /** * Play a sound. * @param soundId the id of the sound to play (buffer id). - * @param SourceGroupId the source group that will be used to play the sound. - * @param pitch pitch multiplier. e.g 1.0 is unaltered, 0.5 is 1 octave lower. + * @param sourceGroupId the source group that will be used to play the sound. + * @param pitch pitch multiplier. e.g 1.0 is unaltered, 0.5 is 1 octave lower. * @param pan stereo position. -1 is fully left, 0 is centre and 1 is fully right. * @param gain gain multiplier. e.g. 1.0 is unaltered, 0.5 is half the gain * @param loop should the sound be looped or one shot. - * @return the id of the source being used to play the sound or CD_MUTE if the sound engine is muted or non functioning + * @return the id of the source being used to play the sound or CD_MUTE if the sound engine is muted or non functioning * or CD_NO_SOURCE if a problem occurs setting up the source - * + * */ - (ALuint)playSound:(int) soundId sourceGroupId:(int)sourceGroupId pitch:(float) pitch pan:(float) pan gain:(float) gain loop:(BOOL) loop { @@ -837,22 +837,22 @@ static BOOL _mixerRateSet = NO; CDLOGINFO(@"Denshion::CDSoundEngine - sound playback aborted because sound engine is not functioning"); } else if (_buffers[soundId].bufferState != CD_BS_LOADED) { CDLOGINFO(@"Denshion::CDSoundEngine - sound playback aborted because buffer %i is not loaded", soundId); - } -#endif + } +#endif return CD_MUTE; - } + } int sourceIndex = [self _getSourceIndexForSourceGroup:sourceGroupId];//This method ensures sourceIndex is valid - + if (sourceIndex != CD_NO_SOURCE) { ALint state; ALuint source = _sources[sourceIndex].sourceId; ALuint buffer = _buffers[soundId].bufferId; - alGetError();//Clear the error code + alGetError();//Clear the error code alGetSourcei(source, AL_SOURCE_STATE, &state); if (state == AL_PLAYING) { alSourceStop(source); - } + } alSourcei(source, AL_BUFFER, buffer);//Attach to sound alSourcef(source, AL_PITCH, pitch);//Set pitch alSourcei(source, AL_LOOPING, loop);//Set looping @@ -869,12 +869,12 @@ static BOOL _mixerRateSet = NO; if (alcGetCurrentContext() == NULL) { CDLOGINFO(@"Denshion::CDSoundEngine - posting bad OpenAL context message"); [[NSNotificationCenter defaultCenter] postNotificationName:kCDN_BadAlContext object:nil]; - } + } return CD_NO_SOURCE; - } - } else { + } + } else { return CD_NO_SOURCE; - } + } } -(BOOL) _soundSourceAttachToBuffer:(CDSoundSource*) soundSource soundId:(int) soundId { @@ -886,7 +886,7 @@ static BOOL _mixerRateSet = NO; if (state == AL_PLAYING) { alSourceStop(source); } - alGetError();//Clear the error code + alGetError();//Clear the error code alSourcei(source, AL_BUFFER, buffer);//Attach to sound data if((lastErrorCode_ = alGetError()) == AL_NO_ERROR) { _sources[soundSource->_sourceIndex].attachedBufferId = buffer; @@ -895,20 +895,20 @@ static BOOL _mixerRateSet = NO; return YES; } else { return NO; - } -} + } +} /** * Get a sound source for the specified sound in the specified source group */ --(CDSoundSource *) soundSourceForSound:(int) soundId sourceGroupId:(int) sourceGroupId +-(CDSoundSource *) soundSourceForSound:(int) soundId sourceGroupId:(int) sourceGroupId { if (!functioning_) { return nil; - } + } //Check if a source is available int sourceIndex = [self _getSourceIndexForSourceGroup:sourceGroupId]; - if (sourceIndex != CD_NO_SOURCE) { + if (sourceIndex != CD_NO_SOURCE) { CDSoundSource *result = [[CDSoundSource alloc] init:_sources[sourceIndex].sourceId sourceIndex:sourceIndex soundEngine:self]; [self _lockSource:sourceIndex lock:YES]; //Try to attach to the buffer @@ -923,34 +923,34 @@ static BOOL _mixerRateSet = NO; //Release the sound source we just created, this will also unlock the source [result release]; return nil; - } + } } else { //No available source within that source group return nil; } -} +} -(void) _soundSourcePreRelease:(CDSoundSource *) soundSource { CDLOGINFO(@"Denshion::CDSoundEngine _soundSourcePreRelease %i",soundSource->_sourceIndex); //Unlock the sound source's source [self _lockSource:soundSource->_sourceIndex lock:NO]; -} +} /** * Stop all sounds playing within a source group */ - (void) stopSourceGroup:(int) sourceGroupId { - + if (!functioning_ || sourceGroupId >= _sourceGroupTotal || sourceGroupId < 0) { return; - } + } int sourceCount = _sourceGroups[sourceGroupId].totalSources; for (int i=0; i < sourceCount; i++) { int sourceIndex = _sourceGroups[sourceGroupId].sourceStatuses[i] >> 1; alSourceStop(_sources[sourceIndex].sourceId); } alGetError();//Clear error in case we stopped any sounds that couldn't be stopped -} +} /** * Stop a sound playing. @@ -959,7 +959,7 @@ static BOOL _mixerRateSet = NO; - (void)stopSound:(ALuint) sourceId { if (!functioning_) { return; - } + } alSourceStop(sourceId); alGetError();//Clear error in case we stopped any sounds that couldn't be stopped } @@ -967,9 +967,9 @@ static BOOL _mixerRateSet = NO; - (void) stopAllSounds { for (int i=0; i < sourceTotal_; i++) { alSourceStop(_sources[i].sourceId); - } + } alGetError();//Clear error in case we stopped any sounds that couldn't be stopped -} +} - (void) pauseSound:(ALuint) sourceId { if (!functioning_) { @@ -990,7 +990,7 @@ static BOOL _mixerRateSet = NO; if (!functioning_) { return; } - + // only resume a sound id that is paused ALint state; alGetSourcei(soundId, AL_SOURCE_STATE, &state); @@ -998,7 +998,7 @@ static BOOL _mixerRateSet = NO; { return; } - + alSourcePlay(soundId); alGetError();//Clear error in case we stopped any sounds that couldn't be resumed } @@ -1020,19 +1020,19 @@ static BOOL _mixerRateSet = NO; if (sourceGroupId < 0 || sourceGroupId >= _sourceGroupTotal) { CDLOG(@"Denshion::CDSoundEngine setSourceGroupNonInterruptible invalid source group id %i",sourceGroupId); return; - } - + } + if (isNonInterruptible) { _sourceGroups[sourceGroupId].nonInterruptible = true; } else { _sourceGroups[sourceGroupId].nonInterruptible = false; - } + } } /** * Set the mute property for a source group. If mute is turned on any sounds in that source group * will be stopped and further sounds in that source group will play. However, turning mute off - * will not restart any sounds that were playing when mute was turned on. Also the mute setting + * will not restart any sounds that were playing when mute was turned on. Also the mute setting * for the sound engine must be taken into account. If the sound engine is mute no sounds will play * no matter what the source group mute setting is. */ @@ -1041,14 +1041,14 @@ static BOOL _mixerRateSet = NO; if (sourceGroupId < 0 || sourceGroupId >= _sourceGroupTotal) { CDLOG(@"Denshion::CDSoundEngine setSourceGroupEnabled invalid source group id %i",sourceGroupId); return; - } - + } + if (enabled) { _sourceGroups[sourceGroupId].enabled = true; [self stopSourceGroup:sourceGroupId]; } else { - _sourceGroups[sourceGroupId].enabled = false; - } + _sourceGroups[sourceGroupId].enabled = false; + } } /** @@ -1060,10 +1060,10 @@ static BOOL _mixerRateSet = NO; -(ALCcontext *) openALContext { return context; -} +} - (void) _dumpSourceGroupsInfo { -#ifdef CD_DEBUG +#ifdef CD_DEBUG CDLOGINFO(@"-------------- source Group Info --------------"); for (int i=0; i < _sourceGroupTotal; i++) { CDLOGINFO(@"Group: %i start:%i total:%i",i,_sourceGroups[i].startIndex, _sourceGroups[i].totalSources); @@ -1071,10 +1071,10 @@ static BOOL _mixerRateSet = NO; CDLOGINFO(@"----- Source statuses ----"); for (int j=0; j < _sourceGroups[i].totalSources; j++) { CDLOGINFO(@"Source status:%i index=%i locked=%i",j,_sourceGroups[i].sourceStatuses[j] >> 1, _sourceGroups[i].sourceStatuses[j] & 1); - } - } -#endif -} + } + } +#endif +} @end @@ -1095,7 +1095,7 @@ static BOOL _mixerRateSet = NO; enabled_ = YES; mute_ = NO; _preMuteGain = self.gain; - } + } return self; } @@ -1106,19 +1106,19 @@ static BOOL _mixerRateSet = NO; //Notify sound engine we are about to release [_engine _soundSourcePreRelease:self]; [super dealloc]; -} +} - (void) setPitch:(float) newPitchValue { alSourcef(_sourceId, AL_PITCH, newPitchValue); CDSOUNDSOURCE_UPDATE_LAST_ERROR; -} +} - (void) setGain:(float) newGainValue { if (!mute_) { - alSourcef(_sourceId, AL_GAIN, newGainValue); + alSourcef(_sourceId, AL_GAIN, newGainValue); } else { _preMuteGain = newGainValue; - } + } CDSOUNDSOURCE_UPDATE_LAST_ERROR; } @@ -1140,7 +1140,7 @@ static BOOL _mixerRateSet = NO; alGetSourcei(_sourceId, AL_SOURCE_STATE, &state); CDSOUNDSOURCE_UPDATE_LAST_ERROR; return (state == AL_PLAYING); -} +} - (float) pitch { ALfloat pitchVal; @@ -1164,8 +1164,8 @@ static BOOL _mixerRateSet = NO; return val; } else { return _preMuteGain; - } -} + } +} - (BOOL) looping { ALfloat val; @@ -1177,7 +1177,7 @@ static BOOL _mixerRateSet = NO; -(BOOL) stop { alSourceStop(_sourceId); return CDSOUNDSOURCE_ERROR_HANDLER; -} +} -(BOOL) play { if (enabled_) { @@ -1187,15 +1187,15 @@ static BOOL _mixerRateSet = NO; if (alcGetCurrentContext() == NULL) { CDLOGINFO(@"Denshion::CDSoundSource - posting bad OpenAL context message"); [[NSNotificationCenter defaultCenter] postNotificationName:kCDN_BadAlContext object:nil]; - } + } return NO; } else { return YES; - } + } } else { return NO; } -} +} -(BOOL) pause { alSourcePause(_sourceId); @@ -1213,26 +1213,26 @@ static BOOL _mixerRateSet = NO; -(int) soundId { return _soundId; -} +} -(float) durationInSeconds { return [_engine bufferDurationInSeconds:_soundId]; -} +} #pragma mark CDSoundSource AudioInterrupt protocol - (BOOL) mute { return mute_; -} +} /** * Setting mute silences all sounds but playing sounds continue to advance playback */ - (void) setMute:(BOOL) newMuteValue { - + if (newMuteValue == mute_) { return; } - + if (newMuteValue) { //Remember what the gain was _preMuteGain = self.gain; @@ -1242,7 +1242,7 @@ static BOOL _mixerRateSet = NO; //Restore gain to what it was before being muted mute_ = newMuteValue; self.gain = _preMuteGain; - } + } } - (BOOL) enabled { @@ -1253,12 +1253,12 @@ static BOOL _mixerRateSet = NO; { if (enabled_ == enabledValue) { return; - } + } enabled_ = enabledValue; if (enabled_ == NO) { [self stop]; - } -} + } +} @end @@ -1275,35 +1275,35 @@ static BOOL _mixerRateSet = NO; mute_ = NO; } return self; -} +} -(void) addAudioInterruptTarget:(NSObject*) interruptibleTarget { //Synchronize child with group settings; [interruptibleTarget setMute:mute_]; [interruptibleTarget setEnabled:enabled_]; [children_ addObject:interruptibleTarget]; -} +} -(void) removeAudioInterruptTarget:(NSObject*) interruptibleTarget { [children_ removeObjectIdenticalTo:interruptibleTarget]; -} +} - (BOOL) mute { return mute_; -} +} /** * Setting mute silences all sounds but playing sounds continue to advance playback */ - (void) setMute:(BOOL) newMuteValue { - + if (newMuteValue == mute_) { return; } - + for (NSObject* target in children_) { [target setMute:newMuteValue]; - } + } } - (BOOL) enabled { @@ -1315,11 +1315,11 @@ static BOOL _mixerRateSet = NO; if (enabledValue == enabled_) { return; } - + for (NSObject* target in children_) { [target setEnabled:enabledValue]; - } -} + } +} @end @@ -1338,9 +1338,9 @@ static BOOL _mixerRateSet = NO; [_loadRequests retain]; _soundEngine = theSoundEngine; [_soundEngine retain]; - } + } return self; -} +} -(void) main { CDLOGINFO(@"Denshion::CDAsynchBufferLoader - loading buffers"); @@ -1353,20 +1353,20 @@ static BOOL _mixerRateSet = NO; for (CDBufferLoadRequest *loadRequest in _loadRequests) { [_soundEngine loadBuffer:loadRequest.soundId filePath:loadRequest.filePath]; _soundEngine.asynchLoadProgress += increment; - } - } - + } + } + //Completed _soundEngine.asynchLoadProgress = 1.0f; [[NSNotificationCenter defaultCenter] postNotificationName:kCDN_AsynchLoadComplete object:nil]; - -} + +} -(void) dealloc { [_loadRequests release]; [_soundEngine release]; [super dealloc]; -} +} @end @@ -1402,13 +1402,13 @@ static BOOL _mixerRateSet = NO; @synthesize start,end,interpolationType; -(float) interpolate:(float) t { - + if (t < 1.0f) { switch (interpolationType) { case kIT_Linear: //Linear interpolation return ((end - start) * t) + start; - + case kIT_SCurve: //Cubic s curve t^2 * (3 - 2t) return ((t * t * (3.0f - (2.0f * t))) * (end - start)) + start; @@ -1429,7 +1429,7 @@ static BOOL _mixerRateSet = NO; } } else { return end; - } + } } -(id) init:(tCDInterpolationType) type startVal:(float) startVal endVal:(float) endVal { @@ -1437,7 +1437,7 @@ static BOOL _mixerRateSet = NO; start = startVal; end = endVal; interpolationType = type; - } + } return self; } @@ -1456,7 +1456,7 @@ static BOOL _mixerRateSet = NO; if (target) { //Release the previous target if there is one [target release]; - } + } target = theTarget; #if CD_DEBUG //Check target is of the required type @@ -1464,26 +1464,26 @@ static BOOL _mixerRateSet = NO; CDLOG(@"Denshion::CDPropertyModifier target is not of type %@",[self _allowableType]); NSAssert([theTarget isKindOfClass:[CDSoundEngine class]], @"CDPropertyModifier target not of required type"); } -#endif +#endif [target retain]; startValue = startVal; endValue = endVal; if (interpolator) { //Release previous interpolator if there is one [interpolator release]; - } + } interpolator = [[CDFloatInterpolator alloc] init:type startVal:startVal endVal:endVal]; stopTargetWhenComplete = NO; } return self; -} +} -(void) dealloc { CDLOGINFO(@"Denshion::CDPropertyModifier deallocated %@",self); [target release]; [interpolator release]; [super dealloc]; -} +} -(void) modify:(float) t { if (t < 1.0f) { @@ -1493,9 +1493,9 @@ static BOOL _mixerRateSet = NO; [self _setTargetProperty:endValue]; if (stopTargetWhenComplete) { [self _stopTarget]; - } - } -} + } + } +} -(float) startValue { return startValue; @@ -1505,7 +1505,7 @@ static BOOL _mixerRateSet = NO; { startValue = startVal; interpolator.start = startVal; -} +} -(float) endValue { return startValue; @@ -1515,7 +1515,7 @@ static BOOL _mixerRateSet = NO; { endValue = endVal; interpolator.end = endVal; -} +} -(tCDInterpolationType) interpolationType { return interpolator.interpolationType; @@ -1523,23 +1523,23 @@ static BOOL _mixerRateSet = NO; -(void) setInterpolationType:(tCDInterpolationType) interpolationType { interpolator.interpolationType = interpolationType; -} +} -(void) _setTargetProperty:(float) newVal { -} +} -(float) _getTargetProperty { return 0.0f; -} +} -(void) _stopTarget { -} +} -(Class) _allowableType { return [NSObject class]; -} +} @end /////////////////////////////////////////////////////////////////////////////////////// @@ -1550,7 +1550,7 @@ static BOOL _mixerRateSet = NO; -(void) _setTargetProperty:(float) newVal { ((CDSoundSource*)target).gain = newVal; -} +} -(float) _getTargetProperty { return ((CDSoundSource*)target).gain; @@ -1562,7 +1562,7 @@ static BOOL _mixerRateSet = NO; -(Class) _allowableType { return [CDSoundSource class]; -} +} @end @@ -1574,7 +1574,7 @@ static BOOL _mixerRateSet = NO; -(void) _setTargetProperty:(float) newVal { ((CDSoundSource*)target).pan = newVal; -} +} -(float) _getTargetProperty { return ((CDSoundSource*)target).pan; @@ -1586,7 +1586,7 @@ static BOOL _mixerRateSet = NO; -(Class) _allowableType { return [CDSoundSource class]; -} +} @end @@ -1598,7 +1598,7 @@ static BOOL _mixerRateSet = NO; -(void) _setTargetProperty:(float) newVal { ((CDSoundSource*)target).pitch = newVal; -} +} -(float) _getTargetProperty { return ((CDSoundSource*)target).pitch; @@ -1610,7 +1610,7 @@ static BOOL _mixerRateSet = NO; -(Class) _allowableType { return [CDSoundSource class]; -} +} @end @@ -1622,7 +1622,7 @@ static BOOL _mixerRateSet = NO; -(void) _setTargetProperty:(float) newVal { ((CDSoundEngine*)target).masterGain = newVal; -} +} -(float) _getTargetProperty { return ((CDSoundEngine*)target).masterGain; @@ -1634,7 +1634,8 @@ static BOOL _mixerRateSet = NO; -(Class) _allowableType { return [CDSoundEngine class]; -} +} @end + diff --git a/native/cocos/audio/mac/SimpleAudioEngine.mm b/native/cocos/audio/mac/SimpleAudioEngine.mm index f8b5f9ed8a..86bf64378a 100644 --- a/native/cocos/audio/mac/SimpleAudioEngine.mm +++ b/native/cocos/audio/mac/SimpleAudioEngine.mm @@ -57,7 +57,7 @@ static void static_pauseBackgroundMusic() static void static_resumeBackgroundMusic() { [[SimpleAudioEngine sharedEngine] resumeBackgroundMusic]; -} +} static void static_rewindBackgroundMusic() { @@ -84,12 +84,12 @@ static void static_setBackgroundMusicVolume(float volume) volume = MAX( MIN(volume, 1.0), 0 ); [SimpleAudioEngine sharedEngine].backgroundMusicVolume = volume; } - + static float static_getEffectsVolume() { return [[SimpleAudioEngine sharedEngine] effectsVolume]; } - + static void static_setEffectsVolume(float volume) { volume = MAX( MIN(volume, 1.0), 0 ); @@ -100,17 +100,17 @@ static unsigned int static_playEffect(const char* pszFilePath, bool bLoop, Float { return [[SimpleAudioEngine sharedEngine] playEffect:[NSString stringWithUTF8String: pszFilePath] loop:bLoop pitch:pszPitch pan: pszPan gain:pszGain ]; } - + static void static_stopEffect(int nSoundId) { [[SimpleAudioEngine sharedEngine] stopEffect: nSoundId]; } - + static void static_preloadEffect(const char* pszFilePath) { [[SimpleAudioEngine sharedEngine] preloadEffect: [NSString stringWithUTF8String: pszFilePath]]; } - + static void static_unloadEffect(const char* pszFilePath) { [[SimpleAudioEngine sharedEngine] unloadEffect: [NSString stringWithUTF8String: pszFilePath]]; @@ -161,7 +161,7 @@ SimpleAudioEngine* SimpleAudioEngine::getInstance() { s_pEngine = new (std::nothrow) SimpleAudioEngine(); } - + return s_pEngine; } @@ -172,7 +172,7 @@ void SimpleAudioEngine::end() delete s_pEngine; s_pEngine = nullptr; } - + static_end(); } @@ -203,7 +203,7 @@ void SimpleAudioEngine::pauseBackgroundMusic() void SimpleAudioEngine::resumeBackgroundMusic() { static_resumeBackgroundMusic(); -} +} void SimpleAudioEngine::rewindBackgroundMusic() { diff --git a/native/cocos/audio/mac/SimpleAudioEngine_objc.h b/native/cocos/audio/mac/SimpleAudioEngine_objc.h index 6b5d12dc08..68f633447f 100644 --- a/native/cocos/audio/mac/SimpleAudioEngine_objc.h +++ b/native/cocos/audio/mac/SimpleAudioEngine_objc.h @@ -1,16 +1,16 @@ /* Copyright (c) 2010 Steve Oldmeadow - + 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 @@ -18,7 +18,7 @@ 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. - + $Id$ */ @@ -30,15 +30,15 @@ This is recommended for basic audio requirements. If you just want to play some sound fx and some background music and have no interest in learning the lower level workings then this is the interface to use. - + Requirements: - - Firmware: OS 2.2 or greater + - Firmware: OS 2.2 or greater - Files: SimpleAudioEngine.*, CocosDenshion.* - Frameworks: OpenAL, AudioToolbox, AVFoundation @since v0.8 */ @interface SimpleAudioEngine : NSObject { - + BOOL mute_; BOOL enabled_; } diff --git a/native/cocos/audio/mac/SimpleAudioEngine_objc.m b/native/cocos/audio/mac/SimpleAudioEngine_objc.m index 57efd6973f..2617d06a5e 100644 --- a/native/cocos/audio/mac/SimpleAudioEngine_objc.m +++ b/native/cocos/audio/mac/SimpleAudioEngine_objc.m @@ -1,16 +1,16 @@ /* Copyright (c) 2010 Steve Oldmeadow - + 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 @@ -18,7 +18,7 @@ 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. - + $Id$ */ @@ -71,14 +71,14 @@ static CDBufferManager *bufferManager = nil; [super dealloc]; } -+(void) end ++(void) end { am = nil; [CDAudioManager end]; [bufferManager release]; [sharedEngine release]; sharedEngine = nil; -} +} #pragma mark SimpleAudioEngine - background music @@ -103,11 +103,11 @@ static CDBufferManager *bufferManager = nil; -(void) pauseBackgroundMusic { [am pauseBackgroundMusic]; -} +} -(void) resumeBackgroundMusic { [am resumeBackgroundMusic]; -} +} -(void) rewindBackgroundMusic { [am rewindBackgroundMusic]; @@ -115,7 +115,7 @@ static CDBufferManager *bufferManager = nil; -(BOOL) isBackgroundMusicPlaying { return [am isBackgroundMusicPlaying]; -} +} -(BOOL) willPlayBackgroundMusic { return [am willPlayBackgroundMusic]; @@ -135,12 +135,12 @@ static CDBufferManager *bufferManager = nil; return [soundEngine playSound:soundId sourceGroupId:0 pitch:pitch pan:pan gain:gain loop:loop]; } else { return CD_MUTE; - } + } } -(void) stopEffect:(ALuint) soundId { [soundEngine stopSound:soundId]; -} +} -(void) pauseEffect:(ALuint) soundId { [soundEngine pauseSound: soundId]; @@ -187,7 +187,7 @@ static CDBufferManager *bufferManager = nil; if (mute_ != muteValue) { mute_ = muteValue; am.mute = mute_; - } + } } -(BOOL) enabled @@ -200,7 +200,7 @@ static CDBufferManager *bufferManager = nil; if (enabled_ != enabledValue) { enabled_ = enabledValue; am.enabled = enabled_; - } + } } @@ -208,23 +208,23 @@ static CDBufferManager *bufferManager = nil; -(float) backgroundMusicVolume { return am.backgroundMusic.volume; -} +} -(void) setBackgroundMusicVolume:(float) volume { am.backgroundMusic.volume = volume; -} +} #pragma mark SimpleAudioEngine - EffectsVolume -(float) effectsVolume { return am.soundEngine.masterGain; -} +} -(void) setEffectsVolume:(float) volume { am.soundEngine.masterGain = volume; -} +} -(CDSoundSource *) soundSourceForFile:(NSString*) filePath { int soundId = [bufferManager bufferForFile:filePath create:YES]; @@ -234,7 +234,7 @@ static CDBufferManager *bufferManager = nil; return result; } else { return nil; - } -} + } +} @end diff --git a/native/cocos/audio/win32/AudioCache.cpp b/native/cocos/audio/win32/AudioCache.cpp index a0e88cc4aa..a2b11db03c 100644 --- a/native/cocos/audio/win32/AudioCache.cpp +++ b/native/cocos/audio/win32/AudioCache.cpp @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2014 Chukong Technologies Inc. + Copyright (c) 2014-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -30,350 +30,350 @@ #include "audio/win32/AudioCache.h" #include -#include -#include "vorbis/codec.h" -#include "vorbis/vorbisfile.h" -#include "platform/CCFileUtils.h" -#include "mpg123/mpg123.h" #include "base/CCDirector.h" #include "base/CCScheduler.h" -#include +#include "audio/win32/AudioDecoderManager.h" +#include "audio/win32/AudioDecoder.h" -#define PCMDATA_CACHEMAXSIZE 2621440 +#define VERY_VERY_VERBOSE_LOGGING +#ifdef VERY_VERY_VERBOSE_LOGGING +#define ALOGVV ALOGV +#else +#define ALOGVV(...) do{} while(false) +#endif +namespace { +unsigned int __idIndex = 0; +} + +#define INVALID_AL_BUFFER_ID 0xFFFFFFFF +#define PCMDATA_CACHEMAXSIZE 1048576 + +using namespace cocos2d; using namespace cocos2d::experimental; -//FIXME: Move _winLog, winLog to a separated file -static void _winLog(const char *format, va_list args) -{ - static const int MAX_LOG_LENGTH = 16 * 1024; - int bufferSize = MAX_LOG_LENGTH; - char* buf = nullptr; - - do - { - buf = new (std::nothrow) char[bufferSize]; - if (buf == nullptr) - return; // not enough memory - - int ret = vsnprintf(buf, bufferSize - 3, format, args); - if (ret < 0) - { - bufferSize *= 2; - - delete[] buf; - } - else - break; - - } while (true); - - strcat(buf, "\n"); - - int pos = 0; - int len = strlen(buf); - char tempBuf[MAX_LOG_LENGTH + 1] = { 0 }; - WCHAR wszBuf[MAX_LOG_LENGTH + 1] = { 0 }; - - do - { - std::copy(buf + pos, buf + pos + MAX_LOG_LENGTH, tempBuf); - - tempBuf[MAX_LOG_LENGTH] = 0; - - MultiByteToWideChar(CP_UTF8, 0, tempBuf, -1, wszBuf, sizeof(wszBuf)); - OutputDebugStringW(wszBuf); - - pos += MAX_LOG_LENGTH; - - } while (pos < len); - - delete[] buf; -} - -void audioLog(const char * format, ...) -{ - va_list args; - va_start(args, format); - _winLog(format, args); - va_end(args); -} - AudioCache::AudioCache() -: _pcmData(nullptr) -, _pcmDataSize(0) -, _bytesOfRead(0) -, _alBufferReady(false) -, _loadFail(false) -, _fileFormat(FileFormat::UNKNOWN) +: _totalFrames(0) +, _framesRead(0) +, _format(-1) +, _duration(0.0f) +, _alBufferId(INVALID_AL_BUFFER_ID) +, _pcmData(nullptr) , _queBufferFrames(0) -, _queBufferBytes(0) -, _mp3Encoding(0) +, _state(State::INITIAL) +, _isDestroyed(std::make_shared(false)) +, _id(++__idIndex) +, _isLoadingFinished(false) +, _isSkipReadDataTask(false) { - -} - -AudioCache::AudioCache(const AudioCache& cache) -{ - _pcmData = cache._pcmData; - _pcmDataSize = cache._pcmDataSize; - _bytesOfRead = cache._bytesOfRead; - _alBufferReady = cache._alBufferReady; - _fileFormat = cache._fileFormat; - _queBufferFrames = cache._queBufferFrames; - _queBufferBytes = cache._queBufferBytes; - _mp3Encoding = cache._mp3Encoding; + ALOGVV("AudioCache() %p, id=%u", this, _id); + for (int i = 0; i < QUEUEBUFFER_NUM; ++i) + { + _queBuffers[i] = nullptr; + _queBufferSize[i] = 0; + } } AudioCache::~AudioCache() { - if(_pcmData){ - if (_alBufferReady){ - alDeleteBuffers(1, &_alBufferId); + ALOGVV("~AudioCache() %p, id=%u, begin", this, _id); + *_isDestroyed = true; + while (!_isLoadingFinished) + { + if (_isSkipReadDataTask) + { + ALOGV("id=%u, Skip read data task, don't continue to wait!", _id); + break; + } + ALOGVV("id=%u, waiting readData thread to finish ...", _id); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + //wait for the 'readDataTask' task to exit + _readDataTaskMutex.lock(); + _readDataTaskMutex.unlock(); + + if (_pcmData) + { + if (_state == State::READY) + { + if (_alBufferId != INVALID_AL_BUFFER_ID && alIsBuffer(_alBufferId)) + { + ALOGV("~AudioCache(id=%u), delete buffer: %u", _id, _alBufferId); + alDeleteBuffers(1, &_alBufferId); + _alBufferId = INVALID_AL_BUFFER_ID; + } + } + else + { + ALOGW("AudioCache (%p), id=%u, buffer isn't ready, state=%d", this, _id, _state); } - //wait for the 'readDataTask' task to exit - _readDataTaskMutex.lock(); - _readDataTaskMutex.unlock(); free(_pcmData); } - if (_queBufferFrames > 0) { - for (int index = 0; index < QUEUEBUFFER_NUM; ++index) { + if (_queBufferFrames > 0) + { + for (int index = 0; index < QUEUEBUFFER_NUM; ++index) + { free(_queBuffers[index]); } } + ALOGVV("~AudioCache() %p, id=%u, end", this, _id); } -void AudioCache::readDataTask() +void AudioCache::readDataTask(unsigned int selfId) { + //Note: It's in sub thread + ALOGVV("readDataTask begin, cache id=%u", selfId); + _readDataTaskMutex.lock(); + _state = State::LOADING; - OggVorbis_File* vf = nullptr; - mpg123_handle* mpg123handle = nullptr; - long totalFrames = 0; - - switch (_fileFormat) - { - case FileFormat::OGG: - { - vf = new OggVorbis_File; - int openCode; - if (openCode = ov_fopen(FileUtils::getInstance()->getSuitableFOpen(_fileFullPath).c_str(), vf)){ - ALOGE("Input does not appear to be an Ogg bitstream: %s. Code: 0x%x\n", _fileFullPath.c_str(), openCode); - goto ExitThread; - } - - auto vi = ov_info(vf,-1); - totalFrames = (long)ov_pcm_total(vf,-1); - _bytesPerFrame = vi->channels * 2; - _alBufferFormat = (vi->channels > 1) ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16; - _sampleRate = vi->rate; - _pcmDataSize = totalFrames * _bytesPerFrame; - _duration = 1.0f * totalFrames / _sampleRate; - } - break; - case FileFormat::MP3: - { - long rate = 0; - int error = MPG123_OK; - mpg123handle = mpg123_new(nullptr, &error); - if (!mpg123handle){ - ALOGE("Basic setup goes wrong: %s", mpg123_plain_strerror(error)); - goto ExitThread; - } - - if (mpg123_open(mpg123handle,_fileFullPath.c_str()) != MPG123_OK || - mpg123_getformat(mpg123handle, &rate, &_channels, &_mp3Encoding) != MPG123_OK) { - ALOGE("Trouble with mpg123: %s\n", mpg123_strerror(mpg123handle) ); - goto ExitThread; - } - - if (_mp3Encoding == MPG123_ENC_SIGNED_16){ - _bytesPerFrame = 2 * _channels; - } - else if (_mp3Encoding == MPG123_ENC_FLOAT_32){ - _bytesPerFrame = 4 * _channels; - } - else{ - log("Bad encoding: 0x%x!\n", _mp3Encoding); - goto ExitThread; - } - - _alBufferFormat = (_channels > 1) ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16; - _sampleRate = rate; - - /* Ensure that this output format will not change (it could, when we allow it). */ - mpg123_format_none(mpg123handle); - mpg123_format(mpg123handle, rate, _channels, _mp3Encoding); - /* Ensure that we can get accurate length by call mpg123_length */ - mpg123_scan(mpg123handle); - - auto framesLength = mpg123_length(mpg123handle); - totalFrames = framesLength; - _pcmDataSize = totalFrames * _bytesPerFrame; - _duration = 1.0f * totalFrames / _sampleRate; - } - break; - case FileFormat::UNKNOWN: - default: - break; - } - - if (_pcmDataSize <= PCMDATA_CACHEMAXSIZE) + AudioDecoder* decoder = AudioDecoderManager::createDecoder(_fileFullPath.c_str()); + do { - _pcmData = malloc(_pcmDataSize); - auto alError = alGetError(); - alGenBuffers(1, &_alBufferId); - alError = alGetError(); - if (alError != AL_NO_ERROR) { - log("%s: attaching audio to buffer fail: %x\n", __FUNCTION__, alError); - goto ExitThread; - } + if (decoder == nullptr || !decoder->open(_fileFullPath.c_str())) + break; - switch (_fileFormat) + const uint32_t originalTotalFrames = decoder->getTotalFrames(); + const uint32_t bytesPerFrame = decoder->getBytesPerFrame(); + const uint32_t sampleRate = decoder->getSampleRate(); + const uint32_t channelCount = decoder->getChannelCount(); + + uint32_t totalFrames = originalTotalFrames; + uint32_t dataSize = totalFrames * bytesPerFrame; + uint32_t remainingFrames = totalFrames; + uint32_t adjustFrames = 0; + + _format = channelCount > 1 ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16; + _sampleRate = (ALsizei)sampleRate; + _duration = 1.0f * totalFrames / sampleRate; + _totalFrames = totalFrames; + + if (dataSize <= PCMDATA_CACHEMAXSIZE) { - case FileFormat::OGG: + uint32_t framesRead = 0; + const uint32_t framesToReadOnce = std::min(totalFrames, static_cast(sampleRate * QUEUEBUFFER_TIME_STEP * QUEUEBUFFER_NUM)); + + std::vector adjustFrameBuf; + + if (decoder->seek(totalFrames)) { - int current_section; - unsigned int currPos = 0; - long readRet = 0; + char* tmpBuf = (char*)malloc(framesToReadOnce * bytesPerFrame); + adjustFrameBuf.reserve(framesToReadOnce * bytesPerFrame); + + // Adjust total frames by setting position to the end of frames and try to read more data. + // This is a workaround for https://github.com/cocos2d/cocos2d-x/issues/16938 do { - readRet = ov_read(vf,(char*)_pcmData + _bytesOfRead,4096,0,2,1,¤t_section); - if (readRet > 0){ - _bytesOfRead += readRet; + framesRead = decoder->read(framesToReadOnce, tmpBuf); + if (framesRead > 0) + { + adjustFrames += framesRead; + adjustFrameBuf.insert(adjustFrameBuf.end(), tmpBuf, tmpBuf + framesRead * bytesPerFrame); } - } while (_bytesOfRead < _pcmDataSize); - _alBufferReady = true; - _bytesOfRead = _pcmDataSize; - break; + } while (framesRead > 0); + + if (adjustFrames > 0) + { + ALOGV("Orignal total frames: %u, adjust frames: %u, current total frames: %u", totalFrames, adjustFrames, totalFrames + adjustFrames); + totalFrames += adjustFrames; + _totalFrames = remainingFrames = totalFrames; + } + + // Reset dataSize + dataSize = totalFrames * bytesPerFrame; + + free(tmpBuf); } - case FileFormat::MP3: + // Reset to frame 0 + BREAK_IF_ERR_LOG(!decoder->seek(0), "AudioDecoder::seek(0) failed!"); + + _pcmData = (char*)malloc(dataSize); + memset(_pcmData, 0x00, dataSize); + + if (adjustFrames > 0) { - size_t done = 0; - auto err = mpg123_read(mpg123handle,(unsigned char*)_pcmData, _pcmDataSize,&done); - if (err == MPG123_ERR){ - log("Trouble with mpg123: %s\n", mpg123_strerror(mpg123handle) ); - goto ExitThread; - } - if (err == MPG123_DONE || err == MPG123_OK){ - _alBufferReady = true; - _pcmDataSize = done; - _bytesOfRead = done; - } + memcpy(_pcmData + (dataSize - adjustFrameBuf.size()), adjustFrameBuf.data(), adjustFrameBuf.size()); } - break; - case FileFormat::UNKNOWN: - default: - break; + + alGenBuffers(1, &_alBufferId); + auto alError = alGetError(); + if (alError != AL_NO_ERROR) { + ALOGE("%s: attaching audio to buffer fail: %x", __FUNCTION__, alError); + break; + } + + if (*_isDestroyed) + break; + + framesRead = decoder->readFixedFrames(std::min(framesToReadOnce, remainingFrames), _pcmData + _framesRead * bytesPerFrame); + _framesRead += framesRead; + remainingFrames -= framesRead; + + if (*_isDestroyed) + break; + + uint32_t frames = 0; + while (!*_isDestroyed && _framesRead < originalTotalFrames) + { + frames = std::min(framesToReadOnce, remainingFrames); + if (_framesRead + frames > originalTotalFrames) + { + frames = originalTotalFrames - _framesRead; + } + framesRead = decoder->read(frames, _pcmData + _framesRead * bytesPerFrame); + if (framesRead == 0) + break; + _framesRead += framesRead; + remainingFrames -= framesRead; + } + + if (*_isDestroyed) + break; + + if (_framesRead < originalTotalFrames) + { + memset(_pcmData + _framesRead * bytesPerFrame, 0x00, (totalFrames - _framesRead) * bytesPerFrame); + } + ALOGV("pcm buffer was loaded successfully, total frames: %u, total read frames: %u, adjust frames: %u, remainingFrames: %u", totalFrames, _framesRead, adjustFrames, remainingFrames); + + _framesRead += adjustFrames; + + alBufferData(_alBufferId, _format, _pcmData, (ALsizei)dataSize, (ALsizei)sampleRate); + + _state = State::READY; } - alBufferData(_alBufferId,_alBufferFormat,_pcmData,_pcmDataSize,_sampleRate); - } - else{ - _queBufferFrames = _sampleRate * QUEUEBUFFER_TIME_STEP; - _queBufferBytes = _queBufferFrames * _bytesPerFrame; + else + { + _queBufferFrames = sampleRate * QUEUEBUFFER_TIME_STEP; + BREAK_IF_ERR_LOG(_queBufferFrames == 0, "_queBufferFrames == 0"); - for (int index = 0; index < QUEUEBUFFER_NUM; ++index) { - _queBuffers[index] = (char*)malloc(_queBufferBytes); + const uint32_t queBufferBytes = _queBufferFrames * bytesPerFrame; - switch (_fileFormat){ - case FileFormat::MP3: - { - size_t done = 0; - mpg123_read(mpg123handle,(unsigned char*)_queBuffers[index], _queBufferBytes,&done); - _queBufferSize[index] = done; - _bytesOfRead += done; - } - break; - case FileFormat::OGG: - { - int current_section; - auto readRet = ov_read(vf,_queBuffers[index],_queBufferBytes,0,2,1,¤t_section); - _queBufferSize[index] = readRet; - } - break; + for (int index = 0; index < QUEUEBUFFER_NUM; ++index) + { + _queBuffers[index] = (char*)malloc(queBufferBytes); + _queBufferSize[index] = queBufferBytes; + + decoder->readFixedFrames(_queBufferFrames, _queBuffers[index]); } + + _state = State::READY; + } + + } while (false); + + if (decoder != nullptr) + { + decoder->close(); + } + + AudioDecoderManager::destroyDecoder(decoder); + + if (_state != State::READY) + { + _state = State::FAILED; + if (_alBufferId != INVALID_AL_BUFFER_ID && alIsBuffer(_alBufferId)) + { + ALOGV("readDataTask failed, delete buffer: %u", _alBufferId); + alDeleteBuffers(1, &_alBufferId); + _alBufferId = INVALID_AL_BUFFER_ID; } } -ExitThread: - switch (_fileFormat) - { - case FileFormat::OGG: - ov_clear(vf); - delete vf; - break; - case FileFormat::MP3: - mpg123_close(mpg123handle); - mpg123_delete(mpg123handle); - break; - case FileFormat::UNKNOWN: - default: - break; - } - - _readDataTaskMutex.unlock(); - if (_queBufferFrames > 0) - { - _alBufferReady = true; - } - else - { - _loadFail = true; - } - - invokingLoadCallbacks(); + //FIXME: Why to invoke play callback first? Should it be after 'load' callback? invokingPlayCallbacks(); -} + invokingLoadCallbacks(); -void AudioCache::invokingPlayCallbacks() -{ - _callbackMutex.lock(); - auto count = _callbacks.size(); - for (size_t index = 0; index < count; ++index) { - _callbacks[index](); - } - _callbacks.clear(); - _callbackMutex.unlock(); + _isLoadingFinished = true; + _readDataTaskMutex.unlock(); + ALOGVV("readDataTask end, cache id=%u", selfId); } void AudioCache::addPlayCallback(const std::function& callback) { - _callbackMutex.lock(); - if (_alBufferReady) { - callback(); - } else { - _callbacks.push_back(callback); + std::lock_guard lk(_playCallbackMutex); + switch (_state) + { + case State::INITIAL: + case State::LOADING: + _playCallbacks.push_back(callback); + break; + + case State::READY: + // If state is failure, we still need to invoke the callback + // since the callback will set the 'AudioPlayer::_removeByAudioEngine' flag to true. + case State::FAILED: + callback(); + break; + + default: + ALOGE("Invalid state: %d", _state); + break; } - _callbackMutex.unlock(); } -void AudioCache::invokingLoadCallbacks() +void AudioCache::invokingPlayCallbacks() { - auto scheduler = Director::getInstance()->getScheduler(); - scheduler->performFunctionInCocosThread([&](){ - auto count = _loadCallbacks.size(); - for (size_t index = 0; index < count; ++index) { - _loadCallbacks[index](_alBufferReady); - } - _loadCallbacks.clear(); - }); + std::lock_guard lk(_playCallbackMutex); + + for (auto&& cb : _playCallbacks) + { + cb(); + } + + _playCallbacks.clear(); } void AudioCache::addLoadCallback(const std::function& callback) { - if (_alBufferReady) { - callback(true); - } - else if (_loadFail){ - callback(false); - } - else { - _loadCallbacks.push_back(callback); + switch (_state) + { + case State::INITIAL: + case State::LOADING: + _loadCallbacks.push_back(callback); + break; + + case State::READY: + callback(true); + break; + case State::FAILED: + callback(false); + break; + + default: + ALOGE("Invalid state: %d", _state); + break; } } +void AudioCache::invokingLoadCallbacks() +{ + if (*_isDestroyed) + { + ALOGV("AudioCache (%p) was destroyed, don't invoke preload callback ...", this); + return; + } + + auto isDestroyed = _isDestroyed; + auto scheduler = Director::getInstance()->getScheduler(); + scheduler->performFunctionInCocosThread([&, isDestroyed](){ + if (*isDestroyed) + { + ALOGV("invokingLoadCallbacks perform in cocos thread, AudioCache (%p) was destroyed!", this); + return; + } + + for (auto&& cb : _loadCallbacks) + { + cb(_state == State::READY); + } + + _loadCallbacks.clear(); + }); +} + #endif diff --git a/native/cocos/audio/win32/AudioCache.h b/native/cocos/audio/win32/AudioCache.h index 4f8cbf41b4..35ba1647e0 100644 --- a/native/cocos/audio/win32/AudioCache.h +++ b/native/cocos/audio/win32/AudioCache.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2014 Chukong Technologies Inc. + Copyright (c) 2014-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -21,57 +21,24 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ + +#pragma once + #include "platform/CCPlatformConfig.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 -#ifndef __AUDIO_CACHE_H_ -#define __AUDIO_CACHE_H_ - #include #include #include +#include #ifdef OPENAL_PLAIN_INCLUDES #include #else -#include +#include #endif #include "platform/CCPlatformMacros.h" - -#define QUEUEBUFFER_NUM 5 -#define QUEUEBUFFER_TIME_STEP 0.1f - -// log, CCLOG aren't threadsafe, since we uses sub threads for parsing pcm data, threadsafe log output -// is needed. Define the following macros (ALOGV, ALOGD, ALOGI, ALOGW, ALOGE) for threadsafe log output. - -//FIXME:Move the definition of the following macros to a separated file. - -void audioLog(const char * format, ...); - -#define QUOTEME_(x) #x -#define QUOTEME(x) QUOTEME_(x) - -#if defined(COCOS2D_DEBUG) && COCOS2D_DEBUG > 0 -#define ALOGV(fmt, ...) audioLog("V/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__) -#else -#define ALOGV(fmt, ...) do {} while(false) -#endif -#define ALOGD(fmt, ...) audioLog("D/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__) -#define ALOGI(fmt, ...) audioLog("I/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__) -#define ALOGW(fmt, ...) audioLog("W/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__) -#define ALOGE(fmt, ...) audioLog("E/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__) - -#if defined(COCOS2D_DEBUG) && COCOS2D_DEBUG > 0 -#define CHECK_AL_ERROR_DEBUG() \ -do { \ - GLenum __error = alGetError(); \ - if (__error) { \ - ALOGE("OpenAL error 0x%04X in %s %s %d\n", __error, __FILE__, __FUNCTION__, __LINE__); \ - } \ -} while (false) -#else -#define CHECK_AL_ERROR_DEBUG() -#endif +#include "audio/apple/AudioMacros.h" NS_CC_BEGIN namespace experimental{ @@ -79,17 +46,19 @@ namespace experimental{ class AudioEngineImpl; class AudioPlayer; -class CC_DLL AudioCache{ +class CC_DLL AudioCache +{ public: - enum class FileFormat + + enum class State { - UNKNOWN, - OGG, - MP3 + INITIAL, + LOADING, + READY, + FAILED }; AudioCache(); - AudioCache(const AudioCache&); ~AudioCache(); void addPlayCallback(const std::function& callback); @@ -97,53 +66,54 @@ public: void addLoadCallback(const std::function& callback); protected: - void readDataTask(); + void setSkipReadDataTask(bool isSkip) { _isSkipReadDataTask = isSkip; }; + void readDataTask(unsigned int selfId); + void invokingPlayCallbacks(); + void invokingLoadCallbacks(); - std::string _fileFullPath; - FileFormat _fileFormat; //pcm data related stuff - size_t _pcmDataSize; - ALenum _alBufferFormat; - - int _channels; - ALuint _sampleRate; - size_t _bytesPerFrame; + ALenum _format; + ALsizei _sampleRate; float _duration; + uint32_t _totalFrames; + uint32_t _framesRead; /*Cache related stuff; * Cache pcm data when sizeInBytes less than PCMDATA_CACHEMAXSIZE */ ALuint _alBufferId; - void* _pcmData; - size_t _bytesOfRead; + char* _pcmData; /*Queue buffer related stuff * Streaming in OpenAL when sizeInBytes greater then PCMDATA_CACHEMAXSIZE */ char* _queBuffers[QUEUEBUFFER_NUM]; ALsizei _queBufferSize[QUEUEBUFFER_NUM]; - int _queBufferFrames; - int _queBufferBytes; + uint32_t _queBufferFrames; - bool _alBufferReady; - bool _loadFail; - std::mutex _callbackMutex; - std::vector< std::function > _callbacks; + std::mutex _playCallbackMutex; + std::vector< std::function > _playCallbacks; + + // loadCallbacks doesn't need mutex since it's invoked only in Cocos thread. std::vector< std::function > _loadCallbacks; std::mutex _readDataTaskMutex; - int _mp3Encoding; + State _state; + + std::shared_ptr _isDestroyed; + std::string _fileFullPath; + unsigned int _id; + bool _isLoadingFinished; + bool _isSkipReadDataTask; friend class AudioEngineImpl; friend class AudioPlayer; -} ; +}; } NS_CC_END -#endif // __AUDIO_CACHE_H_ #endif - diff --git a/native/cocos/audio/win32/AudioDecoder.cpp b/native/cocos/audio/win32/AudioDecoder.cpp new file mode 100644 index 0000000000..7dae9530f9 --- /dev/null +++ b/native/cocos/audio/win32/AudioDecoder.cpp @@ -0,0 +1,91 @@ +/**************************************************************************** + Copyright (c) 2016-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. + ****************************************************************************/ + +#include "audio/win32/AudioDecoder.h" +#include "audio/win32/AudioMacros.h" +#include "platform/CCFileUtils.h" + +#define LOG_TAG "AudioDecoder" + +namespace cocos2d { namespace experimental { + +AudioDecoder::AudioDecoder() + : _isOpened(false) + , _totalFrames(0) + , _bytesPerFrame(0) + , _sampleRate(0) + , _channelCount(0) + { + + } + + AudioDecoder::~AudioDecoder() + { + } + + + bool AudioDecoder::isOpened() const + { + return _isOpened; + } + + uint32_t AudioDecoder::readFixedFrames(uint32_t framesToRead, char* pcmBuf) + { + uint32_t framesRead = 0; + uint32_t framesReadOnce = 0; + do + { + framesReadOnce = read(framesToRead - framesRead, pcmBuf + framesRead * _bytesPerFrame); + framesRead += framesReadOnce; + } while (framesReadOnce != 0 && framesRead < framesToRead); + + if (framesRead < framesToRead) + { + memset(pcmBuf + framesRead * _bytesPerFrame, 0x00, (framesToRead - framesRead) * _bytesPerFrame); + } + + return framesRead; + } + + uint32_t AudioDecoder::getTotalFrames() const + { + return _totalFrames; + } + + uint32_t AudioDecoder::getBytesPerFrame() const + { + return _bytesPerFrame; + } + + uint32_t AudioDecoder::getSampleRate() const + { + return _sampleRate; + } + + uint32_t AudioDecoder::getChannelCount() const + { + return _channelCount; + } + +}} // namespace cocos2d { namespace experimental { diff --git a/native/cocos/audio/win32/AudioDecoder.h b/native/cocos/audio/win32/AudioDecoder.h new file mode 100644 index 0000000000..2d7b49eca6 --- /dev/null +++ b/native/cocos/audio/win32/AudioDecoder.h @@ -0,0 +1,119 @@ +/**************************************************************************** + Copyright (c) 2016-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. + ****************************************************************************/ + +#pragma once + +#include + +#include "vorbis/vorbisfile.h" + +namespace cocos2d { namespace experimental { + +/** + * @brief The class for decoding compressed audio file to PCM buffer. + */ +class AudioDecoder +{ +public: + static const uint32_t INVALID_FRAME_INDEX = UINT32_MAX; + + /** + * @brief Opens an audio file specified by a file path. + * @return true if succeed, otherwise false. + */ + virtual bool open(const char* path) = 0; + + /** + * @brief Checks whether decoder has opened file successfully. + * @return true if succeed, otherwise false. + */ + virtual bool isOpened() const; + + /** + * @brief Closes opened audio file. + * @note The method will also be automatically invoked in the destructor. + */ + virtual void close() = 0; + + /** + * @brief Reads audio frames of PCM format. + * @param framesToRead The number of frames excepted to be read. + * @param pcmBuf The buffer to hold the frames to be read, its size should be >= |framesToRead| * _bytesPerFrame. + * @return The number of frames actually read, it's probably less than 'framesToRead'. Returns 0 means reach the end of file. + */ + virtual uint32_t read(uint32_t framesToRead, char* pcmBuf) = 0; + + /** + * @brief Reads fixed audio frames of PCM format. + * @param framesToRead The number of frames excepted to be read. + * @param pcmBuf The buffer to hold the frames to be read, its size should be >= |framesToRead| * _bytesPerFrame. + * @return The number of frames actually read, it's probably less than |framesToRead|. Returns 0 means reach the end of file. + * @note The different between |read| and |readFixedFrames| is |readFixedFrames| will do multiple reading operations if |framesToRead| frames + * isn't filled entirely, while |read| just does reading operation once whatever |framesToRead| is or isn't filled entirely. + * If current position reaches the end of frames, the return value may smaller than |framesToRead| and the remaining + * buffer in |pcmBuf| will be set with silence data (0x00). + */ + virtual uint32_t readFixedFrames(uint32_t framesToRead, char* pcmBuf); + + /** + * @brief Sets frame offest to be read. + * @param frameOffset The frame offest to be set. + * @return true if succeed, otherwise false + */ + virtual bool seek(uint32_t frameOffset) = 0; + + /** + * @brief Tells the current frame offset. + * @return The current frame offset. + */ + virtual uint32_t tell() const = 0; + + /** Gets total frames of current audio.*/ + virtual uint32_t getTotalFrames() const; + + /** Gets bytes per frame of current audio.*/ + virtual uint32_t getBytesPerFrame() const; + + /** Gets sample rate of current audio.*/ + virtual uint32_t getSampleRate() const; + + /** Gets the channel count of current audio. + * @note Currently we only support 1 or 2 channels. + */ + virtual uint32_t getChannelCount() const; + +protected: + AudioDecoder(); + virtual ~AudioDecoder(); + + bool _isOpened; + uint32_t _totalFrames; + uint32_t _bytesPerFrame; + uint32_t _sampleRate; + uint32_t _channelCount; + + friend class AudioDecoderManager; +}; + +}} // namespace cocos2d { namespace experimental { diff --git a/native/cocos/audio/win32/AudioDecoderManager.cpp b/native/cocos/audio/win32/AudioDecoderManager.cpp new file mode 100644 index 0000000000..57c405f251 --- /dev/null +++ b/native/cocos/audio/win32/AudioDecoderManager.cpp @@ -0,0 +1,70 @@ +/**************************************************************************** +Copyright (c) 2016-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 "AudioDecoderManager" + +#include "audio/win32/AudioDecoderManager.h" +#include "audio/win32/AudioDecoderOgg.h" +#include "audio/win32/AudioDecoderMp3.h" +#include "audio/win32/AudioMacros.h" +#include "platform/CCFileUtils.h" +#include "base/CCConsole.h" +#include "mpg123.h" + +namespace cocos2d { namespace experimental { + +static bool __mp3Inited = false; + +bool AudioDecoderManager::init() +{ + return true; +} + +void AudioDecoderManager::destroy() +{ + AudioDecoderMp3::destroy(); +} + +AudioDecoder* AudioDecoderManager::createDecoder(const char* path) +{ + std::string suffix = FileUtils::getInstance()->getFileExtension(path); + if (suffix == ".ogg") + { + return new (std::nothrow) AudioDecoderOgg(); + } + else if (suffix == ".mp3") + { + return new (std::nothrow) AudioDecoderMp3(); + } + + return nullptr; +} + +void AudioDecoderManager::destroyDecoder(AudioDecoder* decoder) +{ + delete decoder; +} + +}} // namespace cocos2d { namespace experimental { + diff --git a/native/cocos/audio/win32/AudioDecoderManager.h b/native/cocos/audio/win32/AudioDecoderManager.h new file mode 100644 index 0000000000..adfb998059 --- /dev/null +++ b/native/cocos/audio/win32/AudioDecoderManager.h @@ -0,0 +1,41 @@ +/**************************************************************************** +Copyright (c) 2016-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. +****************************************************************************/ + +#pragma once + +namespace cocos2d { namespace experimental { + +class AudioDecoder; + +class AudioDecoderManager +{ +public: + static bool init(); + static void destroy(); + static AudioDecoder* createDecoder(const char* path); + static void destroyDecoder(AudioDecoder* decoder); +}; + +}} // namespace cocos2d { namespace experimental { + diff --git a/native/cocos/audio/win32/AudioDecoderMp3.cpp b/native/cocos/audio/win32/AudioDecoderMp3.cpp new file mode 100644 index 0000000000..8dc6268300 --- /dev/null +++ b/native/cocos/audio/win32/AudioDecoderMp3.cpp @@ -0,0 +1,183 @@ +/**************************************************************************** + Copyright (c) 2016-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. + ****************************************************************************/ + +#include "audio/win32/AudioDecoderMp3.h" +#include "audio/win32/AudioMacros.h" +#include "platform/CCFileUtils.h" + +#include "base/CCConsole.h" +#include "mpg123.h" + +#define LOG_TAG "AudioDecoderMp3" + +namespace cocos2d { namespace experimental { + + static bool __mp3Inited = false; + + bool AudioDecoderMp3::lazyInit() + { + bool ret = true; + if (!__mp3Inited) + { + int error = mpg123_init(); + if (error == MPG123_OK) + { + __mp3Inited = true; + } + else + { + ALOGE("Basic setup goes wrong: %s", mpg123_plain_strerror(error)); + ret = false; + } + } + return ret; + } + + void AudioDecoderMp3::destroy() + { + if (__mp3Inited) + { + mpg123_exit(); + __mp3Inited = false; + } + } + + AudioDecoderMp3::AudioDecoderMp3() + : _mpg123handle(nullptr) + { + lazyInit(); + } + + AudioDecoderMp3::~AudioDecoderMp3() + { + close(); + } + + bool AudioDecoderMp3::open(const char* path) + { + std::string fullPath = FileUtils::getInstance()->fullPathForFilename(path); + + long rate = 0; + int error = MPG123_OK; + int mp3Encoding = 0; + int channel = 0; + do + { + _mpg123handle = mpg123_new(nullptr, &error); + if (nullptr == _mpg123handle) + { + ALOGE("Basic setup goes wrong: %s", mpg123_plain_strerror(error)); + break; + } + + if (mpg123_open(_mpg123handle, fullPath.c_str()) != MPG123_OK + || mpg123_getformat(_mpg123handle, &rate, &channel, &mp3Encoding) != MPG123_OK) + { + ALOGE("Trouble with mpg123: %s\n", mpg123_strerror(_mpg123handle) ); + break; + } + + _channelCount = channel; + _sampleRate = rate; + + if (mp3Encoding == MPG123_ENC_SIGNED_16) + { + _bytesPerFrame = 2 * _channelCount; + } + else if (mp3Encoding == MPG123_ENC_FLOAT_32) + { + _bytesPerFrame = 4 * _channelCount; + } + else + { + ALOGE("Bad encoding: 0x%x!\n", mp3Encoding); + break; + } + + /* Ensure that this output format will not change (it could, when we allow it). */ + mpg123_format_none(_mpg123handle); + mpg123_format(_mpg123handle, rate, channel, mp3Encoding); + /* Ensure that we can get accurate length by call mpg123_length */ + mpg123_scan(_mpg123handle); + + _totalFrames = mpg123_length(_mpg123handle); + + _isOpened = true; + return true; + } while (false); + + if (_mpg123handle != nullptr) + { + mpg123_close(_mpg123handle); + mpg123_delete(_mpg123handle); + _mpg123handle = nullptr; + } + return false; + } + + void AudioDecoderMp3::close() + { + if (isOpened()) + { + if (_mpg123handle != nullptr) + { + mpg123_close(_mpg123handle); + mpg123_delete(_mpg123handle); + _mpg123handle = nullptr; + } + _isOpened = false; + } + } + + uint32_t AudioDecoderMp3::read(uint32_t framesToRead, char* pcmBuf) + { + int bytesToRead = framesToRead * _bytesPerFrame; + size_t bytesRead = 0; + int err = mpg123_read(_mpg123handle, (unsigned char*)pcmBuf, bytesToRead, &bytesRead); + if (err == MPG123_ERR) + { + ALOGE("Trouble with mpg123: %s\n", mpg123_strerror(_mpg123handle) ); + return 0; + } + + return static_cast(bytesRead / _bytesPerFrame); + } + + bool AudioDecoderMp3::seek(uint32_t frameOffset) + { + off_t offset = mpg123_seek(_mpg123handle, frameOffset, SEEK_SET); + //ALOGD("mpg123_seek return: %d", (int)offset); + if (offset >= 0 && offset == frameOffset) + { + return true; + } + return false; + } + + uint32_t AudioDecoderMp3::tell() const + { + return static_cast(mpg123_tell(_mpg123handle)); + } + +}} // namespace cocos2d { namespace experimental { diff --git a/native/cocos/audio/win32/AudioDecoderMp3.h b/native/cocos/audio/win32/AudioDecoderMp3.h new file mode 100644 index 0000000000..3c85c7ecd1 --- /dev/null +++ b/native/cocos/audio/win32/AudioDecoderMp3.h @@ -0,0 +1,85 @@ +/**************************************************************************** + Copyright (c) 2016-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. + ****************************************************************************/ + +#pragma once + +#include "audio/win32/AudioDecoder.h" + +struct mpg123_handle_struct; + +namespace cocos2d { namespace experimental { + +/** + * @brief The class for decoding compressed audio file to PCM buffer. + */ +class AudioDecoderMp3 : public AudioDecoder +{ +public: + /** + * @brief Opens an audio file specified by a file path. + * @return true if succeed, otherwise false. + */ + virtual bool open(const char* path) override; + + /** + * @brief Closes opened audio file. + * @note The method will also be automatically invoked in the destructor. + */ + virtual void close() override; + + /** + * @brief Reads audio frames of PCM format. + * @param framesToRead The number of frames excepted to be read. + * @param pcmBuf The buffer to hold the frames to be read, its size should be >= |framesToRead| * _bytesPerFrame. + * @return The number of frames actually read, it's probably less than 'framesToRead'. Returns 0 means reach the end of file. + */ + virtual uint32_t read(uint32_t framesToRead, char* pcmBuf) override; + + /** + * @brief Sets frame offest to be read. + * @param frameOffset The frame offest to be set. + * @return true if succeed, otherwise false + */ + virtual bool seek(uint32_t frameOffset) override; + + /** + * @brief Tells the current frame offset. + * @return The current frame offset. + */ + virtual uint32_t tell() const override; + +protected: + + AudioDecoderMp3(); + ~AudioDecoderMp3(); + + static bool lazyInit(); + static void destroy(); + + struct mpg123_handle_struct* _mpg123handle; + + friend class AudioDecoderManager; +}; + +}} // namespace cocos2d { namespace experimental { diff --git a/native/cocos/audio/win32/AudioDecoderOgg.cpp b/native/cocos/audio/win32/AudioDecoderOgg.cpp new file mode 100644 index 0000000000..edfa82b5f2 --- /dev/null +++ b/native/cocos/audio/win32/AudioDecoderOgg.cpp @@ -0,0 +1,86 @@ +/**************************************************************************** + Copyright (c) 2016-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. + ****************************************************************************/ + +#include "audio/win32/AudioDecoderOgg.h" +#include "audio/win32/AudioMacros.h" +#include "platform/CCFileUtils.h" + +#define LOG_TAG "AudioDecoderOgg" + +namespace cocos2d { namespace experimental { + + AudioDecoderOgg::AudioDecoderOgg() + { + } + + AudioDecoderOgg::~AudioDecoderOgg() + { + close(); + } + + bool AudioDecoderOgg::open(const char* path) + { + std::string fullPath = FileUtils::getInstance()->fullPathForFilename(path); + if (0 == ov_fopen(fullPath.c_str(), &_vf)) + { + // header + vorbis_info* vi = ov_info(&_vf, -1); + _sampleRate = static_cast(vi->rate); + _channelCount = vi->channels; + _bytesPerFrame = vi->channels * sizeof(short); + _totalFrames = static_cast(ov_pcm_total(&_vf, -1)); + _isOpened = true; + return true; + } + return false; + } + + void AudioDecoderOgg::close() + { + if (isOpened()) + { + ov_clear(&_vf); + _isOpened = false; + } + } + + uint32_t AudioDecoderOgg::read(uint32_t framesToRead, char* pcmBuf) + { + int currentSection = 0; + int bytesToRead = framesToRead * _bytesPerFrame; + long bytesRead = ov_read(&_vf, pcmBuf, bytesToRead, 0, 2, 1, ¤tSection); + return static_cast(bytesRead / _bytesPerFrame); + } + + bool AudioDecoderOgg::seek(uint32_t frameOffset) + { + return 0 == ov_pcm_seek(&_vf, frameOffset); + } + + uint32_t AudioDecoderOgg::tell() const + { + return static_cast(ov_pcm_tell(const_cast(&_vf))); + } + +}} // namespace cocos2d { namespace experimental { diff --git a/native/cocos/audio/win32/AudioDecoderOgg.h b/native/cocos/audio/win32/AudioDecoderOgg.h new file mode 100644 index 0000000000..be062eef8b --- /dev/null +++ b/native/cocos/audio/win32/AudioDecoderOgg.h @@ -0,0 +1,81 @@ +/**************************************************************************** + Copyright (c) 2016-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. + ****************************************************************************/ + +#pragma once + +#include "audio/win32/AudioDecoder.h" + +#include "vorbis/vorbisfile.h" + +namespace cocos2d { namespace experimental { + +/** + * @brief The class for decoding compressed audio file to PCM buffer. + */ +class AudioDecoderOgg : public AudioDecoder +{ +public: + /** + * @brief Opens an audio file specified by a file path. + * @return true if succeed, otherwise false. + */ + virtual bool open(const char* path) override; + + /** + * @brief Closes opened audio file. + * @note The method will also be automatically invoked in the destructor. + */ + virtual void close() override; + + /** + * @brief Reads audio frames of PCM format. + * @param framesToRead The number of frames excepted to be read. + * @param pcmBuf The buffer to hold the frames to be read, its size should be >= |framesToRead| * _bytesPerFrame. + * @return The number of frames actually read, it's probably less than 'framesToRead'. Returns 0 means reach the end of file. + */ + virtual uint32_t read(uint32_t framesToRead, char* pcmBuf) override; + + /** + * @brief Sets frame offest to be read. + * @param frameOffset The frame offest to be set. + * @return true if succeed, otherwise false + */ + virtual bool seek(uint32_t frameOffset) override; + + /** + * @brief Tells the current frame offset. + * @return The current frame offset. + */ + virtual uint32_t tell() const override; + +protected: + AudioDecoderOgg(); + ~AudioDecoderOgg(); + + OggVorbis_File _vf; + + friend class AudioDecoderManager; +}; + +}} // namespace cocos2d { namespace experimental { diff --git a/native/cocos/audio/win32/AudioEngine-win32.cpp b/native/cocos/audio/win32/AudioEngine-win32.cpp index bf06318cbd..c50f4fa3ae 100644 --- a/native/cocos/audio/win32/AudioEngine-win32.cpp +++ b/native/cocos/audio/win32/AudioEngine-win32.cpp @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2014 Chukong Technologies Inc. + Copyright (c) 2014-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -33,31 +33,97 @@ #include "alc.h" #include "alext.h" #else -#include "OpenalSoft/alc.h" -#include "OpenalSoft/alext.h" +#include "AL/alc.h" +#include "AL/alext.h" #endif #include "audio/include/AudioEngine.h" #include "base/CCDirector.h" #include "base/CCScheduler.h" #include "platform/CCFileUtils.h" -#include "mpg123/mpg123.h" +#include "audio/win32/AudioDecoderManager.h" + +#include + +// log, CCLOG aren't threadsafe, since we uses sub threads for parsing pcm data, threadsafe log output +// is needed. Define the following macros (ALOGV, ALOGD, ALOGI, ALOGW, ALOGE) for threadsafe log output. + +//FIXME: Move _winLog, winLog to a separated file +static void _winLog(const char *format, va_list args) +{ + static const int MAX_LOG_LENGTH = 16 * 1024; + int bufferSize = MAX_LOG_LENGTH; + char* buf = nullptr; + + do + { + buf = new (std::nothrow) char[bufferSize]; + if (buf == nullptr) + return; // not enough memory + + int ret = vsnprintf(buf, bufferSize - 3, format, args); + if (ret < 0) + { + bufferSize *= 2; + + delete[] buf; + } + else + break; + + } while (true); + + strcat(buf, "\n"); + + int pos = 0; + int len = strlen(buf); + char tempBuf[MAX_LOG_LENGTH + 1] = { 0 }; + WCHAR wszBuf[MAX_LOG_LENGTH + 1] = { 0 }; + + do + { + std::copy(buf + pos, buf + pos + MAX_LOG_LENGTH, tempBuf); + + tempBuf[MAX_LOG_LENGTH] = 0; + + MultiByteToWideChar(CP_UTF8, 0, tempBuf, -1, wszBuf, sizeof(wszBuf)); + OutputDebugStringW(wszBuf); + + pos += MAX_LOG_LENGTH; + + } while (pos < len); + + delete[] buf; +} + +void audioLog(const char * format, ...) +{ + va_list args; + va_start(args, format); + _winLog(format, args); + va_end(args); +} using namespace cocos2d; using namespace cocos2d::experimental; static ALCdevice *s_ALDevice = nullptr; static ALCcontext *s_ALContext = nullptr; -static bool MPG123_LAZYINIT = true; 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); @@ -67,30 +133,31 @@ AudioEngineImpl::~AudioEngineImpl() alcDestroyContext(s_ALContext); s_ALContext = nullptr; } + if (s_ALDevice) { alcCloseDevice(s_ALDevice); s_ALDevice = nullptr; } - mpg123_exit(); - MPG123_LAZYINIT = true; + AudioDecoderManager::destroy(); } bool AudioEngineImpl::init() { bool ret = false; do{ - s_ALDevice = alcOpenDevice(NULL); + s_ALDevice = alcOpenDevice(nullptr); if (s_ALDevice) { - auto alError = alGetError(); - s_ALContext = alcCreateContext(s_ALDevice, NULL); + alGetError(); + s_ALContext = alcCreateContext(s_ALDevice, nullptr); alcMakeContextCurrent(s_ALContext); alGenSources(MAX_AUDIOINSTANCES, _alSources); - alError = alGetError(); - if(alError != AL_NO_ERROR){ - ALOGE("%s:generating sources fail! error = %x\n", __FUNCTION__, alError); + auto alError = alGetError(); + if(alError != AL_NO_ERROR) + { + ALOGE("%s:generating sources failed! error = %x\n", __FUNCTION__, alError); break; } @@ -98,7 +165,9 @@ bool AudioEngineImpl::init() _alSourceUsed[_alSources[i]] = false; } - ret = true; + _scheduler = Director::getInstance()->getScheduler(); + ret = AudioDecoderManager::init(); + ALOGI("OpenAL was initialized successfully!"); } }while (false); @@ -109,106 +178,80 @@ AudioCache* AudioEngineImpl::preload(const std::string& filePath, std::function< { AudioCache* audioCache = nullptr; - do - { - auto it = _audioCaches.find(filePath); - if (it != _audioCaches.end()) - { - audioCache = &it->second; - if (callback && audioCache->_alBufferReady) - { - callback(true); - } - break; - } - - AudioCache::FileFormat fileFormat = AudioCache::FileFormat::UNKNOWN; - - std::string fileExtension = FileUtils::getInstance()->getFileExtension(filePath); - if (fileExtension == ".ogg") - { - fileFormat = AudioCache::FileFormat::OGG; - } - else if (fileExtension == ".mp3") - { - fileFormat = AudioCache::FileFormat::MP3; - - if (MPG123_LAZYINIT) - { - auto error = mpg123_init(); - if (error == MPG123_OK) - { - MPG123_LAZYINIT = false; - } - else - { - ALOGE("Basic setup goes wrong: %s", mpg123_plain_strerror(error)); - break; - } - } - } - else - { - ALOGE("Unsupported media type file: %s\n", filePath.c_str()); - break; - } - + auto it = _audioCaches.find(filePath); + if (it == _audioCaches.end()) { audioCache = &_audioCaches[filePath]; - audioCache->_fileFormat = fileFormat; - audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath); - AudioEngine::addTask(std::bind(&AudioCache::readDataTask, audioCache)); - } while (false); - - if (callback) - { - if (audioCache) - { - audioCache->addLoadCallback(callback); - } - else - { - callback(false); - } + 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) { - bool availableSourceExist = false; - ALuint alSource; + 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]) { - availableSourceExist = true; + sourceFlag = true; break; } } - if(!availableSourceExist){ + if(!sourceFlag){ return AudioEngine::INVALID_AUDIO_ID; } - AudioCache* audioCache = preload(filePath, nullptr); - if (audioCache == nullptr) - { + auto player = new (std::nothrow) AudioPlayer; + if (player == nullptr) { return AudioEngine::INVALID_AUDIO_ID; } - auto player = &_audioPlayers[_currentAudioID]; player->_alSource = alSource; player->_loop = loop; player->_volume = volume; - audioCache->addPlayCallback(std::bind(&AudioEngineImpl::_play2d, this, audioCache, _currentAudioID)); + + 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; - - auto scheduler = cocos2d::Director::getInstance()->getScheduler(); - scheduler->schedule(schedule_selector(AudioEngineImpl::update), this, 0.05f, false); + _scheduler->schedule(CC_SCHEDULE_SELECTOR(AudioEngineImpl::update), this, 0.05f, false); } return _currentAudioID++; @@ -216,71 +259,76 @@ int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume void AudioEngineImpl::_play2d(AudioCache *cache, int audioID) { - if(cache->_alBufferReady){ - auto playerIt = _audioPlayers.find(audioID); - if (playerIt != _audioPlayers.end()) { - if (playerIt->second.play2d(cache)) { - AudioEngine::_audioIDInfoMap[audioID].state = AudioEngine::AudioState::PLAYING; - } - else{ - _threadMutex.lock(); - _toRemoveAudioIDs.push_back(audioID); - _threadMutex.unlock(); - } - } - } - else { + //Note: It may bn in sub thread or main thread :( + if (!*cache->_isDestroyed && cache->_state == AudioCache::State::READY) + { _threadMutex.lock(); - _toRemoveCaches.push_back(cache); - _toRemoveAudioIDs.push_back(audioID); + 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; + auto player = _audioPlayers[audioID]; + player->_volume = volume; - if (player._ready) { - alSourcef(_audioPlayers[audioID]._alSource, AL_GAIN, 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\n", __FUNCTION__,audioID,error); + ALOGE("%s: audio id = %d, error = %x", __FUNCTION__,audioID,error); } } } void AudioEngineImpl::setLoop(int audioID, bool loop) { - auto& player = _audioPlayers[audioID]; + auto player = _audioPlayers[audioID]; - if (player._ready) { - if (player._streamingSource) { - player.setLoop(loop); + if (player->_ready) { + if (player->_streamingSource) { + player->setLoop(loop); } else { if (loop) { - alSourcei(player._alSource, AL_LOOPING, AL_TRUE); + alSourcei(player->_alSource, AL_LOOPING, AL_TRUE); } else { - alSourcei(player._alSource, AL_LOOPING, AL_FALSE); + alSourcei(player->_alSource, AL_LOOPING, AL_FALSE); } auto error = alGetError(); if (error != AL_NO_ERROR) { - ALOGE("%s: audio id = %d, error = %x\n", __FUNCTION__,audioID,error); + ALOGE("%s: audio id = %d, error = %x", __FUNCTION__,audioID,error); } } } else { - player._loop = loop; + player->_loop = loop; } } bool AudioEngineImpl::pause(int audioID) { bool ret = true; - alSourcePause(_audioPlayers[audioID]._alSource); + alSourcePause(_audioPlayers[audioID]->_alSource); auto error = alGetError(); if (error != AL_NO_ERROR) { @@ -294,7 +342,7 @@ bool AudioEngineImpl::pause(int audioID) bool AudioEngineImpl::resume(int audioID) { bool ret = true; - alSourcePlay(_audioPlayers[audioID]._alSource); + alSourcePlay(_audioPlayers[audioID]->_alSource); auto error = alGetError(); if (error != AL_NO_ERROR) { @@ -305,66 +353,34 @@ bool AudioEngineImpl::resume(int audioID) return ret; } -bool AudioEngineImpl::stop(int audioID) +void AudioEngineImpl::stop(int audioID) { - bool ret = true; - auto& player = _audioPlayers[audioID]; - if (player._ready) { - alSourceStop(player._alSource); - - auto error = alGetError(); - if (error != AL_NO_ERROR) { - ret = false; - ALOGE("%s: audio id = %d, error = %x\n", __FUNCTION__,audioID,error); - } - } - - alSourcei(player._alSource, AL_BUFFER, NULL); - - _alSourceUsed[player._alSource] = false; - if (player._streamingSource) - { - player._ready = false; - player.notifyExitThread(); - } - else - { - _audioPlayers.erase(audioID); - } - - return ret; + 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(int index = 0; index < MAX_AUDIOINSTANCES; ++index) + for(auto&& player : _audioPlayers) { - alSourceStop(_alSources[index]); - alSourcei(_alSources[index], AL_BUFFER, NULL); - _alSourceUsed[_alSources[index]] = false; - } - - for (auto it = _audioPlayers.begin(); it != _audioPlayers.end();) - { - auto& player = it->second; - if (player._streamingSource) - { - player._ready = false; - player.notifyExitThread(); - ++it; - } - else - { - it = _audioPlayers.erase(it); - } + 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; + auto player = _audioPlayers[audioID]; + if(player->_ready){ + return player->_audioCache->_duration; } else { return AudioEngine::TIME_UNKNOWN; } @@ -373,12 +389,12 @@ float AudioEngineImpl::getDuration(int audioID) float AudioEngineImpl::getCurrentTime(int audioID) { float ret = 0.0f; - auto& player = _audioPlayers[audioID]; - if(player._ready){ - if (player._streamingSource) { - ret = player.getTime(); + auto player = _audioPlayers[audioID]; + if(player->_ready){ + if (player->_streamingSource) { + ret = player->getTime(); } else { - alGetSourcef(player._alSource, AL_SEC_OFFSET, &ret); + alGetSourcef(player->_alSource, AL_SEC_OFFSET, &ret); auto error = alGetError(); if (error != AL_NO_ERROR) { @@ -393,23 +409,29 @@ float AudioEngineImpl::getCurrentTime(int audioID) bool AudioEngineImpl::setCurrentTime(int audioID, float time) { bool ret = false; - auto& player = _audioPlayers[audioID]; + auto player = _audioPlayers[audioID]; do { - if (!player._ready) { + if (!player->_ready) { break; } - if (player._streamingSource) { - ret = player.setTime(time); + if (player->_streamingSource) { + ret = player->setTime(time); break; } else { - alSourcef(player._alSource, AL_SEC_OFFSET, time); + if (player->_audioCache->_framesRead != player->_audioCache->_totalFrames && + (time * player->_audioCache->_sampleRate) > player->_audioCache->_framesRead) { + ALOGE("%s: audio id = %d", __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\n", __FUNCTION__,audioID,error); + ALOGE("%s: audio id = %d, error = %x", __FUNCTION__,audioID,error); } ret = true; } @@ -420,70 +442,52 @@ bool AudioEngineImpl::setCurrentTime(int audioID, float time) void AudioEngineImpl::setFinishCallback(int audioID, const std::function &callback) { - _audioPlayers[audioID]._finishCallbak = callback; + _audioPlayers[audioID]->_finishCallbak = callback; } void AudioEngineImpl::update(float dt) { ALint sourceState; int audioID; + AudioPlayer* player; + ALuint alSource; - if (_threadMutex.try_lock()) { - size_t removeAudioCount = _toRemoveAudioIDs.size(); - for (size_t index = 0; index < removeAudioCount; ++index) { - audioID = _toRemoveAudioIDs[index]; - auto playerIt = _audioPlayers.find(audioID); - if (playerIt != _audioPlayers.end()) { - _alSourceUsed[playerIt->second._alSource] = false; - if(playerIt->second._finishCallbak) { - auto& audioInfo = AudioEngine::_audioIDInfoMap[audioID]; - playerIt->second._finishCallbak(audioID, *audioInfo.filePath); - } - _audioPlayers.erase(audioID); - AudioEngine::remove(audioID); - } - } - size_t removeCacheCount = _toRemoveCaches.size(); - for (size_t index = 0; index < removeCacheCount; ++index) { - auto itEnd = _audioCaches.end(); - for (auto it = _audioCaches.begin(); it != itEnd; ++it) { - if (&it->second == _toRemoveCaches[index]) { - _audioCaches.erase(it); - break; - } - } - } - _threadMutex.unlock(); - } +// ALOGV("AudioPlayer count: %d", (int)_audioPlayers.size()); for (auto it = _audioPlayers.begin(); it != _audioPlayers.end(); ) { audioID = it->first; - auto& player = it->second; - alGetSourcei(player._alSource, AL_SOURCE_STATE, &sourceState); - - if (player._readForRemove && !player._ready) + 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) { - _alSourceUsed[player._alSource] = false; - if (player._finishCallbak) { + else if (player->_ready && sourceState == AL_STOPPED) { + + std::string filePath; + if (player->_finishCallbak) { auto& audioInfo = AudioEngine::_audioIDInfoMap[audioID]; - player._finishCallbak(audioID, *audioInfo.filePath); + filePath = *audioInfo.filePath; } AudioEngine::remove(audioID); + + _threadMutex.lock(); + it = _audioPlayers.erase(it); + _threadMutex.unlock(); - if (player._streamingSource) - { - player._ready = false; - player.notifyExitThread(); - ++it; - } - else - { - it = _audioPlayers.erase(it); + if (player->_finishCallbak) { + player->_finishCallbak(audioID, filePath); //FIXME: callback will delay 50ms } + delete player; + _alSourceUsed[alSource] = false; } else{ ++it; @@ -492,9 +496,7 @@ void AudioEngineImpl::update(float dt) if(_audioPlayers.empty()){ _lazyInitLoop = true; - - auto scheduler = cocos2d::Director::getInstance()->getScheduler(); - scheduler->unschedule(schedule_selector(AudioEngineImpl::update), this); + _scheduler->unschedule(CC_SCHEDULE_SELECTOR(AudioEngineImpl::update), this); } } diff --git a/native/cocos/audio/win32/AudioEngine-win32.h b/native/cocos/audio/win32/AudioEngine-win32.h index 343723f931..f2d0ac67d0 100644 --- a/native/cocos/audio/win32/AudioEngine-win32.h +++ b/native/cocos/audio/win32/AudioEngine-win32.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2014 Chukong Technologies Inc. + Copyright (c) 2014-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -35,7 +35,10 @@ #include "audio/win32/AudioPlayer.h" NS_CC_BEGIN - namespace experimental{ + +class Scheduler; + +namespace experimental { #define MAX_AUDIOINSTANCES 32 class CC_DLL AudioEngineImpl : public cocos2d::Ref @@ -50,7 +53,7 @@ public: void setLoop(int audioID, bool loop); bool pause(int audioID); bool resume(int audioID); - bool stop(int audioID); + void stop(int audioID); void stopAll(); float getDuration(int audioID); float getCurrentTime(int audioID); @@ -60,7 +63,6 @@ public: void uncache(const std::string& filePath); void uncacheAll(); AudioCache* preload(const std::string& filePath, std::function callback); - void update(float dt); private: @@ -75,17 +77,13 @@ private: std::unordered_map _audioCaches; //audioID,AudioInfo - std::unordered_map _audioPlayers; - + std::unordered_map _audioPlayers; std::mutex _threadMutex; - std::vector _toRemoveCaches; - std::vector _toRemoveAudioIDs; - bool _lazyInitLoop; int _currentAudioID; - + Scheduler* _scheduler; }; } NS_CC_END diff --git a/native/cocos/audio/win32/AudioMacros.h b/native/cocos/audio/win32/AudioMacros.h new file mode 100644 index 0000000000..8db9565eae --- /dev/null +++ b/native/cocos/audio/win32/AudioMacros.h @@ -0,0 +1,71 @@ +/**************************************************************************** + Copyright (c) 2016-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. + ****************************************************************************/ + +#pragma once + +#define QUEUEBUFFER_NUM (3) +#define QUEUEBUFFER_TIME_STEP (0.1f) + +// log, CCLOG aren't threadsafe, since we uses sub threads for parsing pcm data, threadsafe log output +// is needed. Define the following macros (ALOGV, ALOGD, ALOGI, ALOGW, ALOGE) for threadsafe log output. + +//FIXME:Move the definition of the following macros to a separated file. + +void audioLog(const char * format, ...); + +#define QUOTEME_(x) #x +#define QUOTEME(x) QUOTEME_(x) + +#if defined(COCOS2D_DEBUG) && COCOS2D_DEBUG > 0 +#define ALOGV(fmt, ...) audioLog("V/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__) +#else +#define ALOGV(fmt, ...) do {} while(false) +#endif +#define ALOGD(fmt, ...) audioLog("D/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__) +#define ALOGI(fmt, ...) audioLog("I/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__) +#define ALOGW(fmt, ...) audioLog("W/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__) +#define ALOGE(fmt, ...) audioLog("E/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__) + +#if defined(COCOS2D_DEBUG) && COCOS2D_DEBUG > 0 +#define CHECK_AL_ERROR_DEBUG() \ +do { \ + GLenum __error = alGetError(); \ + if (__error) { \ + ALOGE("OpenAL error 0x%04X in %s %s %d\n", __error, __FILE__, __FUNCTION__, __LINE__); \ + } \ +} while (false) +#else +#define CHECK_AL_ERROR_DEBUG() +#endif + +#define BREAK_IF(condition) \ + if (!!(condition)) { \ + break; \ + } + +#define BREAK_IF_ERR_LOG(condition, fmt, ...) \ + if (!!(condition)) { \ + ALOGE("(" QUOTEME(condition) ") failed, message: " fmt, ##__VA_ARGS__); \ + break; \ + } diff --git a/native/cocos/audio/win32/AudioPlayer.cpp b/native/cocos/audio/win32/AudioPlayer.cpp index 5de0b0db98..f534c4cc30 100644 --- a/native/cocos/audio/win32/AudioPlayer.cpp +++ b/native/cocos/audio/win32/AudioPlayer.cpp @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2014 Chukong Technologies Inc. + Copyright (c) 2014-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -29,302 +29,301 @@ #if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 #include "audio/win32/AudioPlayer.h" #include "audio/win32/AudioCache.h" -#include "base/CCConsole.h" #include "platform/CCFileUtils.h" -#include "mpg123/mpg123.h" -#include "vorbis/codec.h" -#include "vorbis/vorbisfile.h" +#include "audio/win32/AudioDecoderManager.h" +#include "audio/win32/Audiodecoder.h" +#define VERY_VERY_VERBOSE_LOGGING +#ifdef VERY_VERY_VERBOSE_LOGGING +#define ALOGVV ALOGV +#else +#define ALOGVV(...) do{} while(false) +#endif + +using namespace cocos2d; using namespace cocos2d::experimental; -AudioPlayer::AudioPlayer() - : _exitThread(false) - , _timeDirty(false) - , _streamingSource(false) - , _currTime(0.0f) - , _finishCallbak(nullptr) - , _ready(false) - , _audioCache(nullptr) - , _readForRemove(false) -{ - +namespace { +unsigned int __idIndex = 0; } -AudioPlayer::AudioPlayer(const AudioPlayer& player) +AudioPlayer::AudioPlayer() +: _audioCache(nullptr) +, _finishCallbak(nullptr) +, _isDestroyed(false) +, _removeByAudioEngine(false) +, _ready(false) +, _currTime(0.0f) +, _streamingSource(false) +, _rotateBufferThread(nullptr) +, _timeDirty(false) +, _isRotateThreadExited(false) +, _id(++__idIndex) { - _exitThread = player._exitThread; - _timeDirty = player._timeDirty; - _streamingSource = player._streamingSource; - _currTime = player._currTime; - _finishCallbak = player._finishCallbak; - _ready = player._ready; - _audioCache = player._audioCache; - _readForRemove = player._readForRemove; + memset(_bufferIds, 0, sizeof(_bufferIds)); } AudioPlayer::~AudioPlayer() { - if (_audioCache && _audioCache->_queBufferFrames > 0) { - alDeleteBuffers(QUEUEBUFFER_NUM, _bufferIds); - } -} - -void AudioPlayer::notifyExitThread() -{ - if (_audioCache && _audioCache->_queBufferFrames > 0) { - std::unique_lock lk(_sleepMutex); - _exitThread = true; - _sleepCondition.notify_all(); - } -} - -bool AudioPlayer::play2d(AudioCache* cache) -{ - if (!cache->_alBufferReady) { - return false; - } - _audioCache = cache; - - alSourcei(_alSource, AL_BUFFER, NULL); - alSourcef(_alSource, AL_PITCH, 1.0f); - alSourcef(_alSource, AL_GAIN, _volume); - - if (_audioCache->_queBufferFrames == 0) { - if (_loop) { - alSourcei(_alSource, AL_LOOPING, AL_TRUE); - } - else { - alSourcei(_alSource, AL_LOOPING, AL_FALSE); - } - alSourcei(_alSource, AL_BUFFER, _audioCache->_alBufferId); - - } else { - _streamingSource = true; - alSourcei(_alSource, AL_LOOPING, AL_FALSE); - - auto alError = alGetError(); - alGenBuffers(QUEUEBUFFER_NUM, _bufferIds); - alError = alGetError(); - if (alError == AL_NO_ERROR) { - for (int index = 0; index < QUEUEBUFFER_NUM; ++index) { - alBufferData(_bufferIds[index], _audioCache->_alBufferFormat, _audioCache->_queBuffers[index], _audioCache->_queBufferSize[index], _audioCache->_sampleRate); - } - alSourceQueueBuffers(_alSource, QUEUEBUFFER_NUM, _bufferIds); - } - else { - ALOGE("%s:alGenBuffers error code:%x", __FUNCTION__,alError); - return false; - } - } + ALOGVV("~AudioPlayer() (%p), id=%u", this, _id); + destroy(); if (_streamingSource) { - _rotateBufferThread = std::thread(&AudioPlayer::rotateBufferThread, this, _audioCache->_queBufferFrames * QUEUEBUFFER_NUM + 1); - _rotateBufferThread.detach(); + alDeleteBuffers(3, _bufferIds); } - else - { - alSourcePlay(_alSource); - - auto alError = alGetError(); - if (alError != AL_NO_ERROR) { - ALOGE("%s:alSourcePlay error code:%x\n", __FUNCTION__, alError); - return false; - } - - _ready = true; - } - - return true; } -int AudioPlayer::readPcmData(char* buffer, int bufferSize, const std::function& fileReader) +void AudioPlayer::destroy() { - assert(buffer != nullptr && bufferSize > 0); + if (_isDestroyed) + return; + + ALOGVV("AudioPlayer::destroy begin, id=%u", _id); + + _isDestroyed = true; - int readBytes = 0; - int readBytesOnce = 0; - int remainBytes = bufferSize; do { - readBytesOnce = fileReader(buffer + readBytes, remainBytes); - if (readBytesOnce > 0) + if (_audioCache != nullptr) { - readBytes += readBytesOnce; - remainBytes -= readBytesOnce; - } - } while (readBytesOnce > 0 && readBytes < bufferSize); + if (_audioCache->_state == AudioCache::State::INITIAL) + { + ALOGV("AudioPlayer::destroy, id=%u, cache isn't ready!", _id); + break; + } - return readBytes; + while (!_audioCache->_isLoadingFinished) + { + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + } + + // Wait for play2d to be finished. + _play2dMutex.lock(); + _play2dMutex.unlock(); + + if (_streamingSource) + { + if (_rotateBufferThread != nullptr) + { + while (!_isRotateThreadExited) + { + _sleepCondition.notify_one(); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + + if (_rotateBufferThread->joinable()) { + _rotateBufferThread->join(); + } + + delete _rotateBufferThread; + _rotateBufferThread = nullptr; + ALOGVV("rotateBufferThread exited!"); + } + } + } while(false); + + ALOGVV("Before alSourceStop"); + alSourceStop(_alSource); CHECK_AL_ERROR_DEBUG(); + ALOGVV("Before alSourcei"); + alSourcei(_alSource, AL_BUFFER, NULL); CHECK_AL_ERROR_DEBUG(); + + _removeByAudioEngine = true; + + _ready = false; + ALOGVV("AudioPlayer::destroy end, id=%u", _id); +} + +void AudioPlayer::setCache(AudioCache* cache) +{ + _audioCache = cache; +} + +bool AudioPlayer::play2d() +{ + _play2dMutex.lock(); + ALOGV("AudioPlayer::play2d, _alSource: %u, player id=%u", _alSource, _id); + + /*********************************************************************/ + /* Note that it may be in sub thread or in main thread. **/ + /*********************************************************************/ + bool ret = false; + do + { + if (_audioCache->_state != AudioCache::State::READY) + { + ALOGE("alBuffer isn't ready for play!"); + break; + } + + alSourcei(_alSource, AL_BUFFER, 0);CHECK_AL_ERROR_DEBUG(); + alSourcef(_alSource, AL_PITCH, 1.0f);CHECK_AL_ERROR_DEBUG(); + alSourcef(_alSource, AL_GAIN, _volume);CHECK_AL_ERROR_DEBUG(); + alSourcei(_alSource, AL_LOOPING, AL_FALSE);CHECK_AL_ERROR_DEBUG(); + + if (_audioCache->_queBufferFrames == 0) + { + if (_loop) { + alSourcei(_alSource, AL_LOOPING, AL_TRUE); + CHECK_AL_ERROR_DEBUG(); + } + } + else + { + alGenBuffers(3, _bufferIds); + + auto alError = alGetError(); + if (alError == AL_NO_ERROR) + { + for (int index = 0; index < QUEUEBUFFER_NUM; ++index) + { + alBufferData(_bufferIds[index], _audioCache->_format, _audioCache->_queBuffers[index], _audioCache->_queBufferSize[index], _audioCache->_sampleRate); + } + CHECK_AL_ERROR_DEBUG(); + } + else + { + ALOGE("%s:alGenBuffers error code:%x", __FUNCTION__,alError); + break; + } + _streamingSource = true; + } + + { + std::unique_lock lk(_sleepMutex); + if (_isDestroyed) + break; + + if (_streamingSource) + { + alSourceQueueBuffers(_alSource, QUEUEBUFFER_NUM, _bufferIds); + CHECK_AL_ERROR_DEBUG(); + _rotateBufferThread = new std::thread(&AudioPlayer::rotateBufferThread, this, _audioCache->_queBufferFrames * QUEUEBUFFER_NUM + 1); + } + else + { + alSourcei(_alSource, AL_BUFFER, _audioCache->_alBufferId); + CHECK_AL_ERROR_DEBUG(); + } + + alSourcePlay(_alSource); + } + + auto alError = alGetError(); + if (alError != AL_NO_ERROR) + { + ALOGE("%s:alSourcePlay error code:%x", __FUNCTION__,alError); + break; + } + + ALint state; + alGetSourcei(_alSource, AL_SOURCE_STATE, &state); + if (state != AL_PLAYING) + { + ALOGE("state isn't playing, %d, %s, cache id=%u, player id=%u", state, _audioCache->_fileFullPath.c_str(), _audioCache->_id, _id); + } + assert(state == AL_PLAYING); + _ready = true; + ret = true; + } while (false); + + if (!ret) + { + _removeByAudioEngine = true; + } + + _play2dMutex.unlock(); + return ret; } void AudioPlayer::rotateBufferThread(int offsetFrame) { - ALint sourceState; - ALint bufferProcessed = 0; - mpg123_handle* mpg123handle = nullptr; - OggVorbis_File* vorbisFile = nullptr; - - std::function fileReader = nullptr; - std::function fileSeeker = nullptr; - - auto audioFileFormat = _audioCache->_fileFormat; - char* tmpBuffer = (char*)malloc(_audioCache->_queBufferBytes); - - switch (audioFileFormat) + char* tmpBuffer = nullptr; + AudioDecoder* decoder = AudioDecoderManager::createDecoder(_audioCache->_fileFullPath.c_str()); + do { - case AudioCache::FileFormat::MP3: - { - int error = MPG123_OK; - mpg123handle = mpg123_new(nullptr, &error); - if (!mpg123handle){ - ALOGE("Basic setup goes wrong: %s", mpg123_plain_strerror(error)); - goto ExitBufferThread; - } - long rate = 0; - int channels = 0; - int mp3Encoding = 0; - if (mpg123_open(mpg123handle,_audioCache->_fileFullPath.c_str()) != MPG123_OK - || mpg123_getformat(mpg123handle, &rate, &channels, &mp3Encoding) != MPG123_OK){ - ALOGE("Trouble with mpg123: %s\n", mpg123_strerror(mpg123handle) ); - goto ExitBufferThread; - } + BREAK_IF(decoder == nullptr || !decoder->open(_audioCache->_fileFullPath.c_str())); - /* Ensure that this output format will not change (it could, when we allow it). */ - mpg123_format_none(mpg123handle); - mpg123_format(mpg123handle, _audioCache->_sampleRate, _audioCache->_channels, _audioCache->_mp3Encoding); + uint32_t framesRead = 0; + const uint32_t framesToRead = _audioCache->_queBufferFrames; + const uint32_t bufferSize = framesToRead * decoder->getBytesPerFrame(); + tmpBuffer = (char*)malloc(bufferSize); + memset(tmpBuffer, 0, bufferSize); - if (offsetFrame != 0) { - mpg123_seek(mpg123handle,offsetFrame,SEEK_SET); - } - break; + if (offsetFrame != 0) { + decoder->seek(offsetFrame); } - case AudioCache::FileFormat::OGG: - { - vorbisFile = new OggVorbis_File; - int openCode; - if (openCode = ov_fopen(FileUtils::getInstance()->getSuitableFOpen(_audioCache->_fileFullPath).c_str(), vorbisFile)){ - ALOGE("Input does not appear to be an Ogg bitstream: %s. Code: 0x%x\n", _audioCache->_fileFullPath.c_str(), openCode); - goto ExitBufferThread; - } - if (offsetFrame != 0) { - ov_pcm_seek(vorbisFile,offsetFrame); - } - break; - } - default: - break; - } - alSourcePlay(_alSource); + ALint sourceState; + ALint bufferProcessed = 0; + bool needToExitThread = false; - if (audioFileFormat == AudioCache::FileFormat::MP3) - { - fileReader = [&](char* buffer, int bufferSize) -> int { - size_t ret = 0; - mpg123_read(mpg123handle, (unsigned char*)buffer, bufferSize, &ret); - return ret; - }; - - fileSeeker = [&](int pos) { - mpg123_seek(mpg123handle, pos, SEEK_SET); - }; - } - else if (audioFileFormat == AudioCache::FileFormat::OGG) - { - fileReader = [&](char* buffer, int bufferSize) -> int { - int current_section = 0; - return ov_read(vorbisFile, buffer, bufferSize, 0, 2, 1, ¤t_section); - }; - - fileSeeker = [&](int pos) { - ov_pcm_seek(vorbisFile, pos); - }; - } - - while (!_exitThread) { - alGetSourcei(_alSource, AL_SOURCE_STATE, &sourceState); - if (sourceState == AL_PLAYING) { - _ready = true; - - alGetSourcei(_alSource, AL_BUFFERS_PROCESSED, &bufferProcessed); - while (bufferProcessed > 0) { - bufferProcessed--; - if (_timeDirty) { - _timeDirty = false; - offsetFrame = _currTime * _audioCache->_sampleRate; - fileSeeker(offsetFrame); - } - else { - _currTime += QUEUEBUFFER_TIME_STEP; - if (_currTime > _audioCache->_duration) { - if (_loop) { - _currTime = 0.0f; - } else { - _currTime = _audioCache->_duration; - } - } - } - - int readRet = readPcmData(tmpBuffer, _audioCache->_queBufferBytes, fileReader); - if (readRet <= 0) { - if (_loop) { - fileSeeker(0); - readRet = readPcmData(tmpBuffer, _audioCache->_queBufferBytes, fileReader); + while (!_isDestroyed) { + alGetSourcei(_alSource, AL_SOURCE_STATE, &sourceState); + if (sourceState == AL_PLAYING) { + alGetSourcei(_alSource, AL_BUFFERS_PROCESSED, &bufferProcessed); + while (bufferProcessed > 0) { + bufferProcessed--; + if (_timeDirty) { + _timeDirty = false; + offsetFrame = _currTime * decoder->getSampleRate(); + decoder->seek(offsetFrame); } else { - _exitThread = true; - break; + _currTime += QUEUEBUFFER_TIME_STEP; + if (_currTime > _audioCache->_duration) { + if (_loop) { + _currTime = 0.0f; + } else { + _currTime = _audioCache->_duration; + } + } } - } - else - { - _audioCache->_bytesOfRead += readRet; - } - //ALOGV("readRet: %d, queBufferBytes: %d", (int)readRet, _audioCache->_queBufferBytes); - ALuint bid; - alSourceUnqueueBuffers(_alSource, 1, &bid); - CHECK_AL_ERROR_DEBUG(); - alBufferData(bid, _audioCache->_alBufferFormat, tmpBuffer, readRet, _audioCache->_sampleRate); - CHECK_AL_ERROR_DEBUG(); - alSourceQueueBuffers(_alSource, 1, &bid); - CHECK_AL_ERROR_DEBUG(); + framesRead = decoder->readFixedFrames(framesToRead, tmpBuffer); + + if (framesRead == 0) { + if (_loop) { + decoder->seek(0); + framesRead = decoder->readFixedFrames(framesToRead, tmpBuffer); + } else { + needToExitThread = true; + break; + } + } + + ALuint bid; + alSourceUnqueueBuffers(_alSource, 1, &bid); + alBufferData(bid, _audioCache->_format, tmpBuffer, framesRead * decoder->getBytesPerFrame(), decoder->getSampleRate()); + alSourceQueueBuffers(_alSource, 1, &bid); + } } + + std::unique_lock lk(_sleepMutex); + if (_isDestroyed || needToExitThread) { + break; + } + + _sleepCondition.wait_for(lk,std::chrono::milliseconds(75)); } - std::unique_lock lk(_sleepMutex); - if (_exitThread) - { - ALOGV("thread exit..."); - break; - } + } while(false); - _sleepCondition.wait_for(lk,std::chrono::milliseconds(35)); - } -ExitBufferThread: - switch (audioFileFormat) + ALOGV("Exit rotate buffer thread ..."); + if (decoder != nullptr) { - case AudioCache::FileFormat::OGG: - ov_clear(vorbisFile); - delete vorbisFile; - break; - case AudioCache::FileFormat::MP3: - mpg123_close(mpg123handle); - mpg123_delete(mpg123handle); - break; - case AudioCache::FileFormat::UNKNOWN: - default: - break; + decoder->close(); } + AudioDecoderManager::destroyDecoder(decoder); free(tmpBuffer); - _readForRemove = true; + _isRotateThreadExited = true; ALOGV("%s exited.\n", __FUNCTION__); } bool AudioPlayer::setLoop(bool loop) { - if (!_exitThread ) { + if (!_isDestroyed ) { _loop = loop; return true; } @@ -334,9 +333,11 @@ bool AudioPlayer::setLoop(bool loop) bool AudioPlayer::setTime(float time) { - if (!_exitThread && time >= 0.0f && time < _audioCache->_duration) { + if (!_isDestroyed && time >= 0.0f && time < _audioCache->_duration) { + _currTime = time; _timeDirty = true; + return true; } return false; diff --git a/native/cocos/audio/win32/AudioPlayer.h b/native/cocos/audio/win32/AudioPlayer.h index 9ea7a421d6..44395751ee 100644 --- a/native/cocos/audio/win32/AudioPlayer.h +++ b/native/cocos/audio/win32/AudioPlayer.h @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2014 Chukong Technologies Inc. + Copyright (c) 2014-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -21,23 +21,23 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ + +#pragma once + #include "platform/CCPlatformConfig.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 -#ifndef __AUDIO_PLAYER_H_ -#define __AUDIO_PLAYER_H_ - #include #include +#include #include #ifdef OPENAL_PLAIN_INCLUDES #include #else -#include +#include #endif #include "platform/CCPlatformMacros.h" -#include "audio/win32/AudioCache.h" NS_CC_BEGIN namespace experimental{ @@ -49,19 +49,19 @@ class CC_DLL AudioPlayer { public: AudioPlayer(); - AudioPlayer(const AudioPlayer&); ~AudioPlayer(); + void destroy(); + //queue buffer related stuff bool setTime(float time); float getTime() { return _currTime;} bool setLoop(bool loop); - void notifyExitThread(); protected: + void setCache(AudioCache* cache); void rotateBufferThread(int offsetFrame); - bool play2d(AudioCache* cache); - int readPcmData(char* buffer, int bufferSize, const std::function& fileReader); + bool play2d(); AudioCache* _audioCache; @@ -69,25 +69,30 @@ protected: bool _loop; std::function _finishCallbak; + bool _isDestroyed; + bool _removeByAudioEngine; bool _ready; ALuint _alSource; //play by circular buffer float _currTime; - bool _timeDirty; bool _streamingSource; - ALuint _bufferIds[QUEUEBUFFER_NUM]; - std::thread _rotateBufferThread; - std::mutex _sleepMutex; + ALuint _bufferIds[3]; + std::thread* _rotateBufferThread; std::condition_variable _sleepCondition; - bool _exitThread; - bool _readForRemove; + std::mutex _sleepMutex; + bool _timeDirty; + bool _isRotateThreadExited; + + std::mutex _play2dMutex; + + unsigned int _id; friend class AudioEngineImpl; }; } NS_CC_END -#endif // __AUDIO_PLAYER_H_ + #endif //CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 diff --git a/native/cocos/audio/win32/MciPlayer.h b/native/cocos/audio/win32/MciPlayer.h index eba164982b..8976e7e190 100644 --- a/native/cocos/audio/win32/MciPlayer.h +++ b/native/cocos/audio/win32/MciPlayer.h @@ -18,12 +18,16 @@ public: void Close(); /** - @brief Play sound file - @param pFileName Sound's file name,include the file path. - @param nTimes Play mode£¬default value is 1,paly once + @brief Open audio file + @param pFileName The file name which includes the file path. + @param uId The audio ID */ void Open(const char* pFileName, UINT uId); + /** + @brief Play audio file + @param nTimes The repeat times, its default value is 1 which means only play once + */ void Play(UINT uTimes = 1); /** @@ -73,4 +77,3 @@ private: } // end of namespace CocosDenshion #endif - diff --git a/native/cocos/audio/win32/SimpleAudioEngine.cpp b/native/cocos/audio/win32/SimpleAudioEngine.cpp index cc7b8f0e24..f7aaf08167 100644 --- a/native/cocos/audio/win32/SimpleAudioEngine.cpp +++ b/native/cocos/audio/win32/SimpleAudioEngine.cpp @@ -1,6 +1,6 @@ /**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2013-2014 Chukong Technologies Inc. +Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -78,12 +78,10 @@ void SimpleAudioEngine::end() { sharedMusic().Close(); - EffectList::iterator p = sharedList().begin(); - while (p != sharedList().end()) + for (auto& iter : sharedList()) { - delete p->second; - p->second = nullptr; - p++; + delete iter.second; + iter.second = nullptr; } sharedList().clear(); return; @@ -204,10 +202,9 @@ void SimpleAudioEngine::pauseEffect(unsigned int nSoundId) void SimpleAudioEngine::pauseAllEffects() { - EffectList::iterator iter; - for (iter = sharedList().begin(); iter != sharedList().end(); iter++) + for (auto& iter : sharedList()) { - iter->second->Pause(); + iter.second->Pause(); } } @@ -222,19 +219,17 @@ void SimpleAudioEngine::resumeEffect(unsigned int nSoundId) void SimpleAudioEngine::resumeAllEffects() { - EffectList::iterator iter; - for (iter = sharedList().begin(); iter != sharedList().end(); iter++) + for (auto& iter : sharedList()) { - iter->second->Resume(); + iter.second->Resume(); } } void SimpleAudioEngine::stopAllEffects() { - EffectList::iterator iter; - for (iter = sharedList().begin(); iter != sharedList().end(); iter++) + for (auto& iter : sharedList()) { - iter->second->Stop(); + iter.second->Stop(); } } diff --git a/native/cocos/network/Android.mk b/native/cocos/network/Android.mk index 4c5a16a88e..2be5204318 100644 --- a/native/cocos/network/Android.mk +++ b/native/cocos/network/Android.mk @@ -11,7 +11,8 @@ LOCAL_SRC_FILES := HttpClient-android.cpp \ SocketIO.cpp \ WebSocket.cpp \ CCDownloader.cpp \ -CCDownloader-android.cpp +CCDownloader-android.cpp \ +Uri.cpp LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) diff --git a/native/cocos/network/SocketIO.cpp b/native/cocos/network/SocketIO.cpp index e49fdc07f4..b2cc0cde83 100644 --- a/native/cocos/network/SocketIO.cpp +++ b/native/cocos/network/SocketIO.cpp @@ -1,6 +1,6 @@ /**************************************************************************** Copyright (c) 2015 Chris Hannon http://www.channon.us - Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -28,16 +28,18 @@ ****************************************************************************/ #include "network/SocketIO.h" +#include "network/Uri.h" #include #include #include +#include "base/ccUTF8.h" #include "base/CCDirector.h" #include "base/CCScheduler.h" #include "network/WebSocket.h" #include "network/HttpClient.h" #include "json/rapidjson.h" -#include "json/document.h" +#include "json/document-wrapper.h" #include "json/stringbuffer.h" #include "json/writer.h" @@ -101,7 +103,7 @@ private: std::vector _typesMessage; }; -SocketIOPacket::SocketIOPacket() :_separator(":"), _endpointseparator("") +SocketIOPacket::SocketIOPacket() :_endpointseparator(""), _separator(":") { _types.push_back("disconnect"); _types.push_back("connect"); @@ -344,8 +346,10 @@ class SIOClientImpl : public WebSocket::Delegate { private: - int _port, _heartbeat, _timeout; - std::string _host, _sid, _uri; + int _heartbeat, _timeout; + std::string _sid; + Uri _uri; + std::string _caFilePath; bool _connected; SocketIOPacket::SocketIOVersion _version; @@ -354,10 +358,10 @@ private: Map _clients; public: - SIOClientImpl(const std::string& host, int port); + SIOClientImpl(const Uri& uri, const std::string& caFilePath); virtual ~SIOClientImpl(); - static SIOClientImpl* create(const std::string& host, int port); + static SIOClientImpl* create(const Uri& uri, const std::string& caFilePath); virtual void onOpen(WebSocket* ws); virtual void onMessage(WebSocket* ws, const WebSocket::Data& data); @@ -389,16 +393,12 @@ public: //method implementations //begin SIOClientImpl methods -SIOClientImpl::SIOClientImpl(const std::string& host, int port) : - _port(port), - _host(host), - _connected(false) +SIOClientImpl::SIOClientImpl(const Uri& uri, const std::string& caFilePath) : + _uri(uri), + _caFilePath(caFilePath), + _connected(false), + _ws(nullptr) { - std::stringstream s; - s << host << ":" << port; - _uri = s.str(); - - _ws = nullptr; } SIOClientImpl::~SIOClientImpl() @@ -414,7 +414,13 @@ void SIOClientImpl::handshake() CCLOGINFO("SIOClientImpl::handshake() called"); std::stringstream pre; - pre << "http://" << _uri << "/socket.io/1/?EIO=2&transport=polling&b64=true"; + + if (_uri.isSecure()) + pre << "https://"; + else + pre << "http://"; + + pre << _uri.getAuthority() << "/socket.io/1/?EIO=2&transport=polling&b64=true"; HttpRequest* request = new (std::nothrow) HttpRequest(); request->setUrl(pre.str()); @@ -425,6 +431,10 @@ void SIOClientImpl::handshake() CCLOGINFO("SIOClientImpl::handshake() waiting"); + if (_uri.isSecure() && !_caFilePath.empty()) + { + HttpClient::getInstance()->setSSLVerification(_caFilePath); + } HttpClient::getInstance()->send(request); request->release(); @@ -432,10 +442,9 @@ void SIOClientImpl::handshake() return; } -void SIOClientImpl::handshakeResponse(HttpClient *sender, HttpResponse *response) +void SIOClientImpl::handshakeResponse(HttpClient* /*sender*/, HttpResponse *response) { CCLOGINFO("SIOClientImpl::handshakeResponse() called"); - CC_UNUSED_PARAM(sender); if (0 != strlen(response->getHttpRequest()->getTag())) { @@ -452,9 +461,9 @@ void SIOClientImpl::handshakeResponse(HttpClient *sender, HttpResponse *response CCLOGERROR("SIOClientImpl::handshake() failed"); CCLOGERROR("error buffer: %s", response->getErrorBuffer()); - for (auto iter = _clients.begin(); iter != _clients.end(); ++iter) + for (auto& client : _clients) { - iter->second->getDelegate()->onError(iter->second, response->getErrorBuffer()); + client.second->getDelegate()->onError(client.second, response->getErrorBuffer()); } return; @@ -466,9 +475,9 @@ void SIOClientImpl::handshakeResponse(HttpClient *sender, HttpResponse *response std::stringstream s; s.str(""); - for (unsigned int i = 0; i < buffer->size(); i++) + for (const auto& iter : *buffer) { - s << (*buffer)[i]; + s << iter; } CCLOGINFO("SIOClientImpl::handshake() dump data: %s", s.str().c_str()); @@ -496,7 +505,6 @@ void SIOClientImpl::handshakeResponse(HttpClient *sender, HttpResponse *response temp = temp.erase(0, b + 1); // chomp past the upgrades - a = temp.find(":"); b = temp.find(","); temp = temp.erase(0, b + 1); @@ -562,18 +570,23 @@ void SIOClientImpl::openSocket() std::stringstream s; + if (_uri.isSecure()) + s << "wss://"; + else + s << "ws://"; + switch (_version) { case SocketIOPacket::SocketIOVersion::V09x: - s << _uri << "/socket.io/1/websocket/" << _sid; + s << _uri.getAuthority() << "/socket.io/1/websocket/" << _sid; break; case SocketIOPacket::SocketIOVersion::V10x: - s << _uri << "/socket.io/1/websocket/?EIO=2&transport=websocket&sid=" << _sid; + s << _uri.getAuthority() << "/socket.io/1/websocket/?EIO=2&transport=websocket&sid=" << _sid; break; } _ws = new (std::nothrow) WebSocket(); - if (!_ws->init(*this, s.str())) + if (!_ws->init(*this, s.str(), nullptr, _caFilePath)) { CC_SAFE_DELETE(_ws); } @@ -609,16 +622,17 @@ void SIOClientImpl::disconnect() Director::getInstance()->getScheduler()->unscheduleAllForTarget(this); - _ws->close(); - _connected = false; - SocketIO::getInstance()->removeSocket(_uri); + SocketIO::getInstance()->removeSocket(_uri.getAuthority()); + + // Close websocket connection should be at last. + _ws->close(); } -SIOClientImpl* SIOClientImpl::create(const std::string& host, int port) +SIOClientImpl* SIOClientImpl::create(const Uri& uri, const std::string& caFilePath) { - SIOClientImpl *s = new (std::nothrow) SIOClientImpl(host, port); + SIOClientImpl *s = new (std::nothrow) SIOClientImpl(uri, caFilePath); if (s && s->init()) { @@ -666,9 +680,8 @@ void SIOClientImpl::disconnectFromEndpoint(const std::string& endpoint) } } -void SIOClientImpl::heartbeat(float dt) +void SIOClientImpl::heartbeat(float /*dt*/) { - CC_UNUSED_PARAM(dt); SocketIOPacket *packet = SocketIOPacket::createPacketWithType("heartbeat", _version); this->send(packet); @@ -718,12 +731,11 @@ void SIOClientImpl::emit(const std::string& endpoint, const std::string& eventna this->send(packet); } -void SIOClientImpl::onOpen(WebSocket* ws) +void SIOClientImpl::onOpen(WebSocket* /*ws*/) { - CC_UNUSED_PARAM(ws); _connected = true; - SocketIO::getInstance()->addSocket(_uri, this); + SocketIO::getInstance()->addSocket(_uri.getAuthority(), this); if (_version == SocketIOPacket::SocketIOVersion::V10x) { @@ -733,18 +745,17 @@ void SIOClientImpl::onOpen(WebSocket* ws) Director::getInstance()->getScheduler()->schedule(CC_SCHEDULE_SELECTOR(SIOClientImpl::heartbeat), this, (_heartbeat * .9f), false); - for (auto iter = _clients.begin(); iter != _clients.end(); ++iter) + for (auto& client : _clients) { - iter->second->onOpen(); + client.second->onOpen(); } CCLOGINFO("SIOClientImpl::onOpen socket connected!"); } -void SIOClientImpl::onMessage(WebSocket* ws, const WebSocket::Data& data) +void SIOClientImpl::onMessage(WebSocket* /*ws*/, const WebSocket::Data& data) { CCLOGINFO("SIOClientImpl::onMessage received: %s", data.bytes); - CC_UNUSED_PARAM(ws); std::string payload = data.bytes; int control = atoi(payload.substr(0, 1).c_str()); @@ -880,7 +891,6 @@ void SIOClientImpl::onMessage(WebSocket* ws, const WebSocket::Data& data) int control2 = payload.at(0) - '0'; CCLOGINFO("Message code: [%i]", control2); - SocketIOPacket *packetOut = SocketIOPacket::createPacketWithType("event", _version); std::string endpoint = ""; std::string::size_type a = payload.find("/"); @@ -902,8 +912,6 @@ void SIOClientImpl::onMessage(WebSocket* ws, const WebSocket::Data& data) // we didn't find and endpoint and we are in the default namespace if (endpoint == "") endpoint = "/"; - packetOut->setEndpoint(endpoint); - c = getClient(endpoint); payload = payload.substr(1); @@ -976,37 +984,33 @@ void SIOClientImpl::onMessage(WebSocket* ws, const WebSocket::Data& data) return; } -void SIOClientImpl::onClose(WebSocket* ws) +void SIOClientImpl::onClose(WebSocket* /*ws*/) { - CC_UNUSED_PARAM(ws); if (!_clients.empty()) { - for (auto iter = _clients.begin(); iter != _clients.end(); ++iter) + for (auto& client : _clients) { - iter->second->socketClosed(); + client.second->socketClosed(); } // discard this client _connected = false; if (Director::getInstance()) Director::getInstance()->getScheduler()->unscheduleAllForTarget(this); - SocketIO::getInstance()->removeSocket(_uri); + SocketIO::getInstance()->removeSocket(_uri.getAuthority()); } this->release(); } -void SIOClientImpl::onError(WebSocket* ws, const WebSocket::ErrorCode& error) +void SIOClientImpl::onError(WebSocket* /*ws*/, const WebSocket::ErrorCode& error) { - CC_UNUSED_PARAM(ws); CCLOGERROR("Websocket error received: %d", static_cast(error)); } //begin SIOClient methods -SIOClient::SIOClient(const std::string& host, int port, const std::string& path, SIOClientImpl* impl, SocketIO::SIODelegate& delegate) - : _port(port) - , _host(host) - , _path(path) +SIOClient::SIOClient(const std::string& path, SIOClientImpl* impl, SocketIO::SIODelegate& delegate) + : _path(path) , _connected(false) , _socket(impl) , _delegate(&delegate) @@ -1131,55 +1135,33 @@ void SocketIO::destroyInstance() CC_SAFE_DELETE(_inst); } +SIOClient* SocketIO::connect(SocketIO::SIODelegate& delegate, const std::string& uri) +{ + return SocketIO::connect(uri, delegate); +} + SIOClient* SocketIO::connect(const std::string& uri, SocketIO::SIODelegate& delegate) { - std::string host = uri; - int port = 0; - size_t pos = 0; + return SocketIO::connect(uri, delegate, ""); +} - pos = host.find("//"); - if (pos != std::string::npos) - { - host.erase(0, pos+2); - } +SIOClient* SocketIO::connect(const std::string& uri, SocketIO::SIODelegate& delegate, const std::string& caFilePath) +{ + Uri uriObj = Uri::parse(uri); - pos = host.find(":"); - if (pos != std::string::npos) - { - port = atoi(host.substr(pos+1, host.size()).c_str()); - } - - pos = host.find("/", 0); - std::string path = "/"; - if (pos != std::string::npos) - { - path += host.substr(pos + 1, host.size()); - } - - pos = host.find(":"); - if (pos != std::string::npos) - { - host.erase(pos, host.size()); - } - else if ((pos = host.find("/")) != std::string::npos) - { - host.erase(pos, host.size()); - } - - std::stringstream s; - s << host << ":" << port; - - SIOClientImpl* socket = nullptr; + SIOClientImpl *socket = SocketIO::getInstance()->getSocket(uriObj.getAuthority()); SIOClient *c = nullptr; - socket = SocketIO::getInstance()->getSocket(s.str()); + std::string path = uriObj.getPath(); + if (path == "") + path = "/"; - if(socket == nullptr) + if (socket == nullptr) { //create a new socket, new client, connect - socket = SIOClientImpl::create(host, port); + socket = SIOClientImpl::create(uriObj, caFilePath); - c = new (std::nothrow) SIOClient(host, port, path, socket, delegate); + c = new (std::nothrow) SIOClient(path, socket, delegate); socket->addClient(path, c); @@ -1192,7 +1174,7 @@ SIOClient* SocketIO::connect(const std::string& uri, SocketIO::SIODelegate& dele if(c == nullptr) { - c = new (std::nothrow) SIOClient(host, port, path, socket, delegate); + c = new (std::nothrow) SIOClient(path, socket, delegate); socket->addClient(path, c); @@ -1204,11 +1186,8 @@ SIOClient* SocketIO::connect(const std::string& uri, SocketIO::SIODelegate& dele c->disconnect(); CCLOG("SocketIO: recreate a new socket, new client, connect"); - SIOClientImpl* newSocket = nullptr; - SIOClient *newC = nullptr; - - newSocket = SIOClientImpl::create(host, port); - newC = new (std::nothrow) SIOClient(host, port, path, newSocket, delegate); + SIOClientImpl* newSocket = SIOClientImpl::create(uriObj, caFilePath); + SIOClient *newC = new (std::nothrow) SIOClient(path, newSocket, delegate); newSocket->addClient(path, newC); newSocket->connect(); diff --git a/native/cocos/network/SocketIO.h b/native/cocos/network/SocketIO.h index c0b8cdfec6..cc0d84ea4c 100644 --- a/native/cocos/network/SocketIO.h +++ b/native/cocos/network/SocketIO.h @@ -1,6 +1,6 @@ /**************************************************************************** Copyright (c) 2015 Chris Hannon http://www.channon.us - Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2013-2017 Chukong Technologies Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -60,6 +60,7 @@ in the onClose method the pointer should be set to NULL or used to connect to a #define __CC_SOCKETIO_H__ #include +#include #include "platform/CCPlatformMacros.h" #include "base/CCMap.h" @@ -109,7 +110,7 @@ public: * * @param client the connected SIOClient object. */ - virtual void onConnect(SIOClient* client) { CC_UNUSED_PARAM(client); CCLOG("SIODelegate onConnect fired"); }; + virtual void onConnect(SIOClient* client) { CCLOG("SIODelegate onConnect fired"); }; /** * This is kept for backwards compatibility, message is now fired as a socket.io event "message" * @@ -118,9 +119,9 @@ public: * @param client the connected SIOClient object. * @param data the message,it could be json message */ - virtual void onMessage(SIOClient* client, const std::string& data) { CC_UNUSED_PARAM(client); CCLOG("SIODelegate onMessage fired with data: %s", data.c_str()); }; + virtual void onMessage(SIOClient* client, const std::string& data) { CCLOG("SIODelegate onMessage fired with data: %s", data.c_str()); }; /** - * Pure virtual callback function, this function should be overrided by the subclass. + * Pure virtual callback function, this function should be overridden by the subclass. * * This function would be called when the related SIOClient object disconnect or receive disconnect signal. * @@ -128,7 +129,7 @@ public: */ virtual void onClose(SIOClient* client) = 0; /** - * Pure virtual callback function, this function should be overrided by the subclass. + * Pure virtual callback function, this function should be overridden by the subclass. * * This function would be called when the related SIOClient object receive error signal or didn't connect the endpoint but do some network operation, eg.,send and emit,etc. * @@ -143,7 +144,7 @@ public: * @param eventName the event's name. * @param data the event's data information. */ - virtual void fireEventToScript(SIOClient* client, const std::string& eventName, const std::string& data) { CC_UNUSED_PARAM(client); CCLOG("SIODelegate event '%s' fired with data: %s", eventName.c_str(), data.c_str()); }; + virtual void fireEventToScript(SIOClient* client, const std::string& eventName, const std::string& data) { CCLOG("SIODelegate event '%s' fired with data: %s", eventName.c_str(), data.c_str()); }; }; /** @@ -154,6 +155,23 @@ public: */ static SIOClient* connect(const std::string& uri, SocketIO::SIODelegate& delegate); + /** + * Static client creation method, similar to socketio.connect(uri) in JS. + * @param uri the URI of the socket.io server. + * @param delegate the delegate which want to receive events from the socket.io client. + * @param caFilePath The ca file path for wss connection + * @return SIOClient* an initialized SIOClient if connected successfully, otherwise nullptr. + */ + static SIOClient* connect(const std::string& uri, SocketIO::SIODelegate& delegate, const std::string& caFilePath); + + /** + * Static client creation method, similar to socketio.connect(uri) in JS. + * @param delegate the delegate which want to receive events from the socket.io client. + * @param uri the URI of the socket.io server. + * @return SIOClient* an initialized SIOClient if connected successfully, otherwise nullptr. + */ + CC_DEPRECATED_ATTRIBUTE static SIOClient* connect(SocketIO::SIODelegate& delegate, const std::string& uri); + private: SocketIO(); @@ -186,8 +204,9 @@ class CC_DLL SIOClient : public cocos2d::Ref { private: - int _port; - std::string _host, _path, _tag; + friend class SocketIO; // Only SocketIO class could contruct a SIOClient instance. + + std::string _path, _tag; bool _connected; SIOClientImpl* _socket; @@ -203,7 +222,6 @@ private: friend class SIOClientImpl; -public: /** * Constructor of SIOClient class. * @@ -213,12 +231,13 @@ public: * @param impl the SIOClientImpl object. * @param delegate the SIODelegate object. */ - SIOClient(const std::string& host, int port, const std::string& path, SIOClientImpl* impl, SocketIO::SIODelegate& delegate); + SIOClient(const std::string& path, SIOClientImpl* impl, SocketIO::SIODelegate& delegate); /** * Destructor of SIOClient class. */ virtual ~SIOClient(); +public: /** * Get the delegate for the client * @return the delegate object for the client @@ -260,10 +279,10 @@ public: * Get tag of SIOClient. * @return const char* the pointer point to the _tag. */ - inline const char* getTag() + const char* getTag() { return _tag.c_str(); - }; + } }; diff --git a/native/cocos/network/Uri.cpp b/native/cocos/network/Uri.cpp new file mode 100644 index 0000000000..f62e533d50 --- /dev/null +++ b/native/cocos/network/Uri.cpp @@ -0,0 +1,377 @@ +/* + * Copyright 2017 Facebook, Inc. + * Copyright (c) 2017 Chukong Technologies + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * Uri class is based on the original file here https://github.com/facebook/folly/blob/master/folly/Uri.cpp + */ + +#include "network/Uri.h" +#include "base/CCConsole.h" // For CCLOGERROR macro + +#include +#include + +#include +#include + +#undef LIKELY +#undef UNLIKELY + +#if defined(__GNUC__) && __GNUC__ >= 4 +#define LIKELY(x) (__builtin_expect((x), 1)) +#define UNLIKELY(x) (__builtin_expect((x), 0)) +#else +#define LIKELY(x) (x) +#define UNLIKELY(x) (x) +#endif + + +namespace { + +template +std::string toString(T arg) +{ + std::stringstream ss; + ss << arg; + return ss.str(); +} + +std::string submatch(const std::smatch& m, int idx) +{ + auto& sub = m[idx]; + return std::string(sub.first, sub.second); +} + +template +void toLower(String& s) +{ + for (auto& c : s) { + c = char(tolower(c)); + } +} + +} // namespace + +NS_CC_BEGIN + +namespace network { + +Uri::Uri() +: _isValid(false) +, _isSecure(false) +, _hasAuthority(false) +, _port(0) +{ + +} + +Uri::Uri(const Uri& o) +{ + *this = o; +} + +Uri::Uri(Uri&& o) +{ + *this = std::move(o); +} + +Uri& Uri::operator=(const Uri& o) +{ + if (this != &o) + { + _isValid = o._isValid; + _isSecure = o._isSecure; + _scheme = o._scheme; + _username = o._username; + _password = o._password; + _host = o._host; + _hostName = o._hostName; + _hasAuthority = o._hasAuthority; + _port = o._port; + _authority = o._authority; + _pathEtc = o._pathEtc; + _path = o._path; + _query = o._query; + _fragment = o._fragment; + _queryParams = o._queryParams; + } + + return *this; +} + +Uri& Uri::operator=(Uri&& o) +{ + if (this != &o) + { + _isValid = o._isValid; + o._isValid = false; + _isSecure = o._isSecure; + o._isSecure = false; + _scheme = std::move(o._scheme); + _username = std::move(o._username); + _password = std::move(o._password); + _host = std::move(o._host); + _hostName = std::move(o._hostName); + _hasAuthority = o._hasAuthority; + o._hasAuthority = false; + _port = o._port; + o._port = 0; + _authority = std::move(o._authority); + _pathEtc = std::move(o._pathEtc); + _path = std::move(o._path); + _query = std::move(o._query); + _fragment = std::move(o._fragment); + _queryParams = std::move(o._queryParams); + } + return *this; +} + +bool Uri::operator==(const Uri& o) const +{ + return (_isValid == o._isValid + && _isSecure == o._isSecure + && _scheme == o._scheme + && _username == o._username + && _password == o._password + && _host == o._host + && _hostName == o._hostName + && _hasAuthority == o._hasAuthority + && _port == o._port + && _authority == o._authority + && _pathEtc == o._pathEtc + && _path == o._path + && _query == o._query + && _fragment == o._fragment + && _queryParams == o._queryParams); +} + +Uri Uri::parse(const std::string &str) +{ + Uri uri; + + if (!uri.doParse(str)) + { + uri.clear(); + } + + return uri; +} + +bool Uri::doParse(const std::string& str) +{ + static const std::regex uriRegex( + "([a-zA-Z][a-zA-Z0-9+.-]*):" // scheme: + "([^?#]*)" // authority and path + "(?:\\?([^#]*))?" // ?query + "(?:#(.*))?"); // #fragment + static const std::regex authorityAndPathRegex("//([^/]*)(/.*)?"); + + if (str.empty()) + { + CCLOGERROR("%s", "Empty URI is invalid!"); + return false; + } + + bool hasScheme = true;; + std::string copied(str); + if (copied.find("://") == std::string::npos) + { + hasScheme = false; + copied.insert(0, "abc://"); // Just make regex happy. + } + + std::smatch match; + if (UNLIKELY(!std::regex_match(copied.cbegin(), copied.cend(), match, uriRegex))) { + CCLOGERROR("Invalid URI: %s", str.c_str()); + return false; + } + + if (hasScheme) + { + _scheme = submatch(match, 1); + toLower(_scheme); + if (_scheme == "https" || _scheme == "wss") + { + _isSecure = true; + } + } + + std::string authorityAndPath(match[2].first, match[2].second); + std::smatch authorityAndPathMatch; + if (!std::regex_match(authorityAndPath.cbegin(), + authorityAndPath.cend(), + authorityAndPathMatch, + authorityAndPathRegex)) { + // Does not start with //, doesn't have authority + _hasAuthority = false; + _path = authorityAndPath; + } else { + static const std::regex authorityRegex( + "(?:([^@:]*)(?::([^@]*))?@)?" // username, password + "(\\[[^\\]]*\\]|[^\\[:]*)" // host (IP-literal (e.g. '['+IPv6+']', + // dotted-IPv4, or named host) + "(?::(\\d*))?"); // port + + auto authority = authorityAndPathMatch[1]; + std::smatch authorityMatch; + if (!std::regex_match(authority.first, + authority.second, + authorityMatch, + authorityRegex)) { + std::string invalidAuthority(authority.first, authority.second); + CCLOGERROR("Invalid URI authority: %s", invalidAuthority.c_str()); + return false; + } + + std::string port(authorityMatch[4].first, authorityMatch[4].second); + if (!port.empty()) { + _port = static_cast(atoi(port.c_str())); + } + + _hasAuthority = true; + _username = submatch(authorityMatch, 1); + _password = submatch(authorityMatch, 2); + _host = submatch(authorityMatch, 3); + _path = submatch(authorityAndPathMatch, 2); + } + + _query = submatch(match, 3); + _fragment = submatch(match, 4); + _isValid = true; + + // Assign authority part + // + // Port is 5 characters max and we have up to 3 delimiters. + _authority.reserve(getHost().size() + getUserName().size() + getPassword().size() + 8); + + if (!getUserName().empty() || !getPassword().empty()) { + _authority.append(getUserName()); + + if (!getPassword().empty()) { + _authority.push_back(':'); + _authority.append(getPassword()); + } + + _authority.push_back('@'); + } + + _authority.append(getHost()); + + if (getPort() != 0) { + _authority.push_back(':'); + _authority.append(::toString(getPort())); + } + + // Assign path etc part + _pathEtc = _path; + if (!_query.empty()) + { + _pathEtc += '?'; + _pathEtc += _query; + } + + if (!_fragment.empty()) + { + _pathEtc += '#'; + _pathEtc += _fragment; + } + + // Assign host name + if (!_host.empty() && _host[0] == '[') { + // If it starts with '[', then it should end with ']', this is ensured by + // regex + _hostName = _host.substr(1, _host.size() - 2); + } else { + _hostName = _host; + } + + return true; +} + +void Uri::clear() +{ + _isValid = false; + _isSecure = false; + _scheme.clear(); + _username.clear(); + _password.clear(); + _host.clear(); + _hostName.clear(); + _hasAuthority = false; + _port = 0; + _authority.clear(); + _pathEtc.clear(); + _path.clear(); + _query.clear(); + _fragment.clear(); + _queryParams.clear(); +} + +const std::vector>& Uri::getQueryParams() +{ + if (!_query.empty() && _queryParams.empty()) { + // Parse query string + static const std::regex queryParamRegex( + "(^|&)" /*start of query or start of parameter "&"*/ + "([^=&]*)=?" /*parameter name and "=" if value is expected*/ + "([^=&]*)" /*parameter value*/ + "(?=(&|$))" /*forward reference, next should be end of query or + start of next parameter*/); + std::cregex_iterator paramBeginItr( + _query.data(), _query.data() + _query.size(), queryParamRegex); + std::cregex_iterator paramEndItr; + for (auto itr = paramBeginItr; itr != paramEndItr; itr++) { + if (itr->length(2) == 0) { + // key is empty, ignore it + continue; + } + _queryParams.emplace_back( + std::string((*itr)[2].first, (*itr)[2].second), // parameter name + std::string((*itr)[3].first, (*itr)[3].second) // parameter value + ); + } + } + return _queryParams; +} + +std::string Uri::toString() const +{ + std::stringstream ss; + if (_hasAuthority) { + ss << _scheme << "://"; + if (!_password.empty()) { + ss << _username << ":" << _password << "@"; + } else if (!_username.empty()) { + ss << _username << "@"; + } + ss << _host; + if (_port != 0) { + ss << ":" << _port; + } + } else { + ss << _scheme << ":"; + } + ss << _path; + if (!_query.empty()) { + ss << "?" << _query; + } + if (!_fragment.empty()) { + ss << "#" << _fragment; + } + return ss.str(); +} + +} // namespace network { + +NS_CC_END diff --git a/native/cocos/network/Uri.h b/native/cocos/network/Uri.h new file mode 100644 index 0000000000..0516a1e7f4 --- /dev/null +++ b/native/cocos/network/Uri.h @@ -0,0 +1,184 @@ +/* + * Copyright 2017 Facebook, Inc. + * Copyright (c) 2017 Chukong Technologies + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Uri class is based on the original file here https://github.com/facebook/folly/blob/master/folly/Uri.cpp + */ + +#pragma once + +#include "platform/CCPlatformMacros.h" + +#include +#include +#include + +/** + * @addtogroup network + * @{ + */ + +NS_CC_BEGIN + +namespace network { + +/** + * Class representing a URI. + * + * Consider http://www.facebook.com/foo/bar?key=foo#anchor + * + * The URI is broken down into its parts: scheme ("http"), authority + * (ie. host and port, in most cases: "www.facebook.com"), path + * ("/foo/bar"), query ("key=foo") and fragment ("anchor"). The scheme is + * lower-cased. + * + * If this Uri represents a URL, note that, to prevent ambiguity, the component + * parts are NOT percent-decoded; you should do this yourself with + * uriUnescape() (for the authority and path) and uriUnescape(..., + * UriEscapeMode::QUERY) (for the query, but probably only after splitting at + * '&' to identify the individual parameters). + */ +class CC_DLL Uri +{ +public: + /** + * Parse a Uri from a string. Throws std::invalid_argument on parse error. + */ + static Uri parse(const std::string& str); + + /** Default constructor */ + Uri(); + + /** Copy constructor */ + Uri(const Uri& o); + + /** Move constructor */ + Uri(Uri&& o); + + /** Copy assignment */ + Uri& operator=(const Uri& o); + + /** Move assignment */ + Uri& operator=(Uri&& o); + + /** Checks whether two Uri instances contain the same values */ + bool operator==(const Uri& o) const; + + /** Checks wether it's a valid URI */ + bool isValid() const { return _isValid; } + + /** Checks whether it's a SSL connection */ + bool isSecure() const { return _isSecure; } + + /** Gets the scheme name for this URI. */ + const std::string& getScheme() const { return _scheme; } + + /** Gets the user name with the specified URI. */ + const std::string& getUserName() const { return _username; } + + /** Gets the password with the specified URI. */ + const std::string& getPassword() const { return _password; } + /** + * Get host part of URI. If host is an IPv6 address, square brackets will be + * returned, for example: "[::1]". + */ + const std::string& getHost() const { return _host; } + /** + * Get host part of URI. If host is an IPv6 address, square brackets will not + * be returned, for exmaple "::1"; otherwise it returns the same thing as + * getHost(). + * + * getHostName() is what one needs to call if passing the host to any other tool + * or API that connects to that host/port; e.g. getaddrinfo() only understands + * IPv6 host without square brackets + */ + const std::string& getHostName() const { return _hostName; } + + /** Gets the port number of the URI. */ + uint16_t getPort() const { return _port; } + + /** Gets the path part of the URI. */ + const std::string& getPath() const { return _path; } + + /// Gets the path, query and fragment parts of the URI. + const std::string& getPathEtc() const { return _pathEtc; } + + /** Gets the query part of the URI. */ + const std::string& getQuery() const { return _query; } + + /** Gets the fragment part of the URI */ + const std::string& getFragment() const { return _fragment; } + + /** Gets the authority part (userName, password, host and port) of the URI. + * @note If the port number is a well-known port + * number for the given scheme (e.g., 80 for http), it + * is not included in the authority. + */ + const std::string& getAuthority() const { return _authority; } + + /** Gets a string representation of the URI. */ + std::string toString() const; + + /** + * Get query parameters as key-value pairs. + * e.g. for URI containing query string: key1=foo&key2=&key3&=bar&=bar= + * In returned list, there are 3 entries: + * "key1" => "foo" + * "key2" => "" + * "key3" => "" + * Parts "=bar" and "=bar=" are ignored, as they are not valid query + * parameters. "=bar" is missing parameter name, while "=bar=" has more than + * one equal signs, we don't know which one is the delimiter for key and + * value. + * + * Note, this method is not thread safe, it might update internal state, but + * only the first call to this method update the state. After the first call + * is finished, subsequent calls to this method are thread safe. + * + * @return query parameter key-value pairs in a vector, each element is a + * pair of which the first element is parameter name and the second + * one is parameter value + */ + const std::vector>& getQueryParams(); + + /** Clears all parts of the URI. */ + void clear(); + +private: + bool doParse(const std::string& str); + + bool _isValid; + bool _isSecure; + std::string _scheme; + std::string _username; + std::string _password; + std::string _host; + std::string _hostName; + bool _hasAuthority; + uint16_t _port; + std::string _authority; + std::string _pathEtc; + std::string _path; + std::string _query; + std::string _fragment; + std::vector> _queryParams; +}; + +} // namespace network { + +NS_CC_END + +// end group +/// @} diff --git a/native/cocos/network/WebSocket.cpp b/native/cocos/network/WebSocket.cpp index de271df147..a49e744233 100644 --- a/native/cocos/network/WebSocket.cpp +++ b/native/cocos/network/WebSocket.cpp @@ -28,6 +28,7 @@ ****************************************************************************/ #include "network/WebSocket.h" +#include "network/Uri.h" #include "base/CCDirector.h" #include "base/CCScheduler.h" #include "base/CCEventDispatcher.h" @@ -361,6 +362,7 @@ void WsThreadHelper::onSubThreadLoop() if (msg->what == WS_MSG_TO_SUBTHREAD_CREATE_CONNECTION) { ws->onClientOpenConnectionRequest(); + delete *iter; iter = __wsHelper->_subThreadWsMessageQueue->erase(iter); } else @@ -508,6 +510,7 @@ void WebSocket::closeAllConnections() std::lock_guard lk(__instanceMutex); __websocketInstances->clear(); + delete __websocketInstances; __websocketInstances = nullptr; } } @@ -581,12 +584,9 @@ bool WebSocket::init(const Delegate& delegate, _url = url; _caFilePath = caFilePath; - // make sure url start with 'ws://' or 'wss://' - if (_url.size() < 6) + if (_url.empty()) return false; - CCASSERT(0 == strncmp(_url.c_str(), "ws://", 5) || 0 == strncmp(_url.c_str(), "wss://", 6), "Invalid URL"); - if (protocols != nullptr && !protocols->empty()) { size_t size = protocols->size(); @@ -616,11 +616,11 @@ bool WebSocket::init(const Delegate& delegate, } } - // WebSocket thread needs to be invoked at the end of this method. + bool isWebSocketThreadCreated = true; if (__wsHelper == nullptr) { __wsHelper = new (std::nothrow) WsThreadHelper(); - __wsHelper->createWebSocketThread(); + isWebSocketThreadCreated = false; } WsMessage* msg = new (std::nothrow) WsMessage(); @@ -628,6 +628,14 @@ bool WebSocket::init(const Delegate& delegate, msg->user = this; __wsHelper->sendMessageToWebSocketThread(msg); + // fixed https://github.com/cocos2d/cocos2d-x/issues/17433 + // createWebSocketThread has to be after message WS_MSG_TO_SUBTHREAD_CREATE_CONNECTION was sent. + // And websocket thread should only be created once. + if (!isWebSocketThreadCreated) + { + __wsHelper->createWebSocketThread(); + } + return true; } @@ -861,24 +869,11 @@ void WebSocket::onClientOpenConnectionRequest() _readyState = State::CONNECTING; _readyStateMutex.unlock(); - const char* prot = nullptr; - const char* address = nullptr; - const char* path = nullptr; - int port = -1; - - // lws_parse_uri will modify its first parameter, but _url is the member variable that we don't want it to be changed. - // Therefore, use a temporary url variable here. - std::string tmpUrl = _url; - if (lws_parse_uri((char*)tmpUrl.c_str(), &prot, &address, &port, &path)) - { - LOGE("lws_parse_uri failed: %s", _url.c_str()); - return; - } - - LOGD("protocol: %s, host: %s, port: %d, path: %s\n", prot, address, port, path); + Uri uri = Uri::parse(_url); + LOGD("scheme: %s, host: %s, port: %d, path: %s\n", uri.getScheme().c_str(), uri.getHostName().c_str(), static_cast(uri.getPort()), uri.getPathEtc().c_str()); int sslConnection = 0; - if (0 == strcmp(prot, "wss")) + if (uri.isSecure()) sslConnection = LCCSCF_USE_SSL; struct lws_vhost* vhost = nullptr; @@ -891,15 +886,25 @@ void WebSocket::onClientOpenConnectionRequest() vhost = createVhost(__defaultProtocols, sslConnection); } + int port = static_cast(uri.getPort()); + if (port == 0) + port = uri.isSecure() ? 443 : 80; + + const std::string& hostName = uri.getHostName(); + std::string path = uri.getPathEtc(); + const std::string& authority = uri.getAuthority(); + if (path.empty()) + path = "/"; + struct lws_client_connect_info connectInfo; memset(&connectInfo, 0, sizeof(connectInfo)); connectInfo.context = __wsContext; - connectInfo.address = address; + connectInfo.address = hostName.c_str(); connectInfo.port = port; connectInfo.ssl_connection = sslConnection; - connectInfo.path = path; - connectInfo.host = address; - connectInfo.origin = address; + connectInfo.path = path.c_str(); + connectInfo.host = hostName.c_str(); + connectInfo.origin = authority.c_str(); connectInfo.protocol = _clientSupportedProtocols.empty() ? nullptr : _clientSupportedProtocols.c_str(); connectInfo.ietf_version_or_minus_one = -1; connectInfo.userdata = this; diff --git a/native/cocos/network/WebSocket.h b/native/cocos/network/WebSocket.h index 5c9e9f626f..1f73264392 100644 --- a/native/cocos/network/WebSocket.h +++ b/native/cocos/network/WebSocket.h @@ -27,8 +27,7 @@ ****************************************************************************/ -#ifndef __CC_WEBSOCKET_H__ -#define __CC_WEBSOCKET_H__ +#pragma once #include #include @@ -273,11 +272,10 @@ private: friend class WebSocketCallbackWrapper; }; -} +} // namespace network { NS_CC_END // end group /// @} -#endif /* defined(__CC_JSB_WEBSOCKET_H__) */ diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java index 40dd7050e9..50ca8835d0 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java @@ -304,6 +304,7 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe protected void onResume() { Log.d(TAG, "onResume()"); super.onResume(); + Cocos2dxAudioFocusManager.registerAudioFocusListener(this); this.hideVirtualButton(); resumeIfHasFocus(); } @@ -329,12 +330,14 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe protected void onPause() { Log.d(TAG, "onPause()"); super.onPause(); + Cocos2dxAudioFocusManager.unregisterAudioFocusListener(this); Cocos2dxHelper.onPause(); mGLSurfaceView.onPause(); } @Override protected void onDestroy() { + Cocos2dxAudioFocusManager.unregisterAudioFocusListener(this); super.onDestroy(); } diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxAudioFocusManager.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxAudioFocusManager.java new file mode 100644 index 0000000000..253e1c7462 --- /dev/null +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxAudioFocusManager.java @@ -0,0 +1,131 @@ +/**************************************************************************** + * Copyright (c) 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. + ****************************************************************************/ + +package org.cocos2dx.lib; + +import android.content.Context; +import android.media.AudioManager; +import android.util.Log; + +class Cocos2dxAudioFocusManager { + + private final static String TAG = "AudioFocusManager"; + // Audio focus values synchronized with which in cocos/platform/android/javaactivity-android.cpp + private final static int AUDIOFOCUS_GAIN = 0; + private final static int AUDIOFOCUS_LOST = 1; + private final static int AUDIOFOCUS_LOST_TRANSIENT = 2; + private final static int AUDIOFOCUS_LOST_TRANSIENT_CAN_DUCK = 3; + + private static AudioManager.OnAudioFocusChangeListener sAfChangeListener = + new AudioManager.OnAudioFocusChangeListener() { + public void onAudioFocusChange(int focusChange) { + + Log.d(TAG, "onAudioFocusChange: " + focusChange + ", thread: " + Thread.currentThread().getName()); + + if (focusChange == AudioManager.AUDIOFOCUS_LOSS) { + // Permanent loss of audio focus + // Pause playback immediately + Log.d(TAG, "Pause music by AUDIOFOCUS_LOSS"); + Cocos2dxHelper.runOnGLThread(new Runnable() { + @Override + public void run() { + nativeOnAudioFocusChange(AUDIOFOCUS_LOST); + Cocos2dxHelper.setAudioFocus(false); + } + }); + + } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) { + // Pause playback + Log.d(TAG, "Pause music by AUDIOFOCUS_LOSS_TRANSILENT"); + Cocos2dxHelper.runOnGLThread(new Runnable() { + @Override + public void run() { + nativeOnAudioFocusChange(AUDIOFOCUS_LOST_TRANSIENT); + Cocos2dxHelper.setAudioFocus(false); + } + }); + } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) { + // Lower the volume, keep playing + Log.d(TAG, "Lower the volume, keep playing by AUDIOFOCUS_LOSS_TRANSILENT_CAN_DUCK"); + Cocos2dxHelper.runOnGLThread(new Runnable() { + @Override + public void run() { + nativeOnAudioFocusChange(AUDIOFOCUS_LOST_TRANSIENT_CAN_DUCK); + Cocos2dxHelper.setAudioFocus(false); + } + }); + } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) { + // Your app has been granted audio focus again + // Raise volume to normal, restart playback if necessary + Log.d(TAG, "Resume music by AUDIOFOCUS_GAIN"); + Cocos2dxHelper.runOnGLThread(new Runnable() { + @Override + public void run() { + nativeOnAudioFocusChange(AUDIOFOCUS_GAIN); + Cocos2dxHelper.setAudioFocus(true); + } + }); + } + } + }; + + static boolean registerAudioFocusListener(Context context) { + AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); + + // Request audio focus for playback + int result = am.requestAudioFocus(sAfChangeListener, + // Use the music stream. + AudioManager.STREAM_MUSIC, + // Request permanent focus. + AudioManager.AUDIOFOCUS_GAIN); + + if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { + Log.d(TAG, "requestAudioFocus succeed"); + return true; + } + + Log.e(TAG, "requestAudioFocus failed!"); + return false; + } + + static void unregisterAudioFocusListener(Context context) { + AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); + int result = am.abandonAudioFocus(sAfChangeListener); + if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { + Log.d(TAG, "abandonAudioFocus succeed!"); + } else { + Log.e(TAG, "abandonAudioFocus failed!"); + } + + Cocos2dxHelper.runOnGLThread(new Runnable() { + @Override + public void run() { + Cocos2dxHelper.setAudioFocus(true); + nativeOnAudioFocusChange(AUDIOFOCUS_GAIN); + } + }); + } + + private static native void nativeOnAudioFocusChange(int focusChange); +} diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java index c53b269014..dd87151de7 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java @@ -1,6 +1,6 @@ /**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2013-2014 Chukong Technologies Inc. +Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -410,6 +410,11 @@ public class Cocos2dxHelper { Cocos2dxHelper.sCocos2dSound.stopAllEffects(); } + static void setAudioFocus(boolean isAudioFocus) { + sCocos2dMusic.setAudioFocus(isAudioFocus); + sCocos2dSound.setAudioFocus(isAudioFocus); + } + public static void end() { Cocos2dxHelper.sCocos2dMusic.end(); Cocos2dxHelper.sCocos2dSound.end(); @@ -515,7 +520,7 @@ public class Cocos2dxHelper { } } - return false; + return defaultValue; } public static int getIntegerForKey(String key, int defaultValue) { @@ -543,7 +548,7 @@ public class Cocos2dxHelper { } } - return 0; + return defaultValue; } public static float getFloatForKey(String key, float defaultValue) { @@ -552,7 +557,7 @@ public class Cocos2dxHelper { return settings.getFloat(key, defaultValue); } catch (Exception ex) { - ex.printStackTrace();; + ex.printStackTrace(); Map allValues = settings.getAll(); Object value = allValues.get(key); @@ -571,7 +576,7 @@ public class Cocos2dxHelper { } } - return 0.0f; + return defaultValue; } public static double getDoubleForKey(String key, double defaultValue) { @@ -595,21 +600,21 @@ public class Cocos2dxHelper { SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean(key, value); - editor.commit(); + editor.apply(); } public static void setIntegerForKey(String key, int value) { SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putInt(key, value); - editor.commit(); + editor.apply(); } public static void setFloatForKey(String key, float value) { SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putFloat(key, value); - editor.commit(); + editor.apply(); } public static void setDoubleForKey(String key, double value) { @@ -617,21 +622,21 @@ public class Cocos2dxHelper { SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putFloat(key, (float)value); - editor.commit(); + editor.apply(); } public static void setStringForKey(String key, String value) { SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putString(key, value); - editor.commit(); + editor.apply(); } public static void deleteValueForKey(String key) { SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.remove(key); - editor.commit(); + editor.apply(); } public static byte[] conversionEncoding(byte[] text, String fromCharset,String newCharset) diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxMusic.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxMusic.java index 413c7e6b71..2aeec41a67 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxMusic.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxMusic.java @@ -1,6 +1,6 @@ /**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2013-2016 Chukong Technologies Inc. +Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -51,6 +51,7 @@ public class Cocos2dxMusic { private boolean mPaused; // whether music is paused state. private boolean mIsLoop = false; private boolean mManualPaused = false; // whether music is paused manually before the program is switched to the background. + private boolean mIsAudioFocus = true; private String mCurrentPath; // =========================================================== @@ -137,7 +138,7 @@ public class Cocos2dxMusic { if (this.mBackgroundMediaPlayer != null) { mBackgroundMediaPlayer.release(); mBackgroundMediaPlayer = createMediaPlayer(mCurrentPath); - + /** * should set the state, if not, the following sequence will be error * play -> pause -> stop -> resume @@ -226,7 +227,7 @@ public class Cocos2dxMusic { } this.mLeftVolume = this.mRightVolume = volume; - if (this.mBackgroundMediaPlayer != null) { + if (this.mBackgroundMediaPlayer != null && mIsAudioFocus) { this.mBackgroundMediaPlayer.setVolume(this.mLeftVolume, this.mRightVolume); } } @@ -241,7 +242,7 @@ public class Cocos2dxMusic { Log.e(TAG, "onEnterBackground, IllegalStateException was triggered!"); } } - + public void onEnterForeground(){ try { if (!this.mManualPaused) { @@ -254,7 +255,7 @@ public class Cocos2dxMusic { Log.e(TAG, "onEnterForeground, IllegalStateException was triggered!"); } } - + private void initData() { this.mLeftVolume = 0.5f; this.mRightVolume = 0.5f; @@ -298,6 +299,16 @@ public class Cocos2dxMusic { return mediaPlayer; } + void setAudioFocus(boolean isFocus) { + mIsAudioFocus = isFocus; + + if (mBackgroundMediaPlayer != null) { + float lVolume = mIsAudioFocus ? mLeftVolume : 0.0f; + float rVolume = mIsAudioFocus ? mRightVolume : 0.0f; + mBackgroundMediaPlayer.setVolume(lVolume, rVolume); + } + } + // =========================================================== // Inner and Anonymous Classes // =========================================================== diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxSound.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxSound.java index e81dbcaed7..bfb5973fcd 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxSound.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxSound.java @@ -1,6 +1,6 @@ /**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2013-2016 Chukong Technologies Inc. +Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -52,15 +52,19 @@ public class Cocos2dxSound { private SoundPool mSoundPool; private float mLeftVolume; private float mRightVolume; + private boolean mIsAudioFocus = true; // sound path and stream ids map // a file may be played many times at the same time // so there is an array map to a file path private final HashMap> mPathStreamIDsMap = new HashMap>(); + // A lock for mPathStreamIDsMap operation to keep mPathStreamIDsMap being visited in only one thread at a time. + private final Object mLockPathStreamIDsMap = new Object(); private final HashMap mPathSoundIDMap = new HashMap(); - private ConcurrentHashMap mPlayWhenLoadedEffects = + // Key: SoundID, Value: SoundInfoForLoadedCompleted + private ConcurrentHashMap mPlayWhenLoadedEffects = new ConcurrentHashMap(); private static final int MAX_SIMULTANEOUS_STREAMS_DEFAULT = 5; @@ -111,24 +115,26 @@ public class Cocos2dxSound { } public void unloadEffect(final String path) { - // stop effects - final ArrayList streamIDs = this.mPathStreamIDsMap.get(path); - if (streamIDs != null) { - for (final Integer steamID : streamIDs) { - this.mSoundPool.stop(steamID); + synchronized (mLockPathStreamIDsMap) { + // stop effects + final ArrayList streamIDs = this.mPathStreamIDsMap.get(path); + if (streamIDs != null) { + for (final Integer steamID : streamIDs) { + this.mSoundPool.stop(steamID); + } } + this.mPathStreamIDsMap.remove(path); } - this.mPathStreamIDsMap.remove(path); // unload effect final Integer soundID = this.mPathSoundIDMap.get(path); - if(soundID != null){ + if (soundID != null) { this.mSoundPool.unload(soundID); this.mPathSoundIDMap.remove(path); } } - private static int LOAD_TIME_OUT = 500; + private static final int LOAD_TIME_OUT = 500; public int playEffect(final String path, final boolean loop, float pitch, float pan, float gain){ Integer soundID = this.mPathSoundIDMap.get(path); @@ -153,11 +159,11 @@ public class Cocos2dxSound { synchronized(info) { try { info.wait(LOAD_TIME_OUT); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } } + streamID = info.effectID; mPlayWhenLoadedEffects.remove(soundID); } @@ -168,11 +174,13 @@ public class Cocos2dxSound { public void stopEffect(final int steamID) { this.mSoundPool.stop(steamID); - // remove record - for (final String pPath : this.mPathStreamIDsMap.keySet()) { - if (this.mPathStreamIDsMap.get(pPath).contains(steamID)) { - this.mPathStreamIDsMap.get(pPath).remove(this.mPathStreamIDsMap.get(pPath).indexOf(steamID)); - break; + synchronized (mLockPathStreamIDsMap) { + // remove record + for (final String pPath : this.mPathStreamIDsMap.keySet()) { + if (this.mPathStreamIDsMap.get(pPath).contains(steamID)) { + this.mPathStreamIDsMap.get(pPath).remove(this.mPathStreamIDsMap.get(pPath).indexOf(steamID)); + break; + } } } } @@ -186,46 +194,51 @@ public class Cocos2dxSound { } public void pauseAllEffects() { - if (!this.mPathStreamIDsMap.isEmpty()) { - final Iterator>> iter = this.mPathStreamIDsMap.entrySet().iterator(); - while (iter.hasNext()) { - final Entry> entry = iter.next(); - for (final int steamID : entry.getValue()) { - this.mSoundPool.pause(steamID); + synchronized (mLockPathStreamIDsMap) { + if (!this.mPathStreamIDsMap.isEmpty()) { + final Iterator>> iter = this.mPathStreamIDsMap.entrySet().iterator(); + while (iter.hasNext()) { + final Entry> entry = iter.next(); + for (final int steamID : entry.getValue()) { + this.mSoundPool.pause(steamID); + } } } } } public void resumeAllEffects() { - // can not only invoke SoundPool.autoResume() here, because - // it only resumes all effects paused by pauseAllEffects() - if (!this.mPathStreamIDsMap.isEmpty()) { - final Iterator>> iter = this.mPathStreamIDsMap.entrySet().iterator(); - while (iter.hasNext()) { - final Entry> entry = iter.next(); - for (final int steamID : entry.getValue()) { - this.mSoundPool.resume(steamID); + synchronized (mLockPathStreamIDsMap) { + // can not only invoke SoundPool.autoResume() here, because + // it only resumes all effects paused by pauseAllEffects() + if (!this.mPathStreamIDsMap.isEmpty()) { + final Iterator>> iter = this.mPathStreamIDsMap.entrySet().iterator(); + while (iter.hasNext()) { + final Entry> entry = iter.next(); + for (final int steamID : entry.getValue()) { + this.mSoundPool.resume(steamID); + } } } } } - @SuppressWarnings("unchecked") public void stopAllEffects() { - // stop effects - if (!this.mPathStreamIDsMap.isEmpty()) { - final Iterator iter = this.mPathStreamIDsMap.entrySet().iterator(); - while (iter.hasNext()) { - final Map.Entry> entry = (Map.Entry>) iter.next(); - for (final int steamID : entry.getValue()) { - this.mSoundPool.stop(steamID); + synchronized (mLockPathStreamIDsMap) { + // stop effects + if (!this.mPathStreamIDsMap.isEmpty()) { + final Iterator iter = this.mPathStreamIDsMap.entrySet().iterator(); + while (iter.hasNext()) { + final Map.Entry> entry = (Map.Entry>) iter.next(); + for (final int steamID : entry.getValue()) { + this.mSoundPool.stop(steamID); + } } } - } - // remove records - this.mPathStreamIDsMap.clear(); + // remove records + this.mPathStreamIDsMap.clear(); + } } public float getEffectsVolume() { @@ -243,13 +256,22 @@ public class Cocos2dxSound { this.mLeftVolume = this.mRightVolume = volume; - // change the volume of playing sounds - if (!this.mPathStreamIDsMap.isEmpty()) { - final Iterator>> iter = this.mPathStreamIDsMap.entrySet().iterator(); - while (iter.hasNext()) { - final Entry> entry = iter.next(); - for (final int steamID : entry.getValue()) { - this.mSoundPool.setVolume(steamID, this.mLeftVolume, this.mRightVolume); + if (!mIsAudioFocus) + return; + + setEffectsVolumeInternal(mLeftVolume, mRightVolume); + } + + private void setEffectsVolumeInternal(float left, float right) { + synchronized (mLockPathStreamIDsMap) { + // change the volume of playing sounds + if (!this.mPathStreamIDsMap.isEmpty()) { + final Iterator>> iter = this.mPathStreamIDsMap.entrySet().iterator(); + while (iter.hasNext()) { + final Entry> entry = iter.next(); + for (final int steamID : entry.getValue()) { + this.mSoundPool.setVolume(steamID, left, right); + } } } } @@ -257,7 +279,9 @@ public class Cocos2dxSound { public void end() { this.mSoundPool.release(); - this.mPathStreamIDsMap.clear(); + synchronized (mLockPathStreamIDsMap) { + this.mPathStreamIDsMap.clear(); + } this.mPathSoundIDMap.clear(); this.mPlayWhenLoadedEffects.clear(); @@ -267,7 +291,7 @@ public class Cocos2dxSound { this.initData(); } - public int createSoundIDFromAsset(final String path) { + private int createSoundIDFromAsset(final String path) { int soundID = Cocos2dxSound.INVALID_SOUND_ID; try { @@ -294,11 +318,14 @@ public class Cocos2dxSound { return soundID; } - private float clamp(float value, float min, float max) { - return Math.max(min, (Math.min(value, max))); - } + private float clamp(float value, float min, float max) { + return Math.max(min, (Math.min(value, max))); + } - private int doPlayEffect(final String path, final int soundId, final boolean loop, float pitch, float pan, float gain) { + // Adds 'synchronized' keyword for doPlayeEffect since it's possible to be invoked in GL thread and main thread. + // In Cocos2dxSound.playEffect, it's in GL thread. + // In onLoadComplete callback, it's in main thread. + private synchronized int doPlayEffect(final String path, final int soundId, final boolean loop, float pitch, float pan, float gain) { float leftVolume = this.mLeftVolume * gain * (1.0f - this.clamp(pan, 0.0f, 1.0f)); float rightVolume = this.mRightVolume * gain * (1.0f - this.clamp(-pan, 0.0f, 1.0f)); float soundRate = this.clamp(SOUND_RATE * pitch, 0.5f, 2.0f); @@ -306,13 +333,15 @@ public class Cocos2dxSound { // play sound int streamID = this.mSoundPool.play(soundId, this.clamp(leftVolume, 0.0f, 1.0f), this.clamp(rightVolume, 0.0f, 1.0f), Cocos2dxSound.SOUND_PRIORITY, loop ? -1 : 0, soundRate); - // record stream id - ArrayList streamIDs = this.mPathStreamIDsMap.get(path); - if (streamIDs == null) { - streamIDs = new ArrayList(); - this.mPathStreamIDsMap.put(path, streamIDs); + synchronized (mLockPathStreamIDsMap) { + // record stream id + ArrayList streamIDs = this.mPathStreamIDsMap.get(path); + if (streamIDs == null) { + streamIDs = new ArrayList(); + this.mPathStreamIDsMap.put(path, streamIDs); + } + streamIDs.add(streamID); } - streamIDs.add(streamID); return streamID; } @@ -325,19 +354,27 @@ public class Cocos2dxSound { this.mSoundPool.autoResume(); } + void setAudioFocus(boolean isFocus) { + mIsAudioFocus = isFocus; + float leftVolume = mIsAudioFocus ? mLeftVolume : 0.0f; + float rightVolume = mIsAudioFocus ? mRightVolume : 0.0f; + + setEffectsVolumeInternal(leftVolume, rightVolume); + } + // =========================================================== // Inner and Anonymous Classes // =========================================================== - public class SoundInfoForLoadedCompleted { - public boolean isLoop; - public float pitch; - public float pan; - public float gain; - public String path; - public int effectID; + private class SoundInfoForLoadedCompleted { + boolean isLoop; + float pitch; + float pan; + float gain; + String path; + int effectID; - public SoundInfoForLoadedCompleted(String path, boolean isLoop, float pitch, float pan, float gain) { + SoundInfoForLoadedCompleted(String path, boolean isLoop, float pitch, float pan, float gain) { this.path = path; this.isLoop = isLoop; this.pitch = pitch; @@ -351,9 +388,11 @@ public class Cocos2dxSound { @Override public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { + // This callback is in main thread. if (status == 0) { SoundInfoForLoadedCompleted info = mPlayWhenLoadedEffects.get(sampleId); + if (info != null) { info.effectID = doPlayEffect(info.path, sampleId, info.isLoop, info.pitch, info.pan, info.gain); synchronized (info) { diff --git a/native/cocos/platform/android/javaactivity-android.cpp b/native/cocos/platform/android/javaactivity-android.cpp index 9887d6dd69..2ad537eb68 100644 --- a/native/cocos/platform/android/javaactivity-android.cpp +++ b/native/cocos/platform/android/javaactivity-android.cpp @@ -1,5 +1,5 @@ /**************************************************************************** -Copyright (c) 2013-2014 Chukong Technologies Inc. +Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -41,11 +41,13 @@ THE SOFTWARE. #include #include -#define LOG_TAG "main" -#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) +#define LOG_TAG "main" +#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) void cocos_android_app_init(JNIEnv* env) __attribute__((weak)); +void cocos_audioengine_focus_change(int focusChange); + using namespace cocos2d; extern "C" @@ -56,32 +58,32 @@ extern "C" #if __ANDROID_API__ > 19 #include #include - typedef __sighandler_t (*bsd_signal_func_t)(int, __sighandler_t); - bsd_signal_func_t bsd_signal_func = NULL; + typedef __sighandler_t (*bsd_signal_func_t)(int, __sighandler_t); + bsd_signal_func_t bsd_signal_func = NULL; - __sighandler_t bsd_signal(int s, __sighandler_t f) { - if (bsd_signal_func == NULL) { - // For now (up to Android 7.0) this is always available - bsd_signal_func = (bsd_signal_func_t) dlsym(RTLD_DEFAULT, "bsd_signal"); + __sighandler_t bsd_signal(int s, __sighandler_t f) { + if (bsd_signal_func == NULL) { + // For now (up to Android 7.0) this is always available + bsd_signal_func = (bsd_signal_func_t) dlsym(RTLD_DEFAULT, "bsd_signal"); - if (bsd_signal_func == NULL) { - __android_log_assert("", "bsd_signal_wrapper", "bsd_signal symbol not found!"); - } + if (bsd_signal_func == NULL) { + __android_log_assert("", "bsd_signal_wrapper", "bsd_signal symbol not found!"); + } + } + return bsd_signal_func(s, f); } - - return bsd_signal_func(s, f); - } #endif // __ANDROID_API__ > 19 JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) { JniHelper::setJavaVM(vm); + cocos_android_app_init(JniHelper::getEnv()); return JNI_VERSION_1_4; } -JNIEXPORT void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInit(JNIEnv* env, jobject thiz, jint w, jint h) +JNIEXPORT void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInit(JNIEnv* env, jobject thiz, jint w, jint h) { auto director = cocos2d::Director::getInstance(); auto glview = director->getOpenGLView(); @@ -122,6 +124,11 @@ JNIEXPORT jintArray Java_org_cocos2dx_lib_Cocos2dxActivity_getGLContextAttrs(JNI return glContextAttrsJava; } +JNIEXPORT void Java_org_cocos2dx_lib_Cocos2dxAudioFocusManager_nativeOnAudioFocusChange(JNIEnv* env, jobject thiz, jint focusChange) +{ + cocos_audioengine_focus_change(focusChange); +} + JNIEXPORT void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeOnSurfaceChanged(JNIEnv* env, jobject thiz, jint w, jint h) { cocos2d::Application::getInstance()->applicationScreenSizeChanged(w, h); diff --git a/native/cocos/scripting/js-bindings/manual/network/jsb_socketio.cpp b/native/cocos/scripting/js-bindings/manual/network/jsb_socketio.cpp index ff4bc98c0a..bdb878389f 100644 --- a/native/cocos/scripting/js-bindings/manual/network/jsb_socketio.cpp +++ b/native/cocos/scripting/js-bindings/manual/network/jsb_socketio.cpp @@ -1,6 +1,6 @@ /* * Created by Chris Hannon 2014 http://www.channon.us - * Copyright (c) 2014-2016 Chukong Technologies Inc. + * Copyright (c) 2014-2017 Chukong Technologies Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -46,12 +46,12 @@ public: JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); _JSDelegate.construct(cx); } - + ~JSB_SocketIODelegate() { _JSDelegate.destroyIfConstructed(); } - + virtual void onConnect(SIOClient* client) { CCLOG("JSB SocketIO::SIODelegate->onConnect method called from native"); @@ -93,9 +93,9 @@ public: { args = std_string_to_jsval(cx, data); } - + JSB_SIOCallbackRegistry::iterator it = _eventRegistry.find(eventName); - + if(it != _eventRegistry.end()) { std::shared_ptr callback = it->second; @@ -105,7 +105,7 @@ public: callback->invoke(1, &args, &rval); } } - + } void setJSDelegate(JS::HandleObject pJSDelegate) @@ -143,21 +143,46 @@ bool js_cocos2dx_SocketIO_connect(JSContext* cx, uint32_t argc, jsval* vp) CCLOG("JSB SocketIO.connect method called"); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); - if (argc == 1 || argc == 2) + if (argc >= 1 && argc <= 3) { std::string url; + std::string caFilePath; + bool ok = false; + + ok = jsval_to_std_string(cx, args[0], &url); + JSB_PRECONDITION2( ok, cx, false, "Error processing arguments"); - do + if (argc == 2) { - bool ok = jsval_to_std_string(cx, args.get(0), &url); - JSB_PRECONDITION2( ok, cx, false, "Error processing arguments"); - } while (0); + if (args[1].isObject()) + { + // Just ignore the option argument + } + else if (args[1].isString()) + { + // Assume it's CA root file path + ok = jsval_to_std_string(cx, args[1], &caFilePath); + JSB_PRECONDITION2( ok, cx, false, "Error processing arguments"); + } + } + if (argc == 3) + { + // Just ignore the option argument + + if (args[2].isString()) + { + // Assume it's CA root file path + ok = jsval_to_std_string(cx, args[2], &caFilePath); + JSB_PRECONDITION2( ok, cx, false, "Error processing arguments"); + } + } + JSB_SocketIODelegate* siodelegate = new (std::nothrow) JSB_SocketIODelegate(); - + CCLOG("Calling native SocketIO.connect method"); - SIOClient* ret = SocketIO::connect(url, *siodelegate); - + SIOClient* ret = SocketIO::connect(url, *siodelegate, caFilePath); + jsval jsret; do { @@ -202,7 +227,7 @@ bool js_cocos2dx_SocketIO_send(JSContext* cx, uint32_t argc, jsval* vp) if (argc == 1) { std::string payload; - + do { bool ok = jsval_to_std_string(cx, args.get(0), &payload); @@ -225,7 +250,7 @@ bool js_cocos2dx_SocketIO_emit(JSContext* cx, uint32_t argc, jsval* vp) JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); - js_proxy_t *proxy = jsb_get_js_proxy(obj); + js_proxy_t *proxy = jsb_get_js_proxy(obj); SIOClient* cobj = (SIOClient *)(proxy ? proxy->ptr : NULL); JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); @@ -237,7 +262,7 @@ bool js_cocos2dx_SocketIO_emit(JSContext* cx, uint32_t argc, jsval* vp) bool ok = jsval_to_std_string(cx, args.get(0), &eventName); JSB_PRECONDITION2( ok, cx, false, "Error processing arguments"); } while (0); - + std::string payload; do { bool ok = jsval_to_std_string(cx, args.get(1), &payload); @@ -300,7 +325,7 @@ static bool _js_set_SIOClient_tag(JSContext* cx, uint32_t argc, jsval* vp) js_proxy_t *proxy = jsb_get_js_proxy(jsobj); SIOClient* cobj = (SIOClient *)(proxy ? proxy->ptr : NULL); JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); - + if (cobj) { std::string out = ""; @@ -323,7 +348,7 @@ static bool _js_get_SIOClient_tag(JSContext* cx, uint32_t argc, jsval* vp) js_proxy_t *proxy = jsb_get_js_proxy(jsobj); SIOClient* cobj = (SIOClient *)(proxy ? proxy->ptr : NULL); JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); - + if (cobj) { args.rval().set(std_string_to_jsval(cx, cobj->getTag())); @@ -356,7 +381,7 @@ bool js_cocos2dx_SocketIO_on(JSContext* cx, uint32_t argc, jsval* vp) } while (0); CCLOG("JSB SocketIO eventName to: '%s'", eventName.c_str()); - + std::shared_ptr callback(new JSFunctionWrapper(cx, obj, args.get(1), args.thisv())); ((JSB_SocketIODelegate *)cobj->getDelegate())->addEvent(eventName, callback); @@ -397,7 +422,7 @@ void register_jsb_socketio(JSContext *cx, JS::HandleObject global) JS_FN("on", js_cocos2dx_SocketIO_on, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FS_END }; - + static JSFunctionSpec st_funcs[] = { JS_FN("connect", js_cocos2dx_SocketIO_connect, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), @@ -414,7 +439,7 @@ void register_jsb_socketio(JSContext *cx, JS::HandleObject global) funcs, properties, st_funcs); - + anonEvaluate(cx, global, "(function () { return SocketIO; })()").toObjectOrNull(); } diff --git a/native/cocos/scripting/js-bindings/manual/network/jsb_socketio.h b/native/cocos/scripting/js-bindings/manual/network/jsb_socketio.h index 509bb2da89..d50970c356 100644 --- a/native/cocos/scripting/js-bindings/manual/network/jsb_socketio.h +++ b/native/cocos/scripting/js-bindings/manual/network/jsb_socketio.h @@ -1,6 +1,6 @@ /* * Created by Chris Hannon 2014 http://www.channon.us - * Copyright (c) 2014-2016 Chukong Technologies Inc. + * Copyright (c) 2014-2017 Chukong Technologies Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/native/cocos/scripting/js-bindings/manual/network/jsb_websocket.cpp b/native/cocos/scripting/js-bindings/manual/network/jsb_websocket.cpp index f058208e56..8e6940bdd1 100644 --- a/native/cocos/scripting/js-bindings/manual/network/jsb_websocket.cpp +++ b/native/cocos/scripting/js-bindings/manual/network/jsb_websocket.cpp @@ -209,7 +209,7 @@ public: _JSDelegate.ref() = pJSDelegate; } private: - mozilla::Maybe _JSDelegate; + mozilla::Maybe _JSDelegate; }; JSClass *js_cocos2dx_websocket_class; @@ -317,11 +317,12 @@ bool js_cocos2dx_extension_WebSocket_constructor(JSContext *cx, uint32_t argc, j do { bool ok = jsval_to_std_string(cx, args.get(0), &url); - JSB_PRECONDITION2( ok, cx, false, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); } while (0); JS::RootedObject proto(cx, js_cocos2dx_websocket_prototype); JS::RootedObject obj(cx, JS_NewObject(cx, js_cocos2dx_websocket_class, proto, JS::NullPtr())); + //JS::RootedObject obj(cx, JS_NewObjectForConstructor(cx, js_cocos2dx_websocket_class, args)); WebSocket* cobj = nullptr; if (argc >= 2) @@ -334,7 +335,7 @@ bool js_cocos2dx_extension_WebSocket_constructor(JSContext *cx, uint32_t argc, j std::string protocol; do { bool ok = jsval_to_std_string(cx, args.get(1), &protocol); - JSB_PRECONDITION2( ok, cx, false, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); } while (0); protocols.push_back(protocol); } @@ -342,19 +343,19 @@ bool js_cocos2dx_extension_WebSocket_constructor(JSContext *cx, uint32_t argc, j { bool ok = true; JS::RootedObject arg2(cx, args.get(1).toObjectOrNull()); - JSB_PRECONDITION(JS_IsArrayObject( cx, arg2 ), "Object must be an array"); + JSB_PRECONDITION(JS_IsArrayObject(cx, arg2), "Object must be an array"); uint32_t len = 0; JS_GetArrayLength(cx, arg2, &len); - for( uint32_t i=0; i< len;i++ ) + for (uint32_t i = 0; i< len; i++) { JS::RootedValue valarg(cx); JS_GetElement(cx, arg2, i, &valarg); std::string protocol; do { ok = jsval_to_std_string(cx, valarg, &protocol); - JSB_PRECONDITION2( ok, cx, false, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); } while (0); protocols.push_back(protocol); @@ -365,10 +366,10 @@ bool js_cocos2dx_extension_WebSocket_constructor(JSContext *cx, uint32_t argc, j { do { bool ok = jsval_to_std_string(cx, args.get(2), &caFilePath); - JSB_PRECONDITION2( ok, cx, false, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); } while (0); } - + cobj = new (std::nothrow) WebSocket(); JSB_WebSocketDelegate* delegate = new (std::nothrow) JSB_WebSocketDelegate(); delegate->setJSDelegate(obj);