BsOAAudio.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsOAAudio.h"
  4. #include "BsOAAudioClip.h"
  5. #include "BsOAAudioListener.h"
  6. #include "BsOAAudioSource.h"
  7. #include "BsMath.h"
  8. #include "BsTaskScheduler.h"
  9. #include "BsAudioUtility.h"
  10. #include "AL\al.h"
  11. namespace bs
  12. {
  13. OAAudio::OAAudio()
  14. :mVolume(1.0f), mIsPaused(false)
  15. {
  16. bool enumeratedDevices;
  17. if(_isExtensionSupported("ALC_ENUMERATE_ALL_EXT"))
  18. {
  19. const ALCchar* defaultDevice = alcGetString(nullptr, ALC_DEFAULT_ALL_DEVICES_SPECIFIER);
  20. mDefaultDevice.name = toWString(defaultDevice);
  21. const ALCchar* devices = alcGetString(nullptr, ALC_ALL_DEVICES_SPECIFIER);
  22. Vector<wchar_t> deviceName;
  23. while(true)
  24. {
  25. if(*devices == 0)
  26. {
  27. if (deviceName.size() == 0)
  28. break;
  29. // Clean up the name to get the actual hardware name
  30. WString fixedName(deviceName.data(), deviceName.size());
  31. fixedName = StringUtil::replaceAll(fixedName, L"OpenAL Soft on ", L"");
  32. mAllDevices.push_back({ fixedName });
  33. deviceName.clear();
  34. devices++;
  35. continue;
  36. }
  37. deviceName.push_back(*devices);
  38. devices++;
  39. }
  40. enumeratedDevices = true;
  41. }
  42. else
  43. {
  44. mAllDevices.push_back({ L"" });
  45. enumeratedDevices = false;
  46. }
  47. mActiveDevice = mDefaultDevice;
  48. String defaultDeviceName = toString(mDefaultDevice.name);
  49. if(enumeratedDevices)
  50. mDevice = alcOpenDevice(defaultDeviceName.c_str());
  51. else
  52. mDevice = alcOpenDevice(nullptr);
  53. if (mDevice == nullptr)
  54. {
  55. BS_EXCEPT(InternalErrorException, "Failed to open OpenAL device: " + defaultDeviceName);
  56. return;
  57. }
  58. rebuildContexts();
  59. }
  60. OAAudio::~OAAudio()
  61. {
  62. assert(mListeners.size() == 0 && mSources.size() == 0); // Everything should be destroyed at this point
  63. clearContexts();
  64. alcCloseDevice(mDevice);
  65. }
  66. void OAAudio::setVolume(float volume)
  67. {
  68. mVolume = Math::clamp01(volume);
  69. for (auto& listener : mListeners)
  70. listener->rebuild();
  71. }
  72. float OAAudio::getVolume() const
  73. {
  74. return mVolume;
  75. }
  76. void OAAudio::setPaused(bool paused)
  77. {
  78. if (mIsPaused == paused)
  79. return;
  80. mIsPaused = paused;
  81. for (auto& source : mSources)
  82. source->setGlobalPause(paused);
  83. }
  84. void OAAudio::_update()
  85. {
  86. auto worker = [this]() { updateStreaming(); };
  87. // If previous task still hasn't completed, just skip streaming this frame, queuing more tasks won't help
  88. if (mStreamingTask != nullptr && !mStreamingTask->isComplete())
  89. return;
  90. mStreamingTask = Task::create("AudioStream", worker, TaskPriority::VeryHigh);
  91. TaskScheduler::instance().addTask(mStreamingTask);
  92. Audio::_update();
  93. }
  94. void OAAudio::setActiveDevice(const AudioDevice& device)
  95. {
  96. if (mAllDevices.size() == 1)
  97. return; // No devices to change to, keep the active device as is
  98. clearContexts();
  99. alcCloseDevice(mDevice);
  100. mActiveDevice = device;
  101. String narrowName = toString(device.name);
  102. mDevice = alcOpenDevice(narrowName.c_str());
  103. if (mDevice == nullptr)
  104. {
  105. BS_EXCEPT(InternalErrorException, "Failed to open OpenAL device: " + narrowName);
  106. return;
  107. }
  108. rebuildContexts();
  109. }
  110. bool OAAudio::_isExtensionSupported(const String& extension) const
  111. {
  112. if ((extension.length() > 2) && (extension.substr(0, 3) == "ALC"))
  113. return alcIsExtensionPresent(mDevice, extension.c_str()) != AL_FALSE;
  114. else
  115. return alIsExtensionPresent(extension.c_str()) != AL_FALSE;
  116. }
  117. void OAAudio::_registerListener(OAAudioListener* listener)
  118. {
  119. mListeners.push_back(listener);
  120. rebuildContexts();
  121. }
  122. void OAAudio::_unregisterListener(OAAudioListener* listener)
  123. {
  124. auto iterFind = std::find(mListeners.begin(), mListeners.end(), listener);
  125. if (iterFind != mListeners.end())
  126. mListeners.erase(iterFind);
  127. rebuildContexts();
  128. }
  129. void OAAudio::_registerSource(OAAudioSource* source)
  130. {
  131. mSources.insert(source);
  132. }
  133. void OAAudio::_unregisterSource(OAAudioSource* source)
  134. {
  135. mSources.erase(source);
  136. }
  137. void OAAudio::startStreaming(OAAudioSource* source)
  138. {
  139. Lock(mMutex);
  140. mStreamingCommandQueue.push_back({ StreamingCommandType::Start, source });
  141. mDestroyedSources.erase(source);
  142. }
  143. void OAAudio::stopStreaming(OAAudioSource* source)
  144. {
  145. Lock(mMutex);
  146. mStreamingCommandQueue.push_back({ StreamingCommandType::Stop, source });
  147. mDestroyedSources.insert(source);
  148. }
  149. ALCcontext* OAAudio::_getContext(const OAAudioListener* listener) const
  150. {
  151. if (mListeners.size() > 0)
  152. {
  153. assert(mListeners.size() == mContexts.size());
  154. UINT32 numContexts = (UINT32)mContexts.size();
  155. for(UINT32 i = 0; i < numContexts; i++)
  156. {
  157. if (mListeners[i] == listener)
  158. return mContexts[i];
  159. }
  160. }
  161. else
  162. return mContexts[0];
  163. LOGERR("Unable to find context for an audio listener.");
  164. return nullptr;
  165. }
  166. SPtr<AudioClip> OAAudio::createClip(const SPtr<DataStream>& samples, UINT32 streamSize, UINT32 numSamples,
  167. const AUDIO_CLIP_DESC& desc)
  168. {
  169. return bs_core_ptr_new<OAAudioClip>(samples, streamSize, numSamples, desc);
  170. }
  171. SPtr<AudioListener> OAAudio::createListener()
  172. {
  173. return bs_shared_ptr_new<OAAudioListener>();
  174. }
  175. SPtr<AudioSource> OAAudio::createSource()
  176. {
  177. return bs_shared_ptr_new<OAAudioSource>();
  178. }
  179. void OAAudio::rebuildContexts()
  180. {
  181. for (auto& source : mSources)
  182. source->clear();
  183. clearContexts();
  184. UINT32 numListeners = (UINT32)mListeners.size();
  185. UINT32 numContexts = numListeners > 1 ? numListeners : 1;
  186. for(UINT32 i = 0; i < numContexts; i++)
  187. {
  188. ALCcontext* context = alcCreateContext(mDevice, nullptr);
  189. mContexts.push_back(context);
  190. }
  191. // If only one context is available keep it active as an optimization. Audio listeners and sources will avoid
  192. // excessive context switching in such case.
  193. alcMakeContextCurrent(mContexts[0]);
  194. for (auto& listener : mListeners)
  195. listener->rebuild();
  196. for (auto& source : mSources)
  197. source->rebuild();
  198. }
  199. void OAAudio::clearContexts()
  200. {
  201. alcMakeContextCurrent(nullptr);
  202. for (auto& context : mContexts)
  203. alcDestroyContext(context);
  204. mContexts.clear();
  205. }
  206. void OAAudio::updateStreaming()
  207. {
  208. {
  209. Lock(mMutex);
  210. for(auto& command : mStreamingCommandQueue)
  211. {
  212. switch(command.type)
  213. {
  214. case StreamingCommandType::Start:
  215. mStreamingSources.insert(command.source);
  216. break;
  217. case StreamingCommandType::Stop:
  218. mStreamingSources.erase(command.source);
  219. break;
  220. default:
  221. break;
  222. }
  223. }
  224. mStreamingCommandQueue.clear();
  225. mDestroyedSources.clear();
  226. }
  227. for (auto& source : mStreamingSources)
  228. {
  229. // Check if the source got destroyed while streaming
  230. {
  231. Lock(mMutex);
  232. auto iterFind = mDestroyedSources.find(source);
  233. if (iterFind != mDestroyedSources.end())
  234. continue;
  235. }
  236. source->stream();
  237. }
  238. }
  239. ALenum OAAudio::_getOpenALBufferFormat(UINT32 numChannels, UINT32 bitDepth)
  240. {
  241. switch (bitDepth)
  242. {
  243. case 8:
  244. {
  245. switch (numChannels)
  246. {
  247. case 1: return AL_FORMAT_MONO8;
  248. case 2: return AL_FORMAT_STEREO8;
  249. case 4: return alGetEnumValue("AL_FORMAT_QUAD8");
  250. case 6: return alGetEnumValue("AL_FORMAT_51CHN8");
  251. case 7: return alGetEnumValue("AL_FORMAT_61CHN8");
  252. case 8: return alGetEnumValue("AL_FORMAT_71CHN8");
  253. default:
  254. assert(false);
  255. return 0;
  256. }
  257. }
  258. case 16:
  259. {
  260. switch (numChannels)
  261. {
  262. case 1: return AL_FORMAT_MONO16;
  263. case 2: return AL_FORMAT_STEREO16;
  264. case 4: return alGetEnumValue("AL_FORMAT_QUAD16");
  265. case 6: return alGetEnumValue("AL_FORMAT_51CHN16");
  266. case 7: return alGetEnumValue("AL_FORMAT_61CHN16");
  267. case 8: return alGetEnumValue("AL_FORMAT_71CHN16");
  268. default:
  269. assert(false);
  270. return 0;
  271. }
  272. }
  273. case 32:
  274. {
  275. switch (numChannels)
  276. {
  277. case 1: return alGetEnumValue("AL_FORMAT_MONO_FLOAT32");
  278. case 2: return alGetEnumValue("AL_FORMAT_STEREO_FLOAT32");
  279. case 4: return alGetEnumValue("AL_FORMAT_QUAD32");
  280. case 6: return alGetEnumValue("AL_FORMAT_51CHN32");
  281. case 7: return alGetEnumValue("AL_FORMAT_61CHN32");
  282. case 8: return alGetEnumValue("AL_FORMAT_71CHN32");
  283. default:
  284. assert(false);
  285. return 0;
  286. }
  287. }
  288. default:
  289. assert(false);
  290. return 0;
  291. }
  292. }
  293. void OAAudio::_writeToOpenALBuffer(UINT32 bufferId, UINT8* samples, const AudioDataInfo& info)
  294. {
  295. if (info.numChannels <= 2) // Mono or stereo
  296. {
  297. if (info.bitDepth > 16)
  298. {
  299. if (_isExtensionSupported("AL_EXT_float32"))
  300. {
  301. UINT32 bufferSize = info.numSamples * sizeof(float);
  302. float* sampleBufferFloat = (float*)bs_stack_alloc(bufferSize);
  303. AudioUtility::convertToFloat(samples, info.bitDepth, sampleBufferFloat, info.numSamples);
  304. ALenum format = _getOpenALBufferFormat(info.numChannels, info.bitDepth);
  305. alBufferData(bufferId, format, sampleBufferFloat, bufferSize, info.sampleRate);
  306. bs_stack_free(sampleBufferFloat);
  307. }
  308. else
  309. {
  310. LOGWRN("OpenAL doesn't support bit depth larger than 16. Your audio data will be truncated.");
  311. UINT32 bufferSize = info.numSamples * 2;
  312. UINT8* sampleBuffer16 = (UINT8*)bs_stack_alloc(bufferSize);
  313. AudioUtility::convertBitDepth(samples, info.bitDepth, sampleBuffer16, 16, info.numSamples);
  314. ALenum format = _getOpenALBufferFormat(info.numChannels, 16);
  315. alBufferData(bufferId, format, sampleBuffer16, bufferSize, info.sampleRate);
  316. bs_stack_free(sampleBuffer16);
  317. }
  318. }
  319. else if(info.bitDepth == 8)
  320. {
  321. // OpenAL expects unsigned 8-bit data, but engine stores it as signed, so convert
  322. UINT32 bufferSize = info.numSamples * (info.bitDepth / 8);
  323. UINT8* sampleBuffer = (UINT8*)bs_stack_alloc(bufferSize);
  324. for(UINT32 i = 0; i < info.numSamples; i++)
  325. sampleBuffer[i] = ((INT8*)samples)[i] + 128;
  326. ALenum format = _getOpenALBufferFormat(info.numChannels, 16);
  327. alBufferData(bufferId, format, sampleBuffer, bufferSize, info.sampleRate);
  328. bs_stack_free(sampleBuffer);
  329. }
  330. else
  331. {
  332. ALenum format = _getOpenALBufferFormat(info.numChannels, info.bitDepth);
  333. alBufferData(bufferId, format, samples, info.numSamples * (info.bitDepth / 8), info.sampleRate);
  334. }
  335. }
  336. else // Multichannel
  337. {
  338. // Note: Assuming AL_EXT_MCFORMATS is supported. If it's not, channels should be reduced to mono or stereo.
  339. if (info.bitDepth == 24) // 24-bit not supported, convert to 32-bit
  340. {
  341. UINT32 bufferSize = info.numSamples * sizeof(INT32);
  342. UINT8* sampleBuffer32 = (UINT8*)bs_stack_alloc(bufferSize);
  343. AudioUtility::convertBitDepth(samples, info.bitDepth, sampleBuffer32, 32, info.numSamples);
  344. ALenum format = _getOpenALBufferFormat(info.numChannels, 32);
  345. alBufferData(bufferId, format, sampleBuffer32, bufferSize, info.sampleRate);
  346. bs_stack_free(sampleBuffer32);
  347. }
  348. else if (info.bitDepth == 8)
  349. {
  350. // OpenAL expects unsigned 8-bit data, but engine stores it as signed, so convert
  351. UINT32 bufferSize = info.numSamples * (info.bitDepth / 8);
  352. UINT8* sampleBuffer = (UINT8*)bs_stack_alloc(bufferSize);
  353. for (UINT32 i = 0; i < info.numSamples; i++)
  354. sampleBuffer[i] = ((INT8*)samples)[i] + 128;
  355. ALenum format = _getOpenALBufferFormat(info.numChannels, 16);
  356. alBufferData(bufferId, format, sampleBuffer, bufferSize, info.sampleRate);
  357. bs_stack_free(sampleBuffer);
  358. }
  359. else
  360. {
  361. ALenum format = _getOpenALBufferFormat(info.numChannels, info.bitDepth);
  362. alBufferData(bufferId, format, samples, info.numSamples * (info.bitDepth / 8), info.sampleRate);
  363. }
  364. }
  365. }
  366. OAAudio& gOAAudio()
  367. {
  368. return static_cast<OAAudio&>(OAAudio::instance());
  369. }
  370. }