Audio.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 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. #ifdef USE_OPENGL
  36. #include <portaudio.h>
  37. #else
  38. #define DIRECTSOUND_VERSION 0x0800
  39. #include "Thread.h"
  40. #include "Timer.h"
  41. #include <windows.h>
  42. #include <mmsystem.h>
  43. #include <dsound.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 unsigned numInstances = 0;
  52. static int AudioCallback(const void* inputBuffer, void* outputBuffer, unsigned long framesPerBuffer,
  53. const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void* userData);
  54. #else
  55. /// DirectSound audio output stream.
  56. class AudioStream : public Thread
  57. {
  58. public:
  59. /// Construct.
  60. AudioStream(Audio* owner) :
  61. owner_(owner),
  62. dsObject_(0),
  63. dsBuffer_(0)
  64. {
  65. }
  66. /// Destruct.
  67. ~AudioStream()
  68. {
  69. Close();
  70. if (dsObject_)
  71. {
  72. dsObject_->Release();
  73. dsObject_ = 0;
  74. }
  75. }
  76. /// Create the DirectSound buffer.
  77. bool Open(unsigned windowHandle, int bufferLengthMSec, int mixRate, bool stereo)
  78. {
  79. Close();
  80. if (!dsObject_)
  81. {
  82. if (DirectSoundCreate(0, &dsObject_, 0) != DS_OK)
  83. return false;
  84. }
  85. if (dsObject_->SetCooperativeLevel((HWND)windowHandle, DSSCL_PRIORITY) != DS_OK)
  86. return false;
  87. WAVEFORMATEX waveFormat;
  88. waveFormat.wFormatTag = WAVE_FORMAT_PCM;
  89. waveFormat.nSamplesPerSec = mixRate;
  90. waveFormat.wBitsPerSample = 16;
  91. if (stereo)
  92. waveFormat.nChannels = 2;
  93. else
  94. waveFormat.nChannels = 1;
  95. sampleSize_ = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
  96. unsigned numSamples = (bufferLengthMSec * mixRate) / 1000;
  97. waveFormat.nAvgBytesPerSec = mixRate * sampleSize_;
  98. waveFormat.nBlockAlign = sampleSize_;
  99. waveFormat.cbSize = 0;
  100. DSBUFFERDESC bufferDesc;
  101. memset(&bufferDesc, 0, sizeof(bufferDesc));
  102. bufferDesc.dwSize = sizeof(bufferDesc);
  103. bufferDesc.dwFlags = DSBCAPS_STICKYFOCUS;
  104. bufferDesc.dwBufferBytes = numSamples * sampleSize_;
  105. bufferDesc.lpwfxFormat = &waveFormat;
  106. bufferSize_ = bufferDesc.dwBufferBytes;
  107. return dsObject_->CreateSoundBuffer(&bufferDesc, &dsBuffer_, 0) == DS_OK;
  108. }
  109. /// Destroy the DirectSound buffer.
  110. void Close()
  111. {
  112. StopPlayback();
  113. if (dsBuffer_)
  114. {
  115. dsBuffer_->Release();
  116. dsBuffer_ = 0;
  117. }
  118. }
  119. /// Start playback.
  120. bool StartPlayback()
  121. {
  122. if (IsStarted())
  123. return true;
  124. if (!dsBuffer_)
  125. return false;
  126. // Clear the buffer before starting playback
  127. DWORD bytes1, bytes2;
  128. void *ptr1, *ptr2;
  129. if (dsBuffer_->Lock(0, bufferSize_, &ptr1, &bytes1, &ptr2, &bytes2, 0) == DS_OK)
  130. {
  131. if (bytes1)
  132. memset(ptr1, 0, bytes1);
  133. if (bytes2)
  134. memset(ptr2, 0, bytes2);
  135. dsBuffer_->Unlock(ptr1, bytes1, ptr2, bytes2);
  136. }
  137. if (Start())
  138. {
  139. SetPriority(THREAD_PRIORITY_ABOVE_NORMAL);
  140. return true;
  141. }
  142. else
  143. return false;
  144. }
  145. /// Stop playback.
  146. void StopPlayback()
  147. {
  148. if (dsBuffer_ && IsStarted())
  149. Stop();
  150. }
  151. /// Mixing thread function.
  152. void ThreadFunction()
  153. {
  154. DWORD playCursor = 0;
  155. DWORD writeCursor = 0;
  156. while (shouldRun_)
  157. {
  158. Timer audioUpdateTimer;
  159. // Restore buffer / restart playback if necessary
  160. DWORD status;
  161. dsBuffer_->GetStatus(&status);
  162. if (status == DSBSTATUS_BUFFERLOST)
  163. {
  164. dsBuffer_->Restore();
  165. dsBuffer_->GetStatus(&status);
  166. }
  167. if (!(status & DSBSTATUS_PLAYING))
  168. {
  169. dsBuffer_->Play(0, 0, DSBPLAY_LOOPING);
  170. writeCursor = 0;
  171. }
  172. // Get current buffer position
  173. dsBuffer_->GetCurrentPosition(&playCursor, 0);
  174. playCursor %= bufferSize_;
  175. playCursor &= -((int)sampleSize_);
  176. if (playCursor != writeCursor)
  177. {
  178. int writeBytes = playCursor - writeCursor;
  179. if (writeBytes < 0)
  180. writeBytes += bufferSize_;
  181. // Try to lock buffer
  182. DWORD bytes1, bytes2;
  183. void *ptr1, *ptr2;
  184. if (dsBuffer_->Lock(writeCursor, writeBytes, &ptr1, &bytes1, &ptr2, &bytes2, 0) == DS_OK)
  185. {
  186. // Mix sound to locked positions
  187. {
  188. MutexLock lock(owner_->GetMutex());
  189. if (bytes1)
  190. owner_->MixOutput(ptr1, bytes1 / sampleSize_);
  191. if (bytes2)
  192. owner_->MixOutput(ptr2, bytes2 / sampleSize_);
  193. }
  194. // Unlock buffer and update write cursor
  195. dsBuffer_->Unlock(ptr1, bytes1, ptr2, bytes2);
  196. writeCursor += writeBytes;
  197. if (writeCursor >= bufferSize_)
  198. writeCursor -= bufferSize_;
  199. }
  200. }
  201. // Sleep the remaining time of the audio update period
  202. int audioSleepTime = Max(1000 / AUDIO_FPS - (int)audioUpdateTimer.GetMSec(false), 0);
  203. Sleep(audioSleepTime);
  204. }
  205. dsBuffer_->Stop();
  206. }
  207. private:
  208. /// Audio subsystem.
  209. Audio* owner_;
  210. /// DirectSound interface.
  211. IDirectSound* dsObject_;
  212. /// DirectSound buffer.
  213. IDirectSoundBuffer* dsBuffer_;
  214. /// Sound buffer size in bytes.
  215. unsigned bufferSize_;
  216. /// Sound buffer sample size.
  217. unsigned sampleSize_;
  218. /// Playing flag.
  219. bool playing_;
  220. };
  221. #endif
  222. OBJECTTYPESTATIC(Audio);
  223. Audio::Audio(Context* context) :
  224. Object(context),
  225. stream_(0),
  226. sampleSize_(0),
  227. playing_(false),
  228. listenerPosition_(Vector3::ZERO),
  229. listenerRotation_(Quaternion::IDENTITY)
  230. {
  231. SubscribeToEvent(E_RENDERUPDATE, HANDLER(Audio, HandleRenderUpdate));
  232. for (unsigned i = 0; i < MAX_SOUND_TYPES; ++i)
  233. masterGain_[i] = 1.0f;
  234. // Initialize PortAudio under static mutex in case this is the first instance
  235. #ifdef USE_OPENGL
  236. {
  237. MutexLock lock(GetStaticMutex());
  238. if (!numInstances)
  239. {
  240. if (Pa_Initialize() != paNoError)
  241. LOGERROR("Could not initialize PortAudio");
  242. }
  243. ++numInstances;
  244. }
  245. #endif
  246. }
  247. Audio::~Audio()
  248. {
  249. Release();
  250. // Uninitialize PortAudio under static mutex in case this is the last instance
  251. #ifdef USE_OPENGL
  252. {
  253. MutexLock lock(GetStaticMutex());
  254. --numInstances;
  255. if (!numInstances)
  256. Pa_Terminate();
  257. }
  258. #else
  259. delete (AudioStream*)stream_;
  260. stream_ = 0;
  261. #endif
  262. }
  263. bool Audio::SetMode(int bufferLengthMSec, int mixRate, bool stereo, bool interpolate)
  264. {
  265. Release();
  266. bufferLengthMSec = Max(bufferLengthMSec, MIN_BUFFERLENGTH);
  267. mixRate = Clamp(mixRate, MIN_MIXRATE, MAX_MIXRATE);
  268. // Guarantee a fragment size that is low enough so that Vorbis decoding buffers do not wrap
  269. fragmentSize_ = NextPowerOfTwo(mixRate >> 6);
  270. #ifdef USE_OPENGL
  271. PaStreamParameters outputParams;
  272. outputParams.device = Pa_GetDefaultOutputDevice();
  273. outputParams.channelCount = stereo ? 2 : 1;
  274. outputParams.sampleFormat = paInt16;
  275. outputParams.suggestedLatency = bufferLengthMSec / 1000.0;
  276. outputParams.hostApiSpecificStreamInfo = 0;
  277. if (Pa_OpenStream(&stream_, 0, &outputParams, mixRate, fragmentSize_, 0, AudioCallback, this) != paNoError)
  278. {
  279. LOGERROR("Failed to open audio stream");
  280. return false;
  281. }
  282. #else
  283. if (!stream_)
  284. stream_ = new AudioStream(this);
  285. unsigned windowHandle = 0;
  286. Graphics* graphics = GetSubsystem<Graphics>();
  287. if (graphics)
  288. windowHandle = graphics->GetWindowHandle();
  289. if (!((AudioStream*)stream_)->Open(windowHandle, bufferLengthMSec, mixRate, stereo))
  290. {
  291. LOGERROR("Failed to open audio stream");
  292. return false;
  293. }
  294. #endif
  295. clipBuffer_ = new int[stereo ? fragmentSize_ << 1 : fragmentSize_];
  296. sampleSize_ = sizeof(short);
  297. if (stereo)
  298. sampleSize_ <<= 1;
  299. mixRate_ = mixRate;
  300. stereo_ = stereo;
  301. interpolate_ = interpolate;
  302. LOGINFO("Set audio mode " + String(mixRate_) + " Hz " + (stereo_ ? "stereo" : "mono") + " " +
  303. (interpolate_ ? "interpolated" : ""));
  304. return Play();
  305. }
  306. void Audio::Update(float timeStep)
  307. {
  308. PROFILE(UpdateAudio);
  309. // Update in reverse order, because sound sources might remove themselves
  310. for (unsigned i = soundSources_.Size() - 1; i < soundSources_.Size(); --i)
  311. soundSources_[i]->Update(timeStep);
  312. }
  313. bool Audio::Play()
  314. {
  315. if (playing_)
  316. return true;
  317. if (!stream_)
  318. {
  319. LOGERROR("No audio mode set, can not start playback");
  320. return false;
  321. }
  322. #ifdef USE_OPENGL
  323. if (Pa_StartStream(stream_) != paNoError)
  324. {
  325. LOGERROR("Failed to start playback");
  326. return false;
  327. }
  328. #else
  329. if (!((AudioStream*)stream_)->StartPlayback())
  330. {
  331. LOGERROR("Failed to start playback");
  332. return false;
  333. }
  334. #endif
  335. playing_ = true;
  336. return true;
  337. }
  338. void Audio::Stop()
  339. {
  340. if (!stream_ || !playing_)
  341. return;
  342. #ifdef USE_OPENGL
  343. Pa_StopStream(stream_);
  344. #else
  345. ((AudioStream*)stream_)->StopPlayback();
  346. #endif
  347. playing_ = false;
  348. }
  349. void Audio::SetMasterGain(SoundType type, float gain)
  350. {
  351. if (type >= MAX_SOUND_TYPES)
  352. return;
  353. masterGain_[type] = Clamp(gain, 0.0f, 1.0f);
  354. }
  355. void Audio::SetListenerPosition(const Vector3& position)
  356. {
  357. listenerPosition_ = position;
  358. }
  359. void Audio::SetListenerRotation(const Quaternion& rotation)
  360. {
  361. listenerRotation_ = rotation;
  362. }
  363. void Audio::SetListenerTransform(const Vector3& position, const Quaternion& rotation)
  364. {
  365. listenerPosition_ = position;
  366. listenerRotation_ = rotation;
  367. }
  368. void Audio::StopSound(Sound* soundClip)
  369. {
  370. for (PODVector<SoundSource*>::Iterator i = soundSources_.Begin(); i != soundSources_.End(); ++i)
  371. {
  372. if ((*i)->GetSound() == soundClip)
  373. (*i)->Stop();
  374. }
  375. }
  376. float Audio::GetMasterGain(SoundType type) const
  377. {
  378. if (type >= MAX_SOUND_TYPES)
  379. return 0.0f;
  380. return masterGain_[type];
  381. }
  382. void Audio::AddSoundSource(SoundSource* channel)
  383. {
  384. MutexLock lock(audioMutex_);
  385. soundSources_.Push(channel);
  386. }
  387. void Audio::RemoveSoundSource(SoundSource* channel)
  388. {
  389. PODVector<SoundSource*>::Iterator i = soundSources_.Find(channel);
  390. if (i != soundSources_.End())
  391. {
  392. MutexLock lock(audioMutex_);
  393. soundSources_.Erase(i);
  394. }
  395. }
  396. #ifdef USE_OPENGL
  397. int AudioCallback(const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo*
  398. timeInfo, PaStreamCallbackFlags statusFlags, void *userData)
  399. {
  400. Audio* audio = static_cast<Audio*>(userData);
  401. {
  402. MutexLock lock(audio->GetMutex());
  403. audio->MixOutput(outputBuffer, framesPerBuffer);
  404. }
  405. return 0;
  406. }
  407. #endif
  408. void Audio::MixOutput(void *dest, unsigned samples)
  409. {
  410. while (samples)
  411. {
  412. // If sample count exceeds the fragment (clip buffer) size, split the work
  413. unsigned workSamples = Min((int)samples, (int)fragmentSize_);
  414. unsigned clipSamples = workSamples;
  415. if (stereo_)
  416. clipSamples <<= 1;
  417. // Clear clip buffer
  418. memset(clipBuffer_.Get(), 0, clipSamples * sizeof(int));
  419. int* clipPtr = clipBuffer_.Get();
  420. // Mix samples to clip buffer
  421. for (PODVector<SoundSource*>::Iterator i = soundSources_.Begin(); i != soundSources_.End(); ++i)
  422. (*i)->Mix(clipPtr, workSamples, mixRate_, stereo_, interpolate_);
  423. // Copy output from clip buffer to destination
  424. clipPtr = clipBuffer_.Get();
  425. short* destPtr = (short*)dest;
  426. while (clipSamples--)
  427. *destPtr++ = Clamp(*clipPtr++, -32768, 32767);
  428. samples -= workSamples;
  429. ((unsigned char*&)destPtr) += sampleSize_ * workSamples;
  430. }
  431. }
  432. void Audio::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  433. {
  434. using namespace RenderUpdate;
  435. Update(eventData[P_TIMESTEP].GetFloat());
  436. }
  437. void Audio::Release()
  438. {
  439. Stop();
  440. if (stream_)
  441. {
  442. #ifdef USE_OPENGL
  443. Pa_CloseStream(stream_);
  444. stream_ = 0;
  445. #else
  446. ((AudioStream*)stream_)->Close();
  447. #endif
  448. clipBuffer_.Reset();
  449. }
  450. }
  451. void RegisterAudioLibrary(Context* context)
  452. {
  453. Sound::RegisterObject(context);
  454. SoundSource::RegisterObject(context);
  455. SoundSource3D::RegisterObject(context);
  456. }