Source.cpp 30 KB

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