Audio.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Audio.h"
  25. #include "Context.h"
  26. #include "CoreEvents.h"
  27. #include "Graphics.h"
  28. #include "GraphicsEvents.h"
  29. #include "Log.h"
  30. #include "Mutex.h"
  31. #include "ProcessUtils.h"
  32. #include "Profiler.h"
  33. #include "Sound.h"
  34. #include "SoundSource3D.h"
  35. #ifndef USE_OPENGL
  36. #define DIRECTSOUND_VERSION 0x0800
  37. #include "Thread.h"
  38. #include "Timer.h"
  39. #include <windows.h>
  40. #include <mmsystem.h>
  41. #include <dsound.h>
  42. #else
  43. #include <SDL.h>
  44. #endif
  45. #include "DebugNew.h"
  46. static const int MIN_BUFFERLENGTH = 20;
  47. static const int MIN_MIXRATE = 11025;
  48. static const int MAX_MIXRATE = 48000;
  49. static const int AUDIO_FPS = 100;
  50. #ifdef USE_OPENGL
  51. static void SDLAudioCallback(void *userdata, Uint8 *stream, int len);
  52. #else
  53. /// DirectSound audio output stream.
  54. class AudioStream : public Thread
  55. {
  56. public:
  57. /// Construct.
  58. AudioStream(Audio* owner) :
  59. owner_(owner),
  60. dsObject_(0),
  61. dsBuffer_(0)
  62. {
  63. }
  64. /// Destruct.
  65. ~AudioStream()
  66. {
  67. Close();
  68. if (dsObject_)
  69. {
  70. dsObject_->Release();
  71. dsObject_ = 0;
  72. }
  73. }
  74. /// Create the DirectSound buffer.
  75. bool Open(unsigned windowHandle, int bufferLengthMSec, int mixRate, bool stereo)
  76. {
  77. Close();
  78. if (!dsObject_)
  79. {
  80. if (DirectSoundCreate(0, &dsObject_, 0) != DS_OK)
  81. return false;
  82. }
  83. if (dsObject_->SetCooperativeLevel((HWND)windowHandle, DSSCL_PRIORITY) != DS_OK)
  84. return false;
  85. WAVEFORMATEX waveFormat;
  86. waveFormat.wFormatTag = WAVE_FORMAT_PCM;
  87. waveFormat.nSamplesPerSec = mixRate;
  88. waveFormat.wBitsPerSample = 16;
  89. if (stereo)
  90. waveFormat.nChannels = 2;
  91. else
  92. waveFormat.nChannels = 1;
  93. sampleSize_ = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
  94. unsigned numSamples = (bufferLengthMSec * mixRate) / 1000;
  95. waveFormat.nAvgBytesPerSec = mixRate * sampleSize_;
  96. waveFormat.nBlockAlign = sampleSize_;
  97. waveFormat.cbSize = 0;
  98. DSBUFFERDESC bufferDesc;
  99. memset(&bufferDesc, 0, sizeof(bufferDesc));
  100. bufferDesc.dwSize = sizeof(bufferDesc);
  101. bufferDesc.dwFlags = DSBCAPS_STICKYFOCUS;
  102. bufferDesc.dwBufferBytes = numSamples * sampleSize_;
  103. bufferDesc.lpwfxFormat = &waveFormat;
  104. bufferSize_ = bufferDesc.dwBufferBytes;
  105. return dsObject_->CreateSoundBuffer(&bufferDesc, &dsBuffer_, 0) == DS_OK;
  106. }
  107. /// Destroy the DirectSound buffer.
  108. void Close()
  109. {
  110. StopPlayback();
  111. if (dsBuffer_)
  112. {
  113. dsBuffer_->Release();
  114. dsBuffer_ = 0;
  115. }
  116. }
  117. /// Start playback.
  118. bool StartPlayback()
  119. {
  120. if (IsStarted())
  121. return true;
  122. if (!dsBuffer_)
  123. return false;
  124. // Clear the buffer before starting playback
  125. DWORD bytes1, bytes2;
  126. void *ptr1, *ptr2;
  127. if (dsBuffer_->Lock(0, bufferSize_, &ptr1, &bytes1, &ptr2, &bytes2, 0) == DS_OK)
  128. {
  129. if (bytes1)
  130. memset(ptr1, 0, bytes1);
  131. if (bytes2)
  132. memset(ptr2, 0, bytes2);
  133. dsBuffer_->Unlock(ptr1, bytes1, ptr2, bytes2);
  134. }
  135. if (Start())
  136. {
  137. SetPriority(THREAD_PRIORITY_ABOVE_NORMAL);
  138. return true;
  139. }
  140. else
  141. return false;
  142. }
  143. /// Stop playback.
  144. void StopPlayback()
  145. {
  146. if (dsBuffer_ && IsStarted())
  147. Stop();
  148. }
  149. /// Mixing thread function.
  150. void ThreadFunction()
  151. {
  152. DWORD playCursor = 0;
  153. DWORD writeCursor = 0;
  154. while (shouldRun_)
  155. {
  156. Timer audioUpdateTimer;
  157. // Restore buffer / restart playback if necessary
  158. DWORD status;
  159. dsBuffer_->GetStatus(&status);
  160. if (status == DSBSTATUS_BUFFERLOST)
  161. {
  162. dsBuffer_->Restore();
  163. dsBuffer_->GetStatus(&status);
  164. }
  165. if (!(status & DSBSTATUS_PLAYING))
  166. {
  167. dsBuffer_->Play(0, 0, DSBPLAY_LOOPING);
  168. writeCursor = 0;
  169. }
  170. // Get current buffer position
  171. dsBuffer_->GetCurrentPosition(&playCursor, 0);
  172. playCursor %= bufferSize_;
  173. playCursor &= -((int)sampleSize_);
  174. if (playCursor != writeCursor)
  175. {
  176. int writeBytes = playCursor - writeCursor;
  177. if (writeBytes < 0)
  178. writeBytes += bufferSize_;
  179. // Try to lock buffer
  180. DWORD bytes1, bytes2;
  181. void *ptr1, *ptr2;
  182. if (dsBuffer_->Lock(writeCursor, writeBytes, &ptr1, &bytes1, &ptr2, &bytes2, 0) == DS_OK)
  183. {
  184. // Mix sound to locked positions
  185. {
  186. MutexLock lock(owner_->GetMutex());
  187. if (bytes1)
  188. owner_->MixOutput(ptr1, bytes1 / sampleSize_);
  189. if (bytes2)
  190. owner_->MixOutput(ptr2, bytes2 / sampleSize_);
  191. }
  192. // Unlock buffer and update write cursor
  193. dsBuffer_->Unlock(ptr1, bytes1, ptr2, bytes2);
  194. writeCursor += writeBytes;
  195. if (writeCursor >= bufferSize_)
  196. writeCursor -= bufferSize_;
  197. }
  198. }
  199. // Sleep the remaining time of the audio update period
  200. int audioSleepTime = Max(1000 / AUDIO_FPS - (int)audioUpdateTimer.GetMSec(false), 0);
  201. Sleep(audioSleepTime);
  202. }
  203. dsBuffer_->Stop();
  204. }
  205. private:
  206. /// Audio subsystem.
  207. Audio* owner_;
  208. /// DirectSound interface.
  209. IDirectSound* dsObject_;
  210. /// DirectSound buffer.
  211. IDirectSoundBuffer* dsBuffer_;
  212. /// Sound buffer size in bytes.
  213. unsigned bufferSize_;
  214. /// Sound buffer sample size.
  215. unsigned sampleSize_;
  216. /// Playing flag.
  217. bool playing_;
  218. };
  219. #endif
  220. OBJECTTYPESTATIC(Audio);
  221. Audio::Audio(Context* context) :
  222. Object(context),
  223. stream_(0),
  224. sampleSize_(0),
  225. playing_(false),
  226. listenerPosition_(Vector3::ZERO),
  227. listenerRotation_(Quaternion::IDENTITY)
  228. {
  229. SubscribeToEvent(E_RENDERUPDATE, HANDLER(Audio, HandleRenderUpdate));
  230. for (unsigned i = 0; i < MAX_SOUND_TYPES; ++i)
  231. masterGain_[i] = 1.0f;
  232. }
  233. Audio::~Audio()
  234. {
  235. Release();
  236. #ifndef USE_OPENGL
  237. delete (AudioStream*)stream_;
  238. stream_ = 0;
  239. #endif
  240. }
  241. bool Audio::SetMode(int bufferLengthMSec, int mixRate, bool stereo, bool interpolation)
  242. {
  243. Release();
  244. bufferLengthMSec = Max(bufferLengthMSec, MIN_BUFFERLENGTH);
  245. mixRate = Clamp(mixRate, MIN_MIXRATE, MAX_MIXRATE);
  246. // Guarantee a fragment size that is low enough so that Vorbis decoding buffers do not wrap
  247. fragmentSize_ = NextPowerOfTwo(mixRate >> 6);
  248. #ifdef USE_OPENGL
  249. SDL_AudioSpec desired;
  250. SDL_AudioSpec obtained;
  251. desired.freq = mixRate;
  252. desired.format = AUDIO_S16SYS;
  253. desired.channels = 1;
  254. if (stereo)
  255. desired.channels = 2;
  256. // For SDL, do not actually use the buffer length, but calculate a suitable power-of-two size from the mixrate
  257. if (desired.freq <= 11025)
  258. desired.samples = 512;
  259. else if (desired.freq <= 22050)
  260. desired.samples = 1024;
  261. else if (desired.freq <= 44100)
  262. desired.samples = 2048;
  263. else
  264. desired.samples = 4096;
  265. desired.callback = SDLAudioCallback;
  266. desired.userdata = this;
  267. stream_ = SDL_OpenAudioDevice(0, SDL_FALSE, &desired, &obtained, SDL_AUDIO_ALLOW_ANY_CHANGE);
  268. if (!stream_)
  269. {
  270. LOGERROR("Could not initialize audio output");
  271. return false;
  272. }
  273. if (obtained.format != AUDIO_S16SYS && obtained.format != AUDIO_S16LSB && obtained.format != AUDIO_S16MSB)
  274. {
  275. LOGERROR("Could not initialize audio output, 16-bit buffer format not supported");
  276. SDL_CloseAudioDevice(stream_);
  277. stream_ = 0;
  278. return false;
  279. }
  280. if (obtained.channels == 2)
  281. stereo_ = true;
  282. fragmentSize_ = obtained.samples;
  283. #else
  284. if (!stream_)
  285. stream_ = new AudioStream(this);
  286. unsigned windowHandle = 0;
  287. Graphics* graphics = GetSubsystem<Graphics>();
  288. if (graphics)
  289. windowHandle = graphics->GetWindowHandle();
  290. if (!((AudioStream*)stream_)->Open(windowHandle, bufferLengthMSec, mixRate, stereo))
  291. {
  292. LOGERROR("Failed to open audio stream");
  293. return false;
  294. }
  295. #endif
  296. clipBuffer_ = new int[stereo ? fragmentSize_ << 1 : fragmentSize_];
  297. sampleSize_ = sizeof(short);
  298. if (stereo)
  299. sampleSize_ <<= 1;
  300. mixRate_ = mixRate;
  301. stereo_ = stereo;
  302. interpolation_ = interpolation;
  303. LOGINFO("Set audio mode " + String(mixRate_) + " Hz " + (stereo_ ? "stereo" : "mono") + " " +
  304. (interpolation_ ? "interpolated" : ""));
  305. return Play();
  306. }
  307. void Audio::Update(float timeStep)
  308. {
  309. PROFILE(UpdateAudio);
  310. // Update in reverse order, because sound sources might remove themselves
  311. for (unsigned i = soundSources_.Size() - 1; i < soundSources_.Size(); --i)
  312. soundSources_[i]->Update(timeStep);
  313. }
  314. bool Audio::Play()
  315. {
  316. if (playing_)
  317. return true;
  318. if (!stream_)
  319. {
  320. LOGERROR("No audio mode set, can not start playback");
  321. return false;
  322. }
  323. #ifdef USE_OPENGL
  324. if (!clipBuffer_)
  325. {
  326. LOGERROR("No audio buffer, can not start playback");
  327. return false;
  328. }
  329. SDL_PauseAudioDevice(stream_, 0);
  330. #else
  331. if (!((AudioStream*)stream_)->StartPlayback())
  332. {
  333. LOGERROR("Failed to start playback");
  334. return false;
  335. }
  336. #endif
  337. playing_ = true;
  338. return true;
  339. }
  340. void Audio::Stop()
  341. {
  342. if (!playing_)
  343. return;
  344. #ifdef USE_OPENGL
  345. SDL_PauseAudioDevice(stream_, 1);
  346. #else
  347. if (stream_)
  348. ((AudioStream*)stream_)->StopPlayback();
  349. #endif
  350. playing_ = false;
  351. }
  352. void Audio::SetMasterGain(SoundType type, float gain)
  353. {
  354. if (type >= MAX_SOUND_TYPES)
  355. return;
  356. masterGain_[type] = Clamp(gain, 0.0f, 1.0f);
  357. }
  358. void Audio::SetListenerPosition(const Vector3& position)
  359. {
  360. listenerPosition_ = position;
  361. }
  362. void Audio::SetListenerRotation(const Quaternion& rotation)
  363. {
  364. listenerRotation_ = rotation;
  365. }
  366. void Audio::SetListenerTransform(const Vector3& position, const Quaternion& rotation)
  367. {
  368. listenerPosition_ = position;
  369. listenerRotation_ = rotation;
  370. }
  371. void Audio::StopSound(Sound* soundClip)
  372. {
  373. for (PODVector<SoundSource*>::Iterator i = soundSources_.Begin(); i != soundSources_.End(); ++i)
  374. {
  375. if ((*i)->GetSound() == soundClip)
  376. (*i)->Stop();
  377. }
  378. }
  379. float Audio::GetMasterGain(SoundType type) const
  380. {
  381. if (type >= MAX_SOUND_TYPES)
  382. return 0.0f;
  383. return masterGain_[type];
  384. }
  385. void Audio::AddSoundSource(SoundSource* channel)
  386. {
  387. MutexLock lock(audioMutex_);
  388. soundSources_.Push(channel);
  389. }
  390. void Audio::RemoveSoundSource(SoundSource* channel)
  391. {
  392. PODVector<SoundSource*>::Iterator i = soundSources_.Find(channel);
  393. if (i != soundSources_.End())
  394. {
  395. MutexLock lock(audioMutex_);
  396. soundSources_.Erase(i);
  397. }
  398. }
  399. #ifdef USE_OPENGL
  400. void SDLAudioCallback(void *userdata, Uint8* stream, int len)
  401. {
  402. Audio* audio = static_cast<Audio*>(userdata);
  403. {
  404. MutexLock Lock(audio->GetMutex());
  405. audio->MixOutput(stream, len / audio->GetSampleSize());
  406. }
  407. }
  408. #endif
  409. void Audio::MixOutput(void *dest, unsigned samples)
  410. {
  411. if (!playing_ || !clipBuffer_)
  412. {
  413. memset(dest, 0, samples * sampleSize_);
  414. return;
  415. }
  416. while (samples)
  417. {
  418. // If sample count exceeds the fragment (clip buffer) size, split the work
  419. unsigned workSamples = Min((int)samples, (int)fragmentSize_);
  420. unsigned clipSamples = workSamples;
  421. if (stereo_)
  422. clipSamples <<= 1;
  423. // Clear clip buffer
  424. memset(clipBuffer_.Get(), 0, clipSamples * sizeof(int));
  425. int* clipPtr = clipBuffer_.Get();
  426. // Mix samples to clip buffer
  427. for (PODVector<SoundSource*>::Iterator i = soundSources_.Begin(); i != soundSources_.End(); ++i)
  428. (*i)->Mix(clipPtr, workSamples, mixRate_, stereo_, interpolation_);
  429. // Copy output from clip buffer to destination
  430. clipPtr = clipBuffer_.Get();
  431. short* destPtr = (short*)dest;
  432. while (clipSamples--)
  433. *destPtr++ = Clamp(*clipPtr++, -32768, 32767);
  434. samples -= workSamples;
  435. ((unsigned char*&)destPtr) += sampleSize_ * workSamples;
  436. }
  437. }
  438. void Audio::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  439. {
  440. using namespace RenderUpdate;
  441. Update(eventData[P_TIMESTEP].GetFloat());
  442. }
  443. void Audio::Release()
  444. {
  445. Stop();
  446. if (stream_)
  447. {
  448. #ifdef USE_OPENGL
  449. if (clipBuffer_)
  450. {
  451. SDL_CloseAudioDevice(stream_);
  452. stream_ = 0;
  453. clipBuffer_.Reset();
  454. }
  455. #else
  456. ((AudioStream*)stream_)->Close();
  457. #endif
  458. clipBuffer_.Reset();
  459. }
  460. }
  461. void RegisterAudioLibrary(Context* context)
  462. {
  463. Sound::RegisterObject(context);
  464. SoundSource::RegisterObject(context);
  465. SoundSource3D::RegisterObject(context);
  466. }