Source.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519
  1. /**
  2. * Copyright (c) 2006-2021 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. #include "Source.h"
  21. #include "Filter.h"
  22. #include "Pool.h"
  23. #include "Audio.h"
  24. #include "common/math.h"
  25. // STD
  26. #include <iostream>
  27. #include <algorithm>
  28. #define audiomodule() (Module::getInstance<Audio>(Module::M_AUDIO))
  29. using love::thread::Lock;
  30. namespace love
  31. {
  32. namespace audio
  33. {
  34. namespace openal
  35. {
  36. class InvalidFormatException : public love::Exception
  37. {
  38. public:
  39. InvalidFormatException(int channels, int bitdepth)
  40. : Exception("%d-channel Sources with %d bits per sample are not supported.", channels, bitdepth)
  41. {
  42. }
  43. };
  44. class SpatialSupportException : public love::Exception
  45. {
  46. public:
  47. SpatialSupportException()
  48. : Exception("This spatial audio functionality is only available for mono Sources. \
  49. Ensure the Source is not multi-channel before calling this function.")
  50. {
  51. }
  52. };
  53. class QueueFormatMismatchException : public love::Exception
  54. {
  55. public:
  56. QueueFormatMismatchException()
  57. : Exception("Queued sound data must have same format as sound Source.")
  58. {
  59. }
  60. };
  61. class QueueTypeMismatchException : public love::Exception
  62. {
  63. public:
  64. QueueTypeMismatchException()
  65. : Exception("Only queueable Sources can be queued with sound data.")
  66. {
  67. }
  68. };
  69. class QueueMalformedLengthException : public love::Exception
  70. {
  71. public:
  72. QueueMalformedLengthException(int bytes)
  73. : Exception("Data length must be a multiple of sample size (%d bytes).", bytes)
  74. {
  75. }
  76. };
  77. class QueueLoopingException : public love::Exception
  78. {
  79. public:
  80. QueueLoopingException()
  81. : Exception("Queueable Sources can not be looped.")
  82. {
  83. }
  84. };
  85. StaticDataBuffer::StaticDataBuffer(ALenum format, const ALvoid *data, ALsizei size, ALsizei freq)
  86. : size(size)
  87. {
  88. alGenBuffers(1, &buffer);
  89. alBufferData(buffer, format, data, size, freq);
  90. }
  91. StaticDataBuffer::~StaticDataBuffer()
  92. {
  93. alDeleteBuffers(1, &buffer);
  94. }
  95. Source::Source(Pool *pool, love::sound::SoundData *soundData)
  96. : love::audio::Source(Source::TYPE_STATIC)
  97. , pool(pool)
  98. , sampleRate(soundData->getSampleRate())
  99. , channels(soundData->getChannelCount())
  100. , bitDepth(soundData->getBitDepth())
  101. {
  102. ALenum fmt = Audio::getFormat(soundData->getBitDepth(), soundData->getChannelCount());
  103. if (fmt == AL_NONE)
  104. throw InvalidFormatException(soundData->getChannelCount(), soundData->getBitDepth());
  105. staticBuffer.set(new StaticDataBuffer(fmt, soundData->getData(), (ALsizei) soundData->getSize(), sampleRate), Acquire::NORETAIN);
  106. float z[3] = {0, 0, 0};
  107. setFloatv(position, z);
  108. setFloatv(velocity, z);
  109. setFloatv(direction, z);
  110. for (int i = 0; i < audiomodule()->getMaxSourceEffects(); i++)
  111. slotlist.push(i);
  112. }
  113. Source::Source(Pool *pool, love::sound::Decoder *decoder)
  114. : love::audio::Source(Source::TYPE_STREAM)
  115. , pool(pool)
  116. , sampleRate(decoder->getSampleRate())
  117. , channels(decoder->getChannelCount())
  118. , bitDepth(decoder->getBitDepth())
  119. , decoder(decoder)
  120. , buffers(DEFAULT_BUFFERS)
  121. {
  122. if (Audio::getFormat(decoder->getBitDepth(), decoder->getChannelCount()) == AL_NONE)
  123. throw InvalidFormatException(decoder->getChannelCount(), decoder->getBitDepth());
  124. for (int i = 0; i < buffers; i++)
  125. {
  126. ALuint buf;
  127. alGenBuffers(1, &buf);
  128. if (alGetError() == AL_NO_ERROR)
  129. unusedBuffers.push(buf);
  130. else
  131. {
  132. buffers = i;
  133. break;
  134. }
  135. }
  136. float z[3] = {0, 0, 0};
  137. setFloatv(position, z);
  138. setFloatv(velocity, z);
  139. setFloatv(direction, z);
  140. for (int i = 0; i < audiomodule()->getMaxSourceEffects(); i++)
  141. slotlist.push(i);
  142. }
  143. Source::Source(Pool *pool, int sampleRate, int bitDepth, int channels, int buffers)
  144. : love::audio::Source(Source::TYPE_QUEUE)
  145. , pool(pool)
  146. , sampleRate(sampleRate)
  147. , channels(channels)
  148. , bitDepth(bitDepth)
  149. , buffers(buffers)
  150. {
  151. ALenum fmt = Audio::getFormat(bitDepth, channels);
  152. if (fmt == AL_NONE)
  153. throw InvalidFormatException(channels, bitDepth);
  154. if (buffers < 1)
  155. buffers = DEFAULT_BUFFERS;
  156. if (buffers > MAX_BUFFERS)
  157. buffers = MAX_BUFFERS;
  158. for (int i = 0; i < buffers; i++)
  159. {
  160. ALuint buf;
  161. alGenBuffers(1, &buf);
  162. if (alGetError() == AL_NO_ERROR)
  163. unusedBuffers.push(buf);
  164. else
  165. {
  166. buffers = i;
  167. break;
  168. }
  169. }
  170. float z[3] = {0, 0, 0};
  171. setFloatv(position, z);
  172. setFloatv(velocity, z);
  173. setFloatv(direction, z);
  174. for (int i = 0; i < audiomodule()->getMaxSourceEffects(); i++)
  175. slotlist.push(i);
  176. }
  177. Source::Source(const Source &s)
  178. : love::audio::Source(s.sourceType)
  179. , pool(s.pool)
  180. , valid(false)
  181. , staticBuffer(s.staticBuffer)
  182. , pitch(s.pitch)
  183. , volume(s.volume)
  184. , relative(s.relative)
  185. , looping(s.looping)
  186. , minVolume(s.minVolume)
  187. , maxVolume(s.maxVolume)
  188. , referenceDistance(s.referenceDistance)
  189. , rolloffFactor(s.rolloffFactor)
  190. , maxDistance(s.maxDistance)
  191. , cone(s.cone)
  192. , offsetSamples(0)
  193. , sampleRate(s.sampleRate)
  194. , channels(s.channels)
  195. , bitDepth(s.bitDepth)
  196. , decoder(nullptr)
  197. , toLoop(0)
  198. , buffers(s.buffers)
  199. {
  200. if (sourceType == TYPE_STREAM)
  201. {
  202. if (s.decoder.get())
  203. decoder.set(s.decoder->clone(), Acquire::NORETAIN);
  204. }
  205. if (sourceType != TYPE_STATIC)
  206. {
  207. for (int i = 0; i < buffers; i++)
  208. {
  209. ALuint buf;
  210. alGenBuffers(1, &buf);
  211. if (alGetError() == AL_NO_ERROR)
  212. unusedBuffers.push(buf);
  213. else
  214. {
  215. buffers = i;
  216. break;
  217. }
  218. }
  219. }
  220. if (s.directfilter)
  221. directfilter = s.directfilter->clone();
  222. for (auto e : s.effectmap)
  223. {
  224. Filter *filter = e.second.filter ? e.second.filter->clone() : nullptr;
  225. effectmap[e.first] = { filter, e.second.slot, e.second.target };
  226. }
  227. setFloatv(position, s.position);
  228. setFloatv(velocity, s.velocity);
  229. setFloatv(direction, s.direction);
  230. for (int i = 0; i < audiomodule()->getMaxSourceEffects(); i++)
  231. {
  232. // filter out already taken slots
  233. bool push = true;
  234. for (auto e : effectmap)
  235. {
  236. if (e.second.slot)
  237. {
  238. push = false;
  239. break;
  240. }
  241. }
  242. if (push)
  243. slotlist.push(i);
  244. }
  245. }
  246. Source::~Source()
  247. {
  248. stop();
  249. if (sourceType != TYPE_STATIC)
  250. {
  251. while (!streamBuffers.empty())
  252. {
  253. alDeleteBuffers(1, &streamBuffers.front());
  254. streamBuffers.pop();
  255. }
  256. while (!unusedBuffers.empty())
  257. {
  258. alDeleteBuffers(1, &unusedBuffers.top());
  259. unusedBuffers.pop();
  260. }
  261. }
  262. if (directfilter)
  263. delete directfilter;
  264. for (auto e : effectmap)
  265. {
  266. if (e.second.filter)
  267. delete e.second.filter;
  268. }
  269. }
  270. love::audio::Source *Source::clone()
  271. {
  272. return new Source(*this);
  273. }
  274. bool Source::play()
  275. {
  276. Lock l = pool->lock();
  277. ALuint out;
  278. char wasPlaying;
  279. if (!pool->assignSource(this, out, wasPlaying))
  280. return valid = false;
  281. if (!wasPlaying)
  282. return valid = playAtomic(out);
  283. resumeAtomic();
  284. return valid = true;
  285. }
  286. void Source::stop()
  287. {
  288. if (!valid)
  289. return;
  290. Lock l = pool->lock();
  291. pool->releaseSource(this);
  292. }
  293. void Source::pause()
  294. {
  295. Lock l = pool->lock();
  296. if (pool->isPlaying(this))
  297. pauseAtomic();
  298. }
  299. bool Source::isPlaying() const
  300. {
  301. if (!valid)
  302. return false;
  303. ALenum state;
  304. alGetSourcei(source, AL_SOURCE_STATE, &state);
  305. return state == AL_PLAYING;
  306. }
  307. bool Source::isFinished() const
  308. {
  309. if (!valid)
  310. return false;
  311. if (sourceType == TYPE_STREAM && (isLooping() || !decoder->isFinished()))
  312. return false;
  313. ALenum state;
  314. alGetSourcei(source, AL_SOURCE_STATE, &state);
  315. return state == AL_STOPPED;
  316. }
  317. bool Source::update()
  318. {
  319. if (!valid)
  320. return false;
  321. switch (sourceType)
  322. {
  323. case TYPE_STATIC:
  324. {
  325. // Looping mode could have changed.
  326. // FIXME: make looping mode change atomically so this is not needed
  327. alSourcei(source, AL_LOOPING, isLooping() ? AL_TRUE : AL_FALSE);
  328. return !isFinished();
  329. }
  330. case TYPE_STREAM:
  331. if (!isFinished())
  332. {
  333. ALint processed;
  334. alGetSourcei(source, AL_BUFFERS_PROCESSED, &processed);
  335. // It would theoretically be better to unqueue all processed
  336. // buffers in a single call to alSourceUnqueueBuffers, but on
  337. // iOS I observed occasional (every ~5-10 seconds) pops in the
  338. // streaming source test I was using, when doing that. Perhaps
  339. // there was a bug in this code when I was testing, or maybe
  340. // this code runs into the same problem but now it's much harder
  341. // to reproduce. The test I used is the play-stop-play .love
  342. // from https://bitbucket.org/rude/love/issues/1484/
  343. while (processed--)
  344. {
  345. int curOffsetSamples;
  346. alGetSourcei(source, AL_SAMPLE_OFFSET, &curOffsetSamples);
  347. ALuint buffer;
  348. alSourceUnqueueBuffers(source, 1, &buffer);
  349. int newOffsetSamples;
  350. alGetSourcei(source, AL_SAMPLE_OFFSET, &newOffsetSamples);
  351. offsetSamples += (curOffsetSamples - newOffsetSamples);
  352. if (streamAtomic(buffer, decoder.get()) > 0)
  353. alSourceQueueBuffers(source, 1, &buffer);
  354. else
  355. unusedBuffers.push(buffer);
  356. }
  357. while (!unusedBuffers.empty())
  358. {
  359. ALuint b = unusedBuffers.top();
  360. if (streamAtomic(b, decoder.get()) > 0)
  361. {
  362. alSourceQueueBuffers(source, 1, &b);
  363. unusedBuffers.pop();
  364. }
  365. else
  366. break;
  367. }
  368. return true;
  369. }
  370. return false;
  371. case TYPE_QUEUE:
  372. {
  373. ALint processed;
  374. ALuint buffers[MAX_BUFFERS];
  375. alGetSourcei(source, AL_BUFFERS_PROCESSED, &processed);
  376. alSourceUnqueueBuffers(source, processed, buffers);
  377. for (int i = 0; i < processed; i++)
  378. {
  379. ALint size;
  380. alGetBufferi(buffers[i], AL_SIZE, &size);
  381. bufferedBytes -= size;
  382. unusedBuffers.push(buffers[i]);
  383. }
  384. return !isFinished();
  385. }
  386. case TYPE_MAX_ENUM:
  387. break;
  388. }
  389. return false;
  390. }
  391. void Source::setPitch(float pitch)
  392. {
  393. if (valid)
  394. alSourcef(source, AL_PITCH, pitch);
  395. this->pitch = pitch;
  396. }
  397. float Source::getPitch() const
  398. {
  399. if (valid)
  400. {
  401. ALfloat f;
  402. alGetSourcef(source, AL_PITCH, &f);
  403. return f;
  404. }
  405. // In case the Source isn't playing.
  406. return pitch;
  407. }
  408. void Source::setVolume(float volume)
  409. {
  410. if (valid)
  411. alSourcef(source, AL_GAIN, volume);
  412. this->volume = volume;
  413. }
  414. float Source::getVolume() const
  415. {
  416. if (valid)
  417. {
  418. ALfloat f;
  419. alGetSourcef(source, AL_GAIN, &f);
  420. return f;
  421. }
  422. // In case the Source isn't playing.
  423. return volume;
  424. }
  425. void Source::seek(double offset, Source::Unit unit)
  426. {
  427. Lock l = pool->lock();
  428. int offsetSamples = 0;
  429. double offsetSeconds = 0.0f;
  430. switch (unit)
  431. {
  432. case Source::UNIT_SAMPLES:
  433. offsetSamples = (int) offset;
  434. offsetSeconds = offset / (double) sampleRate;
  435. break;
  436. case Source::UNIT_SECONDS:
  437. default:
  438. offsetSeconds = offset;
  439. offsetSamples = (int) (offset * sampleRate);
  440. break;
  441. }
  442. bool wasPlaying = isPlaying();
  443. switch (sourceType)
  444. {
  445. case TYPE_STATIC:
  446. if (valid)
  447. {
  448. alSourcei(source, AL_SAMPLE_OFFSET, offsetSamples);
  449. offsetSamples = offsetSeconds = 0;
  450. }
  451. break;
  452. case TYPE_STREAM:
  453. {
  454. // To drain all buffers
  455. if (valid)
  456. stop();
  457. decoder->seek(offsetSeconds);
  458. if (wasPlaying)
  459. play();
  460. break;
  461. }
  462. case TYPE_QUEUE:
  463. if (valid)
  464. {
  465. alSourcei(source, AL_SAMPLE_OFFSET, offsetSamples);
  466. offsetSamples = offsetSeconds = 0;
  467. }
  468. else
  469. {
  470. //emulate AL behavior, discarding buffer once playback head is past one
  471. while (!unusedBuffers.empty())
  472. {
  473. ALint size;
  474. auto buffer = unusedBuffers.top();
  475. alGetBufferi(buffer, AL_SIZE, &size);
  476. if (offsetSamples < size / (bitDepth / 8 * channels))
  477. break;
  478. unusedBuffers.pop();
  479. bufferedBytes -= size;
  480. offsetSamples -= size / (bitDepth / 8 * channels);
  481. }
  482. if (unusedBuffers.empty())
  483. offsetSamples = 0;
  484. offsetSeconds = offsetSamples / (double) sampleRate;
  485. }
  486. break;
  487. case TYPE_MAX_ENUM:
  488. break;
  489. }
  490. if (wasPlaying && (alGetError() == AL_INVALID_VALUE || (sourceType == TYPE_STREAM && !isPlaying())))
  491. {
  492. stop();
  493. if (isLooping())
  494. play();
  495. return;
  496. }
  497. this->offsetSamples = offsetSamples;
  498. }
  499. double Source::tell(Source::Unit unit)
  500. {
  501. Lock l = pool->lock();
  502. int offset = 0;
  503. if (valid)
  504. alGetSourcei(source, AL_SAMPLE_OFFSET, &offset);
  505. offset += offsetSamples;
  506. if (unit == UNIT_SECONDS)
  507. return offset / (double) sampleRate;
  508. else
  509. return offset;
  510. }
  511. double Source::getDuration(Unit unit)
  512. {
  513. Lock l = pool->lock();
  514. switch (sourceType)
  515. {
  516. case TYPE_STATIC:
  517. {
  518. ALsizei size = staticBuffer->getSize();
  519. ALsizei samples = (size / channels) / (bitDepth / 8);
  520. if (unit == UNIT_SAMPLES)
  521. return (double) samples;
  522. else
  523. return (double) samples / (double) sampleRate;
  524. }
  525. case TYPE_STREAM:
  526. {
  527. double seconds = decoder->getDuration();
  528. if (unit == UNIT_SECONDS)
  529. return seconds;
  530. else
  531. return seconds * decoder->getSampleRate();
  532. }
  533. case TYPE_QUEUE:
  534. {
  535. ALsizei samples = (bufferedBytes / channels) / (bitDepth / 8);
  536. if (unit == UNIT_SAMPLES)
  537. return (double)samples;
  538. else
  539. return (double)samples / (double)sampleRate;
  540. }
  541. case TYPE_MAX_ENUM:
  542. return 0.0;
  543. }
  544. return 0.0;
  545. }
  546. void Source::setPosition(float *v)
  547. {
  548. if (channels > 1)
  549. throw SpatialSupportException();
  550. if (valid)
  551. alSourcefv(source, AL_POSITION, v);
  552. setFloatv(position, v);
  553. }
  554. void Source::getPosition(float *v) const
  555. {
  556. if (channels > 1)
  557. throw SpatialSupportException();
  558. if (valid)
  559. alGetSourcefv(source, AL_POSITION, v);
  560. else
  561. setFloatv(v, position);
  562. }
  563. void Source::setVelocity(float *v)
  564. {
  565. if (channels > 1)
  566. throw SpatialSupportException();
  567. if (valid)
  568. alSourcefv(source, AL_VELOCITY, v);
  569. setFloatv(velocity, v);
  570. }
  571. void Source::getVelocity(float *v) const
  572. {
  573. if (channels > 1)
  574. throw SpatialSupportException();
  575. if (valid)
  576. alGetSourcefv(source, AL_VELOCITY, v);
  577. else
  578. setFloatv(v, velocity);
  579. }
  580. void Source::setDirection(float *v)
  581. {
  582. if (channels > 1)
  583. throw SpatialSupportException();
  584. if (valid)
  585. alSourcefv(source, AL_DIRECTION, v);
  586. else
  587. setFloatv(direction, v);
  588. }
  589. void Source::getDirection(float *v) const
  590. {
  591. if (channels > 1)
  592. throw SpatialSupportException();
  593. if (valid)
  594. alGetSourcefv(source, AL_DIRECTION, v);
  595. else
  596. setFloatv(v, direction);
  597. }
  598. void Source::setCone(float innerAngle, float outerAngle, float outerVolume, float outerHighGain)
  599. {
  600. if (channels > 1)
  601. throw SpatialSupportException();
  602. cone.innerAngle = (int) LOVE_TODEG(innerAngle);
  603. cone.outerAngle = (int) LOVE_TODEG(outerAngle);
  604. cone.outerVolume = outerVolume;
  605. cone.outerHighGain = outerHighGain;
  606. if (valid)
  607. {
  608. alSourcei(source, AL_CONE_INNER_ANGLE, cone.innerAngle);
  609. alSourcei(source, AL_CONE_OUTER_ANGLE, cone.outerAngle);
  610. alSourcef(source, AL_CONE_OUTER_GAIN, cone.outerVolume);
  611. #ifdef ALC_EXT_EFX
  612. alSourcef(source, AL_CONE_OUTER_GAINHF, cone.outerHighGain);
  613. #endif
  614. }
  615. }
  616. void Source::getCone(float &innerAngle, float &outerAngle, float &outerVolume, float &outerHighGain) const
  617. {
  618. if (channels > 1)
  619. throw SpatialSupportException();
  620. innerAngle = LOVE_TORAD(cone.innerAngle);
  621. outerAngle = LOVE_TORAD(cone.outerAngle);
  622. outerVolume = cone.outerVolume;
  623. outerHighGain = cone.outerHighGain;
  624. }
  625. void Source::setRelative(bool enable)
  626. {
  627. if (channels > 1)
  628. throw SpatialSupportException();
  629. if (valid)
  630. alSourcei(source, AL_SOURCE_RELATIVE, enable ? AL_TRUE : AL_FALSE);
  631. relative = enable;
  632. }
  633. bool Source::isRelative() const
  634. {
  635. if (channels > 1)
  636. throw SpatialSupportException();
  637. return relative;
  638. }
  639. void Source::setLooping(bool enable)
  640. {
  641. if (sourceType == TYPE_QUEUE)
  642. throw QueueLoopingException();
  643. if (valid && sourceType == TYPE_STATIC)
  644. alSourcei(source, AL_LOOPING, enable ? AL_TRUE : AL_FALSE);
  645. looping = enable;
  646. }
  647. bool Source::isLooping() const
  648. {
  649. return looping;
  650. }
  651. bool Source::queue(void *data, size_t length, int dataSampleRate, int dataBitDepth, int dataChannels)
  652. {
  653. if (sourceType != TYPE_QUEUE)
  654. throw QueueTypeMismatchException();
  655. if (dataSampleRate != sampleRate || dataBitDepth != bitDepth || dataChannels != channels )
  656. throw QueueFormatMismatchException();
  657. if (length % (bitDepth / 8 * channels) != 0)
  658. throw QueueMalformedLengthException(bitDepth / 8 * channels);
  659. if (length == 0)
  660. return true;
  661. Lock l = pool->lock();
  662. if (unusedBuffers.empty())
  663. return false;
  664. auto buffer = unusedBuffers.top();
  665. unusedBuffers.pop();
  666. alBufferData(buffer, Audio::getFormat(bitDepth, channels), data, length, sampleRate);
  667. bufferedBytes += length;
  668. if (valid)
  669. alSourceQueueBuffers(source, 1, &buffer);
  670. else
  671. streamBuffers.push(buffer);
  672. return true;
  673. }
  674. int Source::getFreeBufferCount() const
  675. {
  676. switch (sourceType) //why not :^)
  677. {
  678. case TYPE_STATIC:
  679. return 0;
  680. case TYPE_STREAM:
  681. return unusedBuffers.size();
  682. case TYPE_QUEUE:
  683. return unusedBuffers.size();
  684. case TYPE_MAX_ENUM:
  685. return 0;
  686. }
  687. return 0;
  688. }
  689. void Source::prepareAtomic()
  690. {
  691. // This Source may now be associated with an OpenAL source that still has
  692. // the properties of another love Source. Let's reset it to the settings
  693. // of the new one.
  694. reset();
  695. switch (sourceType)
  696. {
  697. case TYPE_STATIC:
  698. alSourcei(source, AL_BUFFER, staticBuffer->getBuffer());
  699. break;
  700. case TYPE_STREAM:
  701. while (!unusedBuffers.empty())
  702. {
  703. auto b = unusedBuffers.top();
  704. if (streamAtomic(b, decoder.get()) == 0)
  705. break;
  706. alSourceQueueBuffers(source, 1, &b);
  707. unusedBuffers.pop();
  708. if (decoder->isFinished())
  709. break;
  710. }
  711. break;
  712. case TYPE_QUEUE:
  713. {
  714. while (!streamBuffers.empty())
  715. {
  716. alSourceQueueBuffers(source, 1, &streamBuffers.front());
  717. streamBuffers.pop();
  718. }
  719. break;
  720. }
  721. case TYPE_MAX_ENUM:
  722. break;
  723. }
  724. // Seek to the current/pending offset.
  725. alSourcei(source, AL_SAMPLE_OFFSET, offsetSamples);
  726. }
  727. void Source::teardownAtomic()
  728. {
  729. switch (sourceType)
  730. {
  731. case TYPE_STATIC:
  732. break;
  733. case TYPE_STREAM:
  734. {
  735. ALint queued = 0;
  736. ALuint buffers[MAX_BUFFERS];
  737. // Some decoders (e.g. ModPlug) can rewind() more reliably than seek(0).
  738. decoder->rewind();
  739. // Drain buffers.
  740. // NOTE: The Apple implementation of OpenAL on iOS doesn't return
  741. // correct buffer ids for single alSourceUnqueueBuffers calls past the
  742. // first queued buffer, so we must unqueue them all at once.
  743. alGetSourcei(source, AL_BUFFERS_QUEUED, &queued);
  744. alSourceUnqueueBuffers(source, queued, buffers);
  745. for (int i = 0; i < queued; i++)
  746. unusedBuffers.push(buffers[i]);
  747. break;
  748. }
  749. case TYPE_QUEUE:
  750. {
  751. ALint queued;
  752. ALuint buffers[MAX_BUFFERS];
  753. alGetSourcei(source, AL_BUFFERS_QUEUED, &queued);
  754. alSourceUnqueueBuffers(source, queued, buffers);
  755. for (int i = 0; i < queued; i++)
  756. unusedBuffers.push(buffers[i]);
  757. break;
  758. }
  759. case TYPE_MAX_ENUM:
  760. break;
  761. }
  762. alSourcei(source, AL_BUFFER, AL_NONE);
  763. toLoop = 0;
  764. valid = false;
  765. offsetSamples = 0;
  766. }
  767. bool Source::playAtomic(ALuint source)
  768. {
  769. this->source = source;
  770. prepareAtomic();
  771. // Clear errors.
  772. alGetError();
  773. alSourcePlay(source);
  774. bool success = alGetError() == AL_NO_ERROR;
  775. if (sourceType == TYPE_STREAM)
  776. {
  777. valid = true; //isPlaying() needs source to be valid
  778. if (!isPlaying())
  779. success = false;
  780. }
  781. if (!success)
  782. {
  783. valid = true; //stop() needs source to be valid
  784. stop();
  785. }
  786. // Static sources: reset the pending offset since it's not valid anymore.
  787. if (sourceType != TYPE_STREAM)
  788. offsetSamples = 0;
  789. return success;
  790. }
  791. void Source::stopAtomic()
  792. {
  793. if (!valid)
  794. return;
  795. alSourceStop(source);
  796. teardownAtomic();
  797. }
  798. void Source::pauseAtomic()
  799. {
  800. if (valid)
  801. alSourcePause(source);
  802. }
  803. void Source::resumeAtomic()
  804. {
  805. if (valid && !isPlaying())
  806. {
  807. alSourcePlay(source);
  808. //failed to play or nothing to play
  809. if (alGetError() == AL_INVALID_VALUE || (sourceType == TYPE_STREAM && (int) unusedBuffers.size() == buffers))
  810. stop();
  811. }
  812. }
  813. bool Source::play(const std::vector<love::audio::Source*> &sources)
  814. {
  815. if (sources.size() == 0)
  816. return true;
  817. Pool *pool = ((Source*) sources[0])->pool;
  818. Lock l = pool->lock();
  819. // NOTE: not bool, because std::vector<bool> is implemented as a bitvector
  820. // which means no bool references can be created.
  821. std::vector<char> wasPlaying(sources.size());
  822. std::vector<ALuint> ids(sources.size());
  823. for (size_t i = 0; i < sources.size(); i++)
  824. {
  825. if (!pool->assignSource((Source*) sources[i], ids[i], wasPlaying[i]))
  826. {
  827. for (size_t j = 0; j < i; j++)
  828. if (!wasPlaying[j])
  829. pool->releaseSource((Source*) sources[j], false);
  830. return false;
  831. }
  832. }
  833. std::vector<ALuint> toPlay;
  834. toPlay.reserve(sources.size());
  835. for (size_t i = 0; i < sources.size(); i++)
  836. {
  837. // If the source was paused, wasPlaying[i] will be true but we still
  838. // want to resume it. We don't want to call alSourcePlay on sources
  839. // that are actually playing though.
  840. if (wasPlaying[i] && sources[i]->isPlaying())
  841. continue;
  842. if (!wasPlaying[i])
  843. {
  844. Source *source = (Source*) sources[i];
  845. source->source = ids[i];
  846. source->prepareAtomic();
  847. }
  848. toPlay.push_back(ids[i]);
  849. }
  850. alGetError();
  851. alSourcePlayv((ALsizei) toPlay.size(), &toPlay[0]);
  852. bool success = alGetError() == AL_NO_ERROR;
  853. for (auto &_source : sources)
  854. {
  855. Source *source = (Source*) _source;
  856. source->valid = source->valid || success;
  857. if (success && source->sourceType != TYPE_STREAM)
  858. source->offsetSamples = 0;
  859. }
  860. return success;
  861. }
  862. void Source::stop(const std::vector<love::audio::Source*> &sources)
  863. {
  864. if (sources.size() == 0)
  865. return;
  866. Pool *pool = ((Source*) sources[0])->pool;
  867. Lock l = pool->lock();
  868. std::vector<ALuint> sourceIds;
  869. sourceIds.reserve(sources.size());
  870. for (auto &_source : sources)
  871. {
  872. Source *source = (Source*) _source;
  873. if (source->valid)
  874. sourceIds.push_back(source->source);
  875. }
  876. alSourceStopv((ALsizei) sourceIds.size(), &sourceIds[0]);
  877. for (auto &_source : sources)
  878. {
  879. Source *source = (Source*) _source;
  880. if (source->valid)
  881. source->teardownAtomic();
  882. pool->releaseSource(source, false);
  883. }
  884. }
  885. void Source::pause(const std::vector<love::audio::Source*> &sources)
  886. {
  887. if (sources.size() == 0)
  888. return;
  889. Lock l = ((Source*) sources[0])->pool->lock();
  890. std::vector<ALuint> sourceIds;
  891. sourceIds.reserve(sources.size());
  892. for (auto &_source : sources)
  893. {
  894. Source *source = (Source*) _source;
  895. if (source->valid)
  896. sourceIds.push_back(source->source);
  897. }
  898. alSourcePausev((ALsizei) sourceIds.size(), &sourceIds[0]);
  899. }
  900. std::vector<love::audio::Source*> Source::pause(Pool *pool)
  901. {
  902. Lock l = pool->lock();
  903. std::vector<love::audio::Source*> sources = pool->getPlayingSources();
  904. auto newend = std::remove_if(sources.begin(), sources.end(), [](love::audio::Source* s) {
  905. return !s->isPlaying();
  906. });
  907. sources.erase(newend, sources.end());
  908. pause(sources);
  909. return sources;
  910. }
  911. void Source::stop(Pool *pool)
  912. {
  913. Lock l = pool->lock();
  914. stop(pool->getPlayingSources());
  915. }
  916. void Source::reset()
  917. {
  918. alSourcei(source, AL_BUFFER, AL_NONE);
  919. alSourcefv(source, AL_POSITION, position);
  920. alSourcefv(source, AL_VELOCITY, velocity);
  921. alSourcefv(source, AL_DIRECTION, direction);
  922. alSourcef(source, AL_PITCH, pitch);
  923. alSourcef(source, AL_GAIN, volume);
  924. alSourcef(source, AL_MIN_GAIN, minVolume);
  925. alSourcef(source, AL_MAX_GAIN, maxVolume);
  926. alSourcef(source, AL_REFERENCE_DISTANCE, referenceDistance);
  927. alSourcef(source, AL_ROLLOFF_FACTOR, rolloffFactor);
  928. alSourcef(source, AL_MAX_DISTANCE, maxDistance);
  929. alSourcei(source, AL_LOOPING, (sourceType == TYPE_STATIC) && isLooping() ? AL_TRUE : AL_FALSE);
  930. alSourcei(source, AL_SOURCE_RELATIVE, relative ? AL_TRUE : AL_FALSE);
  931. alSourcei(source, AL_CONE_INNER_ANGLE, cone.innerAngle);
  932. alSourcei(source, AL_CONE_OUTER_ANGLE, cone.outerAngle);
  933. alSourcef(source, AL_CONE_OUTER_GAIN, cone.outerVolume);
  934. #ifdef ALC_EXT_EFX
  935. alSourcef(source, AL_AIR_ABSORPTION_FACTOR, absorptionFactor);
  936. alSourcef(source, AL_CONE_OUTER_GAINHF, cone.outerHighGain);
  937. alSourcef(source, AL_ROOM_ROLLOFF_FACTOR, rolloffFactor); //reverb-specific rolloff
  938. alSourcei(source, AL_DIRECT_FILTER, directfilter ? directfilter->getFilter() : AL_FILTER_NULL);
  939. // clear all send slots, then re-enable applied ones
  940. for (int i = 0; i < audiomodule()->getMaxSourceEffects(); i++)
  941. alSource3i(source, AL_AUXILIARY_SEND_FILTER, AL_EFFECTSLOT_NULL, i, AL_FILTER_NULL);
  942. for (auto i : effectmap)
  943. alSource3i(source, AL_AUXILIARY_SEND_FILTER, i.second.target, i.second.slot, i.second.filter ? i.second.filter->getFilter() : AL_FILTER_NULL);
  944. //alGetError();
  945. #endif
  946. }
  947. void Source::setFloatv(float *dst, const float *src) const
  948. {
  949. dst[0] = src[0];
  950. dst[1] = src[1];
  951. dst[2] = src[2];
  952. }
  953. int Source::streamAtomic(ALuint buffer, love::sound::Decoder *d)
  954. {
  955. // Get more sound data.
  956. int decoded = std::max(d->decode(), 0);
  957. // OpenAL implementations are allowed to ignore 0-size alBufferData calls.
  958. if (decoded > 0)
  959. {
  960. int fmt = Audio::getFormat(d->getBitDepth(), d->getChannelCount());
  961. if (fmt != AL_NONE)
  962. alBufferData(buffer, fmt, d->getBuffer(), decoded, d->getSampleRate());
  963. else
  964. decoded = 0;
  965. }
  966. if (decoder->isFinished() && isLooping())
  967. {
  968. int queued, processed;
  969. alGetSourcei(source, AL_BUFFERS_QUEUED, &queued);
  970. alGetSourcei(source, AL_BUFFERS_PROCESSED, &processed);
  971. if (queued > processed)
  972. toLoop = queued-processed;
  973. else
  974. toLoop = buffers-processed;
  975. d->rewind();
  976. }
  977. if (toLoop > 0)
  978. {
  979. if (--toLoop == 0)
  980. {
  981. offsetSamples = 0;
  982. }
  983. }
  984. return decoded;
  985. }
  986. void Source::setMinVolume(float volume)
  987. {
  988. if (valid)
  989. alSourcef(source, AL_MIN_GAIN, volume);
  990. minVolume = volume;
  991. }
  992. float Source::getMinVolume() const
  993. {
  994. if (valid)
  995. {
  996. ALfloat f;
  997. alGetSourcef(source, AL_MIN_GAIN, &f);
  998. return f;
  999. }
  1000. // In case the Source isn't playing.
  1001. return this->minVolume;
  1002. }
  1003. void Source::setMaxVolume(float volume)
  1004. {
  1005. if (valid)
  1006. alSourcef(source, AL_MAX_GAIN, volume);
  1007. maxVolume = volume;
  1008. }
  1009. float Source::getMaxVolume() const
  1010. {
  1011. if (valid)
  1012. {
  1013. ALfloat f;
  1014. alGetSourcef(source, AL_MAX_GAIN, &f);
  1015. return f;
  1016. }
  1017. // In case the Source isn't playing.
  1018. return maxVolume;
  1019. }
  1020. void Source::setReferenceDistance(float distance)
  1021. {
  1022. if (channels > 1)
  1023. throw SpatialSupportException();
  1024. if (valid)
  1025. alSourcef(source, AL_REFERENCE_DISTANCE, distance);
  1026. referenceDistance = distance;
  1027. }
  1028. float Source::getReferenceDistance() const
  1029. {
  1030. if (channels > 1)
  1031. throw SpatialSupportException();
  1032. if (valid)
  1033. {
  1034. ALfloat f;
  1035. alGetSourcef(source, AL_REFERENCE_DISTANCE, &f);
  1036. return f;
  1037. }
  1038. // In case the Source isn't playing.
  1039. return referenceDistance;
  1040. }
  1041. void Source::setRolloffFactor(float factor)
  1042. {
  1043. if (channels > 1)
  1044. throw SpatialSupportException();
  1045. if (valid)
  1046. alSourcef(source, AL_ROLLOFF_FACTOR, factor);
  1047. rolloffFactor = factor;
  1048. }
  1049. float Source::getRolloffFactor() const
  1050. {
  1051. if (channels > 1)
  1052. throw SpatialSupportException();
  1053. if (valid)
  1054. {
  1055. ALfloat f;
  1056. alGetSourcef(source, AL_ROLLOFF_FACTOR, &f);
  1057. return f;
  1058. }
  1059. // In case the Source isn't playing.
  1060. return rolloffFactor;
  1061. }
  1062. void Source::setMaxDistance(float distance)
  1063. {
  1064. if (channels > 1)
  1065. throw SpatialSupportException();
  1066. distance = std::min(distance, MAX_ATTENUATION_DISTANCE);
  1067. if (valid)
  1068. alSourcef(source, AL_MAX_DISTANCE, distance);
  1069. maxDistance = distance;
  1070. }
  1071. float Source::getMaxDistance() const
  1072. {
  1073. if (channels > 1)
  1074. throw SpatialSupportException();
  1075. if (valid)
  1076. {
  1077. ALfloat f;
  1078. alGetSourcef(source, AL_MAX_DISTANCE, &f);
  1079. return f;
  1080. }
  1081. // In case the Source isn't playing.
  1082. return maxDistance;
  1083. }
  1084. void Source::setAirAbsorptionFactor(float factor)
  1085. {
  1086. if (channels > 1)
  1087. throw SpatialSupportException();
  1088. absorptionFactor = factor;
  1089. #ifdef ALC_EXT_EFX
  1090. if (valid)
  1091. {
  1092. alSourcef(source, AL_AIR_ABSORPTION_FACTOR, absorptionFactor);
  1093. //alGetError();
  1094. }
  1095. #endif
  1096. }
  1097. float Source::getAirAbsorptionFactor() const
  1098. {
  1099. if (channels > 1)
  1100. throw SpatialSupportException();
  1101. return absorptionFactor;
  1102. }
  1103. int Source::getChannelCount() const
  1104. {
  1105. return channels;
  1106. }
  1107. bool Source::setFilter(const std::map<Filter::Parameter, float> &params)
  1108. {
  1109. if (!directfilter)
  1110. directfilter = new Filter();
  1111. bool result = directfilter->setParams(params);
  1112. #ifdef ALC_EXT_EFX
  1113. if (valid)
  1114. {
  1115. //in case of failure contains AL_FILTER_NULL, a valid non-filter
  1116. alSourcei(source, AL_DIRECT_FILTER, directfilter->getFilter());
  1117. //alGetError();
  1118. }
  1119. #endif
  1120. return result;
  1121. }
  1122. bool Source::setFilter()
  1123. {
  1124. if (directfilter)
  1125. delete directfilter;
  1126. directfilter = nullptr;
  1127. #ifdef ALC_EXT_EFX
  1128. if (valid)
  1129. {
  1130. alSourcei(source, AL_DIRECT_FILTER, AL_FILTER_NULL);
  1131. //alGetError();
  1132. }
  1133. #endif
  1134. return true;
  1135. }
  1136. bool Source::getFilter(std::map<Filter::Parameter, float> &params)
  1137. {
  1138. if (!directfilter)
  1139. return false;
  1140. params = directfilter->getParams();
  1141. return true;
  1142. }
  1143. bool Source::setEffect(const char *name)
  1144. {
  1145. ALuint slot, target;
  1146. Filter *filter;
  1147. // effect with this name doesn't exist
  1148. if (!dynamic_cast<Audio*>(audiomodule())->getEffectID(name, target))
  1149. return false;
  1150. auto iter = effectmap.find(name);
  1151. if (iter == effectmap.end())
  1152. {
  1153. // new send target needed but no more room
  1154. if (slotlist.empty())
  1155. return false;
  1156. slot = slotlist.top();
  1157. slotlist.pop();
  1158. }
  1159. else
  1160. {
  1161. slot = iter->second.slot;
  1162. filter = iter->second.filter;
  1163. if (filter)
  1164. delete filter;
  1165. }
  1166. effectmap[name] = {nullptr, slot, target};
  1167. #ifdef ALC_EXT_EFX
  1168. if (valid)
  1169. {
  1170. alSource3i(source, AL_AUXILIARY_SEND_FILTER, target, slot, AL_FILTER_NULL);
  1171. //alGetError();
  1172. }
  1173. #endif
  1174. return true;
  1175. }
  1176. bool Source::setEffect(const char *name, const std::map<Filter::Parameter, float> &params)
  1177. {
  1178. ALuint slot, target;
  1179. Filter *filter = nullptr;
  1180. // effect with this name doesn't exist
  1181. if (!dynamic_cast<Audio*>(audiomodule())->getEffectID(name, target))
  1182. return false;
  1183. auto iter = effectmap.find(name);
  1184. if (iter == effectmap.end())
  1185. {
  1186. // new send target needed but no more room
  1187. if (slotlist.empty())
  1188. return false;
  1189. slot = slotlist.top();
  1190. slotlist.pop();
  1191. }
  1192. else
  1193. {
  1194. slot = iter->second.slot;
  1195. filter = iter->second.filter;
  1196. }
  1197. if (!filter)
  1198. filter = new Filter();
  1199. effectmap[name] = {filter, slot, target};
  1200. filter->setParams(params);
  1201. #ifdef ALC_EXT_EFX
  1202. if (valid)
  1203. {
  1204. //in case of failure contains AL_FILTER_NULL, a valid non-filter
  1205. alSource3i(source, AL_AUXILIARY_SEND_FILTER, target, slot, filter->getFilter());
  1206. //alGetError();
  1207. }
  1208. #endif
  1209. return true;
  1210. }
  1211. bool Source::unsetEffect(const char *name)
  1212. {
  1213. auto iter = effectmap.find(name);
  1214. if (iter == effectmap.end())
  1215. return false;
  1216. ALuint slot = iter->second.slot;
  1217. Filter *filter = iter->second.filter;
  1218. if (filter)
  1219. delete filter;
  1220. #ifdef ALC_EXT_EFX
  1221. if (valid)
  1222. {
  1223. alSource3i(source, AL_AUXILIARY_SEND_FILTER, AL_EFFECTSLOT_NULL, slot, AL_FILTER_NULL);
  1224. //alGetError();
  1225. }
  1226. #endif
  1227. effectmap.erase(iter);
  1228. slotlist.push(slot);
  1229. return true;
  1230. }
  1231. bool Source::getEffect(const char *name, std::map<Filter::Parameter, float> &params)
  1232. {
  1233. auto iter = effectmap.find(name);
  1234. if (iter == effectmap.end())
  1235. return false;
  1236. if (iter->second.filter)
  1237. params = iter->second.filter->getParams();
  1238. return true;
  1239. }
  1240. bool Source::getActiveEffects(std::vector<std::string> &list) const
  1241. {
  1242. if (effectmap.empty())
  1243. return false;
  1244. list.reserve(effectmap.size());
  1245. for (auto i : effectmap)
  1246. list.push_back(i.first);
  1247. return true;
  1248. }
  1249. } // openal
  1250. } // audio
  1251. } // love