AudioCachePlayer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. /*
  2. * cocos2d-x http://www.cocos2d-x.org
  3. *
  4. * Copyright (c) 2010-2011 - cocos2d-x community
  5. * Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  6. *
  7. * Portions Copyright (c) Microsoft Open Technologies, Inc.
  8. * All Rights Reserved
  9. *
  10. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
  11. * You may obtain a copy of the License at
  12. *
  13. * http://www.apache.org/licenses/LICENSE-2.0
  14. *
  15. * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
  16. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. * See the License for the specific language governing permissions and limitations under the License.
  18. */
  19. #include "platform/CCPlatformConfig.h"
  20. #if CC_TARGET_PLATFORM == CC_PLATFORM_WINRT
  21. #include "audio/winrt/AudioCachePlayer.h"
  22. #include "base/CCDirector.h"
  23. #include "base/CCScheduler.h"
  24. using namespace cocos2d;
  25. using namespace cocos2d::experimental;
  26. inline void ThrowIfFailed(HRESULT hr)
  27. {
  28. if (FAILED(hr)) {
  29. // Set a breakpoint on this line to catch XAudio2 API errors.
  30. throw Platform::Exception::CreateException(hr);
  31. }
  32. }
  33. // AudioCache
  34. AudioCache::AudioCache()
  35. : _isReady(false)
  36. , _retry(false)
  37. , _fileFullPath("")
  38. , _srcReader(nullptr)
  39. , _fileFormat(FileFormat::UNKNOWN)
  40. {
  41. _callbacks.clear();
  42. memset(&_audInfo, 0, sizeof(AudioInfo));
  43. }
  44. AudioCache::~AudioCache()
  45. {
  46. _callbacks.clear();
  47. if (nullptr != _srcReader) {
  48. delete _srcReader;
  49. _srcReader = nullptr;
  50. }
  51. }
  52. void AudioCache::readDataTask()
  53. {
  54. if (_isReady) {
  55. return;
  56. }
  57. if (nullptr != _srcReader) {
  58. delete _srcReader;
  59. _srcReader = nullptr;
  60. }
  61. switch (_fileFormat)
  62. {
  63. case FileFormat::WAV:
  64. _srcReader = new (std::nothrow) WAVReader();
  65. break;
  66. case FileFormat::OGG:
  67. _srcReader = new (std::nothrow) OGGReader();
  68. break;
  69. case FileFormat::MP3:
  70. _srcReader = new (std::nothrow) MP3Reader();
  71. break;
  72. case FileFormat::UNKNOWN:
  73. default:
  74. break;
  75. }
  76. if (_srcReader && _srcReader->initialize(_fileFullPath)) {
  77. _audInfo._totalAudioBytes = _srcReader->getTotalAudioBytes();
  78. _audInfo._wfx = _srcReader->getWaveFormatInfo();
  79. _isReady = true;
  80. _retry = false;
  81. invokePlayCallbacks();
  82. }
  83. if (!_isReady) {
  84. _retry = true;
  85. log("Failed to read input file: %s.\n", _fileFullPath.c_str());
  86. }
  87. invokeLoadCallbacks();
  88. }
  89. void AudioCache::addPlayCallback(const std::function<void()> &callback)
  90. {
  91. _cbMutex.lock();
  92. if (_isReady) {
  93. callback();
  94. }
  95. else {
  96. _callbacks.push_back(callback);
  97. }
  98. _cbMutex.unlock();
  99. if (_retry) {
  100. readDataTask();
  101. }
  102. }
  103. void AudioCache::addLoadCallback(const std::function<void(bool)> &callback)
  104. {
  105. if (_isReady) {
  106. callback(true);
  107. }
  108. else {
  109. _loadCallbacks.push_back(callback);
  110. }
  111. if (_retry) {
  112. readDataTask();
  113. }
  114. }
  115. void AudioCache::invokePlayCallbacks()
  116. {
  117. _cbMutex.lock();
  118. auto cnt = _callbacks.size();
  119. for (size_t ind = 0; ind < cnt; ind++)
  120. {
  121. _callbacks[ind]();
  122. }
  123. _callbacks.clear();
  124. _cbMutex.unlock();
  125. }
  126. void AudioCache::invokeLoadCallbacks()
  127. {
  128. auto scheduler = Director::getInstance()->getScheduler();
  129. scheduler->performFunctionInCocosThread([&](){
  130. auto cnt = _loadCallbacks.size();
  131. for (size_t ind = 0; ind < cnt; ind++)
  132. {
  133. _loadCallbacks[ind](_isReady);
  134. }
  135. _loadCallbacks.clear();
  136. });
  137. }
  138. bool AudioCache::getChunk(AudioDataChunk& chunk)
  139. {
  140. bool ret = false;
  141. if (nullptr != _srcReader) {
  142. ret = _srcReader->consumeChunk(chunk);
  143. }
  144. return ret;
  145. }
  146. void AudioCache::doBuffering()
  147. {
  148. if (isStreamingSource()){
  149. _srcReader->produceChunk();
  150. }
  151. }
  152. bool AudioCache::isStreamingSource()
  153. {
  154. if (nullptr != _srcReader) {
  155. return _srcReader->isStreamingSource();
  156. }
  157. return false;
  158. }
  159. void AudioCache::seek(const float ratio)
  160. {
  161. if (nullptr != _srcReader){
  162. _srcReader->seekTo(ratio);
  163. }
  164. }
  165. // AudioPlayer
  166. AudioPlayer::AudioPlayer()
  167. : _loop(false)
  168. , _ready(false)
  169. , _current(0.0)
  170. , _volume(0.0)
  171. , _duration(0.0)
  172. , _cache(nullptr)
  173. , _totalSamples(0)
  174. , _samplesOffset(0)
  175. , _criticalError(false)
  176. , _isStreaming(false)
  177. , _finishCallback(nullptr)
  178. , _xaMasterVoice(nullptr)
  179. , _xaSourceVoice(nullptr)
  180. , _state(AudioPlayerState::INITIALIZING)
  181. {
  182. init();
  183. }
  184. AudioPlayer::~AudioPlayer()
  185. {
  186. free();
  187. }
  188. void AudioPlayer::stop()
  189. {
  190. _stop();
  191. }
  192. void AudioPlayer::pause()
  193. {
  194. _stop(true);
  195. }
  196. bool AudioPlayer::update()
  197. {
  198. if (_criticalError){
  199. free();
  200. init();
  201. }
  202. if (_cache != nullptr) {
  203. _cache->doBuffering();
  204. }
  205. //log("bufferQueued: %d, _current: %f", _cachedBufferQ.size(), _current);
  206. return _criticalError;
  207. }
  208. void AudioPlayer::resume()
  209. {
  210. _play(true);
  211. }
  212. bool AudioPlayer::isInError()
  213. {
  214. return _criticalError;
  215. }
  216. float AudioPlayer::getDuration()
  217. {
  218. if (nullptr == _cache) {
  219. return _duration;
  220. }
  221. auto fmt = _cache->_audInfo._wfx;
  222. if (!fmt.nChannels) {
  223. return _duration;
  224. }
  225. if ((int)_duration <= 0)
  226. {
  227. switch (fmt.wFormatTag)
  228. {
  229. case WAVE_FORMAT_PCM:
  230. case WAVE_FORMAT_ADPCM:
  231. _duration = (float(_cache->_audInfo._totalAudioBytes / ((fmt.wBitsPerSample / 8) * fmt.nChannels)) / fmt.nSamplesPerSec) * 1000;
  232. _totalSamples = fmt.nSamplesPerSec * _duration / 1000;
  233. break;
  234. default:
  235. break;
  236. }
  237. }
  238. return _duration;
  239. }
  240. float AudioPlayer::getCurrentTime()
  241. {
  242. _stMutex.lock();
  243. auto samplesPlayed = getSourceVoiceState().SamplesPlayed;
  244. //log("_samplesOffset: %lu, samplesPlayed: %lu, _current: %f", (UINT32)_samplesOffset, (UINT32)samplesPlayed, _current);
  245. _current += ((samplesPlayed - _samplesOffset) / (float)_totalSamples) * _duration;
  246. _current = _current > _duration ? 0.0 : _current;
  247. _samplesOffset = samplesPlayed;
  248. _stMutex.unlock();
  249. return _current;
  250. }
  251. bool AudioPlayer::setTime(float time)
  252. {
  253. bool ret = true;
  254. _stop();
  255. if (!_isStreaming) {
  256. auto fmt = _cache->_audInfo._wfx;
  257. int seek = (time / _duration) * _totalSamples;
  258. seek -= (seek % (fmt.nChannels * fmt.nBlockAlign));
  259. _xaBuffer.LoopCount = 0;
  260. _xaBuffer.PlayBegin = seek;
  261. _xaBuffer.PlayLength = _totalSamples - seek;
  262. if (_xaBuffer.PlayBegin >= _totalSamples) {
  263. _xaBuffer.PlayBegin = _totalSamples - (fmt.nChannels * fmt.nBlockAlign);
  264. _xaBuffer.PlayLength = (fmt.nChannels * fmt.nBlockAlign);
  265. }
  266. }
  267. _stMutex.lock();
  268. _samplesOffset = getSourceVoiceState().SamplesPlayed;
  269. _current = time;
  270. _stMutex.unlock();
  271. _play();
  272. return ret;
  273. }
  274. void AudioPlayer::setVolume(float volume)
  275. {
  276. if (_xaMasterVoice != nullptr){
  277. if (FAILED(_xaMasterVoice->SetVolume(volume))) {
  278. error();
  279. }
  280. else {
  281. _volume = volume;
  282. }
  283. }
  284. }
  285. bool AudioPlayer::play2d(AudioCache* cache)
  286. {
  287. bool ret = false;
  288. HRESULT hr = S_OK;
  289. if (cache != nullptr)
  290. {
  291. _cache = cache;
  292. if (nullptr == _xaSourceVoice && _ready) {
  293. XAUDIO2_SEND_DESCRIPTOR descriptors[1];
  294. descriptors[0].pOutputVoice = _xaMasterVoice;
  295. descriptors[0].Flags = 0;
  296. XAUDIO2_VOICE_SENDS sends = { 0 };
  297. sends.SendCount = 1;
  298. sends.pSends = descriptors;
  299. hr = _xaEngine->CreateSourceVoice(&_xaSourceVoice, &cache->_audInfo._wfx, 0, 1.0, this, &sends);
  300. }
  301. if (SUCCEEDED(hr)) {
  302. _isStreaming = _cache->isStreamingSource();
  303. _duration = getDuration();
  304. ret = _play();
  305. }
  306. else {
  307. error();
  308. }
  309. }
  310. return ret;
  311. }
  312. void AudioPlayer::init()
  313. {
  314. do {
  315. memset(&_xaBuffer, 0, sizeof(_xaBuffer));
  316. if (FAILED(XAudio2Create(_xaEngine.ReleaseAndGetAddressOf()))) {
  317. error();
  318. break;
  319. }
  320. #if defined(_DEBUG)
  321. XAUDIO2_DEBUG_CONFIGURATION debugConfig = { 0 };
  322. debugConfig.BreakMask = XAUDIO2_LOG_ERRORS;
  323. debugConfig.TraceMask = XAUDIO2_LOG_ERRORS;
  324. _xaEngine->SetDebugConfiguration(&debugConfig);
  325. #endif
  326. _xaEngine->RegisterForCallbacks(this);
  327. if (FAILED(_xaEngine->CreateMasteringVoice(&_xaMasterVoice, XAUDIO2_DEFAULT_CHANNELS, XAUDIO2_DEFAULT_SAMPLERATE, 0, nullptr, nullptr, AudioCategory_GameMedia))) {
  328. error();
  329. break;
  330. }
  331. _ready = true;
  332. _state = AudioPlayerState::READY;
  333. } while (false);
  334. }
  335. void AudioPlayer::free()
  336. {
  337. _ready = false;
  338. _stop();
  339. memset(&_xaBuffer, 0, sizeof(_xaBuffer));
  340. if (_xaEngine) {
  341. _xaEngine->UnregisterForCallbacks(this);
  342. _xaEngine->StopEngine();
  343. }
  344. if (_xaSourceVoice != nullptr) {
  345. _xaSourceVoice->DestroyVoice();
  346. _xaSourceVoice = nullptr;
  347. }
  348. if (_xaMasterVoice != nullptr) {
  349. _xaMasterVoice->DestroyVoice();
  350. _xaMasterVoice = nullptr;
  351. }
  352. while (!_cachedBufferQ.empty()) {
  353. popBuffer();
  354. }
  355. }
  356. bool AudioPlayer::_play(bool resume)
  357. {
  358. do {
  359. if (!resume) {
  360. _cache->seek(_current / _duration);
  361. submitBuffers();
  362. }
  363. if (_state == AudioPlayerState::PAUSED && !resume || nullptr == _xaSourceVoice) break;
  364. if (FAILED(_xaMasterVoice->SetVolume(_volume)) || FAILED(_xaSourceVoice->Start())) {
  365. error();
  366. }
  367. else {
  368. _state = AudioPlayerState::PLAYING;
  369. }
  370. } while (false);
  371. return !_criticalError;
  372. }
  373. void AudioPlayer::_stop(bool pause)
  374. {
  375. if (_xaSourceVoice != nullptr) {
  376. if (FAILED(_xaSourceVoice->Stop())) {
  377. error();
  378. }
  379. else {
  380. if (!pause) {
  381. _xaSourceVoice->FlushSourceBuffers();
  382. if (_state != AudioPlayerState::PAUSED) _state = AudioPlayerState::STOPPED;
  383. }
  384. else {
  385. _state = AudioPlayerState::PAUSED;
  386. }
  387. }
  388. }
  389. }
  390. void AudioPlayer::error()
  391. {
  392. _criticalError = true;
  393. _ready = false;
  394. _state = AudioPlayerState::ERRORED;
  395. CCLOG("Audio system encountered error.");
  396. }
  397. void AudioPlayer::popBuffer()
  398. {
  399. _bqMutex.lock();
  400. if (!_cachedBufferQ.empty()) {
  401. _cachedBufferQ.pop();
  402. }
  403. _bqMutex.unlock();
  404. }
  405. bool AudioPlayer::submitBuffers()
  406. {
  407. bool ret = false;
  408. _bqMutex.lock();
  409. do {
  410. if (nullptr == _xaSourceVoice) break;
  411. if (!_cachedBufferQ.size() || (_isStreaming && _cachedBufferQ.size() < QUEUEBUFFER_NUM)) {
  412. AudioDataChunk chunk;
  413. if (_cache->getChunk(chunk) && chunk._dataSize) {
  414. _xaBuffer.AudioBytes = static_cast<UINT32>(chunk._dataSize);
  415. _xaBuffer.pAudioData = chunk._data->data();
  416. _xaBuffer.Flags = chunk._endOfStream ? XAUDIO2_END_OF_STREAM : 0;
  417. _cachedBufferQ.push(chunk);
  418. ret = SUCCEEDED(_xaSourceVoice->SubmitSourceBuffer(&_xaBuffer));
  419. if (!_isStreaming) break;
  420. }
  421. else {
  422. break;
  423. }
  424. }
  425. else if (!_isStreaming) {
  426. ret = SUCCEEDED(_xaSourceVoice->SubmitSourceBuffer(&_xaBuffer));
  427. break;
  428. }
  429. else {
  430. break;
  431. }
  432. } while (ret);
  433. _bqMutex.unlock();
  434. return ret;
  435. }
  436. void AudioPlayer::updateState()
  437. {
  438. if (!_isStreaming) {
  439. _stMutex.lock();
  440. _samplesOffset = getSourceVoiceState().SamplesPlayed;
  441. _stMutex.unlock();
  442. }
  443. else {
  444. if (_cachedBufferQ.size() > getSourceVoiceState(true).BuffersQueued) {
  445. popBuffer();
  446. }
  447. }
  448. }
  449. void AudioPlayer::onBufferRunOut()
  450. {
  451. _stMutex.lock();
  452. _samplesOffset = 0;
  453. _current = 0.0;
  454. _xaBuffer.PlayBegin = _xaBuffer.PlayLength = 0;
  455. _stMutex.unlock();
  456. if (!_loop) {
  457. _stop();
  458. //invokeFinishCallback();
  459. }
  460. else {
  461. _play();
  462. }
  463. }
  464. void AudioPlayer::invokeFinishCallback()
  465. {
  466. if (_finishCallback) {
  467. _finishCallback(0, "");
  468. }
  469. }
  470. XAUDIO2_VOICE_STATE AudioPlayer::getSourceVoiceState(bool fast)
  471. {
  472. XAUDIO2_VOICE_STATE state;
  473. memset(&state, 0, sizeof(XAUDIO2_VOICE_STATE));
  474. if (_xaSourceVoice != nullptr) {
  475. _xaSourceVoice->GetState(&state, fast ? XAUDIO2_VOICE_NOSAMPLESPLAYED : 0);
  476. }
  477. return state;
  478. }
  479. // IXAudio2EngineCallback
  480. void AudioPlayer::OnProcessingPassStart()
  481. {
  482. }
  483. void AudioPlayer::OnProcessingPassEnd()
  484. {
  485. }
  486. void AudioPlayer::OnCriticalError(HRESULT err)
  487. {
  488. UNREFERENCED_PARAMETER(err);
  489. if (_ready) {
  490. error();
  491. }
  492. }
  493. // IXAudio2VoiceCallback
  494. void AudioPlayer::OnVoiceProcessingPassStart(UINT32 uBytesRequired)
  495. {
  496. if (_ready && uBytesRequired && _isStreaming){
  497. submitBuffers();
  498. }
  499. }
  500. void AudioPlayer::OnVoiceProcessingPassEnd()
  501. {
  502. }
  503. void AudioPlayer::OnStreamEnd()
  504. {
  505. if (_ready) {
  506. onBufferRunOut();
  507. }
  508. }
  509. void AudioPlayer::OnBufferStart(void* pBufferContext)
  510. {
  511. UNREFERENCED_PARAMETER(pBufferContext);
  512. }
  513. void AudioPlayer::OnBufferEnd(void* pBufferContext)
  514. {
  515. UNREFERENCED_PARAMETER(pBufferContext);
  516. if (_ready) {
  517. updateState();
  518. }
  519. }
  520. void AudioPlayer::OnLoopEnd(void* pBufferContext)
  521. {
  522. UNREFERENCED_PARAMETER(pBufferContext);
  523. if (_ready && !_loop) {
  524. _stop();
  525. }
  526. }
  527. void AudioPlayer::OnVoiceError(void* pBufferContext, HRESULT err)
  528. {
  529. UNREFERENCED_PARAMETER(pBufferContext);
  530. UNREFERENCED_PARAMETER(err);
  531. if (_ready) {
  532. error();
  533. }
  534. }
  535. #endif