BsOAAudio.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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 "Math/BsMath.h"
  8. #include "Threading/BsTaskScheduler.h"
  9. #include "Audio/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. LOGERR("Failed to open OpenAL device: " + defaultDeviceName);
  55. rebuildContexts();
  56. }
  57. OAAudio::~OAAudio()
  58. {
  59. assert(mListeners.size() == 0 && mSources.size() == 0); // Everything should be destroyed at this point
  60. clearContexts();
  61. if(mDevice != nullptr)
  62. alcCloseDevice(mDevice);
  63. }
  64. void OAAudio::setVolume(float volume)
  65. {
  66. mVolume = Math::clamp01(volume);
  67. for (auto& listener : mListeners)
  68. listener->rebuild();
  69. }
  70. float OAAudio::getVolume() const
  71. {
  72. return mVolume;
  73. }
  74. void OAAudio::setPaused(bool paused)
  75. {
  76. if (mIsPaused == paused)
  77. return;
  78. mIsPaused = paused;
  79. for (auto& source : mSources)
  80. source->setGlobalPause(paused);
  81. }
  82. void OAAudio::_update()
  83. {
  84. auto worker = [this]() { updateStreaming(); };
  85. // If previous task still hasn't completed, just skip streaming this frame, queuing more tasks won't help
  86. if (mStreamingTask != nullptr && !mStreamingTask->isComplete())
  87. return;
  88. mStreamingTask = Task::create("AudioStream", worker, TaskPriority::VeryHigh);
  89. TaskScheduler::instance().addTask(mStreamingTask);
  90. Audio::_update();
  91. }
  92. void OAAudio::setActiveDevice(const AudioDevice& device)
  93. {
  94. if (mAllDevices.size() == 1)
  95. return; // No devices to change to, keep the active device as is
  96. clearContexts();
  97. if(mDevice != nullptr)
  98. alcCloseDevice(mDevice);
  99. mActiveDevice = device;
  100. String narrowName = toString(device.name);
  101. mDevice = alcOpenDevice(narrowName.c_str());
  102. if (mDevice == nullptr)
  103. LOGERR("Failed to open OpenAL device: " + narrowName);
  104. rebuildContexts();
  105. }
  106. bool OAAudio::_isExtensionSupported(const String& extension) const
  107. {
  108. if (mDevice == nullptr)
  109. return false;
  110. if ((extension.length() > 2) && (extension.substr(0, 3) == "ALC"))
  111. return alcIsExtensionPresent(mDevice, extension.c_str()) != AL_FALSE;
  112. else
  113. return alIsExtensionPresent(extension.c_str()) != AL_FALSE;
  114. }
  115. void OAAudio::_registerListener(OAAudioListener* listener)
  116. {
  117. mListeners.push_back(listener);
  118. rebuildContexts();
  119. }
  120. void OAAudio::_unregisterListener(OAAudioListener* listener)
  121. {
  122. auto iterFind = std::find(mListeners.begin(), mListeners.end(), listener);
  123. if (iterFind != mListeners.end())
  124. mListeners.erase(iterFind);
  125. rebuildContexts();
  126. }
  127. void OAAudio::_registerSource(OAAudioSource* source)
  128. {
  129. mSources.insert(source);
  130. }
  131. void OAAudio::_unregisterSource(OAAudioSource* source)
  132. {
  133. mSources.erase(source);
  134. }
  135. void OAAudio::startStreaming(OAAudioSource* source)
  136. {
  137. Lock(mMutex);
  138. mStreamingCommandQueue.push_back({ StreamingCommandType::Start, source });
  139. mDestroyedSources.erase(source);
  140. }
  141. void OAAudio::stopStreaming(OAAudioSource* source)
  142. {
  143. Lock(mMutex);
  144. mStreamingCommandQueue.push_back({ StreamingCommandType::Stop, source });
  145. mDestroyedSources.insert(source);
  146. }
  147. ALCcontext* OAAudio::_getContext(const OAAudioListener* listener) const
  148. {
  149. if (mListeners.size() > 0)
  150. {
  151. assert(mListeners.size() == mContexts.size());
  152. UINT32 numContexts = (UINT32)mContexts.size();
  153. for(UINT32 i = 0; i < numContexts; i++)
  154. {
  155. if (mListeners[i] == listener)
  156. return mContexts[i];
  157. }
  158. }
  159. else
  160. return mContexts[0];
  161. LOGERR("Unable to find context for an audio listener.");
  162. return nullptr;
  163. }
  164. SPtr<AudioClip> OAAudio::createClip(const SPtr<DataStream>& samples, UINT32 streamSize, UINT32 numSamples,
  165. const AUDIO_CLIP_DESC& desc)
  166. {
  167. return bs_core_ptr_new<OAAudioClip>(samples, streamSize, numSamples, desc);
  168. }
  169. SPtr<AudioListener> OAAudio::createListener()
  170. {
  171. return bs_shared_ptr_new<OAAudioListener>();
  172. }
  173. SPtr<AudioSource> OAAudio::createSource()
  174. {
  175. return bs_shared_ptr_new<OAAudioSource>();
  176. }
  177. void OAAudio::rebuildContexts()
  178. {
  179. for (auto& source : mSources)
  180. source->clear();
  181. clearContexts();
  182. if (mDevice == nullptr)
  183. return;
  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. }