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