Audio.cpp 7.7 KB

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