Audio.cpp 11 KB

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