AudioEngine-win32.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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 "AudioEngine-Win32"
  21. #include "platform/CCPlatformConfig.h"
  22. #if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
  23. #include "audio/win32/AudioEngine-win32.h"
  24. #ifdef OPENAL_PLAIN_INCLUDES
  25. #include "alc.h"
  26. #include "alext.h"
  27. #else
  28. #include "AL/alc.h"
  29. #include "AL/alext.h"
  30. #endif
  31. #include "audio/include/AudioEngine.h"
  32. #include "base/CCDirector.h"
  33. #include "base/CCScheduler.h"
  34. #include "platform/CCFileUtils.h"
  35. #include "audio/win32/AudioDecoderManager.h"
  36. #include <windows.h>
  37. // log, CCLOG aren't threadsafe, since we uses sub threads for parsing pcm data, threadsafe log output
  38. // is needed. Define the following macros (ALOGV, ALOGD, ALOGI, ALOGW, ALOGE) for threadsafe log output.
  39. //FIXME: Move _winLog, winLog to a separated file
  40. static void _winLog(const char *format, va_list args)
  41. {
  42. static const int MAX_LOG_LENGTH = 16 * 1024;
  43. int bufferSize = MAX_LOG_LENGTH;
  44. char* buf = nullptr;
  45. do
  46. {
  47. buf = new (std::nothrow) char[bufferSize];
  48. if (buf == nullptr)
  49. return; // not enough memory
  50. int ret = vsnprintf(buf, bufferSize - 3, format, args);
  51. if (ret < 0)
  52. {
  53. bufferSize *= 2;
  54. delete[] buf;
  55. }
  56. else
  57. break;
  58. } while (true);
  59. strcat(buf, "\n");
  60. int pos = 0;
  61. int len = strlen(buf);
  62. char tempBuf[MAX_LOG_LENGTH + 1] = { 0 };
  63. WCHAR wszBuf[MAX_LOG_LENGTH + 1] = { 0 };
  64. do
  65. {
  66. std::copy(buf + pos, buf + pos + MAX_LOG_LENGTH, tempBuf);
  67. tempBuf[MAX_LOG_LENGTH] = 0;
  68. MultiByteToWideChar(CP_UTF8, 0, tempBuf, -1, wszBuf, sizeof(wszBuf));
  69. OutputDebugStringW(wszBuf);
  70. pos += MAX_LOG_LENGTH;
  71. } while (pos < len);
  72. delete[] buf;
  73. }
  74. void audioLog(const char * format, ...)
  75. {
  76. va_list args;
  77. va_start(args, format);
  78. _winLog(format, args);
  79. va_end(args);
  80. }
  81. using namespace cocos2d;
  82. using namespace cocos2d::experimental;
  83. static ALCdevice *s_ALDevice = nullptr;
  84. static ALCcontext *s_ALContext = nullptr;
  85. AudioEngineImpl::AudioEngineImpl()
  86. : _lazyInitLoop(true)
  87. , _currentAudioID(0)
  88. , _scheduler(nullptr)
  89. {
  90. }
  91. AudioEngineImpl::~AudioEngineImpl()
  92. {
  93. if (_scheduler != nullptr)
  94. {
  95. _scheduler->unschedule(CC_SCHEDULE_SELECTOR(AudioEngineImpl::update), this);
  96. }
  97. if (s_ALContext) {
  98. alDeleteSources(MAX_AUDIOINSTANCES, _alSources);
  99. _audioCaches.clear();
  100. alcMakeContextCurrent(nullptr);
  101. alcDestroyContext(s_ALContext);
  102. s_ALContext = nullptr;
  103. }
  104. if (s_ALDevice) {
  105. alcCloseDevice(s_ALDevice);
  106. s_ALDevice = nullptr;
  107. }
  108. AudioDecoderManager::destroy();
  109. }
  110. bool AudioEngineImpl::init()
  111. {
  112. bool ret = false;
  113. do{
  114. s_ALDevice = alcOpenDevice(nullptr);
  115. if (s_ALDevice) {
  116. alGetError();
  117. s_ALContext = alcCreateContext(s_ALDevice, nullptr);
  118. alcMakeContextCurrent(s_ALContext);
  119. alGenSources(MAX_AUDIOINSTANCES, _alSources);
  120. auto alError = alGetError();
  121. if(alError != AL_NO_ERROR)
  122. {
  123. ALOGE("%s:generating sources failed! error = %x\n", __FUNCTION__, alError);
  124. break;
  125. }
  126. for (int i = 0; i < MAX_AUDIOINSTANCES; ++i) {
  127. _alSourceUsed[_alSources[i]] = false;
  128. }
  129. _scheduler = Director::getInstance()->getScheduler();
  130. ret = AudioDecoderManager::init();
  131. ALOGI("OpenAL was initialized successfully!");
  132. }
  133. }while (false);
  134. return ret;
  135. }
  136. AudioCache* AudioEngineImpl::preload(const std::string& filePath, std::function<void(bool)> callback)
  137. {
  138. AudioCache* audioCache = nullptr;
  139. auto it = _audioCaches.find(filePath);
  140. if (it == _audioCaches.end()) {
  141. audioCache = &_audioCaches[filePath];
  142. audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
  143. unsigned int cacheId = audioCache->_id;
  144. auto isCacheDestroyed = audioCache->_isDestroyed;
  145. AudioEngine::addTask([audioCache, cacheId, isCacheDestroyed](){
  146. if (*isCacheDestroyed)
  147. {
  148. ALOGV("AudioCache (id=%u) was destroyed, no need to launch readDataTask.", cacheId);
  149. audioCache->setSkipReadDataTask(true);
  150. return;
  151. }
  152. audioCache->readDataTask(cacheId);
  153. });
  154. }
  155. else {
  156. audioCache = &it->second;
  157. }
  158. if (audioCache && callback)
  159. {
  160. audioCache->addLoadCallback(callback);
  161. }
  162. return audioCache;
  163. }
  164. int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume)
  165. {
  166. if (s_ALDevice == nullptr) {
  167. return AudioEngine::INVALID_AUDIO_ID;
  168. }
  169. bool sourceFlag = false;
  170. ALuint alSource = 0;
  171. for (int i = 0; i < MAX_AUDIOINSTANCES; ++i) {
  172. alSource = _alSources[i];
  173. if ( !_alSourceUsed[alSource]) {
  174. sourceFlag = true;
  175. break;
  176. }
  177. }
  178. if(!sourceFlag){
  179. return AudioEngine::INVALID_AUDIO_ID;
  180. }
  181. auto player = new (std::nothrow) AudioPlayer;
  182. if (player == nullptr) {
  183. return AudioEngine::INVALID_AUDIO_ID;
  184. }
  185. player->_alSource = alSource;
  186. player->_loop = loop;
  187. player->_volume = volume;
  188. auto audioCache = preload(filePath, nullptr);
  189. if (audioCache == nullptr) {
  190. delete player;
  191. return AudioEngine::INVALID_AUDIO_ID;
  192. }
  193. player->setCache(audioCache);
  194. _threadMutex.lock();
  195. _audioPlayers[_currentAudioID] = player;
  196. _threadMutex.unlock();
  197. _alSourceUsed[alSource] = true;
  198. audioCache->addPlayCallback(std::bind(&AudioEngineImpl::_play2d,this,audioCache,_currentAudioID));
  199. if (_lazyInitLoop) {
  200. _lazyInitLoop = false;
  201. _scheduler->schedule(CC_SCHEDULE_SELECTOR(AudioEngineImpl::update), this, 0.05f, false);
  202. }
  203. return _currentAudioID++;
  204. }
  205. void AudioEngineImpl::_play2d(AudioCache *cache, int audioID)
  206. {
  207. //Note: It may bn in sub thread or main thread :(
  208. if (!*cache->_isDestroyed && cache->_state == AudioCache::State::READY)
  209. {
  210. _threadMutex.lock();
  211. auto playerIt = _audioPlayers.find(audioID);
  212. if (playerIt != _audioPlayers.end() && playerIt->second->play2d()) {
  213. _scheduler->performFunctionInCocosThread([audioID](){
  214. if (AudioEngine::_audioIDInfoMap.find(audioID) != AudioEngine::_audioIDInfoMap.end()) {
  215. AudioEngine::_audioIDInfoMap[audioID].state = AudioEngine::AudioState::PLAYING;
  216. }
  217. });
  218. }
  219. _threadMutex.unlock();
  220. }
  221. else
  222. {
  223. ALOGD("AudioEngineImpl::_play2d, cache was destroyed or not ready!");
  224. auto iter = _audioPlayers.find(audioID);
  225. if (iter != _audioPlayers.end())
  226. {
  227. iter->second->_removeByAudioEngine = true;
  228. }
  229. }
  230. }
  231. void AudioEngineImpl::setVolume(int audioID,float volume)
  232. {
  233. auto player = _audioPlayers[audioID];
  234. player->_volume = volume;
  235. if (player->_ready) {
  236. alSourcef(_audioPlayers[audioID]->_alSource, AL_GAIN, volume);
  237. auto error = alGetError();
  238. if (error != AL_NO_ERROR) {
  239. ALOGE("%s: audio id = %d, error = %x", __FUNCTION__,audioID,error);
  240. }
  241. }
  242. }
  243. void AudioEngineImpl::setLoop(int audioID, bool loop)
  244. {
  245. auto player = _audioPlayers[audioID];
  246. if (player->_ready) {
  247. if (player->_streamingSource) {
  248. player->setLoop(loop);
  249. } else {
  250. if (loop) {
  251. alSourcei(player->_alSource, AL_LOOPING, AL_TRUE);
  252. } else {
  253. alSourcei(player->_alSource, AL_LOOPING, AL_FALSE);
  254. }
  255. auto error = alGetError();
  256. if (error != AL_NO_ERROR) {
  257. ALOGE("%s: audio id = %d, error = %x", __FUNCTION__,audioID,error);
  258. }
  259. }
  260. }
  261. else {
  262. player->_loop = loop;
  263. }
  264. }
  265. bool AudioEngineImpl::pause(int audioID)
  266. {
  267. bool ret = true;
  268. alSourcePause(_audioPlayers[audioID]->_alSource);
  269. auto error = alGetError();
  270. if (error != AL_NO_ERROR) {
  271. ret = false;
  272. ALOGE("%s: audio id = %d, error = %x\n", __FUNCTION__,audioID,error);
  273. }
  274. return ret;
  275. }
  276. bool AudioEngineImpl::resume(int audioID)
  277. {
  278. bool ret = true;
  279. alSourcePlay(_audioPlayers[audioID]->_alSource);
  280. auto error = alGetError();
  281. if (error != AL_NO_ERROR) {
  282. ret = false;
  283. ALOGE("%s: audio id = %d, error = %x\n", __FUNCTION__,audioID,error);
  284. }
  285. return ret;
  286. }
  287. void AudioEngineImpl::stop(int audioID)
  288. {
  289. auto player = _audioPlayers[audioID];
  290. player->destroy();
  291. //Note: Don't set the flag to false here, it should be set in 'update' function.
  292. // Otherwise, the state got from alSourceState may be wrong
  293. // _alSourceUsed[player->_alSource] = false;
  294. }
  295. void AudioEngineImpl::stopAll()
  296. {
  297. for(auto&& player : _audioPlayers)
  298. {
  299. player.second->destroy();
  300. }
  301. //Note: Don't set the flag to false here, it should be set in 'update' function.
  302. // Otherwise, the state got from alSourceState may be wrong
  303. // for(int index = 0; index < MAX_AUDIOINSTANCES; ++index)
  304. // {
  305. // _alSourceUsed[_alSources[index]] = false;
  306. // }
  307. }
  308. float AudioEngineImpl::getDuration(int audioID)
  309. {
  310. auto player = _audioPlayers[audioID];
  311. if(player->_ready){
  312. return player->_audioCache->_duration;
  313. } else {
  314. return AudioEngine::TIME_UNKNOWN;
  315. }
  316. }
  317. float AudioEngineImpl::getCurrentTime(int audioID)
  318. {
  319. float ret = 0.0f;
  320. auto player = _audioPlayers[audioID];
  321. if(player->_ready){
  322. if (player->_streamingSource) {
  323. ret = player->getTime();
  324. } else {
  325. alGetSourcef(player->_alSource, AL_SEC_OFFSET, &ret);
  326. auto error = alGetError();
  327. if (error != AL_NO_ERROR) {
  328. ALOGE("%s, audio id:%d,error code:%x", __FUNCTION__,audioID,error);
  329. }
  330. }
  331. }
  332. return ret;
  333. }
  334. bool AudioEngineImpl::setCurrentTime(int audioID, float time)
  335. {
  336. bool ret = false;
  337. auto player = _audioPlayers[audioID];
  338. do {
  339. if (!player->_ready) {
  340. break;
  341. }
  342. if (player->_streamingSource) {
  343. ret = player->setTime(time);
  344. break;
  345. }
  346. else {
  347. if (player->_audioCache->_framesRead != player->_audioCache->_totalFrames &&
  348. (time * player->_audioCache->_sampleRate) > player->_audioCache->_framesRead) {
  349. ALOGE("%s: audio id = %d", __FUNCTION__,audioID);
  350. break;
  351. }
  352. alSourcef(player->_alSource, AL_SEC_OFFSET, time);
  353. auto error = alGetError();
  354. if (error != AL_NO_ERROR) {
  355. ALOGE("%s: audio id = %d, error = %x", __FUNCTION__,audioID,error);
  356. }
  357. ret = true;
  358. }
  359. } while (0);
  360. return ret;
  361. }
  362. void AudioEngineImpl::setFinishCallback(int audioID, const std::function<void (int, const std::string &)> &callback)
  363. {
  364. _audioPlayers[audioID]->_finishCallbak = callback;
  365. }
  366. void AudioEngineImpl::update(float dt)
  367. {
  368. ALint sourceState;
  369. int audioID;
  370. AudioPlayer* player;
  371. ALuint alSource;
  372. // ALOGV("AudioPlayer count: %d", (int)_audioPlayers.size());
  373. for (auto it = _audioPlayers.begin(); it != _audioPlayers.end(); ) {
  374. audioID = it->first;
  375. player = it->second;
  376. alSource = player->_alSource;
  377. alGetSourcei(alSource, AL_SOURCE_STATE, &sourceState);
  378. if (player->_removeByAudioEngine)
  379. {
  380. AudioEngine::remove(audioID);
  381. _threadMutex.lock();
  382. it = _audioPlayers.erase(it);
  383. _threadMutex.unlock();
  384. delete player;
  385. _alSourceUsed[alSource] = false;
  386. }
  387. else if (player->_ready && sourceState == AL_STOPPED) {
  388. std::string filePath;
  389. if (player->_finishCallbak) {
  390. auto& audioInfo = AudioEngine::_audioIDInfoMap[audioID];
  391. filePath = *audioInfo.filePath;
  392. }
  393. AudioEngine::remove(audioID);
  394. _threadMutex.lock();
  395. it = _audioPlayers.erase(it);
  396. _threadMutex.unlock();
  397. if (player->_finishCallbak) {
  398. player->_finishCallbak(audioID, filePath); //FIXME: callback will delay 50ms
  399. }
  400. delete player;
  401. _alSourceUsed[alSource] = false;
  402. }
  403. else{
  404. ++it;
  405. }
  406. }
  407. if(_audioPlayers.empty()){
  408. _lazyInitLoop = true;
  409. _scheduler->unschedule(CC_SCHEDULE_SELECTOR(AudioEngineImpl::update), this);
  410. }
  411. }
  412. void AudioEngineImpl::uncache(const std::string &filePath)
  413. {
  414. _audioCaches.erase(filePath);
  415. }
  416. void AudioEngineImpl::uncacheAll()
  417. {
  418. _audioCaches.clear();
  419. }
  420. #endif