1
0

AudioEngine.cpp 16 KB

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