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