Audio.cpp 7.8 KB

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