Audio.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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 "Channel.h"
  26. #include "Log.h"
  27. #include "Song.h"
  28. #include "Sound.h"
  29. #include "StringUtils.h"
  30. #define DIRECTSOUND_VERSION 0x0800
  31. #include <windows.h>
  32. #include <dsound.h>
  33. #include <mmsystem.h>
  34. #include <process.h>
  35. #include "DebugNew.h"
  36. static const int AUDIO_FPS = 100;
  37. //! Holds the DirectSound buffer and audio thread handle
  38. class AudioImpl
  39. {
  40. friend class Audio;
  41. public:
  42. //! Construct with a window handle
  43. AudioImpl(HWND windowHandle) :
  44. mDSObject(0),
  45. mDSBuffer(0),
  46. mAudioThread(0),
  47. mWindow(windowHandle)
  48. {
  49. }
  50. private:
  51. //! DirectSound interface
  52. IDirectSound* mDSObject;
  53. //! DirectSound buffer
  54. IDirectSoundBuffer* mDSBuffer;
  55. //! Audio thread handle
  56. HANDLE mAudioThread;
  57. //! Window handle
  58. HWND mWindow;
  59. //! Runs the audio mixing loop
  60. static DWORD WINAPI threadFunction(void* data);
  61. };
  62. Audio::Audio(unsigned windowHandle) :
  63. mImpl(0),
  64. mPlaying(false),
  65. mBufferSamples(0),
  66. mBufferSize(0),
  67. mSampleSize(0),
  68. mListenerPosition(Vector3::sZero),
  69. mListenerRotation(Quaternion::sIdentity)
  70. {
  71. LOGINFO("Audio created");
  72. mImpl = new AudioImpl((HWND)windowHandle);
  73. for (unsigned i = 0; i < MAX_CHANNEL_TYPES; ++i)
  74. mMasterGain[i] = 1.0f;
  75. }
  76. Audio::~Audio()
  77. {
  78. releaseBuffer();
  79. if (mImpl->mDSObject)
  80. {
  81. mImpl->mDSObject->Release();
  82. mImpl->mDSObject = 0;
  83. }
  84. delete mImpl;
  85. mImpl = 0;
  86. LOGINFO("Audio shut down");
  87. }
  88. bool Audio::setMode(int bufferLengthMSec, int mixRate, bool sixteenBit, bool stereo, bool interpolate)
  89. {
  90. releaseBuffer();
  91. if (mImpl->mWindow == INVALID_HANDLE_VALUE)
  92. return false;
  93. if (!mImpl->mDSObject)
  94. {
  95. if (DirectSoundCreate(0, &mImpl->mDSObject, 0) != DS_OK)
  96. {
  97. LOGERROR("Could not create DirectSound object");
  98. return false;
  99. }
  100. }
  101. if (mImpl->mDSObject->SetCooperativeLevel(mImpl->mWindow, DSSCL_PRIORITY) != DS_OK)
  102. {
  103. LOGERROR("Could not set DirectSound cooperative level");
  104. return false;
  105. }
  106. DSCAPS dsCaps;
  107. dsCaps.dwSize = sizeof(dsCaps);
  108. if (mImpl->mDSObject->GetCaps(&dsCaps) != DS_OK)
  109. {
  110. LOGERROR("Could not get DirectSound capabilities");
  111. return false;
  112. }
  113. if (!(dsCaps.dwFlags & (DSCAPS_SECONDARY16BIT|DSCAPS_PRIMARY16BIT)))
  114. sixteenBit = false;
  115. if (!(dsCaps.dwFlags & (DSCAPS_SECONDARYSTEREO|DSCAPS_PRIMARYSTEREO)))
  116. stereo = false;
  117. bufferLengthMSec = max(bufferLengthMSec, 50);
  118. mixRate = clamp(mixRate, 11025, 48000);
  119. WAVEFORMATEX waveFormat;
  120. waveFormat.wFormatTag = WAVE_FORMAT_PCM;
  121. waveFormat.nSamplesPerSec = mixRate;
  122. if (sixteenBit)
  123. waveFormat.wBitsPerSample = 16;
  124. else
  125. waveFormat.wBitsPerSample = 8;
  126. if (stereo)
  127. waveFormat.nChannels = 2;
  128. else
  129. waveFormat.nChannels = 1;
  130. unsigned sampleSize = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
  131. unsigned numSounds = (bufferLengthMSec * mixRate) / 1000;
  132. waveFormat.nAvgBytesPerSec = mixRate * sampleSize;
  133. waveFormat.nBlockAlign = sampleSize;
  134. waveFormat.cbSize = 0;
  135. DSBUFFERDESC bufferDesc;
  136. memset(&bufferDesc, 0, sizeof(bufferDesc));
  137. bufferDesc.dwSize = sizeof(bufferDesc);
  138. bufferDesc.dwFlags = DSBCAPS_STICKYFOCUS;
  139. bufferDesc.dwBufferBytes = numSounds * sampleSize;
  140. bufferDesc.lpwfxFormat = &waveFormat;
  141. if (mImpl->mDSObject->CreateSoundBuffer(&bufferDesc, &mImpl->mDSBuffer, 0) != DS_OK)
  142. {
  143. LOGERROR("Could not create DirectSound buffer");
  144. return false;
  145. }
  146. mClipBuffer = new int[numSounds * waveFormat.nChannels];
  147. mBufferSamples = numSounds;
  148. mBufferSize = numSounds * sampleSize;
  149. mSampleSize = sampleSize;
  150. mMixRate = mixRate;
  151. mSixteenBit = sixteenBit;
  152. mStereo = stereo;
  153. mInterpolate = interpolate;
  154. LOGINFO("Set audio mode " + toString(mMixRate) + " Hz " + (mStereo ? "stereo" : "mono") + " " + (mSixteenBit ? "16-bit" : "8-bit") + " " +
  155. (mInterpolate ? "interpolated" : ""));
  156. return play();
  157. }
  158. void Audio::update(float timeStep)
  159. {
  160. MutexLock lock(mAudioMutex);
  161. // Update in reverse order, because channels might remove themselves
  162. for (unsigned i = mChannels.size() - 1; i < mChannels.size(); --i)
  163. mChannels[i]->update(timeStep);
  164. }
  165. bool Audio::play()
  166. {
  167. if (mImpl->mAudioThread)
  168. return true;
  169. if (!mImpl->mDSBuffer)
  170. {
  171. LOGERROR("No audio buffer, can not start playback");
  172. return false;
  173. }
  174. // Clear buffer before starting playback
  175. DWORD bytes1, bytes2;
  176. void *ptr1, *ptr2;
  177. unsigned char value = mSixteenBit ? 0 : 128;
  178. if (mImpl->mDSBuffer->Lock(0, mBufferSize, &ptr1, &bytes1, &ptr2, &bytes2, 0) == DS_OK)
  179. {
  180. if (bytes1)
  181. memset(ptr1, value, bytes1);
  182. if (bytes2)
  183. memset(ptr2, value, bytes2);
  184. mImpl->mDSBuffer->Unlock(ptr1, bytes1, ptr2, bytes2);
  185. }
  186. // Create thread for playback
  187. mPlaying = true;
  188. mImpl->mAudioThread = CreateThread(0, 0, AudioImpl::threadFunction, this, 0, 0);
  189. if (!mImpl->mAudioThread)
  190. {
  191. LOGERROR("Could not create audio thread");
  192. mPlaying = false;
  193. return false;
  194. }
  195. // Set thread priority
  196. SetThreadPriority(mImpl->mAudioThread, THREAD_PRIORITY_ABOVE_NORMAL);
  197. return true;
  198. }
  199. void Audio::stop()
  200. {
  201. mPlaying = false;
  202. if (mImpl->mAudioThread)
  203. {
  204. WaitForSingleObject(mImpl->mAudioThread, INFINITE);
  205. CloseHandle(mImpl->mAudioThread);
  206. mImpl->mAudioThread = 0;
  207. }
  208. }
  209. void Audio::setMasterGain(ChannelType type, float gain)
  210. {
  211. if (type >= MAX_CHANNEL_TYPES)
  212. return;
  213. mMasterGain[type] = clamp(gain, 0.0f, 1.0f);
  214. }
  215. void Audio::setListenerPosition(const Vector3& position)
  216. {
  217. mListenerPosition = position;
  218. }
  219. void Audio::setListenerRotation(const Quaternion& rotation)
  220. {
  221. mListenerRotation = rotation;
  222. }
  223. void Audio::setListenerTransform(const Vector3& position, const Quaternion& rotation)
  224. {
  225. mListenerPosition = position;
  226. mListenerRotation = rotation;
  227. }
  228. void Audio::stopSound(Sound* sound)
  229. {
  230. for (std::vector<Channel*>::iterator i = mChannels.begin(); i != mChannels.end(); ++i)
  231. {
  232. if ((*i)->getSound() == sound)
  233. (*i)->stop();
  234. }
  235. }
  236. bool Audio::hasBuffer() const
  237. {
  238. return mImpl->mDSBuffer != 0;
  239. }
  240. float Audio::getMasterGain(ChannelType type) const
  241. {
  242. if (type >= MAX_CHANNEL_TYPES)
  243. return 0.0f;
  244. return mMasterGain[type];
  245. }
  246. void Audio::addChannel(Channel* channel)
  247. {
  248. MutexLock lock(mAudioMutex);
  249. mChannels.push_back(channel);
  250. }
  251. void Audio::removeChannel(Channel* channel)
  252. {
  253. MutexLock lock(mAudioMutex);
  254. for (std::vector<Channel*>::iterator i = mChannels.begin(); i != mChannels.end(); ++i)
  255. {
  256. if (*i == channel)
  257. {
  258. mChannels.erase(i);
  259. return;
  260. }
  261. }
  262. }
  263. void Audio::addSong(Song* song)
  264. {
  265. MutexLock lock(mAudioMutex);
  266. mSongs.push_back(song);
  267. }
  268. void Audio::removeSong(Song* song)
  269. {
  270. MutexLock lock(mAudioMutex);
  271. for (std::vector<Song*>::iterator i = mSongs.begin(); i != mSongs.end(); ++i)
  272. {
  273. if (*i == song)
  274. {
  275. mSongs.erase(i);
  276. return;
  277. }
  278. }
  279. }
  280. void Audio::releaseBuffer()
  281. {
  282. stop();
  283. if (mImpl->mDSBuffer)
  284. {
  285. mImpl->mDSBuffer->Release();
  286. mImpl->mDSBuffer = 0;
  287. }
  288. }
  289. void Audio::mixOutput(void *dest, unsigned bytes)
  290. {
  291. unsigned mixSounds = bytes;
  292. unsigned clipSounds = bytes;
  293. if (mStereo)
  294. mixSounds >>= 1;
  295. if (mSixteenBit)
  296. {
  297. clipSounds >>= 1;
  298. mixSounds >>= 1;
  299. }
  300. // Clear clip buffer
  301. memset(mClipBuffer.getPtr(), 0, clipSounds * sizeof(int));
  302. int* clipPtr = mClipBuffer.getPtr();
  303. // Mix samples to clip buffer / call players as necessary
  304. while (mixSounds)
  305. {
  306. unsigned samplesUntilPlay = mixSounds;
  307. // See which song's tempo counter will expire soonest
  308. for (std::vector<Song*>::iterator i = mSongs.begin(); i != mSongs.end(); ++i)
  309. {
  310. Song* song = *i;
  311. if (!song->getSampleCount())
  312. song->update();
  313. if (song->getSampleCount() < samplesUntilPlay)
  314. samplesUntilPlay = song->getSampleCount();
  315. }
  316. // Mix channels until next player call
  317. for (std::vector<Channel*>::iterator i = mChannels.begin(); i != mChannels.end(); ++i)
  318. (*i)->mix(clipPtr, samplesUntilPlay, mMixRate, mStereo, mInterpolate);
  319. mixSounds -= samplesUntilPlay;
  320. if (mStereo)
  321. clipPtr += samplesUntilPlay * 2;
  322. else
  323. clipPtr += samplesUntilPlay;
  324. for (std::vector<Song*>::iterator i = mSongs.begin(); i != mSongs.end(); ++i)
  325. (*i)->decSampleCount(samplesUntilPlay);
  326. }
  327. // Copy output from clip buffer to destination
  328. clipPtr = mClipBuffer.getPtr();
  329. if (mSixteenBit)
  330. {
  331. short* destPtr = (short*)dest;
  332. while (clipSounds--)
  333. {
  334. int sample = *clipPtr++;
  335. if (sample > 32767) sample = 32767;
  336. if (sample < -32768) sample = -32768;
  337. *destPtr++ = sample;
  338. }
  339. }
  340. else
  341. {
  342. unsigned char* destPtr = (unsigned char*)dest;
  343. while (clipSounds--)
  344. {
  345. int sample = ((*clipPtr++) >> 8) + 128;
  346. if (sample > 255) sample = 255;
  347. if (sample < 0) sample = 0;
  348. *destPtr++ = sample;
  349. }
  350. }
  351. }
  352. DWORD WINAPI AudioImpl::threadFunction(void* data)
  353. {
  354. Audio* audio = (Audio*)data;
  355. AudioImpl* impl = audio->getImpl();
  356. DWORD playCursor = 0;
  357. DWORD writeCursor = 0;
  358. while (audio->isPlaying())
  359. {
  360. Timer audioUpdateTimer;
  361. // Restore buffer / restart playback if necessary
  362. DWORD status;
  363. impl->mDSBuffer->GetStatus(&status);
  364. if (status == DSBSTATUS_BUFFERLOST)
  365. {
  366. impl->mDSBuffer->Restore();
  367. impl->mDSBuffer->GetStatus(&status);
  368. }
  369. if (!(status & DSBSTATUS_PLAYING))
  370. {
  371. impl->mDSBuffer->Play(0, 0, DSBPLAY_LOOPING);
  372. writeCursor = 0;
  373. }
  374. // Get current buffer position
  375. impl->mDSBuffer->GetCurrentPosition(&playCursor, 0);
  376. playCursor %= audio->getBufferSize(); // Paranoia
  377. playCursor &= -((int)audio->getSampleSize());
  378. if (playCursor != writeCursor)
  379. {
  380. int writeBytes = playCursor - writeCursor;
  381. if (writeBytes < 0)
  382. writeBytes += audio->getBufferSize();
  383. // Try to lock buffer
  384. DWORD bytes1, bytes2;
  385. void *ptr1, *ptr2;
  386. if (impl->mDSBuffer->Lock(writeCursor, writeBytes, &ptr1, &bytes1, &ptr2, &bytes2, 0) == DS_OK)
  387. {
  388. // Mix sound to locked positions
  389. {
  390. MutexLock lock(audio->getMutex());
  391. if (bytes1)
  392. audio->mixOutput(ptr1, bytes1);
  393. if (bytes2)
  394. audio->mixOutput(ptr2, bytes2);
  395. }
  396. // Unlock buffer and update write cursor
  397. impl->mDSBuffer->Unlock(ptr1, bytes1, ptr2, bytes2);
  398. writeCursor += writeBytes;
  399. if (writeCursor >= audio->getBufferSize())
  400. writeCursor -= audio->getBufferSize();
  401. }
  402. }
  403. // Sleep the remaining time of the audio update period
  404. int audioSleepTime = max(1000 / AUDIO_FPS - (int)audioUpdateTimer.getMSec(false), 0);
  405. Sleep(audioSleepTime);
  406. }
  407. impl->mDSBuffer->Stop();
  408. return 0;
  409. }