AudioEngine.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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. #include "platform/CCPlatformConfig.h"
  22. #include "audio/include/AudioEngine.h"
  23. #include <condition_variable>
  24. #include <queue>
  25. #include "platform/CCFileUtils.h"
  26. #include "base/ccUtils.h"
  27. #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
  28. #include "audio/android/AudioEngine-inl.h"
  29. #elif CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC
  30. #include "audio/apple/AudioEngine-inl.h"
  31. #elif CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
  32. #include "audio/win32/AudioEngine-win32.h"
  33. #elif CC_TARGET_PLATFORM == CC_PLATFORM_WINRT
  34. #include "audio/winrt/AudioEngine-winrt.h"
  35. #elif CC_TARGET_PLATFORM == CC_PLATFORM_LINUX
  36. #include "audio/linux/AudioEngine-linux.h"
  37. #elif CC_TARGET_PLATFORM == CC_PLATFORM_TIZEN
  38. #include "audio/tizen/AudioEngine-tizen.h"
  39. #endif
  40. #define TIME_DELAY_PRECISION 0.0001
  41. #ifdef ERROR
  42. #undef ERROR
  43. #endif // ERROR
  44. using namespace cocos2d;
  45. using namespace cocos2d::experimental;
  46. const int AudioEngine::INVALID_AUDIO_ID = -1;
  47. const float AudioEngine::TIME_UNKNOWN = -1.0f;
  48. //audio file path,audio IDs
  49. std::unordered_map<std::string,std::list<int>> AudioEngine::_audioPathIDMap;
  50. //profileName,ProfileHelper
  51. std::unordered_map<std::string, AudioEngine::ProfileHelper> AudioEngine::_audioPathProfileHelperMap;
  52. unsigned int AudioEngine::_maxInstances = MAX_AUDIOINSTANCES;
  53. AudioEngine::ProfileHelper* AudioEngine::_defaultProfileHelper = nullptr;
  54. std::unordered_map<int, AudioEngine::AudioInfo> AudioEngine::_audioIDInfoMap;
  55. AudioEngineImpl* AudioEngine::_audioEngineImpl = nullptr;
  56. AudioEngine::AudioEngineThreadPool* AudioEngine::s_threadPool = nullptr;
  57. bool AudioEngine::_isEnabled = true;
  58. AudioEngine::AudioInfo::AudioInfo()
  59. : filePath(nullptr)
  60. , profileHelper(nullptr)
  61. , volume(1.0f)
  62. , loop(false)
  63. , duration(TIME_UNKNOWN)
  64. , state(AudioState::INITIALIZING)
  65. {
  66. }
  67. AudioEngine::AudioInfo::~AudioInfo()
  68. {
  69. }
  70. class AudioEngine::AudioEngineThreadPool
  71. {
  72. public:
  73. AudioEngineThreadPool(int threads = 4)
  74. : _stop(false)
  75. {
  76. for (int index = 0; index < threads; ++index)
  77. {
  78. _workers.emplace_back(std::thread(std::bind(&AudioEngineThreadPool::threadFunc, this)));
  79. }
  80. }
  81. void addTask(const std::function<void()> &task){
  82. std::unique_lock<std::mutex> lk(_queueMutex);
  83. _taskQueue.emplace(task);
  84. _taskCondition.notify_one();
  85. }
  86. ~AudioEngineThreadPool()
  87. {
  88. {
  89. std::unique_lock<std::mutex> lk(_queueMutex);
  90. _stop = true;
  91. _taskCondition.notify_all();
  92. }
  93. for (auto&& worker : _workers) {
  94. worker.join();
  95. }
  96. }
  97. private:
  98. void threadFunc()
  99. {
  100. while (true) {
  101. std::function<void()> task = nullptr;
  102. {
  103. std::unique_lock<std::mutex> lk(_queueMutex);
  104. if (_stop)
  105. {
  106. break;
  107. }
  108. if (!_taskQueue.empty())
  109. {
  110. task = std::move(_taskQueue.front());
  111. _taskQueue.pop();
  112. }
  113. else
  114. {
  115. _taskCondition.wait(lk);
  116. continue;
  117. }
  118. }
  119. task();
  120. }
  121. }
  122. std::vector<std::thread> _workers;
  123. std::queue< std::function<void()> > _taskQueue;
  124. std::mutex _queueMutex;
  125. std::condition_variable _taskCondition;
  126. bool _stop;
  127. };
  128. void AudioEngine::end()
  129. {
  130. if (s_threadPool)
  131. {
  132. delete s_threadPool;
  133. s_threadPool = nullptr;
  134. }
  135. delete _audioEngineImpl;
  136. _audioEngineImpl = nullptr;
  137. delete _defaultProfileHelper;
  138. _defaultProfileHelper = nullptr;
  139. }
  140. bool AudioEngine::lazyInit()
  141. {
  142. if (_audioEngineImpl == nullptr)
  143. {
  144. _audioEngineImpl = new (std::nothrow) AudioEngineImpl();
  145. if(!_audioEngineImpl || !_audioEngineImpl->init() ){
  146. delete _audioEngineImpl;
  147. _audioEngineImpl = nullptr;
  148. return false;
  149. }
  150. }
  151. #if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID)
  152. if (_audioEngineImpl && s_threadPool == nullptr)
  153. {
  154. s_threadPool = new (std::nothrow) AudioEngineThreadPool();
  155. }
  156. #endif
  157. return true;
  158. }
  159. int AudioEngine::play2d(const std::string& filePath, bool loop, float volume, const AudioProfile *profile)
  160. {
  161. int ret = AudioEngine::INVALID_AUDIO_ID;
  162. do {
  163. if (!isEnabled())
  164. {
  165. break;
  166. }
  167. if ( !lazyInit() ){
  168. break;
  169. }
  170. if ( !FileUtils::getInstance()->isFileExist(filePath)){
  171. break;
  172. }
  173. auto profileHelper = _defaultProfileHelper;
  174. if (profile && profile != &profileHelper->profile){
  175. CC_ASSERT(!profile->name.empty());
  176. profileHelper = &_audioPathProfileHelperMap[profile->name];
  177. profileHelper->profile = *profile;
  178. }
  179. if (_audioIDInfoMap.size() >= _maxInstances) {
  180. log("Fail to play %s cause by limited max instance of AudioEngine",filePath.c_str());
  181. break;
  182. }
  183. if (profileHelper)
  184. {
  185. if(profileHelper->profile.maxInstances != 0 && profileHelper->audioIDs.size() >= profileHelper->profile.maxInstances){
  186. log("Fail to play %s cause by limited max instance of AudioProfile",filePath.c_str());
  187. break;
  188. }
  189. if (profileHelper->profile.minDelay > TIME_DELAY_PRECISION) {
  190. auto currTime = utils::gettime();
  191. if (profileHelper->lastPlayTime > TIME_DELAY_PRECISION && currTime - profileHelper->lastPlayTime <= profileHelper->profile.minDelay) {
  192. log("Fail to play %s cause by limited minimum delay",filePath.c_str());
  193. break;
  194. }
  195. }
  196. }
  197. if (volume < 0.0f) {
  198. volume = 0.0f;
  199. }
  200. else if (volume > 1.0f){
  201. volume = 1.0f;
  202. }
  203. ret = _audioEngineImpl->play2d(filePath, loop, volume);
  204. if (ret != INVALID_AUDIO_ID)
  205. {
  206. _audioPathIDMap[filePath].push_back(ret);
  207. auto it = _audioPathIDMap.find(filePath);
  208. auto& audioRef = _audioIDInfoMap[ret];
  209. audioRef.volume = volume;
  210. audioRef.loop = loop;
  211. audioRef.filePath = &it->first;
  212. if (profileHelper) {
  213. profileHelper->lastPlayTime = utils::gettime();
  214. profileHelper->audioIDs.push_back(ret);
  215. }
  216. audioRef.profileHelper = profileHelper;
  217. }
  218. } while (0);
  219. return ret;
  220. }
  221. void AudioEngine::setLoop(int audioID, bool loop)
  222. {
  223. auto it = _audioIDInfoMap.find(audioID);
  224. if (it != _audioIDInfoMap.end() && it->second.loop != loop){
  225. _audioEngineImpl->setLoop(audioID, loop);
  226. it->second.loop = loop;
  227. }
  228. }
  229. void AudioEngine::setVolume(int audioID, float volume)
  230. {
  231. auto it = _audioIDInfoMap.find(audioID);
  232. if (it != _audioIDInfoMap.end()){
  233. if (volume < 0.0f) {
  234. volume = 0.0f;
  235. }
  236. else if (volume > 1.0f){
  237. volume = 1.0f;
  238. }
  239. if (it->second.volume != volume){
  240. _audioEngineImpl->setVolume(audioID, volume);
  241. it->second.volume = volume;
  242. }
  243. }
  244. }
  245. void AudioEngine::pause(int audioID)
  246. {
  247. auto it = _audioIDInfoMap.find(audioID);
  248. if (it != _audioIDInfoMap.end() && it->second.state == AudioState::PLAYING){
  249. _audioEngineImpl->pause(audioID);
  250. it->second.state = AudioState::PAUSED;
  251. }
  252. }
  253. void AudioEngine::pauseAll()
  254. {
  255. auto itEnd = _audioIDInfoMap.end();
  256. for (auto it = _audioIDInfoMap.begin(); it != itEnd; ++it)
  257. {
  258. if (it->second.state == AudioState::PLAYING)
  259. {
  260. _audioEngineImpl->pause(it->first);
  261. it->second.state = AudioState::PAUSED;
  262. }
  263. }
  264. }
  265. void AudioEngine::resume(int audioID)
  266. {
  267. auto it = _audioIDInfoMap.find(audioID);
  268. if (it != _audioIDInfoMap.end() && it->second.state == AudioState::PAUSED){
  269. _audioEngineImpl->resume(audioID);
  270. it->second.state = AudioState::PLAYING;
  271. }
  272. }
  273. void AudioEngine::resumeAll()
  274. {
  275. auto itEnd = _audioIDInfoMap.end();
  276. for (auto it = _audioIDInfoMap.begin(); it != itEnd; ++it)
  277. {
  278. if (it->second.state == AudioState::PAUSED)
  279. {
  280. _audioEngineImpl->resume(it->first);
  281. it->second.state = AudioState::PLAYING;
  282. }
  283. }
  284. }
  285. void AudioEngine::stop(int audioID)
  286. {
  287. auto it = _audioIDInfoMap.find(audioID);
  288. if (it != _audioIDInfoMap.end()){
  289. _audioEngineImpl->stop(audioID);
  290. remove(audioID);
  291. }
  292. }
  293. void AudioEngine::remove(int audioID)
  294. {
  295. auto it = _audioIDInfoMap.find(audioID);
  296. if (it != _audioIDInfoMap.end()){
  297. if (it->second.profileHelper) {
  298. it->second.profileHelper->audioIDs.remove(audioID);
  299. }
  300. _audioPathIDMap[*it->second.filePath].remove(audioID);
  301. _audioIDInfoMap.erase(audioID);
  302. }
  303. }
  304. void AudioEngine::stopAll()
  305. {
  306. if(!_audioEngineImpl){
  307. return;
  308. }
  309. _audioEngineImpl->stopAll();
  310. auto itEnd = _audioIDInfoMap.end();
  311. for (auto it = _audioIDInfoMap.begin(); it != itEnd; ++it)
  312. {
  313. if (it->second.profileHelper){
  314. it->second.profileHelper->audioIDs.remove(it->first);
  315. }
  316. }
  317. _audioPathIDMap.clear();
  318. _audioIDInfoMap.clear();
  319. }
  320. void AudioEngine::uncache(const std::string &filePath)
  321. {
  322. if(!_audioEngineImpl){
  323. return;
  324. }
  325. auto audioIDsIter = _audioPathIDMap.find(filePath);
  326. if (audioIDsIter != _audioPathIDMap.end())
  327. {
  328. //@Note: For safely iterating elements from the audioID list, we need to copy the list
  329. // since 'AudioEngine::remove' may be invoked in '_audioEngineImpl->stop' synchronously.
  330. // If this happens, it will break the iteration, and crash will appear on some devices.
  331. std::list<int> copiedIDs(audioIDsIter->second);
  332. for (int audioID : copiedIDs)
  333. {
  334. _audioEngineImpl->stop(audioID);
  335. auto itInfo = _audioIDInfoMap.find(audioID);
  336. if (itInfo != _audioIDInfoMap.end())
  337. {
  338. if (itInfo->second.profileHelper)
  339. {
  340. itInfo->second.profileHelper->audioIDs.remove(audioID);
  341. }
  342. _audioIDInfoMap.erase(audioID);
  343. }
  344. }
  345. _audioPathIDMap.erase(filePath);
  346. }
  347. if (_audioEngineImpl)
  348. {
  349. _audioEngineImpl->uncache(filePath);
  350. }
  351. }
  352. void AudioEngine::uncacheAll()
  353. {
  354. if(!_audioEngineImpl){
  355. return;
  356. }
  357. stopAll();
  358. _audioEngineImpl->uncacheAll();
  359. }
  360. float AudioEngine::getDuration(int audioID)
  361. {
  362. auto it = _audioIDInfoMap.find(audioID);
  363. if (it != _audioIDInfoMap.end() && it->second.state != AudioState::INITIALIZING)
  364. {
  365. if (it->second.duration == TIME_UNKNOWN)
  366. {
  367. it->second.duration = _audioEngineImpl->getDuration(audioID);
  368. }
  369. return it->second.duration;
  370. }
  371. return TIME_UNKNOWN;
  372. }
  373. bool AudioEngine::setCurrentTime(int audioID, float time)
  374. {
  375. auto it = _audioIDInfoMap.find(audioID);
  376. if (it != _audioIDInfoMap.end() && it->second.state != AudioState::INITIALIZING) {
  377. return _audioEngineImpl->setCurrentTime(audioID, time);
  378. }
  379. return false;
  380. }
  381. float AudioEngine::getCurrentTime(int audioID)
  382. {
  383. auto it = _audioIDInfoMap.find(audioID);
  384. if (it != _audioIDInfoMap.end() && it->second.state != AudioState::INITIALIZING) {
  385. return _audioEngineImpl->getCurrentTime(audioID);
  386. }
  387. return 0.0f;
  388. }
  389. void AudioEngine::setFinishCallback(int audioID, const std::function<void (int, const std::string &)> &callback)
  390. {
  391. auto it = _audioIDInfoMap.find(audioID);
  392. if (it != _audioIDInfoMap.end()){
  393. _audioEngineImpl->setFinishCallback(audioID, callback);
  394. }
  395. }
  396. bool AudioEngine::setMaxAudioInstance(int maxInstances)
  397. {
  398. if (maxInstances > 0 && maxInstances <= MAX_AUDIOINSTANCES) {
  399. _maxInstances = maxInstances;
  400. return true;
  401. }
  402. return false;
  403. }
  404. bool AudioEngine::isLoop(int audioID)
  405. {
  406. auto tmpIterator = _audioIDInfoMap.find(audioID);
  407. if (tmpIterator != _audioIDInfoMap.end())
  408. {
  409. return tmpIterator->second.loop;
  410. }
  411. log("AudioEngine::isLoop-->The audio instance %d is non-existent", audioID);
  412. return false;
  413. }
  414. float AudioEngine::getVolume(int audioID)
  415. {
  416. auto tmpIterator = _audioIDInfoMap.find(audioID);
  417. if (tmpIterator != _audioIDInfoMap.end())
  418. {
  419. return tmpIterator->second.volume;
  420. }
  421. log("AudioEngine::getVolume-->The audio instance %d is non-existent", audioID);
  422. return 0.0f;
  423. }
  424. AudioEngine::AudioState AudioEngine::getState(int audioID)
  425. {
  426. auto tmpIterator = _audioIDInfoMap.find(audioID);
  427. if (tmpIterator != _audioIDInfoMap.end())
  428. {
  429. return tmpIterator->second.state;
  430. }
  431. return AudioState::ERROR;
  432. }
  433. AudioProfile* AudioEngine::getProfile(int audioID)
  434. {
  435. auto it = _audioIDInfoMap.find(audioID);
  436. if (it != _audioIDInfoMap.end())
  437. {
  438. return &it->second.profileHelper->profile;
  439. }
  440. return nullptr;
  441. }
  442. AudioProfile* AudioEngine::getDefaultProfile()
  443. {
  444. if (_defaultProfileHelper == nullptr)
  445. {
  446. _defaultProfileHelper = new (std::nothrow) ProfileHelper();
  447. }
  448. return &_defaultProfileHelper->profile;
  449. }
  450. AudioProfile* AudioEngine::getProfile(const std::string &name)
  451. {
  452. auto it = _audioPathProfileHelperMap.find(name);
  453. if (it != _audioPathProfileHelperMap.end()) {
  454. return &it->second.profile;
  455. } else {
  456. return nullptr;
  457. }
  458. }
  459. void AudioEngine::preload(const std::string& filePath, std::function<void(bool isSuccess)> callback)
  460. {
  461. if (!isEnabled())
  462. {
  463. callback(false);
  464. return;
  465. }
  466. lazyInit();
  467. if (_audioEngineImpl)
  468. {
  469. if (!FileUtils::getInstance()->isFileExist(filePath)){
  470. if (callback)
  471. {
  472. callback(false);
  473. }
  474. return;
  475. }
  476. _audioEngineImpl->preload(filePath, callback);
  477. }
  478. }
  479. void AudioEngine::addTask(const std::function<void()>& task)
  480. {
  481. lazyInit();
  482. if (_audioEngineImpl && s_threadPool)
  483. {
  484. s_threadPool->addTask(task);
  485. }
  486. }
  487. int AudioEngine::getPlayingAudioCount()
  488. {
  489. return static_cast<int>(_audioIDInfoMap.size());
  490. }
  491. void AudioEngine::setEnabled(bool isEnabled)
  492. {
  493. if (_isEnabled != isEnabled)
  494. {
  495. _isEnabled = isEnabled;
  496. if (!_isEnabled)
  497. {
  498. stopAll();
  499. }
  500. }
  501. }
  502. bool AudioEngine::isEnabled()
  503. {
  504. return _isEnabled;
  505. }