llaudioengine_openal.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. /**
  2. * @file audioengine_openal.cpp
  3. * @brief implementation of audio engine using OpenAL
  4. * support as a OpenAL 3D implementation
  5. *
  6. * $LicenseInfo:firstyear=2002&license=viewergpl$
  7. *
  8. * Copyright (c) 2002-2009, Linden Research, Inc.
  9. *
  10. * Second Life Viewer Source Code
  11. * The source code in this file ("Source Code") is provided by Linden Lab
  12. * to you under the terms of the GNU General Public License, version 2.0
  13. * ("GPL"), unless you have obtained a separate licensing agreement
  14. * ("Other License"), formally executed by you and Linden Lab. Terms of
  15. * the GPL can be found in doc/GPL-license.txt in this distribution, or
  16. * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
  17. *
  18. * There are special exceptions to the terms and conditions of the GPL as
  19. * it is applied to this Source Code. View the full text of the exception
  20. * in the file doc/FLOSS-exception.txt in this software distribution, or
  21. * online at
  22. * http://secondlifegrid.net/programs/open_source/licensing/flossexception
  23. *
  24. * By copying, modifying or distributing this software, you acknowledge
  25. * that you have read and understood your obligations described above,
  26. * and agree to abide by those obligations.
  27. *
  28. * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
  29. * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
  30. * COMPLETENESS OR PERFORMANCE.
  31. * $/LicenseInfo$
  32. */
  33. #include "linden_common.h"
  34. #include "AL/alut.h"
  35. #include "AL/alext.h"
  36. #include "llaudioengine_openal.h"
  37. constexpr S32 MAX_NUM_WIND_BUFFERS = 80;
  38. constexpr F32 WIND_BUFFER_SIZE_SEC = 0.05f; // 1/20th sec
  39. LLAudioEngine_OpenAL::LLAudioEngine_OpenAL()
  40. : mWindGen(NULL),
  41. mWindBuf(NULL),
  42. mWindBufFreq(0),
  43. mWindBufSamples(0),
  44. mWindBufBytes(0),
  45. mWindSource(AL_NONE),
  46. mNumEmptyWindALBuffers(MAX_NUM_WIND_BUFFERS)
  47. {
  48. }
  49. //virtual
  50. bool LLAudioEngine_OpenAL::init(void* userdata)
  51. {
  52. mWindGen = NULL;
  53. mAudioDevice.clear();
  54. LLAudioEngine::init(userdata);
  55. if (!alutInit(NULL, NULL))
  56. {
  57. llwarns << "LLAudioEngine_OpenAL::init() ALUT initialization failed: "
  58. << alutGetErrorString(alutGetError()) << llendl;
  59. return false;
  60. }
  61. llinfos << "OpenAL successfully initialized" << llendl;
  62. llinfos << "OpenAL version: " << ll_safe_string(alGetString(AL_VERSION))
  63. << llendl;
  64. llinfos << "OpenAL vendor: " << ll_safe_string(alGetString(AL_VENDOR))
  65. << llendl;
  66. llinfos << "OpenAL renderer: " << ll_safe_string(alGetString(AL_RENDERER))
  67. << llendl;
  68. ALint major = alutGetMajorVersion ();
  69. ALint minor = alutGetMinorVersion ();
  70. llinfos << "ALUT version: " << major << "." << minor << llendl;
  71. ALCdevice* device = alcGetContextsDevice(alcGetCurrentContext());
  72. alcGetIntegerv(device, ALC_MAJOR_VERSION, 1, &major);
  73. alcGetIntegerv(device, ALC_MINOR_VERSION, 1, &minor);
  74. llinfos << "ALC version: " << major << "." << minor << llendl;
  75. mAudioDevice = ll_safe_string(alcGetString(device,
  76. ALC_DEFAULT_DEVICE_SPECIFIER));
  77. llinfos << "ALC default device: " << mAudioDevice << llendl;
  78. return true;
  79. }
  80. //virtual
  81. std::string LLAudioEngine_OpenAL::getDriverName(bool verbose)
  82. {
  83. std::string result = "OpenAL";
  84. if (!verbose)
  85. {
  86. return result;
  87. }
  88. result += " v" + ll_safe_string(alGetString(AL_VERSION));
  89. result += " (" + ll_safe_string(alGetString(AL_RENDERER));
  90. if (!mAudioDevice.empty())
  91. {
  92. result += ": " + mAudioDevice;
  93. }
  94. result += ")";
  95. return result;
  96. }
  97. //virtual
  98. void LLAudioEngine_OpenAL::allocateListener()
  99. {
  100. mListenerp = (LLListener*)new LLListener_OpenAL();
  101. if (!mListenerp)
  102. {
  103. llwarns << "Listener creation failed" << llendl;
  104. }
  105. }
  106. //virtual
  107. void LLAudioEngine_OpenAL::shutdown()
  108. {
  109. llinfos << "Shutting down the audio engine..." << llendl;
  110. LLAudioEngine::shutdown();
  111. // If a subsequent error occurs while there is still an error recorded
  112. // internally, the second error will simply be ignored. Clear previous
  113. // error to make sure we will capture a valid failure reason.
  114. ALenum error = alutGetError();
  115. if (error != ALUT_ERROR_NO_ERROR)
  116. {
  117. llwarns << "Uncleared error state prior to shutdow: "
  118. << alutGetErrorString(error) << llendl;
  119. }
  120. if (!alutExit())
  121. {
  122. llwarns << "ALUT shutdown failed: "
  123. << alutGetErrorString(alutGetError()) << llendl;
  124. }
  125. llinfos << "OpenAL successfully shut down" << llendl;
  126. delete mListenerp;
  127. mListenerp = NULL;
  128. }
  129. LLAudioBuffer* LLAudioEngine_OpenAL::createBuffer()
  130. {
  131. return new LLAudioBufferOpenAL();
  132. }
  133. LLAudioChannel* LLAudioEngine_OpenAL::createChannel()
  134. {
  135. return new LLAudioChannelOpenAL();
  136. }
  137. void LLAudioEngine_OpenAL::setInternalGain(F32 gain)
  138. {
  139. alListenerf(AL_GAIN, gain);
  140. }
  141. LLAudioChannelOpenAL::LLAudioChannelOpenAL()
  142. : mALSource(AL_NONE),
  143. mLastSamplePos(0)
  144. {
  145. alGenSources(1, &mALSource);
  146. }
  147. LLAudioChannelOpenAL::~LLAudioChannelOpenAL()
  148. {
  149. cleanup();
  150. alDeleteSources(1, &mALSource);
  151. }
  152. void LLAudioChannelOpenAL::cleanup()
  153. {
  154. alSourceStop(mALSource);
  155. alSourcei(mALSource, AL_BUFFER, 0);
  156. mCurrentBufferp = NULL;
  157. }
  158. void LLAudioChannelOpenAL::play()
  159. {
  160. if (mALSource == AL_NONE)
  161. {
  162. llwarns << "Playing without a mALSource, aborting" << llendl;
  163. return;
  164. }
  165. if (!isPlaying())
  166. {
  167. alSourcePlay(mALSource);
  168. getSource()->setPlayedOnce(true);
  169. }
  170. }
  171. void LLAudioChannelOpenAL::playSynced(LLAudioChannel* channelp)
  172. {
  173. if (channelp)
  174. {
  175. LLAudioChannelOpenAL *masterchannelp = (LLAudioChannelOpenAL*)channelp;
  176. if (mALSource != AL_NONE && masterchannelp->mALSource != AL_NONE)
  177. {
  178. // we have channels allocated to master and slave
  179. ALfloat master_offset;
  180. alGetSourcef(masterchannelp->mALSource, AL_SEC_OFFSET,
  181. &master_offset);
  182. llinfos << "Syncing with master at " << master_offset << "s"
  183. << llendl;
  184. // *TODO: detect when this fails, maybe use AL_SAMPLE_
  185. alSourcef(mALSource, AL_SEC_OFFSET, master_offset);
  186. }
  187. }
  188. play();
  189. }
  190. bool LLAudioChannelOpenAL::isPlaying()
  191. {
  192. if (mALSource != AL_NONE)
  193. {
  194. ALint state;
  195. alGetSourcei(mALSource, AL_SOURCE_STATE, &state);
  196. if (state == AL_PLAYING)
  197. {
  198. return true;
  199. }
  200. }
  201. return false;
  202. }
  203. bool LLAudioChannelOpenAL::updateBuffer()
  204. {
  205. if (LLAudioChannel::updateBuffer())
  206. {
  207. // Base class update returned true, which means that we need to
  208. // actually set up the source for a different buffer.
  209. LLAudioBufferOpenAL* bufferp;
  210. bufferp = (LLAudioBufferOpenAL*)mCurrentSourcep->getCurrentBuffer();
  211. if (!bufferp)
  212. {
  213. llwarns << "No current buffer !" << llendl;
  214. return false;
  215. }
  216. ALuint buffer = bufferp->getBuffer();
  217. alSourcei(mALSource, AL_BUFFER, buffer);
  218. mLastSamplePos = 0;
  219. }
  220. if (mCurrentSourcep && gAudiop && gAudiop->mListenerp)
  221. {
  222. alSourcef(mALSource, AL_GAIN,
  223. mCurrentSourcep->getGain() * getSecondaryGain());
  224. alSourcei(mALSource, AL_LOOPING,
  225. mCurrentSourcep->isLoop() ? AL_TRUE : AL_FALSE);
  226. alSourcef(mALSource, AL_ROLLOFF_FACTOR,
  227. gAudiop->mListenerp->getRolloffFactor());
  228. }
  229. return true;
  230. }
  231. void LLAudioChannelOpenAL::updateLoop()
  232. {
  233. if (mALSource == AL_NONE)
  234. {
  235. return;
  236. }
  237. // Hack: we keep track of whether we looped or not by seeing when the
  238. // sample position looks like it's going backwards. Not reliable; may
  239. // yield false negatives.
  240. ALint cur_pos;
  241. alGetSourcei(mALSource, AL_SAMPLE_OFFSET, &cur_pos);
  242. if (cur_pos < mLastSamplePos)
  243. {
  244. mLoopedThisFrame = true;
  245. }
  246. mLastSamplePos = cur_pos;
  247. }
  248. void LLAudioChannelOpenAL::update3DPosition()
  249. {
  250. if (!mCurrentSourcep)
  251. {
  252. return;
  253. }
  254. if (mCurrentSourcep->isAmbient())
  255. {
  256. alSource3f(mALSource, AL_POSITION, 0.0, 0.0, 0.0);
  257. alSource3f(mALSource, AL_VELOCITY, 0.0, 0.0, 0.0);
  258. alSourcei(mALSource, AL_SOURCE_RELATIVE, AL_TRUE);
  259. }
  260. else
  261. {
  262. LLVector3 float_pos(mCurrentSourcep->getPositionGlobal());
  263. alSourcefv(mALSource, AL_POSITION, float_pos.mV);
  264. alSourcefv(mALSource, AL_VELOCITY, mCurrentSourcep->getVelocity().mV);
  265. alSourcei(mALSource, AL_SOURCE_RELATIVE, AL_FALSE);
  266. }
  267. alSourcef(mALSource, AL_GAIN,
  268. mCurrentSourcep->getGain() * getSecondaryGain());
  269. }
  270. LLAudioBufferOpenAL::LLAudioBufferOpenAL()
  271. {
  272. mALBuffer = AL_NONE;
  273. }
  274. LLAudioBufferOpenAL::~LLAudioBufferOpenAL()
  275. {
  276. cleanup();
  277. }
  278. void LLAudioBufferOpenAL::cleanup()
  279. {
  280. if (mALBuffer != AL_NONE)
  281. {
  282. alGetError();
  283. alDeleteBuffers(1, &mALBuffer);
  284. ALenum error = alGetError();
  285. if (error != AL_NO_ERROR)
  286. {
  287. llwarns << "Error: " << error << " possible memory leak hit"
  288. << llendl;
  289. }
  290. mALBuffer = AL_NONE;
  291. }
  292. }
  293. bool LLAudioBufferOpenAL::loadWAV(const std::string& filename)
  294. {
  295. if (filename.empty())
  296. {
  297. // invalid filename, abort.
  298. return false;
  299. }
  300. cleanup();
  301. mALBuffer = alutCreateBufferFromFile(filename.c_str());
  302. if (mALBuffer == AL_NONE)
  303. {
  304. ALenum error = alutGetError();
  305. if (LLFile::isfile(filename))
  306. {
  307. llwarns << "Error loading: " << filename << " - "
  308. << alutGetErrorString(error) << llendl;
  309. // If we EVER want to load wav files provided by end users, we need
  310. // to rethink this ! File is probably corrupt - remove it.
  311. LLFile::remove(filename);
  312. }
  313. else
  314. {
  315. // It's common for the file to not actually exist.
  316. LL_DEBUGS("OpenAL") << "Error loading: " << filename
  317. << " - " << alutGetErrorString(error)
  318. << LL_ENDL;
  319. }
  320. return false;
  321. }
  322. return true;
  323. }
  324. U32 LLAudioBufferOpenAL::getLength()
  325. {
  326. if (mALBuffer == AL_NONE)
  327. {
  328. return 0;
  329. }
  330. ALint length;
  331. alGetBufferi(mALBuffer, AL_SIZE, &length);
  332. return length / 2; // convert size in bytes to size in (16-bit) samples
  333. }
  334. bool LLAudioEngine_OpenAL::initWind()
  335. {
  336. ALenum error;
  337. mNumEmptyWindALBuffers = MAX_NUM_WIND_BUFFERS;
  338. alGetError(); /* clear error */
  339. alGenSources(1,&mWindSource);
  340. if ((error = alGetError()) != AL_NO_ERROR)
  341. {
  342. llwarns << "Error creating wind sources: " << error << llendl;
  343. }
  344. mWindGen = new LLWindGen<wind_sample_t>;
  345. mWindBufFreq = mWindGen->getInputSamplingRate();
  346. mWindBufSamples = llceil(mWindBufFreq * WIND_BUFFER_SIZE_SEC);
  347. mWindBufBytes = mWindBufSamples * 2 /*stereo*/ * sizeof(wind_sample_t);
  348. mWindBuf = new wind_sample_t[mWindBufSamples * 2 /*stereo*/];
  349. if (!mWindBuf)
  350. {
  351. llwarns << "Error creating wind memory buffer" << llendl;
  352. llassert(false);
  353. return false;
  354. }
  355. return true;
  356. }
  357. void LLAudioEngine_OpenAL::cleanupWind()
  358. {
  359. if (mWindSource != AL_NONE)
  360. {
  361. // Detach and delete all outstanding buffers on the wind source
  362. alSourceStop(mWindSource);
  363. ALint processed;
  364. alGetSourcei(mWindSource, AL_BUFFERS_PROCESSED, &processed);
  365. while (processed--)
  366. {
  367. ALuint buffer = AL_NONE;
  368. alSourceUnqueueBuffers(mWindSource, 1, &buffer);
  369. alDeleteBuffers(1, &buffer);
  370. }
  371. // Delete the wind source itself
  372. alDeleteSources(1, &mWindSource);
  373. mWindSource = AL_NONE;
  374. }
  375. delete[] mWindBuf;
  376. mWindBuf = NULL;
  377. delete mWindGen;
  378. mWindGen = NULL;
  379. }
  380. void LLAudioEngine_OpenAL::updateWind(LLVector3 wind_vec, F32 camera_altitude)
  381. {
  382. if (!mEnableWind || !mWindBuf)
  383. {
  384. return;
  385. }
  386. if (mWindUpdateTimer.checkExpirationAndReset(LL_WIND_UPDATE_INTERVAL))
  387. {
  388. // Wind comes in as Linden coordinate (+X = forward, +Y = left, +Z =
  389. // up), so we need to convert this to the conventional orientation DS3D
  390. // and OpenAL use where +X = right, +Y = up, +Z = backwards
  391. wind_vec.set(-wind_vec.mV[1], wind_vec.mV[2], -wind_vec.mV[0]);
  392. mWindGen->mTargetFreq =
  393. 80.f * powf(1.f + mapWindVecToPitch(wind_vec),
  394. 2.5f * (mapWindVecToGain(wind_vec) + 1.f));
  395. mWindGen->mTargetGain = mapWindVecToGain(wind_vec) * mMaxWindGain;
  396. mWindGen->mTargetPanGainR = mapWindVecToPan(wind_vec);
  397. alSourcei(mWindSource, AL_LOOPING, AL_FALSE);
  398. alSource3f(mWindSource, AL_POSITION, 0.f, 0.f, 0.f);
  399. alSource3f(mWindSource, AL_VELOCITY, 0.f, 0.f, 0.f);
  400. alSourcef(mWindSource, AL_ROLLOFF_FACTOR, 0.f);
  401. alSourcei(mWindSource, AL_SOURCE_RELATIVE, AL_TRUE);
  402. }
  403. // Let's make a wind buffer now
  404. ALint processed, queued, unprocessed;
  405. alGetSourcei(mWindSource, AL_BUFFERS_PROCESSED, &processed);
  406. alGetSourcei(mWindSource, AL_BUFFERS_QUEUED, &queued);
  407. unprocessed = queued - processed;
  408. // Ensure that there are always at least 3x as many filled buffers queued
  409. // as we managed to empty since last time.
  410. mNumEmptyWindALBuffers =
  411. llmin(mNumEmptyWindALBuffers + processed * 3 - unprocessed,
  412. MAX_NUM_WIND_BUFFERS - unprocessed);
  413. mNumEmptyWindALBuffers = llmax(mNumEmptyWindALBuffers, 0);
  414. while (processed--) // unqueue old buffers
  415. {
  416. ALuint buffer;
  417. ALenum error;
  418. alGetError(); /* clear error */
  419. alSourceUnqueueBuffers(mWindSource, 1, &buffer);
  420. error = alGetError();
  421. if (error != AL_NO_ERROR)
  422. {
  423. llwarns << "Error swapping (unqueuing) buffers" << llendl;
  424. }
  425. else
  426. {
  427. alDeleteBuffers(1, &buffer);
  428. }
  429. }
  430. unprocessed += mNumEmptyWindALBuffers;
  431. while (mNumEmptyWindALBuffers > 0) // fill + queue new buffers
  432. {
  433. alGetError(); /* clear error */
  434. ALuint buffer;
  435. alGenBuffers(1,&buffer);
  436. ALenum error = alGetError();
  437. if (error != AL_NO_ERROR)
  438. {
  439. llwarns << "Error creating wind buffer: " << error << llendl;
  440. break;
  441. }
  442. alBufferData(buffer, AL_FORMAT_STEREO_FLOAT32,
  443. mWindGen->windGenerate(mWindBuf, mWindBufSamples),
  444. mWindBufBytes, mWindBufFreq);
  445. error = alGetError();
  446. if (error != AL_NO_ERROR)
  447. {
  448. llwarns << "Error swapping (bufferdata) buffers" << llendl;
  449. }
  450. alSourceQueueBuffers(mWindSource, 1, &buffer);
  451. error = alGetError();
  452. if (error != AL_NO_ERROR)
  453. {
  454. llwarns << "Error swapping (queuing) buffers" << llendl;
  455. }
  456. --mNumEmptyWindALBuffers;
  457. }
  458. ALint playing;
  459. alGetSourcei(mWindSource, AL_SOURCE_STATE, &playing);
  460. if (playing != AL_PLAYING)
  461. {
  462. alSourcePlay(mWindSource);
  463. LL_DEBUGS("OpenAL") << "Wind had stopped (probably ran out of buffers) restarting: "
  464. << (unprocessed + mNumEmptyWindALBuffers)
  465. << " now queued." << LL_ENDL;
  466. }
  467. }