Audio.cpp 9.1 KB

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