Audio.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Audio.h"
  25. #include "Context.h"
  26. #include "CoreEvents.h"
  27. #include "Graphics.h"
  28. #include "GraphicsEvents.h"
  29. #include "Log.h"
  30. #include "Mutex.h"
  31. #include "ProcessUtils.h"
  32. #include "Profiler.h"
  33. #include "Sound.h"
  34. #include "SoundSource3D.h"
  35. #include <SDL.h>
  36. #include "DebugNew.h"
  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. listenerPosition_(Vector3::ZERO),
  49. listenerRotation_(Quaternion::IDENTITY)
  50. {
  51. SubscribeToEvent(E_RENDERUPDATE, HANDLER(Audio, HandleRenderUpdate));
  52. for (unsigned i = 0; i < MAX_SOUND_TYPES; ++i)
  53. masterGain_[i] = 1.0f;
  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 = 1;
  71. if (stereo)
  72. desired.channels = 2;
  73. // For SDL, do not actually use the buffer length, but calculate a suitable power-of-two size from the mixrate
  74. if (desired.freq <= 11025)
  75. desired.samples = 512;
  76. else if (desired.freq <= 22050)
  77. desired.samples = 1024;
  78. else if (desired.freq <= 44100)
  79. desired.samples = 2048;
  80. else
  81. desired.samples = 4096;
  82. desired.callback = SDLAudioCallback;
  83. desired.userdata = this;
  84. {
  85. MutexLock lock(GetStaticMutex());
  86. deviceID_ = SDL_OpenAudioDevice(0, SDL_FALSE, &desired, &obtained, SDL_AUDIO_ALLOW_ANY_CHANGE);
  87. if (!deviceID_)
  88. {
  89. LOGERROR("Could not initialize audio output");
  90. return false;
  91. }
  92. if (obtained.format != AUDIO_S16SYS && obtained.format != AUDIO_S16LSB && obtained.format != AUDIO_S16MSB)
  93. {
  94. LOGERROR("Could not initialize audio output, 16-bit buffer format not supported");
  95. SDL_CloseAudioDevice(deviceID_);
  96. deviceID_ = 0;
  97. return false;
  98. }
  99. }
  100. stereo_ = obtained.channels == 2;
  101. sampleSize_ = stereo_ ? sizeof(int) : sizeof(short);
  102. fragmentSize_ = obtained.samples;
  103. mixRate_ = mixRate;
  104. interpolation_ = interpolation;
  105. clipBuffer_ = new int[stereo ? fragmentSize_ << 1 : fragmentSize_];
  106. LOGINFO("Set audio mode " + String(mixRate_) + " Hz " + (stereo_ ? "stereo" : "mono") + " " +
  107. (interpolation_ ? "interpolated" : ""));
  108. return Play();
  109. }
  110. void Audio::Update(float timeStep)
  111. {
  112. PROFILE(UpdateAudio);
  113. // Update in reverse order, because sound sources might remove themselves
  114. for (unsigned i = soundSources_.Size() - 1; i < soundSources_.Size(); --i)
  115. soundSources_[i]->Update(timeStep);
  116. }
  117. bool Audio::Play()
  118. {
  119. if (playing_)
  120. return true;
  121. if (!deviceID_)
  122. {
  123. LOGERROR("No audio mode set, can not start playback");
  124. return false;
  125. }
  126. SDL_PauseAudioDevice(deviceID_, 0);
  127. playing_ = true;
  128. return true;
  129. }
  130. void Audio::Stop()
  131. {
  132. playing_ = false;
  133. }
  134. void Audio::SetMasterGain(SoundType type, float gain)
  135. {
  136. if (type >= MAX_SOUND_TYPES)
  137. return;
  138. masterGain_[type] = Clamp(gain, 0.0f, 1.0f);
  139. }
  140. void Audio::SetListenerPosition(const Vector3& position)
  141. {
  142. listenerPosition_ = position;
  143. }
  144. void Audio::SetListenerRotation(const Quaternion& rotation)
  145. {
  146. listenerRotation_ = rotation;
  147. }
  148. void Audio::SetListenerTransform(const Vector3& position, const Quaternion& rotation)
  149. {
  150. listenerPosition_ = position;
  151. listenerRotation_ = rotation;
  152. }
  153. void Audio::StopSound(Sound* soundClip)
  154. {
  155. for (PODVector<SoundSource*>::Iterator i = soundSources_.Begin(); i != soundSources_.End(); ++i)
  156. {
  157. if ((*i)->GetSound() == soundClip)
  158. (*i)->Stop();
  159. }
  160. }
  161. float Audio::GetMasterGain(SoundType type) const
  162. {
  163. if (type >= MAX_SOUND_TYPES)
  164. return 0.0f;
  165. return masterGain_[type];
  166. }
  167. void Audio::AddSoundSource(SoundSource* channel)
  168. {
  169. MutexLock lock(audioMutex_);
  170. soundSources_.Push(channel);
  171. }
  172. void Audio::RemoveSoundSource(SoundSource* channel)
  173. {
  174. PODVector<SoundSource*>::Iterator i = soundSources_.Find(channel);
  175. if (i != soundSources_.End())
  176. {
  177. MutexLock lock(audioMutex_);
  178. soundSources_.Erase(i);
  179. }
  180. }
  181. void SDLAudioCallback(void *userdata, Uint8* stream, int len)
  182. {
  183. Audio* audio = static_cast<Audio*>(userdata);
  184. {
  185. MutexLock Lock(audio->GetMutex());
  186. audio->MixOutput(stream, len / audio->GetSampleSize());
  187. }
  188. }
  189. void Audio::MixOutput(void *dest, unsigned samples)
  190. {
  191. if (!playing_ || !clipBuffer_)
  192. {
  193. memset(dest, 0, samples * sampleSize_);
  194. return;
  195. }
  196. while (samples)
  197. {
  198. // If sample count exceeds the fragment (clip buffer) size, split the work
  199. unsigned workSamples = Min((int)samples, (int)fragmentSize_);
  200. unsigned clipSamples = workSamples;
  201. if (stereo_)
  202. clipSamples <<= 1;
  203. // Clear clip buffer
  204. memset(clipBuffer_.Get(), 0, clipSamples * sizeof(int));
  205. int* clipPtr = clipBuffer_.Get();
  206. // Mix samples to clip buffer
  207. for (PODVector<SoundSource*>::Iterator i = soundSources_.Begin(); i != soundSources_.End(); ++i)
  208. (*i)->Mix(clipPtr, workSamples, mixRate_, stereo_, interpolation_);
  209. // Copy output from clip buffer to destination
  210. clipPtr = clipBuffer_.Get();
  211. short* destPtr = (short*)dest;
  212. while (clipSamples--)
  213. *destPtr++ = Clamp(*clipPtr++, -32768, 32767);
  214. samples -= workSamples;
  215. ((unsigned char*&)destPtr) += sampleSize_ * workSamples;
  216. }
  217. }
  218. void Audio::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  219. {
  220. using namespace RenderUpdate;
  221. Update(eventData[P_TIMESTEP].GetFloat());
  222. }
  223. void Audio::Release()
  224. {
  225. Stop();
  226. if (deviceID_)
  227. {
  228. MutexLock lock(GetStaticMutex());
  229. SDL_CloseAudioDevice(deviceID_);
  230. deviceID_ = 0;
  231. clipBuffer_.Reset();
  232. }
  233. }
  234. void RegisterAudioLibrary(Context* context)
  235. {
  236. Sound::RegisterObject(context);
  237. SoundSource::RegisterObject(context);
  238. SoundSource3D::RegisterObject(context);
  239. }