Audio.cpp 9.3 KB

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