AudioPlayerProvider.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. /****************************************************************************
  2. Copyright (c) 2016-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. #define LOG_TAG "AudioPlayerProvider"
  21. #include "audio/android/AudioPlayerProvider.h"
  22. #include "audio/android/UrlAudioPlayer.h"
  23. #include "audio/android/PcmAudioPlayer.h"
  24. #include "audio/android/AudioDecoder.h"
  25. #include "audio/android/AudioDecoderProvider.h"
  26. #include "audio/android/AudioMixerController.h"
  27. #include "audio/android/PcmAudioService.h"
  28. #include "audio/android/CCThreadPool.h"
  29. #include "audio/android/ICallerThreadUtils.h"
  30. #include "audio/android/utils/Utils.h"
  31. #include "common/CocosConfig.h"
  32. #include <sys/system_properties.h>
  33. #include <stdlib.h>
  34. #include <algorithm> // for std::find_if
  35. namespace cocos2d { namespace experimental {
  36. static int getSystemAPILevel()
  37. {
  38. static int __systemApiLevel = -1;
  39. if (__systemApiLevel > 0)
  40. {
  41. return __systemApiLevel;
  42. }
  43. int apiLevel = getSDKVersion();
  44. if (apiLevel > 0)
  45. {
  46. ALOGD("Android API level: %d", apiLevel);
  47. }
  48. else
  49. {
  50. ALOGE("Fail to get Android API level!");
  51. }
  52. __systemApiLevel = apiLevel;
  53. return apiLevel;
  54. }
  55. struct AudioFileIndicator
  56. {
  57. std::string extension;
  58. int smallSizeIndicator;
  59. };
  60. static AudioFileIndicator __audioFileIndicator[] = {
  61. {"default", 128000}, // If we could not handle the audio format, return default value, the position should be first.
  62. {".wav", 1024000},
  63. {".ogg", 128000},
  64. {".mp3", 160000}
  65. };
  66. AudioPlayerProvider::AudioPlayerProvider(SLEngineItf engineItf, SLObjectItf outputMixObject,
  67. int deviceSampleRate, int bufferSizeInFrames,
  68. const FdGetterCallback &fdGetterCallback,
  69. ICallerThreadUtils* callerThreadUtils)
  70. : _engineItf(engineItf), _outputMixObject(outputMixObject),
  71. _deviceSampleRate(deviceSampleRate), _bufferSizeInFrames(bufferSizeInFrames),
  72. _fdGetterCallback(fdGetterCallback), _callerThreadUtils(callerThreadUtils),
  73. _pcmAudioService(nullptr), _mixController(nullptr),
  74. _threadPool(ThreadPool::newCachedThreadPool(1, 8, 5, 2, 2))
  75. {
  76. ALOGI("deviceSampleRate: %d, bufferSizeInFrames: %d", _deviceSampleRate, _bufferSizeInFrames);
  77. if (getSystemAPILevel() >= CocosConfig::minAudioCacheSupportAndroidSystemVersion())
  78. {
  79. _mixController = new (std::nothrow) AudioMixerController(_bufferSizeInFrames, _deviceSampleRate, 2);
  80. _mixController->init();
  81. _pcmAudioService = new (std::nothrow) PcmAudioService(engineItf, outputMixObject);
  82. _pcmAudioService->init(_mixController, 2, deviceSampleRate, bufferSizeInFrames * 2);
  83. }
  84. ALOG_ASSERT(callerThreadUtils != nullptr, "Caller thread utils parameter should not be nullptr!");
  85. }
  86. AudioPlayerProvider::~AudioPlayerProvider()
  87. {
  88. ALOGV("~AudioPlayerProvider()");
  89. UrlAudioPlayer::stopAll();
  90. SL_SAFE_DELETE(_pcmAudioService);
  91. SL_SAFE_DELETE(_mixController);
  92. SL_SAFE_DELETE(_threadPool);
  93. }
  94. IAudioPlayer *AudioPlayerProvider::getAudioPlayer(const std::string &audioFilePath)
  95. {
  96. // Pcm data decoding by OpenSLES API only supports in API level 17 and later.
  97. if (getSystemAPILevel() < CocosConfig::minAudioCacheSupportAndroidSystemVersion())
  98. {
  99. AudioFileInfo info = getFileInfo(audioFilePath);
  100. if (info.isValid())
  101. {
  102. return createUrlAudioPlayer(info);
  103. }
  104. return nullptr;
  105. }
  106. IAudioPlayer *player = nullptr;
  107. _pcmCacheMutex.lock();
  108. auto iter = _pcmCache.find(audioFilePath);
  109. if (iter != _pcmCache.end())
  110. {// Found pcm cache means it was used to be a PcmAudioService
  111. PcmData pcmData = iter->second;
  112. _pcmCacheMutex.unlock();
  113. player = obtainPcmAudioPlayer(audioFilePath, pcmData);
  114. ALOGV_IF(player == nullptr, "%s, %d: player is nullptr, path: %s", __FUNCTION__, __LINE__, audioFilePath.c_str());
  115. }
  116. else
  117. {
  118. _pcmCacheMutex.unlock();
  119. // Check audio file size to determine to use a PcmAudioService or UrlAudioPlayer,
  120. // generally PcmAudioService is used for playing short audio like game effects while
  121. // playing background music uses UrlAudioPlayer
  122. AudioFileInfo info = getFileInfo(audioFilePath);
  123. if (info.isValid())
  124. {
  125. if (isSmallFile(info))
  126. {
  127. // Put an empty lambda to preloadEffect since we only want the future object to get PcmData
  128. auto pcmData = std::make_shared<PcmData>();
  129. auto isSucceed = std::make_shared<bool>(false);
  130. auto isReturnFromCache = std::make_shared<bool>(false);
  131. auto isPreloadFinished = std::make_shared<bool>(false);
  132. std::thread::id threadId = std::this_thread::get_id();
  133. void* infoPtr = &info;
  134. std::string url = info.url;
  135. preloadEffect(info, [infoPtr, url, threadId, pcmData, isSucceed, isReturnFromCache, isPreloadFinished](bool succeed, PcmData data){
  136. // If the callback is in the same thread as caller's, it means that we found it
  137. // in the cache
  138. *isReturnFromCache = std::this_thread::get_id() == threadId;
  139. *pcmData = data;
  140. *isSucceed = succeed;
  141. *isPreloadFinished = true;
  142. ALOGV("FileInfo (%p), Set isSucceed flag: %d, path: %s", infoPtr, succeed, url.c_str());
  143. }, true);
  144. if (!*isReturnFromCache && !*isPreloadFinished)
  145. {
  146. std::unique_lock<std::mutex> lk(_preloadWaitMutex);
  147. // Wait for 2 seconds for the decoding in sub thread finishes.
  148. ALOGV("FileInfo (%p), Waiting preload (%s) to finish ...", &info, audioFilePath.c_str());
  149. _preloadWaitCond.wait_for(lk, std::chrono::seconds(2));
  150. ALOGV("FileInfo (%p), Waitup preload (%s) ...", &info, audioFilePath.c_str());
  151. }
  152. if (*isSucceed)
  153. {
  154. if (pcmData->isValid())
  155. {
  156. player = obtainPcmAudioPlayer(info.url, *pcmData);
  157. ALOGV_IF(player == nullptr, "%s, %d: player is nullptr, path: %s", __FUNCTION__, __LINE__, audioFilePath.c_str());
  158. }
  159. else
  160. {
  161. ALOGE("pcm data is invalid, path: %s", audioFilePath.c_str());
  162. }
  163. }
  164. else
  165. {
  166. ALOGE("FileInfo (%p), preloadEffect (%s) failed", &info, audioFilePath.c_str());
  167. }
  168. }
  169. else
  170. {
  171. player = createUrlAudioPlayer(info);
  172. ALOGV_IF(player == nullptr, "%s, %d: player is nullptr, path: %s", __FUNCTION__, __LINE__, audioFilePath.c_str());
  173. }
  174. }
  175. else
  176. {
  177. ALOGE("File info is invalid, path: %s", audioFilePath.c_str());
  178. }
  179. }
  180. ALOGV_IF(player == nullptr, "%s, %d return nullptr", __FUNCTION__, __LINE__);
  181. return player;
  182. }
  183. void AudioPlayerProvider::preloadEffect(const std::string &audioFilePath, const PreloadCallback& cb)
  184. {
  185. // Pcm data decoding by OpenSLES API only supports in API level 17 and later.
  186. if (getSystemAPILevel() < CocosConfig::minAudioCacheSupportAndroidSystemVersion())
  187. {
  188. PcmData data;
  189. cb(true, data);
  190. return;
  191. }
  192. _pcmCacheMutex.lock();
  193. auto&& iter = _pcmCache.find(audioFilePath);
  194. if (iter != _pcmCache.end())
  195. {
  196. ALOGV("preload return from cache: (%s)", audioFilePath.c_str());
  197. _pcmCacheMutex.unlock();
  198. cb(true, iter->second);
  199. return;
  200. }
  201. _pcmCacheMutex.unlock();
  202. auto info = getFileInfo(audioFilePath);
  203. preloadEffect(info, [this, cb, audioFilePath](bool succeed, PcmData data){
  204. _callerThreadUtils->performFunctionInCallerThread([this, succeed, data, cb](){
  205. cb(succeed, data);
  206. });
  207. }, false);
  208. }
  209. // Used internally
  210. void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const PreloadCallback& cb, bool isPreloadInPlay2d)
  211. {
  212. PcmData pcmData;
  213. if (!info.isValid())
  214. {
  215. cb(false, pcmData);
  216. return;
  217. }
  218. if (isSmallFile(info))
  219. {
  220. std::string audioFilePath = info.url;
  221. // 1. First time check, if it wasn't in the cache, goto 2 step
  222. _pcmCacheMutex.lock();
  223. auto&& iter = _pcmCache.find(audioFilePath);
  224. if (iter != _pcmCache.end())
  225. {
  226. ALOGV("1. Return pcm data from cache, url: %s", info.url.c_str());
  227. _pcmCacheMutex.unlock();
  228. cb(true, iter->second);
  229. return;
  230. }
  231. _pcmCacheMutex.unlock();
  232. {
  233. // 2. Check whether the audio file is being preloaded, if it has been removed from map just now,
  234. // goto step 3
  235. std::lock_guard<std::mutex> lk(_preloadCallbackMutex);
  236. auto&& preloadIter = _preloadCallbackMap.find(audioFilePath);
  237. if (preloadIter != _preloadCallbackMap.end())
  238. {
  239. ALOGV("audio (%s) is being preloaded, add to callback vector!", audioFilePath.c_str());
  240. PreloadCallbackParam param;
  241. param.callback = cb;
  242. param.isPreloadInPlay2d = isPreloadInPlay2d;
  243. preloadIter->second.push_back(std::move(param));
  244. return;
  245. }
  246. // 3. Check it in cache again. If it has been removed from map just now, the file is in
  247. // the cache absolutely.
  248. _pcmCacheMutex.lock();
  249. auto&& iter = _pcmCache.find(audioFilePath);
  250. if (iter != _pcmCache.end())
  251. {
  252. ALOGV("2. Return pcm data from cache, url: %s", info.url.c_str());
  253. _pcmCacheMutex.unlock();
  254. cb(true, iter->second);
  255. return;
  256. }
  257. _pcmCacheMutex.unlock();
  258. PreloadCallbackParam param;
  259. param.callback = cb;
  260. param.isPreloadInPlay2d = isPreloadInPlay2d;
  261. std::vector<PreloadCallbackParam> callbacks;
  262. callbacks.push_back(std::move(param));
  263. _preloadCallbackMap.insert(std::make_pair(audioFilePath, std::move(callbacks)));
  264. }
  265. _threadPool->pushTask([this, audioFilePath](int tid) {
  266. ALOGV("AudioPlayerProvider::preloadEffect: (%s)", audioFilePath.c_str());
  267. PcmData d;
  268. AudioDecoder* decoder = AudioDecoderProvider::createAudioDecoder(_engineItf, audioFilePath, _bufferSizeInFrames, _deviceSampleRate, _fdGetterCallback);
  269. bool ret = decoder != nullptr && decoder->start();
  270. if (ret)
  271. {
  272. d = decoder->getResult();
  273. std::lock_guard<std::mutex> lk(_pcmCacheMutex);
  274. _pcmCache.insert(std::make_pair(audioFilePath, d));
  275. }
  276. else
  277. {
  278. ALOGE("decode (%s) failed!", audioFilePath.c_str());
  279. }
  280. ALOGV("decode %s", (ret ? "succeed" : "failed"));
  281. std::lock_guard<std::mutex> lk(_preloadCallbackMutex);
  282. auto&& preloadIter = _preloadCallbackMap.find(audioFilePath);
  283. if (preloadIter != _preloadCallbackMap.end())
  284. {
  285. auto&& params = preloadIter->second;
  286. ALOGV("preload (%s) callback count: %d", audioFilePath.c_str(), (int)params.size());
  287. PcmData result = decoder->getResult();
  288. for (auto&& param : params)
  289. {
  290. param.callback(ret, result);
  291. if (param.isPreloadInPlay2d)
  292. {
  293. _preloadWaitCond.notify_one();
  294. }
  295. }
  296. _preloadCallbackMap.erase(preloadIter);
  297. }
  298. AudioDecoderProvider::destroyAudioDecoder(&decoder);
  299. });
  300. }
  301. else
  302. {
  303. ALOGV("File (%s) is too large, ignore preload!", info.url.c_str());
  304. cb(true, pcmData);
  305. }
  306. }
  307. AudioPlayerProvider::AudioFileInfo AudioPlayerProvider::getFileInfo(
  308. const std::string &audioFilePath)
  309. {
  310. AudioFileInfo info;
  311. long fileSize = 0;
  312. off_t start = 0, length = 0;
  313. int assetFd = -1;
  314. if (audioFilePath[0] != '/')
  315. {
  316. std::string relativePath;
  317. size_t position = audioFilePath.find("assets/");
  318. if (0 == position)
  319. {
  320. // "assets/" is at the beginning of the path and we don't want it
  321. relativePath = audioFilePath.substr(strlen("assets/"));
  322. }
  323. else
  324. {
  325. relativePath = audioFilePath;
  326. }
  327. assetFd = _fdGetterCallback(relativePath, &start, &length);
  328. if (assetFd <= 0)
  329. {
  330. ALOGE("Failed to open file descriptor for '%s'", audioFilePath.c_str());
  331. return info;
  332. }
  333. fileSize = length;
  334. }
  335. else
  336. {
  337. FILE *fp = fopen(audioFilePath.c_str(), "rb");
  338. if (fp != nullptr)
  339. {
  340. fseek(fp, 0, SEEK_END);
  341. fileSize = ftell(fp);
  342. fclose(fp);
  343. }
  344. else
  345. {
  346. return info;
  347. }
  348. }
  349. info.url = audioFilePath;
  350. info.assetFd = std::make_shared<AssetFd>(assetFd);
  351. info.start = start;
  352. info.length = fileSize;
  353. ALOGV("(%s) file size: %ld", audioFilePath.c_str(), fileSize);
  354. return info;
  355. }
  356. bool AudioPlayerProvider::isSmallFile(const AudioFileInfo &info)
  357. {
  358. //TODO: If file size is smaller than 100k, we think it's a small file. This value should be set by developers.
  359. AudioFileInfo &audioFileInfo = const_cast<AudioFileInfo &>(info);
  360. size_t judgeCount = sizeof(__audioFileIndicator) / sizeof(__audioFileIndicator[0]);
  361. size_t pos = audioFileInfo.url.rfind(".");
  362. std::string extension;
  363. if (pos != std::string::npos)
  364. {
  365. extension = audioFileInfo.url.substr(pos);
  366. }
  367. auto iter = std::find_if(std::begin(__audioFileIndicator), std::end(__audioFileIndicator),
  368. [&extension](const AudioFileIndicator &judge) -> bool {
  369. return judge.extension == extension;
  370. });
  371. if (iter != std::end(__audioFileIndicator))
  372. {
  373. // ALOGV("isSmallFile: found: %s: ", iter->extension.c_str());
  374. return info.length < iter->smallSizeIndicator;
  375. }
  376. // ALOGV("isSmallFile: not found return default value");
  377. return info.length < __audioFileIndicator[0].smallSizeIndicator;
  378. }
  379. void AudioPlayerProvider::clearPcmCache(const std::string &audioFilePath)
  380. {
  381. std::lock_guard<std::mutex> lk(_pcmCacheMutex);
  382. auto iter = _pcmCache.find(audioFilePath);
  383. if (iter != _pcmCache.end())
  384. {
  385. ALOGV("clear pcm cache: (%s)", audioFilePath.c_str());
  386. _pcmCache.erase(iter);
  387. }
  388. else
  389. {
  390. ALOGW("Couldn't find the pcm cache: (%s)", audioFilePath.c_str());
  391. }
  392. }
  393. void AudioPlayerProvider::clearAllPcmCaches()
  394. {
  395. std::lock_guard<std::mutex> lk(_pcmCacheMutex);
  396. _pcmCache.clear();
  397. }
  398. PcmAudioPlayer *AudioPlayerProvider::obtainPcmAudioPlayer(const std::string &url,
  399. const PcmData &pcmData)
  400. {
  401. PcmAudioPlayer *pcmPlayer = nullptr;
  402. if (pcmData.isValid())
  403. {
  404. pcmPlayer = new(std::nothrow) PcmAudioPlayer(_mixController, _callerThreadUtils);
  405. if (pcmPlayer != nullptr)
  406. {
  407. pcmPlayer->prepare(url, pcmData);
  408. }
  409. }
  410. else
  411. {
  412. ALOGE("obtainPcmAudioPlayer failed, pcmData isn't valid!");
  413. }
  414. return pcmPlayer;
  415. }
  416. UrlAudioPlayer *AudioPlayerProvider::createUrlAudioPlayer(
  417. const AudioPlayerProvider::AudioFileInfo &info)
  418. {
  419. if (info.url.empty())
  420. {
  421. ALOGE("createUrlAudioPlayer failed, url is empty!");
  422. return nullptr;
  423. }
  424. SLuint32 locatorType = info.assetFd->getFd() > 0 ? SL_DATALOCATOR_ANDROIDFD : SL_DATALOCATOR_URI;
  425. auto urlPlayer = new (std::nothrow) UrlAudioPlayer(_engineItf, _outputMixObject, _callerThreadUtils);
  426. bool ret = urlPlayer->prepare(info.url, locatorType, info.assetFd, info.start, info.length);
  427. if (!ret)
  428. {
  429. SL_SAFE_DELETE(urlPlayer);
  430. }
  431. return urlPlayer;
  432. }
  433. void AudioPlayerProvider::pause()
  434. {
  435. if (_mixController != nullptr)
  436. {
  437. _mixController->pause();
  438. }
  439. if (_pcmAudioService != nullptr)
  440. {
  441. _pcmAudioService->pause();
  442. }
  443. }
  444. void AudioPlayerProvider::resume()
  445. {
  446. if (_mixController != nullptr)
  447. {
  448. _mixController->resume();
  449. }
  450. if (_pcmAudioService != nullptr)
  451. {
  452. _pcmAudioService->resume();
  453. }
  454. }
  455. }} // namespace cocos2d { namespace experimental {