Source.cpp 30 KB

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