Audio.cpp 11 KB

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