AudioCache.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. #define LOG_TAG "AudioCache"
  21. #include "platform/CCPlatformConfig.h"
  22. #if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
  23. #include "audio/win32/AudioCache.h"
  24. #include <thread>
  25. #include "base/CCDirector.h"
  26. #include "base/CCScheduler.h"
  27. #include "audio/win32/AudioDecoderManager.h"
  28. #include "audio/win32/AudioDecoder.h"
  29. #define VERY_VERY_VERBOSE_LOGGING
  30. #ifdef VERY_VERY_VERBOSE_LOGGING
  31. #define ALOGVV ALOGV
  32. #else
  33. #define ALOGVV(...) do{} while(false)
  34. #endif
  35. namespace {
  36. unsigned int __idIndex = 0;
  37. }
  38. #define INVALID_AL_BUFFER_ID 0xFFFFFFFF
  39. #define PCMDATA_CACHEMAXSIZE 1048576
  40. using namespace cocos2d;
  41. using namespace cocos2d::experimental;
  42. AudioCache::AudioCache()
  43. : _totalFrames(0)
  44. , _framesRead(0)
  45. , _format(-1)
  46. , _duration(0.0f)
  47. , _alBufferId(INVALID_AL_BUFFER_ID)
  48. , _pcmData(nullptr)
  49. , _queBufferFrames(0)
  50. , _state(State::INITIAL)
  51. , _isDestroyed(std::make_shared<bool>(false))
  52. , _id(++__idIndex)
  53. , _isLoadingFinished(false)
  54. , _isSkipReadDataTask(false)
  55. {
  56. ALOGVV("AudioCache() %p, id=%u", this, _id);
  57. for (int i = 0; i < QUEUEBUFFER_NUM; ++i)
  58. {
  59. _queBuffers[i] = nullptr;
  60. _queBufferSize[i] = 0;
  61. }
  62. }
  63. AudioCache::~AudioCache()
  64. {
  65. ALOGVV("~AudioCache() %p, id=%u, begin", this, _id);
  66. *_isDestroyed = true;
  67. while (!_isLoadingFinished)
  68. {
  69. if (_isSkipReadDataTask)
  70. {
  71. ALOGV("id=%u, Skip read data task, don't continue to wait!", _id);
  72. break;
  73. }
  74. ALOGVV("id=%u, waiting readData thread to finish ...", _id);
  75. std::this_thread::sleep_for(std::chrono::milliseconds(5));
  76. }
  77. //wait for the 'readDataTask' task to exit
  78. _readDataTaskMutex.lock();
  79. _readDataTaskMutex.unlock();
  80. if (_pcmData)
  81. {
  82. if (_state == State::READY)
  83. {
  84. if (_alBufferId != INVALID_AL_BUFFER_ID && alIsBuffer(_alBufferId))
  85. {
  86. ALOGV("~AudioCache(id=%u), delete buffer: %u", _id, _alBufferId);
  87. alDeleteBuffers(1, &_alBufferId);
  88. _alBufferId = INVALID_AL_BUFFER_ID;
  89. }
  90. }
  91. else
  92. {
  93. ALOGW("AudioCache (%p), id=%u, buffer isn't ready, state=%d", this, _id, _state);
  94. }
  95. free(_pcmData);
  96. }
  97. if (_queBufferFrames > 0)
  98. {
  99. for (int index = 0; index < QUEUEBUFFER_NUM; ++index)
  100. {
  101. free(_queBuffers[index]);
  102. }
  103. }
  104. ALOGVV("~AudioCache() %p, id=%u, end", this, _id);
  105. }
  106. void AudioCache::readDataTask(unsigned int selfId)
  107. {
  108. //Note: It's in sub thread
  109. ALOGVV("readDataTask begin, cache id=%u", selfId);
  110. _readDataTaskMutex.lock();
  111. _state = State::LOADING;
  112. AudioDecoder* decoder = AudioDecoderManager::createDecoder(_fileFullPath.c_str());
  113. do
  114. {
  115. if (decoder == nullptr || !decoder->open(_fileFullPath.c_str()))
  116. break;
  117. const uint32_t originalTotalFrames = decoder->getTotalFrames();
  118. const uint32_t bytesPerFrame = decoder->getBytesPerFrame();
  119. const uint32_t sampleRate = decoder->getSampleRate();
  120. const uint32_t channelCount = decoder->getChannelCount();
  121. uint32_t totalFrames = originalTotalFrames;
  122. uint32_t dataSize = totalFrames * bytesPerFrame;
  123. uint32_t remainingFrames = totalFrames;
  124. uint32_t adjustFrames = 0;
  125. _format = channelCount > 1 ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16;
  126. _sampleRate = (ALsizei)sampleRate;
  127. _duration = 1.0f * totalFrames / sampleRate;
  128. _totalFrames = totalFrames;
  129. if (dataSize <= PCMDATA_CACHEMAXSIZE)
  130. {
  131. uint32_t framesRead = 0;
  132. const uint32_t framesToReadOnce = std::min(totalFrames, static_cast<uint32_t>(sampleRate * QUEUEBUFFER_TIME_STEP * QUEUEBUFFER_NUM));
  133. std::vector<char> adjustFrameBuf;
  134. if (decoder->seek(totalFrames))
  135. {
  136. char* tmpBuf = (char*)malloc(framesToReadOnce * bytesPerFrame);
  137. adjustFrameBuf.reserve(framesToReadOnce * bytesPerFrame);
  138. // Adjust total frames by setting position to the end of frames and try to read more data.
  139. // This is a workaround for https://github.com/cocos2d/cocos2d-x/issues/16938
  140. do
  141. {
  142. framesRead = decoder->read(framesToReadOnce, tmpBuf);
  143. if (framesRead > 0)
  144. {
  145. adjustFrames += framesRead;
  146. adjustFrameBuf.insert(adjustFrameBuf.end(), tmpBuf, tmpBuf + framesRead * bytesPerFrame);
  147. }
  148. } while (framesRead > 0);
  149. if (adjustFrames > 0)
  150. {
  151. ALOGV("Orignal total frames: %u, adjust frames: %u, current total frames: %u", totalFrames, adjustFrames, totalFrames + adjustFrames);
  152. totalFrames += adjustFrames;
  153. _totalFrames = remainingFrames = totalFrames;
  154. }
  155. // Reset dataSize
  156. dataSize = totalFrames * bytesPerFrame;
  157. free(tmpBuf);
  158. }
  159. // Reset to frame 0
  160. BREAK_IF_ERR_LOG(!decoder->seek(0), "AudioDecoder::seek(0) failed!");
  161. _pcmData = (char*)malloc(dataSize);
  162. memset(_pcmData, 0x00, dataSize);
  163. if (adjustFrames > 0)
  164. {
  165. memcpy(_pcmData + (dataSize - adjustFrameBuf.size()), adjustFrameBuf.data(), adjustFrameBuf.size());
  166. }
  167. alGenBuffers(1, &_alBufferId);
  168. auto alError = alGetError();
  169. if (alError != AL_NO_ERROR) {
  170. ALOGE("%s: attaching audio to buffer fail: %x", __FUNCTION__, alError);
  171. break;
  172. }
  173. if (*_isDestroyed)
  174. break;
  175. framesRead = decoder->readFixedFrames(std::min(framesToReadOnce, remainingFrames), _pcmData + _framesRead * bytesPerFrame);
  176. _framesRead += framesRead;
  177. remainingFrames -= framesRead;
  178. if (*_isDestroyed)
  179. break;
  180. uint32_t frames = 0;
  181. while (!*_isDestroyed && _framesRead < originalTotalFrames)
  182. {
  183. frames = std::min(framesToReadOnce, remainingFrames);
  184. if (_framesRead + frames > originalTotalFrames)
  185. {
  186. frames = originalTotalFrames - _framesRead;
  187. }
  188. framesRead = decoder->read(frames, _pcmData + _framesRead * bytesPerFrame);
  189. if (framesRead == 0)
  190. break;
  191. _framesRead += framesRead;
  192. remainingFrames -= framesRead;
  193. }
  194. if (*_isDestroyed)
  195. break;
  196. if (_framesRead < originalTotalFrames)
  197. {
  198. memset(_pcmData + _framesRead * bytesPerFrame, 0x00, (totalFrames - _framesRead) * bytesPerFrame);
  199. }
  200. ALOGV("pcm buffer was loaded successfully, total frames: %u, total read frames: %u, adjust frames: %u, remainingFrames: %u", totalFrames, _framesRead, adjustFrames, remainingFrames);
  201. _framesRead += adjustFrames;
  202. alBufferData(_alBufferId, _format, _pcmData, (ALsizei)dataSize, (ALsizei)sampleRate);
  203. _state = State::READY;
  204. }
  205. else
  206. {
  207. _queBufferFrames = sampleRate * QUEUEBUFFER_TIME_STEP;
  208. BREAK_IF_ERR_LOG(_queBufferFrames == 0, "_queBufferFrames == 0");
  209. const uint32_t queBufferBytes = _queBufferFrames * bytesPerFrame;
  210. for (int index = 0; index < QUEUEBUFFER_NUM; ++index)
  211. {
  212. _queBuffers[index] = (char*)malloc(queBufferBytes);
  213. _queBufferSize[index] = queBufferBytes;
  214. decoder->readFixedFrames(_queBufferFrames, _queBuffers[index]);
  215. }
  216. _state = State::READY;
  217. }
  218. } while (false);
  219. if (decoder != nullptr)
  220. {
  221. decoder->close();
  222. }
  223. AudioDecoderManager::destroyDecoder(decoder);
  224. if (_state != State::READY)
  225. {
  226. _state = State::FAILED;
  227. if (_alBufferId != INVALID_AL_BUFFER_ID && alIsBuffer(_alBufferId))
  228. {
  229. ALOGV("readDataTask failed, delete buffer: %u", _alBufferId);
  230. alDeleteBuffers(1, &_alBufferId);
  231. _alBufferId = INVALID_AL_BUFFER_ID;
  232. }
  233. }
  234. //FIXME: Why to invoke play callback first? Should it be after 'load' callback?
  235. invokingPlayCallbacks();
  236. invokingLoadCallbacks();
  237. _isLoadingFinished = true;
  238. _readDataTaskMutex.unlock();
  239. ALOGVV("readDataTask end, cache id=%u", selfId);
  240. }
  241. void AudioCache::addPlayCallback(const std::function<void()>& callback)
  242. {
  243. std::lock_guard<std::mutex> lk(_playCallbackMutex);
  244. switch (_state)
  245. {
  246. case State::INITIAL:
  247. case State::LOADING:
  248. _playCallbacks.push_back(callback);
  249. break;
  250. case State::READY:
  251. // If state is failure, we still need to invoke the callback
  252. // since the callback will set the 'AudioPlayer::_removeByAudioEngine' flag to true.
  253. case State::FAILED:
  254. callback();
  255. break;
  256. default:
  257. ALOGE("Invalid state: %d", _state);
  258. break;
  259. }
  260. }
  261. void AudioCache::invokingPlayCallbacks()
  262. {
  263. std::lock_guard<std::mutex> lk(_playCallbackMutex);
  264. for (auto&& cb : _playCallbacks)
  265. {
  266. cb();
  267. }
  268. _playCallbacks.clear();
  269. }
  270. void AudioCache::addLoadCallback(const std::function<void(bool)>& callback)
  271. {
  272. switch (_state)
  273. {
  274. case State::INITIAL:
  275. case State::LOADING:
  276. _loadCallbacks.push_back(callback);
  277. break;
  278. case State::READY:
  279. callback(true);
  280. break;
  281. case State::FAILED:
  282. callback(false);
  283. break;
  284. default:
  285. ALOGE("Invalid state: %d", _state);
  286. break;
  287. }
  288. }
  289. void AudioCache::invokingLoadCallbacks()
  290. {
  291. if (*_isDestroyed)
  292. {
  293. ALOGV("AudioCache (%p) was destroyed, don't invoke preload callback ...", this);
  294. return;
  295. }
  296. auto isDestroyed = _isDestroyed;
  297. auto scheduler = Director::getInstance()->getScheduler();
  298. scheduler->performFunctionInCocosThread([&, isDestroyed](){
  299. if (*isDestroyed)
  300. {
  301. ALOGV("invokingLoadCallbacks perform in cocos thread, AudioCache (%p) was destroyed!", this);
  302. return;
  303. }
  304. for (auto&& cb : _loadCallbacks)
  305. {
  306. cb(_state == State::READY);
  307. }
  308. _loadCallbacks.clear();
  309. });
  310. }
  311. #endif