Audio.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. //
  2. // Copyright (c) 2008-2020 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. {
  48. context_->RequireSDL(SDL_INIT_AUDIO);
  49. // Set the master to the default value
  50. masterGain_[SOUND_MASTER_HASH] = 1.0f;
  51. // Register Audio library object factories
  52. RegisterAudioLibrary(context_);
  53. SubscribeToEvent(E_RENDERUPDATE, URHO3D_HANDLER(Audio, HandleRenderUpdate));
  54. }
  55. Audio::~Audio()
  56. {
  57. Release();
  58. context_->ReleaseSDL();
  59. }
  60. bool Audio::SetMode(int bufferLengthMSec, int mixRate, bool stereo, bool interpolation)
  61. {
  62. Release();
  63. bufferLengthMSec = Max(bufferLengthMSec, MIN_BUFFERLENGTH);
  64. mixRate = Clamp(mixRate, MIN_MIXRATE, MAX_MIXRATE);
  65. SDL_AudioSpec desired;
  66. SDL_AudioSpec obtained;
  67. desired.freq = mixRate;
  68. desired.format = AUDIO_S16;
  69. desired.channels = (Uint8)(stereo ? 2 : 1);
  70. desired.callback = SDLAudioCallback;
  71. desired.userdata = this;
  72. // SDL uses power of two audio fragments. Determine the closest match
  73. int bufferSamples = mixRate * bufferLengthMSec / 1000;
  74. desired.samples = (Uint16)NextPowerOfTwo((unsigned)bufferSamples);
  75. if (Abs((int)desired.samples / 2 - bufferSamples) < Abs((int)desired.samples - bufferSamples))
  76. desired.samples /= 2;
  77. // Intentionally disallow format change so that the obtained format will always be the desired format, even though that format
  78. // is not matching the device format, however in doing it will enable the SDL's internal audio stream with audio conversion
  79. deviceID_ = SDL_OpenAudioDevice(nullptr, SDL_FALSE, &desired, &obtained, SDL_AUDIO_ALLOW_ANY_CHANGE&~SDL_AUDIO_ALLOW_FORMAT_CHANGE);
  80. if (!deviceID_)
  81. {
  82. URHO3D_LOGERROR("Could not initialize audio output");
  83. return false;
  84. }
  85. if (obtained.format != AUDIO_S16)
  86. {
  87. URHO3D_LOGERROR("Could not initialize audio output, 16-bit buffer format not supported");
  88. SDL_CloseAudioDevice(deviceID_);
  89. deviceID_ = 0;
  90. return false;
  91. }
  92. stereo_ = obtained.channels == 2;
  93. sampleSize_ = (unsigned)(stereo_ ? sizeof(int) : sizeof(short));
  94. // Guarantee a fragment size that is low enough so that Vorbis decoding buffers do not wrap
  95. fragmentSize_ = Min(NextPowerOfTwo((unsigned)mixRate >> 6u), (unsigned)obtained.samples);
  96. mixRate_ = obtained.freq;
  97. interpolation_ = interpolation;
  98. clipBuffer_ = new int[stereo ? fragmentSize_ << 1u : fragmentSize_];
  99. URHO3D_LOGINFO("Set audio mode " + String(mixRate_) + " Hz " + (stereo_ ? "stereo" : "mono") + " " +
  100. (interpolation_ ? "interpolated" : ""));
  101. return Play();
  102. }
  103. void Audio::Update(float timeStep)
  104. {
  105. if (!playing_)
  106. return;
  107. UpdateInternal(timeStep);
  108. }
  109. bool Audio::Play()
  110. {
  111. if (playing_)
  112. return true;
  113. if (!deviceID_)
  114. {
  115. URHO3D_LOGERROR("No audio mode set, can not start playback");
  116. return false;
  117. }
  118. SDL_PauseAudioDevice(deviceID_, 0);
  119. // Update sound sources before resuming playback to make sure 3D positions are up to date
  120. UpdateInternal(0.0f);
  121. playing_ = true;
  122. return true;
  123. }
  124. void Audio::Stop()
  125. {
  126. playing_ = false;
  127. }
  128. void Audio::SetMasterGain(const String& type, float gain)
  129. {
  130. masterGain_[type] = Clamp(gain, 0.0f, 1.0f);
  131. for (PODVector<SoundSource*>::Iterator i = soundSources_.Begin(); i != soundSources_.End(); ++i)
  132. (*i)->UpdateMasterGain();
  133. }
  134. void Audio::PauseSoundType(const String& type)
  135. {
  136. MutexLock lock(audioMutex_);
  137. pausedSoundTypes_.Insert(type);
  138. }
  139. void Audio::ResumeSoundType(const String& type)
  140. {
  141. MutexLock lock(audioMutex_);
  142. pausedSoundTypes_.Erase(type);
  143. // Update sound sources before resuming playback to make sure 3D positions are up to date
  144. // Done under mutex to ensure no mixing happens before we are ready
  145. UpdateInternal(0.0f);
  146. }
  147. void Audio::ResumeAll()
  148. {
  149. MutexLock lock(audioMutex_);
  150. pausedSoundTypes_.Clear();
  151. UpdateInternal(0.0f);
  152. }
  153. void Audio::SetListener(SoundListener* listener)
  154. {
  155. listener_ = listener;
  156. }
  157. void Audio::StopSound(Sound* sound)
  158. {
  159. for (PODVector<SoundSource*>::Iterator i = soundSources_.Begin(); i != soundSources_.End(); ++i)
  160. {
  161. if ((*i)->GetSound() == sound)
  162. (*i)->Stop();
  163. }
  164. }
  165. float Audio::GetMasterGain(const String& type) const
  166. {
  167. // By definition previously unknown types return full volume
  168. HashMap<StringHash, Variant>::ConstIterator findIt = masterGain_.Find(type);
  169. if (findIt == masterGain_.End())
  170. return 1.0f;
  171. return findIt->second_.GetFloat();
  172. }
  173. bool Audio::IsSoundTypePaused(const String& type) const
  174. {
  175. return pausedSoundTypes_.Contains(type);
  176. }
  177. SoundListener* Audio::GetListener() const
  178. {
  179. return listener_;
  180. }
  181. void Audio::AddSoundSource(SoundSource* soundSource)
  182. {
  183. MutexLock lock(audioMutex_);
  184. soundSources_.Push(soundSource);
  185. }
  186. void Audio::RemoveSoundSource(SoundSource* soundSource)
  187. {
  188. PODVector<SoundSource*>::Iterator i = soundSources_.Find(soundSource);
  189. if (i != soundSources_.End())
  190. {
  191. MutexLock lock(audioMutex_);
  192. soundSources_.Erase(i);
  193. }
  194. }
  195. float Audio::GetSoundSourceMasterGain(StringHash typeHash) const
  196. {
  197. HashMap<StringHash, Variant>::ConstIterator masterIt = masterGain_.Find(SOUND_MASTER_HASH);
  198. if (!typeHash)
  199. return masterIt->second_.GetFloat();
  200. HashMap<StringHash, Variant>::ConstIterator typeIt = masterGain_.Find(typeHash);
  201. if (typeIt == masterGain_.End() || typeIt == masterIt)
  202. return masterIt->second_.GetFloat();
  203. return masterIt->second_.GetFloat() * typeIt->second_.GetFloat();
  204. }
  205. void SDLAudioCallback(void* userdata, Uint8* stream, int len)
  206. {
  207. auto* audio = static_cast<Audio*>(userdata);
  208. {
  209. MutexLock Lock(audio->GetMutex());
  210. audio->MixOutput(stream, len / audio->GetSampleSize());
  211. }
  212. }
  213. void Audio::MixOutput(void* dest, unsigned samples)
  214. {
  215. if (!playing_ || !clipBuffer_)
  216. {
  217. memset(dest, 0, samples * (size_t)sampleSize_);
  218. return;
  219. }
  220. while (samples)
  221. {
  222. // If sample count exceeds the fragment (clip buffer) size, split the work
  223. unsigned workSamples = Min(samples, fragmentSize_);
  224. unsigned clipSamples = workSamples;
  225. if (stereo_)
  226. clipSamples <<= 1;
  227. // Clear clip buffer
  228. int* clipPtr = clipBuffer_.Get();
  229. memset(clipPtr, 0, clipSamples * sizeof(int));
  230. // Mix samples to clip buffer
  231. for (PODVector<SoundSource*>::Iterator i = soundSources_.Begin(); i != soundSources_.End(); ++i)
  232. {
  233. SoundSource* source = *i;
  234. // Check for pause if necessary
  235. if (!pausedSoundTypes_.Empty())
  236. {
  237. if (pausedSoundTypes_.Contains(source->GetSoundType()))
  238. continue;
  239. }
  240. source->Mix(clipPtr, workSamples, mixRate_, stereo_, interpolation_);
  241. }
  242. // Copy output from clip buffer to destination
  243. auto* destPtr = (short*)dest;
  244. while (clipSamples--)
  245. *destPtr++ = (short)Clamp(*clipPtr++, -32768, 32767);
  246. samples -= workSamples;
  247. ((unsigned char*&)dest) += sampleSize_ * workSamples;
  248. }
  249. }
  250. void Audio::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  251. {
  252. using namespace RenderUpdate;
  253. Update(eventData[P_TIMESTEP].GetFloat());
  254. }
  255. void Audio::Release()
  256. {
  257. Stop();
  258. if (deviceID_)
  259. {
  260. SDL_CloseAudioDevice(deviceID_);
  261. deviceID_ = 0;
  262. clipBuffer_.Reset();
  263. }
  264. }
  265. void Audio::UpdateInternal(float timeStep)
  266. {
  267. URHO3D_PROFILE(UpdateAudio);
  268. // Update in reverse order, because sound sources might remove themselves
  269. for (unsigned i = soundSources_.Size() - 1; i < soundSources_.Size(); --i)
  270. {
  271. SoundSource* source = soundSources_[i];
  272. // Check for pause if necessary; do not update paused sound sources
  273. if (!pausedSoundTypes_.Empty())
  274. {
  275. if (pausedSoundTypes_.Contains(source->GetSoundType()))
  276. continue;
  277. }
  278. source->Update(timeStep);
  279. }
  280. }
  281. void RegisterAudioLibrary(Context* context)
  282. {
  283. Sound::RegisterObject(context);
  284. SoundSource::RegisterObject(context);
  285. SoundSource3D::RegisterObject(context);
  286. SoundListener::RegisterObject(context);
  287. }
  288. }