AudioPlayerProvider.cpp 18 KB

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