Source.cpp 31 KB

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