BsOAAudio.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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 BansheeEngine
  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. }
  93. void OAAudio::setActiveDevice(const AudioDevice& device)
  94. {
  95. if (mAllDevices.size() == 1)
  96. return; // No devices to change to, keep the active device as is
  97. clearContexts();
  98. alcCloseDevice(mDevice);
  99. mActiveDevice = device;
  100. String narrowName = toString(device.name);
  101. mDevice = alcOpenDevice(narrowName.c_str());
  102. if (mDevice == nullptr)
  103. {
  104. BS_EXCEPT(InternalErrorException, "Failed to open OpenAL device: " + narrowName);
  105. return;
  106. }
  107. rebuildContexts();
  108. }
  109. bool OAAudio::_isExtensionSupported(const String& extension) const
  110. {
  111. if ((extension.length() > 2) && (extension.substr(0, 3) == "ALC"))
  112. return alcIsExtensionPresent(mDevice, extension.c_str()) != AL_FALSE;
  113. else
  114. return alIsExtensionPresent(extension.c_str()) != AL_FALSE;
  115. }
  116. void OAAudio::_registerListener(OAAudioListener* listener)
  117. {
  118. mListeners.push_back(listener);
  119. rebuildContexts();
  120. }
  121. void OAAudio::_unregisterListener(OAAudioListener* listener)
  122. {
  123. auto iterFind = std::find(mListeners.begin(), mListeners.end(), listener);
  124. if (iterFind != mListeners.end())
  125. mListeners.erase(iterFind);
  126. rebuildContexts();
  127. }
  128. void OAAudio::_registerSource(OAAudioSource* source)
  129. {
  130. mSources.insert(source);
  131. }
  132. void OAAudio::_unregisterSource(OAAudioSource* source)
  133. {
  134. mSources.erase(source);
  135. }
  136. void OAAudio::startStreaming(OAAudioSource* source)
  137. {
  138. Lock(mMutex);
  139. mStreamingCommandQueue.push_back({ StreamingCommandType::Start, source });
  140. mDestroyedSources.erase(source);
  141. }
  142. void OAAudio::stopStreaming(OAAudioSource* source)
  143. {
  144. Lock(mMutex);
  145. mStreamingCommandQueue.push_back({ StreamingCommandType::Stop, source });
  146. mDestroyedSources.insert(source);
  147. }
  148. ALCcontext* OAAudio::_getContext(const OAAudioListener* listener) const
  149. {
  150. if (mListeners.size() > 0)
  151. {
  152. assert(mListeners.size() == mContexts.size());
  153. UINT32 numContexts = (UINT32)mContexts.size();
  154. for(UINT32 i = 0; i < numContexts; i++)
  155. {
  156. if (mListeners[i] == listener)
  157. return mContexts[i];
  158. }
  159. }
  160. else
  161. return mContexts[0];
  162. LOGERR("Unable to find context for an audio listener.");
  163. return nullptr;
  164. }
  165. SPtr<AudioClip> OAAudio::createClip(const SPtr<DataStream>& samples, UINT32 streamSize, UINT32 numSamples,
  166. const AUDIO_CLIP_DESC& desc)
  167. {
  168. return bs_core_ptr_new<OAAudioClip>(samples, streamSize, numSamples, desc);
  169. }
  170. SPtr<AudioListener> OAAudio::createListener()
  171. {
  172. return bs_shared_ptr_new<OAAudioListener>();
  173. }
  174. SPtr<AudioSource> OAAudio::createSource()
  175. {
  176. return bs_shared_ptr_new<OAAudioSource>();
  177. }
  178. void OAAudio::rebuildContexts()
  179. {
  180. for (auto& source : mSources)
  181. source->clear();
  182. clearContexts();
  183. UINT32 numListeners = (UINT32)mListeners.size();
  184. UINT32 numContexts = numListeners > 1 ? numListeners : 1;
  185. for(UINT32 i = 0; i < numContexts; i++)
  186. {
  187. ALCcontext* context = alcCreateContext(mDevice, nullptr);
  188. mContexts.push_back(context);
  189. }
  190. // If only one context is available keep it active as an optimization. Audio listeners and sources will avoid
  191. // excessive context switching in such case.
  192. alcMakeContextCurrent(mContexts[0]);
  193. for (auto& listener : mListeners)
  194. listener->rebuild();
  195. for (auto& source : mSources)
  196. source->rebuild();
  197. }
  198. void OAAudio::clearContexts()
  199. {
  200. alcMakeContextCurrent(nullptr);
  201. for (auto& context : mContexts)
  202. alcDestroyContext(context);
  203. mContexts.clear();
  204. }
  205. void OAAudio::updateStreaming()
  206. {
  207. {
  208. Lock(mMutex);
  209. for(auto& command : mStreamingCommandQueue)
  210. {
  211. switch(command.type)
  212. {
  213. case StreamingCommandType::Start:
  214. mStreamingSources.insert(command.source);
  215. break;
  216. case StreamingCommandType::Stop:
  217. mStreamingSources.erase(command.source);
  218. break;
  219. default:
  220. break;
  221. }
  222. }
  223. mStreamingCommandQueue.clear();
  224. mDestroyedSources.clear();
  225. }
  226. for (auto& source : mStreamingSources)
  227. {
  228. // Check if the source got destroyed while streaming
  229. {
  230. Lock(mMutex);
  231. auto iterFind = mDestroyedSources.find(source);
  232. if (iterFind != mDestroyedSources.end())
  233. continue;
  234. }
  235. source->stream();
  236. }
  237. }
  238. ALenum OAAudio::_getOpenALBufferFormat(UINT32 numChannels, UINT32 bitDepth)
  239. {
  240. switch (bitDepth)
  241. {
  242. case 8:
  243. {
  244. switch (numChannels)
  245. {
  246. case 1: return AL_FORMAT_MONO8;
  247. case 2: return AL_FORMAT_STEREO8;
  248. case 4: return alGetEnumValue("AL_FORMAT_QUAD8");
  249. case 6: return alGetEnumValue("AL_FORMAT_51CHN8");
  250. case 7: return alGetEnumValue("AL_FORMAT_61CHN8");
  251. case 8: return alGetEnumValue("AL_FORMAT_71CHN8");
  252. default:
  253. assert(false);
  254. return 0;
  255. }
  256. }
  257. case 16:
  258. {
  259. switch (numChannels)
  260. {
  261. case 1: return AL_FORMAT_MONO16;
  262. case 2: return AL_FORMAT_STEREO16;
  263. case 4: return alGetEnumValue("AL_FORMAT_QUAD16");
  264. case 6: return alGetEnumValue("AL_FORMAT_51CHN16");
  265. case 7: return alGetEnumValue("AL_FORMAT_61CHN16");
  266. case 8: return alGetEnumValue("AL_FORMAT_71CHN16");
  267. default:
  268. assert(false);
  269. return 0;
  270. }
  271. }
  272. case 32:
  273. {
  274. switch (numChannels)
  275. {
  276. case 1: return alGetEnumValue("AL_FORMAT_MONO_FLOAT32");
  277. case 2: return alGetEnumValue("AL_FORMAT_STEREO_FLOAT32");
  278. case 4: return alGetEnumValue("AL_FORMAT_QUAD32");
  279. case 6: return alGetEnumValue("AL_FORMAT_51CHN32");
  280. case 7: return alGetEnumValue("AL_FORMAT_61CHN32");
  281. case 8: return alGetEnumValue("AL_FORMAT_71CHN32");
  282. default:
  283. assert(false);
  284. return 0;
  285. }
  286. }
  287. default:
  288. assert(false);
  289. return 0;
  290. }
  291. }
  292. void OAAudio::_writeToOpenALBuffer(UINT32 bufferId, UINT8* samples, const AudioDataInfo& info)
  293. {
  294. if (info.numChannels <= 2) // Mono or stereo
  295. {
  296. if (info.bitDepth > 16)
  297. {
  298. if (_isExtensionSupported("AL_EXT_float32"))
  299. {
  300. UINT32 bufferSize = info.numSamples * sizeof(float);
  301. float* sampleBufferFloat = (float*)bs_stack_alloc(bufferSize);
  302. AudioUtility::convertToFloat(samples, info.bitDepth, sampleBufferFloat, info.numSamples);
  303. ALenum format = _getOpenALBufferFormat(info.numChannels, info.bitDepth);
  304. alBufferData(bufferId, format, sampleBufferFloat, bufferSize, info.sampleRate);
  305. bs_stack_free(sampleBufferFloat);
  306. }
  307. else
  308. {
  309. LOGWRN("OpenAL doesn't support bit depth larger than 16. Your audio data will be truncated.");
  310. UINT32 bufferSize = info.numSamples * 2;
  311. UINT8* sampleBuffer16 = (UINT8*)bs_stack_alloc(bufferSize);
  312. AudioUtility::convertBitDepth(samples, info.bitDepth, sampleBuffer16, 16, info.numSamples);
  313. ALenum format = _getOpenALBufferFormat(info.numChannels, 16);
  314. alBufferData(bufferId, format, sampleBuffer16, bufferSize, info.sampleRate);
  315. bs_stack_free(sampleBuffer16);
  316. }
  317. }
  318. else if(info.bitDepth == 8)
  319. {
  320. // OpenAL expects unsigned 8-bit data, but engine stores it as signed, so convert
  321. UINT32 bufferSize = info.numSamples * (info.bitDepth / 8);
  322. UINT8* sampleBuffer = (UINT8*)bs_stack_alloc(bufferSize);
  323. for(UINT32 i = 0; i < info.numSamples; i++)
  324. sampleBuffer[i] = ((INT8*)samples)[i] + 128;
  325. ALenum format = _getOpenALBufferFormat(info.numChannels, 16);
  326. alBufferData(bufferId, format, sampleBuffer, bufferSize, info.sampleRate);
  327. bs_stack_free(sampleBuffer);
  328. }
  329. else
  330. {
  331. ALenum format = _getOpenALBufferFormat(info.numChannels, info.bitDepth);
  332. alBufferData(bufferId, format, samples, info.numSamples * (info.bitDepth / 8), info.sampleRate);
  333. }
  334. }
  335. else // Multichannel
  336. {
  337. // Note: Assuming AL_EXT_MCFORMATS is supported. If it's not, channels should be reduced to mono or stereo.
  338. if (info.bitDepth == 24) // 24-bit not supported, convert to 32-bit
  339. {
  340. UINT32 bufferSize = info.numSamples * sizeof(INT32);
  341. UINT8* sampleBuffer32 = (UINT8*)bs_stack_alloc(bufferSize);
  342. AudioUtility::convertBitDepth(samples, info.bitDepth, sampleBuffer32, 32, info.numSamples);
  343. ALenum format = _getOpenALBufferFormat(info.numChannels, 32);
  344. alBufferData(bufferId, format, sampleBuffer32, bufferSize, info.sampleRate);
  345. bs_stack_free(sampleBuffer32);
  346. }
  347. else if (info.bitDepth == 8)
  348. {
  349. // OpenAL expects unsigned 8-bit data, but engine stores it as signed, so convert
  350. UINT32 bufferSize = info.numSamples * (info.bitDepth / 8);
  351. UINT8* sampleBuffer = (UINT8*)bs_stack_alloc(bufferSize);
  352. for (UINT32 i = 0; i < info.numSamples; i++)
  353. sampleBuffer[i] = ((INT8*)samples)[i] + 128;
  354. ALenum format = _getOpenALBufferFormat(info.numChannels, 16);
  355. alBufferData(bufferId, format, sampleBuffer, bufferSize, info.sampleRate);
  356. bs_stack_free(sampleBuffer);
  357. }
  358. else
  359. {
  360. ALenum format = _getOpenALBufferFormat(info.numChannels, info.bitDepth);
  361. alBufferData(bufferId, format, samples, info.numSamples * (info.bitDepth / 8), info.sampleRate);
  362. }
  363. }
  364. }
  365. OAAudio& gOAAudio()
  366. {
  367. return static_cast<OAAudio&>(OAAudio::instance());
  368. }
  369. }