Audio.cpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. //
  2. // Copyright (c) 2008-2013 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.h"
  24. #include "Context.h"
  25. #include "CoreEvents.h"
  26. #include "Log.h"
  27. #include "Mutex.h"
  28. #include "ProcessUtils.h"
  29. #include "Profiler.h"
  30. #include "Sound.h"
  31. #include "SoundListener.h"
  32. #include "SoundSource3D.h"
  33. #include <SDL.h>
  34. #include "DebugNew.h"
  35. namespace Urho3D
  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 void SDLAudioCallback(void *userdata, Uint8 *stream, int len);
  42. OBJECTTYPESTATIC(Audio);
  43. Audio::Audio(Context* context) :
  44. Object(context),
  45. deviceID_(0),
  46. sampleSize_(0),
  47. playing_(false)
  48. {
  49. for (unsigned i = 0; i < MAX_SOUND_TYPES; ++i)
  50. masterGain_[i] = 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. // Guarantee a fragment size that is low enough so that Vorbis decoding buffers do not wrap
  65. fragmentSize_ = NextPowerOfTwo(mixRate >> 6);
  66. SDL_AudioSpec desired;
  67. SDL_AudioSpec obtained;
  68. desired.freq = mixRate;
  69. desired.format = AUDIO_S16SYS;
  70. desired.channels = stereo ? 2 : 1;
  71. // For SDL, do not actually use the buffer length, but calculate a suitable power-of-two size from the mixrate
  72. if (desired.freq <= 11025)
  73. desired.samples = 512;
  74. else if (desired.freq <= 22050)
  75. desired.samples = 1024;
  76. else if (desired.freq <= 44100)
  77. desired.samples = 2048;
  78. else
  79. desired.samples = 4096;
  80. desired.callback = SDLAudioCallback;
  81. desired.userdata = this;
  82. {
  83. MutexLock lock(GetStaticMutex());
  84. deviceID_ = SDL_OpenAudioDevice(0, SDL_FALSE, &desired, &obtained, SDL_AUDIO_ALLOW_ANY_CHANGE);
  85. if (!deviceID_)
  86. {
  87. LOGERROR("Could not initialize audio output");
  88. return false;
  89. }
  90. if (obtained.format != AUDIO_S16SYS && obtained.format != AUDIO_S16LSB && obtained.format != AUDIO_S16MSB)
  91. {
  92. LOGERROR("Could not initialize audio output, 16-bit buffer format not supported");
  93. SDL_CloseAudioDevice(deviceID_);
  94. deviceID_ = 0;
  95. return false;
  96. }
  97. }
  98. stereo_ = obtained.channels == 2;
  99. sampleSize_ = stereo_ ? sizeof(int) : sizeof(short);
  100. fragmentSize_ = obtained.samples;
  101. mixRate_ = mixRate;
  102. interpolation_ = interpolation;
  103. clipBuffer_ = new int[stereo ? fragmentSize_ << 1 : fragmentSize_];
  104. LOGINFO("Set audio mode " + String(mixRate_) + " Hz " + (stereo_ ? "stereo" : "mono") + " " +
  105. (interpolation_ ? "interpolated" : ""));
  106. return Play();
  107. }
  108. void Audio::Update(float timeStep)
  109. {
  110. PROFILE(UpdateAudio);
  111. // Update in reverse order, because sound sources might remove themselves
  112. for (unsigned i = soundSources_.Size() - 1; i < soundSources_.Size(); --i)
  113. soundSources_[i]->Update(timeStep);
  114. }
  115. bool Audio::Play()
  116. {
  117. if (playing_)
  118. return true;
  119. if (!deviceID_)
  120. {
  121. LOGERROR("No audio mode set, can not start playback");
  122. return false;
  123. }
  124. SDL_PauseAudioDevice(deviceID_, 0);
  125. playing_ = true;
  126. return true;
  127. }
  128. void Audio::Stop()
  129. {
  130. playing_ = false;
  131. }
  132. void Audio::SetMasterGain(SoundType type, float gain)
  133. {
  134. if (type >= MAX_SOUND_TYPES)
  135. return;
  136. masterGain_[type] = Clamp(gain, 0.0f, 1.0f);
  137. }
  138. void Audio::SetListener(SoundListener* listener)
  139. {
  140. listener_ = listener;
  141. }
  142. void Audio::StopSound(Sound* soundClip)
  143. {
  144. for (PODVector<SoundSource*>::Iterator i = soundSources_.Begin(); i != soundSources_.End(); ++i)
  145. {
  146. if ((*i)->GetSound() == soundClip)
  147. (*i)->Stop();
  148. }
  149. }
  150. float Audio::GetMasterGain(SoundType type) const
  151. {
  152. if (type >= MAX_SOUND_TYPES)
  153. return 0.0f;
  154. return masterGain_[type];
  155. }
  156. SoundListener* Audio::GetListener() const
  157. {
  158. return listener_;
  159. }
  160. void Audio::AddSoundSource(SoundSource* channel)
  161. {
  162. MutexLock lock(audioMutex_);
  163. soundSources_.Push(channel);
  164. }
  165. void Audio::RemoveSoundSource(SoundSource* channel)
  166. {
  167. PODVector<SoundSource*>::Iterator i = soundSources_.Find(channel);
  168. if (i != soundSources_.End())
  169. {
  170. MutexLock lock(audioMutex_);
  171. soundSources_.Erase(i);
  172. }
  173. }
  174. void SDLAudioCallback(void *userdata, Uint8* stream, int len)
  175. {
  176. Audio* audio = static_cast<Audio*>(userdata);
  177. {
  178. MutexLock Lock(audio->GetMutex());
  179. audio->MixOutput(stream, len / audio->GetSampleSize());
  180. }
  181. }
  182. void Audio::MixOutput(void *dest, unsigned samples)
  183. {
  184. if (!playing_ || !clipBuffer_)
  185. {
  186. memset(dest, 0, samples * sampleSize_);
  187. return;
  188. }
  189. while (samples)
  190. {
  191. // If sample count exceeds the fragment (clip buffer) size, split the work
  192. unsigned workSamples = Min((int)samples, (int)fragmentSize_);
  193. unsigned clipSamples = workSamples;
  194. if (stereo_)
  195. clipSamples <<= 1;
  196. // Clear clip buffer
  197. int* clipPtr = clipBuffer_.Get();
  198. memset(clipPtr, 0, clipSamples * sizeof(int));
  199. // Mix samples to clip buffer
  200. for (PODVector<SoundSource*>::Iterator i = soundSources_.Begin(); i != soundSources_.End(); ++i)
  201. (*i)->Mix(clipPtr, workSamples, mixRate_, stereo_, interpolation_);
  202. // Copy output from clip buffer to destination
  203. short* destPtr = (short*)dest;
  204. while (clipSamples--)
  205. *destPtr++ = Clamp(*clipPtr++, -32768, 32767);
  206. samples -= workSamples;
  207. ((unsigned char*&)destPtr) += sampleSize_ * workSamples;
  208. }
  209. }
  210. void Audio::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  211. {
  212. using namespace RenderUpdate;
  213. Update(eventData[P_TIMESTEP].GetFloat());
  214. }
  215. void Audio::Release()
  216. {
  217. Stop();
  218. if (deviceID_)
  219. {
  220. MutexLock lock(GetStaticMutex());
  221. SDL_CloseAudioDevice(deviceID_);
  222. deviceID_ = 0;
  223. clipBuffer_.Reset();
  224. }
  225. }
  226. void RegisterAudioLibrary(Context* context)
  227. {
  228. Sound::RegisterObject(context);
  229. SoundSource::RegisterObject(context);
  230. SoundSource3D::RegisterObject(context);
  231. SoundListener::RegisterObject(context);
  232. }
  233. }