AudioEngine-inl.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. /****************************************************************************
  2. Copyright (c) 2014-2016 Chukong Technologies Inc.
  3. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
  22. #define LOG_TAG "AudioEngineImpl"
  23. #include "audio/android/AudioEngine-inl.h"
  24. #include <unistd.h>
  25. // for native asset manager
  26. #include <sys/types.h>
  27. #include <android/asset_manager.h>
  28. #include <android/asset_manager_jni.h>
  29. #include <unordered_map>
  30. #include <android/log.h>
  31. #include <thread>
  32. #include <mutex>
  33. #include "audio/include/AudioEngine.h"
  34. #include "platform/CCApplication.h"
  35. #include "base/CCScheduler.h"
  36. #include "base/ccUTF8.h"
  37. #include "platform/android/CCFileUtils-android.h"
  38. #include "platform/android/jni/JniImp.h"
  39. #include "platform/android/jni/JniHelper.h"
  40. #include "audio/android/IAudioPlayer.h"
  41. #include "audio/android/ICallerThreadUtils.h"
  42. #include "audio/android/AudioPlayerProvider.h"
  43. #include "audio/android/cutils/log.h"
  44. #include "audio/android/UrlAudioPlayer.h"
  45. #include "scripting/js-bindings/event/EventDispatcher.h"
  46. #include "scripting/js-bindings/event/CustomEventTypes.h"
  47. using namespace cocos2d;
  48. // Audio focus values synchronized with which in cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java
  49. static const int AUDIOFOCUS_GAIN = 0;
  50. static const int AUDIOFOCUS_LOST = 1;
  51. static const int AUDIOFOCUS_LOST_TRANSIENT = 2;
  52. static const int AUDIOFOCUS_LOST_TRANSIENT_CAN_DUCK = 3;
  53. static int __currentAudioFocus = AUDIOFOCUS_GAIN;
  54. static AudioEngineImpl* __impl = nullptr;
  55. class CallerThreadUtils : public ICallerThreadUtils
  56. {
  57. public:
  58. virtual void performFunctionInCallerThread(const std::function<void()>& func)
  59. {
  60. Application::getInstance()->getScheduler()->performFunctionInCocosThread(func);
  61. };
  62. virtual std::thread::id getCallerThreadId()
  63. {
  64. return _tid;
  65. };
  66. void setCallerThreadId(std::thread::id tid)
  67. {
  68. _tid = tid;
  69. };
  70. private:
  71. std::thread::id _tid;
  72. };
  73. static CallerThreadUtils __callerThreadUtils;
  74. static int fdGetter(const std::string& url, off_t* start, off_t* length)
  75. {
  76. int fd = -1;
  77. if (cocos2d::FileUtilsAndroid::getObbFile() != nullptr)
  78. {
  79. fd = getObbAssetFileDescriptorJNI(url.c_str(), start, length);
  80. }
  81. if (fd <= 0)
  82. {
  83. auto asset = AAssetManager_open(cocos2d::FileUtilsAndroid::getAssetManager(), url.c_str(), AASSET_MODE_UNKNOWN);
  84. // open asset as file descriptor
  85. fd = AAsset_openFileDescriptor(asset, start, length);
  86. AAsset_close(asset);
  87. }
  88. if (fd <= 0)
  89. {
  90. ALOGE("Failed to open file descriptor for '%s'", url.c_str());
  91. }
  92. return fd;
  93. };
  94. //====================================================
  95. AudioEngineImpl::AudioEngineImpl()
  96. : _engineObject(nullptr)
  97. , _engineEngine(nullptr)
  98. , _outputMixObject(nullptr)
  99. , _audioPlayerProvider(nullptr)
  100. , _audioIDIndex(0)
  101. , _lazyInitLoop(true)
  102. {
  103. __callerThreadUtils.setCallerThreadId(std::this_thread::get_id());
  104. __impl = this;
  105. }
  106. AudioEngineImpl::~AudioEngineImpl()
  107. {
  108. if (_audioPlayerProvider != nullptr)
  109. {
  110. delete _audioPlayerProvider;
  111. _audioPlayerProvider = nullptr;
  112. }
  113. if (_outputMixObject)
  114. {
  115. (*_outputMixObject)->Destroy(_outputMixObject);
  116. }
  117. if (_engineObject)
  118. {
  119. (*_engineObject)->Destroy(_engineObject);
  120. }
  121. __impl = nullptr;
  122. }
  123. bool AudioEngineImpl::init()
  124. {
  125. bool ret = false;
  126. do{
  127. // create engine
  128. auto result = slCreateEngine(&_engineObject, 0, nullptr, 0, nullptr, nullptr);
  129. if(SL_RESULT_SUCCESS != result){ ERRORLOG("create opensl engine fail"); break; }
  130. // realize the engine
  131. result = (*_engineObject)->Realize(_engineObject, SL_BOOLEAN_FALSE);
  132. if(SL_RESULT_SUCCESS != result){ ERRORLOG("realize the engine fail"); break; }
  133. // get the engine interface, which is needed in order to create other objects
  134. result = (*_engineObject)->GetInterface(_engineObject, SL_IID_ENGINE, &_engineEngine);
  135. if(SL_RESULT_SUCCESS != result){ ERRORLOG("get the engine interface fail"); break; }
  136. // create output mix
  137. const SLInterfaceID outputMixIIDs[] = {};
  138. const SLboolean outputMixReqs[] = {};
  139. result = (*_engineEngine)->CreateOutputMix(_engineEngine, &_outputMixObject, 0, outputMixIIDs, outputMixReqs);
  140. if(SL_RESULT_SUCCESS != result){ ERRORLOG("create output mix fail"); break; }
  141. // realize the output mix
  142. result = (*_outputMixObject)->Realize(_outputMixObject, SL_BOOLEAN_FALSE);
  143. if(SL_RESULT_SUCCESS != result){ ERRORLOG("realize the output mix fail"); break; }
  144. _audioPlayerProvider = new AudioPlayerProvider(_engineEngine, _outputMixObject, getDeviceSampleRateJNI(), getDeviceAudioBufferSizeInFramesJNI(), fdGetter, &__callerThreadUtils);
  145. ret = true;
  146. }while (false);
  147. return ret;
  148. }
  149. void AudioEngineImpl::setAudioFocusForAllPlayers(bool isFocus)
  150. {
  151. for (const auto& e : _audioPlayers)
  152. {
  153. e.second->setAudioFocus(isFocus);
  154. }
  155. }
  156. int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume)
  157. {
  158. ALOGV("play2d, _audioPlayers.size=%d", (int)_audioPlayers.size());
  159. auto audioId = AudioEngine::INVALID_AUDIO_ID;
  160. do
  161. {
  162. if (_engineEngine == nullptr || _audioPlayerProvider == nullptr)
  163. break;
  164. auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
  165. audioId = _audioIDIndex++;
  166. auto player = _audioPlayerProvider->getAudioPlayer(fullPath);
  167. if (player != nullptr)
  168. {
  169. player->setId(audioId);
  170. _audioPlayers.insert(std::make_pair(audioId, player));
  171. player->setPlayEventCallback([this, player, filePath](IAudioPlayer::State state){
  172. if (state != IAudioPlayer::State::OVER && state != IAudioPlayer::State::STOPPED)
  173. {
  174. ALOGV("Ignore state: %d", static_cast<int>(state));
  175. return;
  176. }
  177. int id = player->getId();
  178. ALOGV("Removing player id=%d, state:%d", id, (int)state);
  179. AudioEngine::remove(id);
  180. if (_audioPlayers.find(id) != _audioPlayers.end())
  181. {
  182. _audioPlayers.erase(id);
  183. }
  184. if (_urlAudioPlayersNeedResume.find(id) != _urlAudioPlayersNeedResume.end())
  185. {
  186. _urlAudioPlayersNeedResume.erase(id);
  187. }
  188. auto iter = _callbackMap.find(id);
  189. if (iter != _callbackMap.end())
  190. {
  191. if (state == IAudioPlayer::State::OVER)
  192. {
  193. iter->second(id, filePath);
  194. }
  195. _callbackMap.erase(iter);
  196. }
  197. });
  198. player->setLoop(loop);
  199. player->setVolume(volume);
  200. player->setAudioFocus(__currentAudioFocus == AUDIOFOCUS_GAIN);
  201. player->play();
  202. }
  203. else
  204. {
  205. ALOGE("Oops, player is null ...");
  206. return AudioEngine::INVALID_AUDIO_ID;
  207. }
  208. AudioEngine::_audioIDInfoMap[audioId].state = AudioEngine::AudioState::PLAYING;
  209. } while (0);
  210. return audioId;
  211. }
  212. void AudioEngineImpl::setVolume(int audioID,float volume)
  213. {
  214. auto iter = _audioPlayers.find(audioID);
  215. if (iter != _audioPlayers.end())
  216. {
  217. auto player = iter->second;
  218. player->setVolume(volume);
  219. }
  220. }
  221. void AudioEngineImpl::setLoop(int audioID, bool loop)
  222. {
  223. auto iter = _audioPlayers.find(audioID);
  224. if (iter != _audioPlayers.end())
  225. {
  226. auto player = iter->second;
  227. player->setLoop(loop);
  228. }
  229. }
  230. void AudioEngineImpl::pause(int audioID)
  231. {
  232. auto iter = _audioPlayers.find(audioID);
  233. if (iter != _audioPlayers.end())
  234. {
  235. auto player = iter->second;
  236. player->pause();
  237. }
  238. }
  239. void AudioEngineImpl::resume(int audioID)
  240. {
  241. auto iter = _audioPlayers.find(audioID);
  242. if (iter != _audioPlayers.end())
  243. {
  244. auto player = iter->second;
  245. player->resume();
  246. }
  247. }
  248. void AudioEngineImpl::stop(int audioID)
  249. {
  250. auto iter = _audioPlayers.find(audioID);
  251. if (iter != _audioPlayers.end())
  252. {
  253. auto player = iter->second;
  254. player->stop();
  255. }
  256. }
  257. void AudioEngineImpl::stopAll()
  258. {
  259. if (_audioPlayers.empty())
  260. {
  261. return;
  262. }
  263. // Create a temporary vector for storing all players since
  264. // p->stop() will trigger _audioPlayers.erase,
  265. // and it will cause a crash as it's already in for loop
  266. std::vector<IAudioPlayer*> players;
  267. players.reserve(_audioPlayers.size());
  268. for (const auto& e : _audioPlayers)
  269. {
  270. players.push_back(e.second);
  271. }
  272. for (auto p : players)
  273. {
  274. p->stop();
  275. }
  276. }
  277. float AudioEngineImpl::getDuration(int audioID)
  278. {
  279. auto iter = _audioPlayers.find(audioID);
  280. if (iter != _audioPlayers.end())
  281. {
  282. auto player = iter->second;
  283. return player->getDuration();
  284. }
  285. return 0.0f;
  286. }
  287. float AudioEngineImpl::getDurationFromFile(const std::string &filePath)
  288. {
  289. if (_audioPlayerProvider != nullptr)
  290. {
  291. auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
  292. return _audioPlayerProvider->getDurationFromFile(fullPath);
  293. }
  294. return 0;
  295. }
  296. float AudioEngineImpl::getCurrentTime(int audioID)
  297. {
  298. auto iter = _audioPlayers.find(audioID);
  299. if (iter != _audioPlayers.end())
  300. {
  301. auto player = iter->second;
  302. return player->getPosition();
  303. }
  304. return 0.0f;
  305. }
  306. bool AudioEngineImpl::setCurrentTime(int audioID, float time)
  307. {
  308. auto iter = _audioPlayers.find(audioID);
  309. if (iter != _audioPlayers.end())
  310. {
  311. auto player = iter->second;
  312. return player->setPosition(time);
  313. }
  314. return false;
  315. }
  316. void AudioEngineImpl::setFinishCallback(int audioID, const std::function<void (int, const std::string &)> &callback)
  317. {
  318. _callbackMap[audioID] = callback;
  319. }
  320. void AudioEngineImpl::preload(const std::string& filePath, const std::function<void(bool)>& callback)
  321. {
  322. if (_audioPlayerProvider != nullptr)
  323. {
  324. std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
  325. _audioPlayerProvider->preloadEffect(fullPath, [callback](bool succeed, PcmData data){
  326. if (callback != nullptr)
  327. {
  328. callback(succeed);
  329. }
  330. });
  331. }
  332. else
  333. {
  334. if (callback != nullptr)
  335. {
  336. callback(false);
  337. }
  338. }
  339. }
  340. void AudioEngineImpl::uncache(const std::string& filePath)
  341. {
  342. if (_audioPlayerProvider != nullptr)
  343. {
  344. std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
  345. _audioPlayerProvider->clearPcmCache(fullPath);
  346. }
  347. }
  348. void AudioEngineImpl::uncacheAll()
  349. {
  350. if (_audioPlayerProvider != nullptr)
  351. {
  352. _audioPlayerProvider->clearAllPcmCaches();
  353. }
  354. }
  355. void AudioEngineImpl::onPause()
  356. {
  357. if (_audioPlayerProvider != nullptr)
  358. {
  359. _audioPlayerProvider->pause();
  360. }
  361. }
  362. void AudioEngineImpl::onResume()
  363. {
  364. if (_audioPlayerProvider != nullptr)
  365. {
  366. _audioPlayerProvider->resume();
  367. }
  368. }
  369. // It's invoked from javaactivity-android.cpp
  370. void cocos_audioengine_focus_change(int focusChange)
  371. {
  372. if (focusChange < AUDIOFOCUS_GAIN || focusChange > AUDIOFOCUS_LOST_TRANSIENT_CAN_DUCK)
  373. {
  374. CCLOGERROR("cocos_audioengine_focus_change: unknown value: %d", focusChange);
  375. return;
  376. }
  377. CCLOG("cocos_audioengine_focus_change: %d", focusChange);
  378. __currentAudioFocus = focusChange;
  379. if (__impl == nullptr)
  380. {
  381. CCLOGWARN("cocos_audioengine_focus_change: AudioEngineImpl isn't ready!");
  382. return;
  383. }
  384. if (__currentAudioFocus == AUDIOFOCUS_GAIN)
  385. {
  386. __impl->setAudioFocusForAllPlayers(true);
  387. }
  388. else
  389. {
  390. __impl->setAudioFocusForAllPlayers(false);
  391. }
  392. }
  393. #endif