Audio.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  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. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "../Audio/Audio.h"
  24. #include "../Core/Context.h"
  25. #include "../Core/CoreEvents.h"
  26. #include "../IO/Log.h"
  27. #include "../Core/Mutex.h"
  28. #include "../Core/ProcessUtils.h"
  29. #include "../Core/Profiler.h"
  30. #include "../Audio/Sound.h"
  31. #include "../Audio/SoundListener.h"
  32. #include "../Audio/SoundSource3D.h"
  33. #include <SDL/include/SDL.h>
  34. #include "../DebugNew.h"
  35. namespace Atomic
  36. {
  37. const char* AUDIO_CATEGORY = "Audio";
  38. static const int MIN_BUFFERLENGTH = 20;
  39. static const int MIN_MIXRATE = 11025;
  40. static const int MAX_MIXRATE = 48000;
  41. static const StringHash SOUND_MASTER_HASH("MASTER");
  42. static void SDLAudioCallback(void *userdata, Uint8 *stream, int len);
  43. Audio::Audio(Context* context) :
  44. Object(context),
  45. deviceID_(0),
  46. sampleSize_(0),
  47. playing_(false)
  48. {
  49. // Set the master to the default value
  50. masterGain_[SOUND_MASTER_HASH] = 1.0f;
  51. // Register Audio library object factories
  52. RegisterAudioLibrary(context_);
  53. SubscribeToEvent(E_RENDERUPDATE, HANDLER(Audio, HandleRenderUpdate));
  54. }
  55. Audio::~Audio()
  56. {
  57. Release();
  58. }
  59. bool Audio::SetMode(int bufferLengthMSec, int mixRate, bool stereo, bool interpolation)
  60. {
  61. Release();
  62. bufferLengthMSec = Max(bufferLengthMSec, MIN_BUFFERLENGTH);
  63. mixRate = Clamp(mixRate, MIN_MIXRATE, MAX_MIXRATE);
  64. SDL_AudioSpec desired;
  65. SDL_AudioSpec obtained;
  66. desired.freq = mixRate;
  67. // The concept behind the emspcripten audio port is to treat it as 16 bit until the final acumulation form the clip buffer
  68. #ifdef EMSCRIPTEN
  69. desired.format = AUDIO_F32LSB;
  70. #else
  71. desired.format = AUDIO_S16;
  72. #endif
  73. desired.channels = stereo ? 2 : 1;
  74. desired.callback = SDLAudioCallback;
  75. desired.userdata = this;
  76. // SDL uses power of two audio fragments. Determine the closest match
  77. int bufferSamples = mixRate * bufferLengthMSec / 1000;
  78. desired.samples = NextPowerOfTwo(bufferSamples);
  79. if (Abs((int)desired.samples / 2 - bufferSamples) < Abs((int)desired.samples - bufferSamples))
  80. desired.samples /= 2;
  81. deviceID_ = SDL_OpenAudioDevice(0, SDL_FALSE, &desired, &obtained, SDL_AUDIO_ALLOW_ANY_CHANGE);
  82. if (!deviceID_)
  83. {
  84. LOGERROR("Could not initialize audio output");
  85. return false;
  86. }
  87. #ifdef EMSCRIPTEN
  88. if (obtained.format != AUDIO_F32LSB && obtained.format != AUDIO_F32MSB && obtained.format != AUDIO_F32SYS)
  89. {
  90. LOGERROR("Could not initialize audio output, 32-bit float buffer format not supported");
  91. SDL_CloseAudioDevice(deviceID_);
  92. deviceID_ = 0;
  93. return false;
  94. }
  95. #else
  96. if (obtained.format != AUDIO_S16SYS && obtained.format != AUDIO_S16LSB && obtained.format != AUDIO_S16MSB)
  97. {
  98. LOGERROR("Could not initialize audio output, 16-bit buffer format not supported");
  99. SDL_CloseAudioDevice(deviceID_);
  100. deviceID_ = 0;
  101. return false;
  102. }
  103. #endif
  104. stereo_ = obtained.channels == 2;
  105. sampleSize_ = stereo_ ? sizeof(int) : sizeof(short);
  106. // Guarantee a fragment size that is low enough so that Vorbis decoding buffers do not wrap
  107. fragmentSize_ = Min((int)NextPowerOfTwo(mixRate >> 6), (int)obtained.samples);
  108. mixRate_ = obtained.freq;
  109. interpolation_ = interpolation;
  110. clipBuffer_ = new int[stereo ? fragmentSize_ << 1 : fragmentSize_];
  111. LOGINFO("Set audio mode " + String(mixRate_) + " Hz " + (stereo_ ? "stereo" : "mono") + " " +
  112. (interpolation_ ? "interpolated" : ""));
  113. return Play();
  114. }
  115. void Audio::Update(float timeStep)
  116. {
  117. PROFILE(UpdateAudio);
  118. // Update in reverse order, because sound sources might remove themselves
  119. for (unsigned i = soundSources_.Size() - 1; i < soundSources_.Size(); --i)
  120. soundSources_[i]->Update(timeStep);
  121. }
  122. bool Audio::Play()
  123. {
  124. if (playing_)
  125. return true;
  126. if (!deviceID_)
  127. {
  128. LOGERROR("No audio mode set, can not start playback");
  129. return false;
  130. }
  131. SDL_PauseAudioDevice(deviceID_, 0);
  132. playing_ = true;
  133. return true;
  134. }
  135. void Audio::Stop()
  136. {
  137. playing_ = false;
  138. }
  139. void Audio::SetMasterGain(const String& type, float gain)
  140. {
  141. masterGain_[type] = Clamp(gain, 0.0f, 1.0f);
  142. for (PODVector<SoundSource*>::Iterator i = soundSources_.Begin(); i != soundSources_.End(); ++i)
  143. (*i)->UpdateMasterGain();
  144. }
  145. void Audio::SetListener(SoundListener* listener)
  146. {
  147. listener_ = listener;
  148. }
  149. void Audio::StopSound(Sound* soundClip)
  150. {
  151. for (PODVector<SoundSource*>::Iterator i = soundSources_.Begin(); i != soundSources_.End(); ++i)
  152. {
  153. if ((*i)->GetSound() == soundClip)
  154. (*i)->Stop();
  155. }
  156. }
  157. float Audio::GetMasterGain(const String& type) const
  158. {
  159. // By definition previously unknown types return full volume
  160. HashMap<StringHash, Variant>::ConstIterator findIt = masterGain_.Find(type);
  161. if (findIt == masterGain_.End())
  162. return 1.0f;
  163. return findIt->second_.GetFloat();
  164. }
  165. SoundListener* Audio::GetListener() const
  166. {
  167. return listener_;
  168. }
  169. void Audio::AddSoundSource(SoundSource* channel)
  170. {
  171. MutexLock lock(audioMutex_);
  172. soundSources_.Push(channel);
  173. }
  174. void Audio::RemoveSoundSource(SoundSource* channel)
  175. {
  176. PODVector<SoundSource*>::Iterator i = soundSources_.Find(channel);
  177. if (i != soundSources_.End())
  178. {
  179. MutexLock lock(audioMutex_);
  180. soundSources_.Erase(i);
  181. }
  182. }
  183. float Audio::GetSoundSourceMasterGain(StringHash typeHash) const
  184. {
  185. HashMap<StringHash, Variant>::ConstIterator masterIt = masterGain_.Find(SOUND_MASTER_HASH);
  186. if (!typeHash)
  187. return masterIt->second_.GetFloat();
  188. HashMap<StringHash, Variant>::ConstIterator typeIt = masterGain_.Find(typeHash);
  189. if (typeIt == masterGain_.End() || typeIt == masterIt)
  190. return masterIt->second_.GetFloat();
  191. return masterIt->second_.GetFloat() * typeIt->second_.GetFloat();
  192. }
  193. void SDLAudioCallback(void *userdata, Uint8* stream, int len)
  194. {
  195. Audio* audio = static_cast<Audio*>(userdata);
  196. {
  197. MutexLock Lock(audio->GetMutex());
  198. audio->MixOutput(stream, len / audio->GetSampleSize() / Audio::SAMPLE_SIZE_MUL);
  199. }
  200. }
  201. void Audio::MixOutput(void *dest, unsigned samples)
  202. {
  203. if (!playing_ || !clipBuffer_)
  204. {
  205. memset(dest, 0, samples * sampleSize_ * SAMPLE_SIZE_MUL);
  206. return;
  207. }
  208. while (samples)
  209. {
  210. // If sample count exceeds the fragment (clip buffer) size, split the work
  211. unsigned workSamples = Min((int)samples, (int)fragmentSize_);
  212. unsigned clipSamples = workSamples;
  213. if (stereo_)
  214. clipSamples <<= 1;
  215. // Clear clip buffer
  216. int* clipPtr = clipBuffer_.Get();
  217. memset(clipPtr, 0, clipSamples * sizeof(int));
  218. // Mix samples to clip buffer
  219. for (PODVector<SoundSource*>::Iterator i = soundSources_.Begin(); i != soundSources_.End(); ++i)
  220. (*i)->Mix(clipPtr, workSamples, mixRate_, stereo_, interpolation_);
  221. // Copy output from clip buffer to destination
  222. #ifdef EMSCRIPTEN
  223. float* destPtr = (float*)dest;
  224. while (clipSamples--)
  225. *destPtr++ = (float)Clamp(*clipPtr++, -32768, 32767) / 32768.0f;
  226. #else
  227. short* destPtr = (short*)dest;
  228. while (clipSamples--)
  229. *destPtr++ = Clamp(*clipPtr++, -32768, 32767);
  230. #endif
  231. samples -= workSamples;
  232. ((unsigned char*&)dest) += sampleSize_ * SAMPLE_SIZE_MUL * workSamples;
  233. }
  234. }
  235. void Audio::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  236. {
  237. using namespace RenderUpdate;
  238. Update(eventData[P_TIMESTEP].GetFloat());
  239. }
  240. void Audio::Release()
  241. {
  242. Stop();
  243. if (deviceID_)
  244. {
  245. SDL_CloseAudioDevice(deviceID_);
  246. deviceID_ = 0;
  247. clipBuffer_.Reset();
  248. }
  249. }
  250. void RegisterAudioLibrary(Context* context)
  251. {
  252. Sound::RegisterObject(context);
  253. SoundSource::RegisterObject(context);
  254. SoundSource3D::RegisterObject(context);
  255. SoundListener::RegisterObject(context);
  256. }
  257. }