Audio.cpp 12 KB

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