Audio.cpp 12 KB

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