Audio.cpp 11 KB

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