Audio.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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 "Profiler.h"
  31. #include "Sound.h"
  32. #include "SoundSource3D.h"
  33. #define DIRECTSOUND_VERSION 0x0800
  34. #include <Windows.h>
  35. #include <MMSystem.h>
  36. #include <dsound.h>
  37. #include "DebugNew.h"
  38. static const int AUDIO_FPS = 100;
  39. /// Audio implementation. Contains the DirectSound buffer
  40. class AudioImpl
  41. {
  42. friend class Audio;
  43. public:
  44. /// Construct
  45. AudioImpl() :
  46. dsObject_(0),
  47. dsBuffer_(0)
  48. {
  49. }
  50. private:
  51. /// DirectSound interface
  52. IDirectSound* dsObject_;
  53. /// DirectSound buffer
  54. IDirectSoundBuffer* dsBuffer_;
  55. };
  56. OBJECTTYPESTATIC(Audio);
  57. Audio::Audio(Context* context) :
  58. Object(context),
  59. impl_(new AudioImpl()),
  60. playing_(false),
  61. windowHandle_(0),
  62. bufferSamples_(0),
  63. bufferSize_(0),
  64. sampleSize_(0),
  65. listenerPosition_(Vector3::ZERO),
  66. listenerRotation_(Quaternion::IDENTITY)
  67. {
  68. SubscribeToEvent(E_SCREENMODE, HANDLER(Audio, HandleScreenMode));
  69. SubscribeToEvent(E_RENDERUPDATE, HANDLER(Audio, HandleRenderUpdate));
  70. for (unsigned i = 0; i < MAX_SOUND_TYPES; ++i)
  71. masterGain_[i] = 1.0f;
  72. // Try to initialize right now, but skip if screen mode is not yet set
  73. Initialize();
  74. }
  75. Audio::~Audio()
  76. {
  77. ReleaseBuffer();
  78. if (impl_->dsObject_)
  79. {
  80. impl_->dsObject_->Release();
  81. impl_->dsObject_ = 0;
  82. }
  83. delete impl_;
  84. impl_ = 0;
  85. }
  86. bool Audio::SetMode(int bufferLengthMSec, int mixRate, bool sixteenBit, bool stereo, bool interpolate)
  87. {
  88. ReleaseBuffer();
  89. if (!impl_->dsObject_)
  90. {
  91. if (DirectSoundCreate(0, &impl_->dsObject_, 0) != DS_OK)
  92. {
  93. LOGERROR("Could not create DirectSound object");
  94. return false;
  95. }
  96. }
  97. if (impl_->dsObject_->SetCooperativeLevel((HWND)windowHandle_, DSSCL_PRIORITY) != DS_OK)
  98. {
  99. LOGERROR("Could not set DirectSound cooperative level");
  100. return false;
  101. }
  102. DSCAPS dsCaps;
  103. dsCaps.dwSize = sizeof(dsCaps);
  104. if (impl_->dsObject_->GetCaps(&dsCaps) != DS_OK)
  105. {
  106. LOGERROR("Could not get DirectSound capabilities");
  107. return false;
  108. }
  109. if (!(dsCaps.dwFlags & (DSCAPS_SECONDARY16BIT|DSCAPS_PRIMARY16BIT)))
  110. sixteenBit = false;
  111. if (!(dsCaps.dwFlags & (DSCAPS_SECONDARYSTEREO|DSCAPS_PRIMARYSTEREO)))
  112. stereo = false;
  113. bufferLengthMSec = Max(bufferLengthMSec, 50);
  114. mixRate = Clamp(mixRate, 11025, 48000);
  115. WAVEFORMATEX waveFormat;
  116. waveFormat.wFormatTag = WAVE_FORMAT_PCM;
  117. waveFormat.nSamplesPerSec = mixRate;
  118. if (sixteenBit)
  119. waveFormat.wBitsPerSample = 16;
  120. else
  121. waveFormat.wBitsPerSample = 8;
  122. if (stereo)
  123. waveFormat.nChannels = 2;
  124. else
  125. waveFormat.nChannels = 1;
  126. unsigned sampleSize = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
  127. unsigned numSamples = (bufferLengthMSec * mixRate) / 1000;
  128. waveFormat.nAvgBytesPerSec = mixRate * sampleSize;
  129. waveFormat.nBlockAlign = sampleSize;
  130. waveFormat.cbSize = 0;
  131. DSBUFFERDESC bufferDesc;
  132. memset(&bufferDesc, 0, sizeof(bufferDesc));
  133. bufferDesc.dwSize = sizeof(bufferDesc);
  134. bufferDesc.dwFlags = DSBCAPS_STICKYFOCUS;
  135. bufferDesc.dwBufferBytes = numSamples * sampleSize;
  136. bufferDesc.lpwfxFormat = &waveFormat;
  137. if (impl_->dsObject_->CreateSoundBuffer(&bufferDesc, &impl_->dsBuffer_, 0) != DS_OK)
  138. {
  139. LOGERROR("Could not create DirectSound buffer");
  140. return false;
  141. }
  142. clipBuffer_ = new int[numSamples * waveFormat.nChannels];
  143. bufferSamples_ = numSamples;
  144. bufferSize_ = numSamples * sampleSize;
  145. sampleSize_ = sampleSize;
  146. mixRate_ = mixRate;
  147. sixteenBit_ = sixteenBit;
  148. stereo_ = stereo;
  149. interpolate_ = interpolate;
  150. LOGINFO("Set audio mode " + String(mixRate_) + " Hz " + (stereo_ ? "stereo" : "mono") + " " +
  151. (sixteenBit_ ? "16-bit" : "8-bit") + " " + (interpolate_ ? "interpolated" : ""));
  152. return Play();
  153. }
  154. void Audio::Update(float timeStep)
  155. {
  156. PROFILE(UpdateAudio);
  157. MutexLock Lock(audioMutex_);
  158. // Update in reverse order, because sound sources might remove themselves
  159. for (unsigned i = soundSources_.Size() - 1; i < soundSources_.Size(); --i)
  160. soundSources_[i]->Update(timeStep);
  161. }
  162. bool Audio::Play()
  163. {
  164. if (playing_)
  165. return true;
  166. if (!impl_->dsBuffer_)
  167. {
  168. LOGERROR("No audio buffer, can not start playback");
  169. return false;
  170. }
  171. // Clear buffer before starting playback
  172. DWORD bytes1, bytes2;
  173. void *ptr1, *ptr2;
  174. unsigned char value = sixteenBit_ ? 0 : 128;
  175. if (impl_->dsBuffer_->Lock(0, bufferSize_, &ptr1, &bytes1, &ptr2, &bytes2, 0) == DS_OK)
  176. {
  177. if (bytes1)
  178. memset(ptr1, value, bytes1);
  179. if (bytes2)
  180. memset(ptr2, value, bytes2);
  181. impl_->dsBuffer_->Unlock(ptr1, bytes1, ptr2, bytes2);
  182. }
  183. // Create playback thread
  184. if (!Start())
  185. {
  186. LOGERROR("Could not create audio thread");
  187. return false;
  188. }
  189. // Adjust playback thread priority
  190. SetPriority(THREAD_PRIORITY_ABOVE_NORMAL);
  191. playing_ = true;
  192. return true;
  193. }
  194. void Audio::Stop()
  195. {
  196. Thread::Stop();
  197. playing_ = false;
  198. }
  199. void Audio::SetMasterGain(SoundType type, float gain)
  200. {
  201. if (type >= MAX_SOUND_TYPES)
  202. return;
  203. masterGain_[type] = Clamp(gain, 0.0f, 1.0f);
  204. }
  205. void Audio::SetListenerPosition(const Vector3& position)
  206. {
  207. listenerPosition_ = position;
  208. }
  209. void Audio::SetListenerRotation(const Quaternion& rotation)
  210. {
  211. listenerRotation_ = rotation;
  212. }
  213. void Audio::SetListenerTransform(const Vector3& position, const Quaternion& rotation)
  214. {
  215. listenerPosition_ = position;
  216. listenerRotation_ = rotation;
  217. }
  218. void Audio::StopSound(Sound* soundClip)
  219. {
  220. for (PODVector<SoundSource*>::Iterator i = soundSources_.Begin(); i != soundSources_.End(); ++i)
  221. {
  222. if ((*i)->GetSound() == soundClip)
  223. (*i)->Stop();
  224. }
  225. }
  226. bool Audio::IsInitialized() const
  227. {
  228. return impl_->dsBuffer_ != 0;
  229. }
  230. float Audio::GetMasterGain(SoundType type) const
  231. {
  232. if (type >= MAX_SOUND_TYPES)
  233. return 0.0f;
  234. return masterGain_[type];
  235. }
  236. void Audio::AddSoundSource(SoundSource* channel)
  237. {
  238. MutexLock Lock(audioMutex_);
  239. soundSources_.Push(channel);
  240. }
  241. void Audio::RemoveSoundSource(SoundSource* channel)
  242. {
  243. MutexLock Lock(audioMutex_);
  244. for (PODVector<SoundSource*>::Iterator i = soundSources_.Begin(); i != soundSources_.End(); ++i)
  245. {
  246. if (*i == channel)
  247. {
  248. soundSources_.Erase(i);
  249. return;
  250. }
  251. }
  252. }
  253. void Audio::ThreadFunction()
  254. {
  255. AudioImpl* impl = impl_;
  256. DWORD playCursor = 0;
  257. DWORD writeCursor = 0;
  258. while (shouldRun_)
  259. {
  260. Timer audioUpdateTimer;
  261. // Restore buffer / restart playback if necessary
  262. DWORD status;
  263. impl->dsBuffer_->GetStatus(&status);
  264. if (status == DSBSTATUS_BUFFERLOST)
  265. {
  266. impl->dsBuffer_->Restore();
  267. impl->dsBuffer_->GetStatus(&status);
  268. }
  269. if (!(status & DSBSTATUS_PLAYING))
  270. {
  271. impl->dsBuffer_->Play(0, 0, DSBPLAY_LOOPING);
  272. writeCursor = 0;
  273. }
  274. // Get current buffer position
  275. impl->dsBuffer_->GetCurrentPosition(&playCursor, 0);
  276. playCursor %= bufferSize_;
  277. playCursor &= -((int)sampleSize_);
  278. if (playCursor != writeCursor)
  279. {
  280. int writeBytes = playCursor - writeCursor;
  281. if (writeBytes < 0)
  282. writeBytes += bufferSize_;
  283. // Try to lock buffer
  284. DWORD bytes1, bytes2;
  285. void *ptr1, *ptr2;
  286. if (impl->dsBuffer_->Lock(writeCursor, writeBytes, &ptr1, &bytes1, &ptr2, &bytes2, 0) == DS_OK)
  287. {
  288. // Mix sound to locked positions
  289. {
  290. MutexLock Lock(audioMutex_);
  291. if (bytes1)
  292. MixOutput(ptr1, bytes1);
  293. if (bytes2)
  294. MixOutput(ptr2, bytes2);
  295. }
  296. // Unlock buffer and update write cursor
  297. impl->dsBuffer_->Unlock(ptr1, bytes1, ptr2, bytes2);
  298. writeCursor += writeBytes;
  299. if (writeCursor >= bufferSize_)
  300. writeCursor -= bufferSize_;
  301. }
  302. }
  303. // Sleep the remaining time of the audio update period
  304. int audioSleepTime = Max(1000 / AUDIO_FPS - (int)audioUpdateTimer.GetMSec(false), 0);
  305. Sleep(audioSleepTime);
  306. }
  307. impl->dsBuffer_->Stop();
  308. }
  309. void Audio::Initialize()
  310. {
  311. Graphics* graphics = GetSubsystem<Graphics>();
  312. if ((!graphics) || (!graphics->IsInitialized()))
  313. return;
  314. windowHandle_ = graphics->GetWindowHandle();
  315. }
  316. void Audio::MixOutput(void *dest, unsigned bytes)
  317. {
  318. unsigned mixSamples = bytes;
  319. unsigned clipSamples = bytes;
  320. if (stereo_)
  321. mixSamples >>= 1;
  322. if (sixteenBit_)
  323. {
  324. clipSamples >>= 1;
  325. mixSamples >>= 1;
  326. }
  327. // Clear clip buffer
  328. memset(clipBuffer_.GetPtr(), 0, clipSamples * sizeof(int));
  329. int* clipPtr = clipBuffer_.GetPtr();
  330. // Mix samples to clip buffer
  331. for (PODVector<SoundSource*>::Iterator i = soundSources_.Begin(); i != soundSources_.End(); ++i)
  332. (*i)->Mix(clipPtr, mixSamples, mixRate_, stereo_, interpolate_);
  333. // Copy output from clip buffer to destination
  334. clipPtr = clipBuffer_.GetPtr();
  335. if (sixteenBit_)
  336. {
  337. short* destPtr = (short*)dest;
  338. while (clipSamples--)
  339. *destPtr++ = Clamp(*clipPtr++, -32768, 32767);
  340. }
  341. else
  342. {
  343. unsigned char* destPtr = (unsigned char*)dest;
  344. while (clipSamples--)
  345. *destPtr++ = Clamp(((*clipPtr++) >> 8) + 128, 0, 255);
  346. }
  347. }
  348. void Audio::ReleaseBuffer()
  349. {
  350. Stop();
  351. if (impl_->dsBuffer_)
  352. {
  353. impl_->dsBuffer_->Release();
  354. impl_->dsBuffer_ = 0;
  355. }
  356. }
  357. void Audio::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  358. {
  359. if (!windowHandle_)
  360. Initialize();
  361. }
  362. void Audio::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  363. {
  364. using namespace RenderUpdate;
  365. Update(eventData[P_TIMESTEP].GetFloat());
  366. }
  367. void RegisterAudioLibrary(Context* context)
  368. {
  369. Sound::RegisterObject(context);
  370. SoundSource::RegisterObject(context);
  371. SoundSource3D::RegisterObject(context);
  372. }