Source.cpp 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253
  1. /**
  2. * Copyright (c) 2006-2016 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 "Pool.h"
  22. #include "common/math.h"
  23. // STD
  24. #include <iostream>
  25. #include <float.h>
  26. #include <algorithm>
  27. namespace love
  28. {
  29. namespace audio
  30. {
  31. namespace openal
  32. {
  33. #ifdef LOVE_IOS
  34. // OpenAL on iOS barfs if the max distance is +inf.
  35. static const float MAX_ATTENUATION_DISTANCE = 1000000.0f;
  36. #else
  37. static const float MAX_ATTENUATION_DISTANCE = FLT_MAX;
  38. #endif
  39. class InvalidFormatException : public love::Exception
  40. {
  41. public:
  42. InvalidFormatException(int channels, int bitdepth)
  43. : Exception("%d-channel Sources with %d bits per sample are not supported.", channels, bitdepth)
  44. {
  45. }
  46. };
  47. class SpatialSupportException : public love::Exception
  48. {
  49. public:
  50. SpatialSupportException()
  51. : Exception("This spatial audio functionality is only available for mono Sources. \
  52. Ensure the Source is not multi-channel before calling this function.")
  53. {
  54. }
  55. };
  56. class QueueFormatMismatchException : public love::Exception
  57. {
  58. public:
  59. QueueFormatMismatchException()
  60. : Exception("Queued sound data must have same format as sound Source.")
  61. {
  62. }
  63. };
  64. class QueueTypeMismatchException : public love::Exception
  65. {
  66. public:
  67. QueueTypeMismatchException()
  68. : Exception("Only queueable Sources can be queued with sound data.")
  69. {
  70. }
  71. };
  72. class QueueMalformedLengthException : public love::Exception
  73. {
  74. public:
  75. QueueMalformedLengthException(int bytes)
  76. : Exception("Data length must be a multiple of sample size (%d bytes).", bytes)
  77. {
  78. }
  79. };
  80. class QueueLoopingException : public love::Exception
  81. {
  82. public:
  83. QueueLoopingException()
  84. : Exception("Queueable Sources can not be looped.")
  85. {
  86. }
  87. };
  88. StaticDataBuffer::StaticDataBuffer(ALenum format, const ALvoid *data, ALsizei size, ALsizei freq)
  89. : size(size)
  90. {
  91. alGenBuffers(1, &buffer);
  92. alBufferData(buffer, format, data, size, freq);
  93. }
  94. StaticDataBuffer::~StaticDataBuffer()
  95. {
  96. alDeleteBuffers(1, &buffer);
  97. }
  98. Source::Source(Pool *pool, love::sound::SoundData *soundData)
  99. : love::audio::Source(Source::TYPE_STATIC)
  100. , pool(pool)
  101. , valid(false)
  102. , staticBuffer(nullptr)
  103. , pitch(1.0f)
  104. , volume(1.0f)
  105. , relative(false)
  106. , looping(false)
  107. , minVolume(0.0f)
  108. , maxVolume(1.0f)
  109. , referenceDistance(1.0f)
  110. , rolloffFactor(1.0f)
  111. , maxDistance(MAX_ATTENUATION_DISTANCE)
  112. , cone()
  113. , offsetSamples(0)
  114. , offsetSeconds(0)
  115. , sampleRate(soundData->getSampleRate())
  116. , channels(soundData->getChannels())
  117. , bitDepth(soundData->getBitDepth())
  118. , decoder(nullptr)
  119. , toLoop(0)
  120. {
  121. ALenum fmt = getFormat(soundData->getChannels(), soundData->getBitDepth());
  122. if (fmt == 0)
  123. throw InvalidFormatException(soundData->getChannels(), soundData->getBitDepth());
  124. staticBuffer.set(new StaticDataBuffer(fmt, soundData->getData(), (ALsizei) soundData->getSize(), sampleRate), Acquire::NORETAIN);
  125. float z[3] = {0, 0, 0};
  126. setFloatv(position, z);
  127. setFloatv(velocity, z);
  128. setFloatv(direction, z);
  129. }
  130. Source::Source(Pool *pool, love::sound::Decoder *decoder)
  131. : love::audio::Source(Source::TYPE_STREAM)
  132. , pool(pool)
  133. , valid(false)
  134. , staticBuffer(nullptr)
  135. , pitch(1.0f)
  136. , volume(1.0f)
  137. , relative(false)
  138. , looping(false)
  139. , minVolume(0.0f)
  140. , maxVolume(1.0f)
  141. , referenceDistance(1.0f)
  142. , rolloffFactor(1.0f)
  143. , maxDistance(MAX_ATTENUATION_DISTANCE)
  144. , cone()
  145. , offsetSamples(0)
  146. , offsetSeconds(0)
  147. , sampleRate(decoder->getSampleRate())
  148. , channels(decoder->getChannels())
  149. , bitDepth(decoder->getBitDepth())
  150. , decoder(decoder)
  151. , toLoop(0)
  152. , unusedBufferTop(MAX_BUFFERS - 1)
  153. {
  154. if (getFormat(decoder->getChannels(), decoder->getBitDepth()) == 0)
  155. throw InvalidFormatException(decoder->getChannels(), decoder->getBitDepth());
  156. alGenBuffers(MAX_BUFFERS, streamBuffers);
  157. for (unsigned int i = 0; i < MAX_BUFFERS; i++)
  158. unusedBuffers[i] = streamBuffers[i];
  159. float z[3] = {0, 0, 0};
  160. setFloatv(position, z);
  161. setFloatv(velocity, z);
  162. setFloatv(direction, z);
  163. }
  164. Source::Source(Pool *pool, int sampleRate, int bitDepth, int channels)
  165. : love::audio::Source(Source::TYPE_QUEUE)
  166. , pool(pool)
  167. , valid(false)
  168. , staticBuffer(nullptr)
  169. , pitch(1.0f)
  170. , volume(1.0f)
  171. , relative(false)
  172. , looping(false)
  173. , minVolume(0.0f)
  174. , maxVolume(1.0f)
  175. , referenceDistance(1.0f)
  176. , rolloffFactor(1.0f)
  177. , maxDistance(MAX_ATTENUATION_DISTANCE)
  178. , cone()
  179. , offsetSamples(0)
  180. , offsetSeconds(0)
  181. , sampleRate(sampleRate)
  182. , channels(channels)
  183. , bitDepth(bitDepth)
  184. , decoder(nullptr)
  185. , toLoop(0)
  186. , unusedBufferTop(-1)
  187. , bufferedBytes(0)
  188. {
  189. ALenum fmt = getFormat(channels, bitDepth);
  190. if (fmt == 0)
  191. throw InvalidFormatException(channels, bitDepth);
  192. alGenBuffers(MAX_BUFFERS, streamBuffers);
  193. for (unsigned int i = 0; i < MAX_BUFFERS; i++)
  194. unusedBuffers[i] = streamBuffers[i];
  195. float z[3] = {0, 0, 0};
  196. setFloatv(position, z);
  197. setFloatv(velocity, z);
  198. setFloatv(direction, z);
  199. }
  200. Source::Source(const Source &s)
  201. : love::audio::Source(s.type)
  202. , pool(s.pool)
  203. , valid(false)
  204. , staticBuffer(s.staticBuffer)
  205. , pitch(s.pitch)
  206. , volume(s.volume)
  207. , relative(s.relative)
  208. , looping(s.looping)
  209. , minVolume(s.minVolume)
  210. , maxVolume(s.maxVolume)
  211. , referenceDistance(s.referenceDistance)
  212. , rolloffFactor(s.rolloffFactor)
  213. , maxDistance(s.maxDistance)
  214. , cone(s.cone)
  215. , offsetSamples(0)
  216. , offsetSeconds(0)
  217. , sampleRate(s.sampleRate)
  218. , channels(s.channels)
  219. , bitDepth(s.bitDepth)
  220. , decoder(nullptr)
  221. , toLoop(0)
  222. , unusedBufferTop(-1)
  223. {
  224. if (type == TYPE_STREAM)
  225. {
  226. if (s.decoder.get())
  227. decoder.set(s.decoder->clone(), Acquire::NORETAIN);
  228. }
  229. if (type != TYPE_STATIC)
  230. {
  231. alGenBuffers(MAX_BUFFERS, streamBuffers);
  232. for (unsigned int i = 0; i < MAX_BUFFERS; i++)
  233. unusedBuffers[i] = streamBuffers[i];
  234. }
  235. setFloatv(position, s.position);
  236. setFloatv(velocity, s.velocity);
  237. setFloatv(direction, s.direction);
  238. }
  239. Source::~Source()
  240. {
  241. if (valid)
  242. pool->stop(this);
  243. if (type != TYPE_STATIC)
  244. alDeleteBuffers(MAX_BUFFERS, streamBuffers);
  245. }
  246. love::audio::Source *Source::clone()
  247. {
  248. return new Source(*this);
  249. }
  250. bool Source::play()
  251. {
  252. valid = pool->play(this);
  253. return valid;
  254. }
  255. void Source::stop()
  256. {
  257. if (valid)
  258. pool->stop(this);
  259. }
  260. void Source::pause()
  261. {
  262. pool->pause(this);
  263. }
  264. bool Source::isPlaying() const
  265. {
  266. if (!valid)
  267. return false;
  268. ALenum state;
  269. alGetSourcei(source, AL_SOURCE_STATE, &state);
  270. return state == AL_PLAYING;
  271. }
  272. bool Source::isFinished() const
  273. {
  274. if (!valid)
  275. return false;
  276. if (type == TYPE_STREAM && (isLooping() || !decoder->isFinished()))
  277. return false;
  278. ALenum state;
  279. alGetSourcei(source, AL_SOURCE_STATE, &state);
  280. return state == AL_STOPPED;
  281. }
  282. bool Source::update()
  283. {
  284. if (!valid)
  285. return false;
  286. switch (type)
  287. {
  288. case TYPE_STATIC:
  289. // Looping mode could have changed.
  290. // FIXME: make looping mode not change without you noticing so that this is not needed
  291. alSourcei(source, AL_LOOPING, isLooping() ? AL_TRUE : AL_FALSE);
  292. return !isFinished();
  293. case TYPE_STREAM:
  294. if (!isFinished())
  295. {
  296. ALint processed;
  297. ALuint buffers[MAX_BUFFERS];
  298. float curOffsetSamples, curOffsetSecs, newOffsetSamples, newOffsetSecs;
  299. int freq = decoder->getSampleRate();
  300. alGetSourcef(source, AL_SAMPLE_OFFSET, &curOffsetSamples);
  301. curOffsetSecs = curOffsetSamples / freq;
  302. alGetSourcei(source, AL_BUFFERS_PROCESSED, &processed);
  303. alSourceUnqueueBuffers(source, processed, buffers);
  304. alGetSourcef(source, AL_SAMPLE_OFFSET, &newOffsetSamples);
  305. newOffsetSecs = newOffsetSamples / freq;
  306. offsetSamples += (curOffsetSamples - newOffsetSamples);
  307. offsetSeconds += (curOffsetSecs - newOffsetSecs);
  308. for (unsigned int i = 0; i < (unsigned int)processed; i++)
  309. unusedBufferPush(buffers[i]);
  310. while (unusedBufferPeek() != AL_NONE)
  311. {
  312. if(streamAtomic(unusedBufferPeek(), decoder.get()) > 0)
  313. alSourceQueueBuffers(source, 1, unusedBufferPop());
  314. else
  315. break;
  316. }
  317. return true;
  318. }
  319. return false;
  320. case TYPE_QUEUE:
  321. {
  322. ALint processed;
  323. ALuint buffers[MAX_BUFFERS];
  324. alGetSourcei(source, AL_BUFFERS_PROCESSED, &processed);
  325. alSourceUnqueueBuffers(source, processed, buffers);
  326. for (unsigned int i = 0; i < (unsigned int)processed; i++)
  327. {
  328. ALint size;
  329. alGetBufferi(buffers[i], AL_SIZE, &size);
  330. bufferedBytes -= size;
  331. unusedBufferPush(buffers[i]);
  332. }
  333. return !isFinished();
  334. }
  335. case TYPE_MAX_ENUM:
  336. break;
  337. }
  338. return false;
  339. }
  340. void Source::setPitch(float pitch)
  341. {
  342. if (valid)
  343. alSourcef(source, AL_PITCH, pitch);
  344. this->pitch = pitch;
  345. }
  346. float Source::getPitch() const
  347. {
  348. if (valid)
  349. {
  350. ALfloat f;
  351. alGetSourcef(source, AL_PITCH, &f);
  352. return f;
  353. }
  354. // In case the Source isn't playing.
  355. return pitch;
  356. }
  357. void Source::setVolume(float volume)
  358. {
  359. if (valid)
  360. alSourcef(source, AL_GAIN, volume);
  361. this->volume = volume;
  362. }
  363. float Source::getVolume() const
  364. {
  365. if (valid)
  366. {
  367. ALfloat f;
  368. alGetSourcef(source, AL_GAIN, &f);
  369. return f;
  370. }
  371. // In case the Source isn't playing.
  372. return volume;
  373. }
  374. void Source::seekAtomic(float offset, void *unit)
  375. {
  376. float offsetSamples, offsetSeconds;
  377. switch (*((Source::Unit *) unit))
  378. {
  379. case Source::UNIT_SAMPLES:
  380. offsetSamples = offset;
  381. offsetSeconds = offset / sampleRate;
  382. break;
  383. case Source::UNIT_SECONDS:
  384. default:
  385. offsetSeconds = offset;
  386. offsetSamples = offset * sampleRate;
  387. break;
  388. }
  389. switch (type)
  390. {
  391. case TYPE_STATIC:
  392. alSourcef(source, AL_SAMPLE_OFFSET, offsetSamples);
  393. offsetSamples = offsetSeconds = 0;
  394. break;
  395. case TYPE_STREAM:
  396. {
  397. bool wasPlaying = isPlaying();
  398. // To drain all buffers
  399. if (valid)
  400. stopAtomic();
  401. decoder->seek(offsetSeconds);
  402. if (wasPlaying)
  403. playAtomic(source);
  404. break;
  405. }
  406. case TYPE_QUEUE:
  407. if (valid)
  408. {
  409. alSourcef(source, AL_SAMPLE_OFFSET, offsetSamples);
  410. offsetSamples = offsetSeconds = 0;
  411. }
  412. else
  413. {
  414. ALint size;
  415. ALuint buffer = unusedBufferPeek();
  416. //emulate AL behavior, discarding buffer once playback head is past one
  417. while (buffer != AL_NONE)
  418. {
  419. alGetBufferi(buffer, AL_SIZE, &size);
  420. if (offsetSamples < size / (bitDepth / 8 * channels))
  421. break;
  422. unusedBufferPop();
  423. buffer = unusedBufferPeek();
  424. bufferedBytes -= size;
  425. offsetSamples -= size / (bitDepth / 8 * channels);
  426. }
  427. if (buffer == AL_NONE)
  428. offsetSamples = 0;
  429. offsetSeconds = offsetSamples / sampleRate;
  430. }
  431. break;
  432. case TYPE_MAX_ENUM:
  433. break;
  434. }
  435. this->offsetSamples = offsetSamples;
  436. this->offsetSeconds = offsetSeconds;
  437. }
  438. void Source::seek(float offset, Source::Unit unit)
  439. {
  440. return pool->seek(this, offset, &unit);
  441. }
  442. float Source::tellAtomic(void *unit) const
  443. {
  444. float offset = 0.0f;
  445. switch (*((Source::Unit *) unit))
  446. {
  447. case Source::UNIT_SAMPLES:
  448. if (valid)
  449. alGetSourcef(source, AL_SAMPLE_OFFSET, &offset);
  450. offset += offsetSamples;
  451. break;
  452. case Source::UNIT_SECONDS:
  453. default:
  454. if (valid)
  455. alGetSourcef(source, AL_SEC_OFFSET, &offset);
  456. offset += offsetSeconds;
  457. break;
  458. }
  459. return offset;
  460. }
  461. float Source::tell(Source::Unit unit)
  462. {
  463. return pool->tell(this, &unit);
  464. }
  465. double Source::getDurationAtomic(void *vunit)
  466. {
  467. Unit unit = *(Unit *) vunit;
  468. switch (type)
  469. {
  470. case TYPE_STATIC:
  471. {
  472. ALsizei size = staticBuffer->getSize();
  473. ALsizei samples = (size / channels) / (bitDepth / 8);
  474. if (unit == UNIT_SAMPLES)
  475. return (double) samples;
  476. else
  477. return (double) samples / (double) sampleRate;
  478. }
  479. case TYPE_STREAM:
  480. {
  481. double seconds = decoder->getDuration();
  482. if (unit == UNIT_SECONDS)
  483. return seconds;
  484. else
  485. return seconds * decoder->getSampleRate();
  486. }
  487. case TYPE_QUEUE:
  488. {
  489. ALsizei samples = (bufferedBytes / channels) / (bitDepth / 8);
  490. if (unit == UNIT_SAMPLES)
  491. return (double)samples;
  492. else
  493. return (double)samples / (double)sampleRate;
  494. }
  495. case TYPE_MAX_ENUM:
  496. return 0.0;
  497. }
  498. return 0.0;
  499. }
  500. double Source::getDuration(Unit unit)
  501. {
  502. return pool->getDuration(this, &unit);
  503. }
  504. void Source::setPosition(float *v)
  505. {
  506. if (channels > 1)
  507. throw SpatialSupportException();
  508. if (valid)
  509. alSourcefv(source, AL_POSITION, v);
  510. setFloatv(position, v);
  511. }
  512. void Source::getPosition(float *v) const
  513. {
  514. if (channels > 1)
  515. throw SpatialSupportException();
  516. if (valid)
  517. alGetSourcefv(source, AL_POSITION, v);
  518. else
  519. setFloatv(v, position);
  520. }
  521. void Source::setVelocity(float *v)
  522. {
  523. if (channels > 1)
  524. throw SpatialSupportException();
  525. if (valid)
  526. alSourcefv(source, AL_VELOCITY, v);
  527. setFloatv(velocity, v);
  528. }
  529. void Source::getVelocity(float *v) const
  530. {
  531. if (channels > 1)
  532. throw SpatialSupportException();
  533. if (valid)
  534. alGetSourcefv(source, AL_VELOCITY, v);
  535. else
  536. setFloatv(v, velocity);
  537. }
  538. void Source::setDirection(float *v)
  539. {
  540. if (channels > 1)
  541. throw SpatialSupportException();
  542. if (valid)
  543. alSourcefv(source, AL_DIRECTION, v);
  544. else
  545. setFloatv(direction, v);
  546. }
  547. void Source::getDirection(float *v) const
  548. {
  549. if (channels > 1)
  550. throw SpatialSupportException();
  551. if (valid)
  552. alGetSourcefv(source, AL_DIRECTION, v);
  553. else
  554. setFloatv(v, direction);
  555. }
  556. void Source::setCone(float innerAngle, float outerAngle, float outerVolume)
  557. {
  558. if (channels > 1)
  559. throw SpatialSupportException();
  560. cone.innerAngle = (int) LOVE_TODEG(innerAngle);
  561. cone.outerAngle = (int) LOVE_TODEG(outerAngle);
  562. cone.outerVolume = outerVolume;
  563. if (valid)
  564. {
  565. alSourcei(source, AL_CONE_INNER_ANGLE, cone.innerAngle);
  566. alSourcei(source, AL_CONE_OUTER_ANGLE, cone.outerAngle);
  567. alSourcef(source, AL_CONE_OUTER_GAIN, cone.outerVolume);
  568. }
  569. }
  570. void Source::getCone(float &innerAngle, float &outerAngle, float &outerVolume) const
  571. {
  572. if (channels > 1)
  573. throw SpatialSupportException();
  574. innerAngle = LOVE_TORAD(cone.innerAngle);
  575. outerAngle = LOVE_TORAD(cone.outerAngle);
  576. outerVolume = cone.outerVolume;
  577. }
  578. void Source::setRelative(bool enable)
  579. {
  580. if (channels > 1)
  581. throw SpatialSupportException();
  582. if (valid)
  583. alSourcei(source, AL_SOURCE_RELATIVE, enable ? AL_TRUE : AL_FALSE);
  584. relative = enable;
  585. }
  586. bool Source::isRelative() const
  587. {
  588. if (channels > 1)
  589. throw SpatialSupportException();
  590. return relative;
  591. }
  592. void Source::setLooping(bool enable)
  593. {
  594. if (type == TYPE_QUEUE)
  595. throw QueueLoopingException();
  596. if (valid && type == TYPE_STATIC)
  597. alSourcei(source, AL_LOOPING, enable ? AL_TRUE : AL_FALSE);
  598. looping = enable;
  599. }
  600. bool Source::isLooping() const
  601. {
  602. return looping;
  603. }
  604. bool Source::queue(void *data, int length, int dataSampleRate, int dataBitDepth, int dataChannels)
  605. {
  606. if (type != TYPE_QUEUE)
  607. throw QueueTypeMismatchException();
  608. if (dataSampleRate != sampleRate || dataBitDepth != bitDepth || dataChannels != channels )
  609. throw QueueFormatMismatchException();
  610. if (length % (bitDepth / 8 * channels) != 0)
  611. throw QueueMalformedLengthException(bitDepth / 8 * channels);
  612. if (length == 0)
  613. return true;
  614. return pool->queue(this, data, (ALsizei)length);
  615. }
  616. bool Source::queueAtomic(void *data, ALsizei length)
  617. {
  618. if (valid)
  619. {
  620. ALuint buffer = unusedBufferPeek();
  621. if (buffer == AL_NONE)
  622. return false;
  623. alBufferData(buffer, getFormat(channels, bitDepth), data, length, sampleRate);
  624. alSourceQueueBuffers(source, 1, &buffer);
  625. unusedBufferPop();
  626. }
  627. else
  628. {
  629. ALuint buffer = unusedBufferPeekNext();
  630. if (buffer == AL_NONE)
  631. return false;
  632. //stack acts as queue while stopped
  633. alBufferData(buffer, getFormat(channels, bitDepth), data, length, sampleRate);
  634. unusedBufferQueue(buffer);
  635. }
  636. bufferedBytes += length;
  637. return true;
  638. }
  639. int Source::getFreeBufferCount() const
  640. {
  641. switch (type) //why not :^)
  642. {
  643. case TYPE_STATIC:
  644. return 0;
  645. case TYPE_STREAM:
  646. return unusedBufferTop + 1;
  647. case TYPE_QUEUE:
  648. return valid ? unusedBufferTop + 1 : (int)MAX_BUFFERS - unusedBufferTop - 1;
  649. case TYPE_MAX_ENUM:
  650. return 0;
  651. }
  652. return 0;
  653. }
  654. void Source::prepareAtomic()
  655. {
  656. // This Source may now be associated with an OpenAL source that still has
  657. // the properties of another love Source. Let's reset it to the settings
  658. // of the new one.
  659. reset();
  660. switch (type)
  661. {
  662. case TYPE_STATIC:
  663. alSourcei(source, AL_BUFFER, staticBuffer->getBuffer());
  664. //source can be seeked while not valid
  665. if (offsetSamples >= 0)
  666. alSourcef(source, AL_SAMPLE_OFFSET, offsetSamples);
  667. break;
  668. case TYPE_STREAM:
  669. while (unusedBufferPeek() != AL_NONE)
  670. {
  671. if(streamAtomic(unusedBufferPeek(), decoder.get()) == 0)
  672. break;
  673. alSourceQueueBuffers(source, 1, unusedBufferPop());
  674. if (decoder->isFinished())
  675. break;
  676. }
  677. break;
  678. case TYPE_QUEUE:
  679. {
  680. int top = unusedBufferTop;
  681. //when queue source is stopped, loaded buffers are stored in unused buffers stack
  682. while (unusedBufferPeek() != AL_NONE)
  683. alSourceQueueBuffers(source, 1, unusedBufferPop());
  684. //construct a stack of unused buffers (beyond the end of stack)
  685. for (unsigned int i = top + 1; i < MAX_BUFFERS; i++)
  686. unusedBufferPush(unusedBuffers[i]);
  687. if (offsetSamples >= 0)
  688. alSourcef(source, AL_SAMPLE_OFFSET, offsetSamples);
  689. break;
  690. }
  691. case TYPE_MAX_ENUM:
  692. break;
  693. }
  694. }
  695. void Source::teardownAtomic()
  696. {
  697. switch (type)
  698. {
  699. case TYPE_STATIC:
  700. alSourcef(source, AL_SAMPLE_OFFSET, 0);
  701. break;
  702. case TYPE_STREAM:
  703. {
  704. ALint queued;
  705. ALuint buffer;
  706. decoder->seek(0);
  707. // drain buffers
  708. //since we only unqueue 1 buffer, it's OK to use singular variable pointer instead of array
  709. alGetSourcei(source, AL_BUFFERS_QUEUED, &queued);
  710. for (unsigned int i = 0; i < (unsigned int)queued; i++)
  711. alSourceUnqueueBuffers(source, 1, &buffer);
  712. // generate unused buffers list
  713. for (unsigned int i = 0; i < MAX_BUFFERS; i++)
  714. unusedBuffers[i] = streamBuffers[i];
  715. unusedBufferTop = MAX_BUFFERS - 1;
  716. break;
  717. }
  718. case TYPE_QUEUE:
  719. {
  720. ALint queued;
  721. ALuint buffer;
  722. alGetSourcei(source, AL_BUFFERS_QUEUED, &queued);
  723. for (unsigned int i = (unsigned int)queued; i > 0; i--)
  724. alSourceUnqueueBuffers(source, 1, &buffer);
  725. // generate unused buffers list
  726. for (unsigned int i = 0; i < MAX_BUFFERS; i++)
  727. unusedBuffers[i] = streamBuffers[i];
  728. unusedBufferTop = -1;
  729. break;
  730. }
  731. case TYPE_MAX_ENUM:
  732. break;
  733. }
  734. alSourcei(source, AL_BUFFER, AL_NONE);
  735. toLoop = 0;
  736. valid = false;
  737. offsetSamples = offsetSeconds = 0;
  738. }
  739. bool Source::playAtomic(ALuint source)
  740. {
  741. this->source = source;
  742. prepareAtomic();
  743. // Clear errors.
  744. alGetError();
  745. alSourcePlay(source);
  746. // alSourcePlay may fail if the system has reached its limit of simultaneous
  747. // playing sources.
  748. bool success = alGetError() == AL_NO_ERROR;
  749. valid = true; //if it fails it will be set to false again
  750. //but this prevents a horrible, horrible bug
  751. if (type != TYPE_STREAM)
  752. offsetSamples = offsetSeconds = 0;
  753. return success;
  754. }
  755. void Source::stopAtomic()
  756. {
  757. if (!valid)
  758. return;
  759. alSourceStop(source);
  760. teardownAtomic();
  761. }
  762. void Source::pauseAtomic()
  763. {
  764. if (valid)
  765. alSourcePause(source);
  766. }
  767. void Source::resumeAtomic()
  768. {
  769. if (valid && !isPlaying())
  770. alSourcePlay(source);
  771. }
  772. bool Source::playAtomic(const std::vector<love::audio::Source*> &sources, const std::vector<ALuint> &ids, const std::vector<char> &wasPlaying)
  773. {
  774. if (sources.size() == 0)
  775. return true;
  776. std::vector<ALuint> toPlay;
  777. toPlay.reserve(sources.size());
  778. for (size_t i = 0; i < sources.size(); i++)
  779. {
  780. if (wasPlaying[i])
  781. continue;
  782. Source *source = (Source*) sources[i];
  783. source->source = ids[i];
  784. source->prepareAtomic();
  785. toPlay.push_back(ids[i]);
  786. }
  787. alGetError();
  788. alSourcePlayv(toPlay.size(), &toPlay[0]);
  789. bool success = alGetError() == AL_NO_ERROR;
  790. for (auto &_source : sources)
  791. {
  792. Source *source = (Source*) _source;
  793. source->valid = source->valid || success;
  794. if (success && source->type != TYPE_STREAM)
  795. source->offsetSamples = source->offsetSeconds = 0;
  796. }
  797. return success;
  798. }
  799. void Source::stopAtomic(const std::vector<love::audio::Source*> &sources)
  800. {
  801. if (sources.size() == 0)
  802. return;
  803. std::vector<ALuint> sourceIds;
  804. sourceIds.reserve(sources.size());
  805. for (auto &_source : sources)
  806. {
  807. Source *source = (Source*) _source;
  808. if (source->valid)
  809. sourceIds.push_back(source->source);
  810. }
  811. alSourceStopv(sources.size(), &sourceIds[0]);
  812. for (auto &_source : sources)
  813. {
  814. Source *source = (Source*) _source;
  815. if (source->valid)
  816. source->teardownAtomic();
  817. }
  818. }
  819. void Source::pauseAtomic(const std::vector<love::audio::Source*> &sources)
  820. {
  821. if (sources.size() == 0)
  822. return;
  823. std::vector<ALuint> sourceIds;
  824. sourceIds.reserve(sources.size());
  825. for (auto &_source : sources)
  826. {
  827. Source *source = (Source*) _source;
  828. if (source->valid)
  829. sourceIds.push_back(source->source);
  830. }
  831. alSourcePausev(sources.size(), &sourceIds[0]);
  832. }
  833. void Source::reset()
  834. {
  835. alSourcei(source, AL_BUFFER, 0);
  836. alSourcefv(source, AL_POSITION, position);
  837. alSourcefv(source, AL_VELOCITY, velocity);
  838. alSourcefv(source, AL_DIRECTION, direction);
  839. alSourcef(source, AL_PITCH, pitch);
  840. alSourcef(source, AL_GAIN, volume);
  841. alSourcef(source, AL_MIN_GAIN, minVolume);
  842. alSourcef(source, AL_MAX_GAIN, maxVolume);
  843. alSourcef(source, AL_REFERENCE_DISTANCE, referenceDistance);
  844. alSourcef(source, AL_ROLLOFF_FACTOR, rolloffFactor);
  845. alSourcef(source, AL_MAX_DISTANCE, maxDistance);
  846. alSourcei(source, AL_LOOPING, (type == TYPE_STATIC) && isLooping() ? AL_TRUE : AL_FALSE);
  847. alSourcei(source, AL_SOURCE_RELATIVE, relative ? AL_TRUE : AL_FALSE);
  848. alSourcei(source, AL_CONE_INNER_ANGLE, cone.innerAngle);
  849. alSourcei(source, AL_CONE_OUTER_ANGLE, cone.outerAngle);
  850. alSourcef(source, AL_CONE_OUTER_GAIN, cone.outerVolume);
  851. }
  852. void Source::setFloatv(float *dst, const float *src) const
  853. {
  854. dst[0] = src[0];
  855. dst[1] = src[1];
  856. dst[2] = src[2];
  857. }
  858. ALenum Source::getFormat(int channels, int bitDepth) const
  859. {
  860. if (channels == 1 && bitDepth == 8)
  861. return AL_FORMAT_MONO8;
  862. else if (channels == 1 && bitDepth == 16)
  863. return AL_FORMAT_MONO16;
  864. else if (channels == 2 && bitDepth == 8)
  865. return AL_FORMAT_STEREO8;
  866. else if (channels == 2 && bitDepth == 16)
  867. return AL_FORMAT_STEREO16;
  868. #ifdef AL_EXT_MCFORMATS
  869. if (alIsExtensionPresent("AL_EXT_MCFORMATS"))
  870. {
  871. if (channels == 6 && bitDepth == 8)
  872. return AL_FORMAT_51CHN8;
  873. else if (channels == 6 && bitDepth == 16)
  874. return AL_FORMAT_51CHN16;
  875. else if (channels == 8 && bitDepth == 8)
  876. return AL_FORMAT_71CHN8;
  877. else if (channels == 8 && bitDepth == 16)
  878. return AL_FORMAT_71CHN16;
  879. }
  880. #endif
  881. return 0;
  882. }
  883. ALuint Source::unusedBufferPeek()
  884. {
  885. return (unusedBufferTop < 0) ? AL_NONE : unusedBuffers[unusedBufferTop];
  886. }
  887. ALuint Source::unusedBufferPeekNext()
  888. {
  889. return (unusedBufferTop >= (int)MAX_BUFFERS - 1) ? AL_NONE : unusedBuffers[unusedBufferTop + 1];
  890. }
  891. ALuint *Source::unusedBufferPop()
  892. {
  893. return &unusedBuffers[unusedBufferTop--];
  894. }
  895. void Source::unusedBufferPush(ALuint buffer)
  896. {
  897. unusedBuffers[++unusedBufferTop] = buffer;
  898. }
  899. void Source::unusedBufferQueue(ALuint buffer)
  900. {
  901. for (unsigned int i = ++unusedBufferTop; i > 0; i--)
  902. unusedBuffers[i] = unusedBuffers[i - 1];
  903. unusedBuffers[0] = buffer;
  904. }
  905. int Source::streamAtomic(ALuint buffer, love::sound::Decoder *d)
  906. {
  907. // Get more sound data.
  908. int decoded = std::max(d->decode(), 0);
  909. // OpenAL implementations are allowed to ignore 0-size alBufferData calls.
  910. if (decoded > 0)
  911. {
  912. int fmt = getFormat(d->getChannels(), d->getBitDepth());
  913. if (fmt != 0)
  914. alBufferData(buffer, fmt, d->getBuffer(), decoded, d->getSampleRate());
  915. else
  916. decoded = 0;
  917. }
  918. if (decoder->isFinished() && isLooping())
  919. {
  920. int queued, processed;
  921. alGetSourcei(source, AL_BUFFERS_QUEUED, &queued);
  922. alGetSourcei(source, AL_BUFFERS_PROCESSED, &processed);
  923. if (queued > processed)
  924. toLoop = queued-processed;
  925. else
  926. toLoop = MAX_BUFFERS-processed;
  927. d->rewind();
  928. }
  929. if (toLoop > 0)
  930. {
  931. if (--toLoop == 0)
  932. {
  933. offsetSamples = 0;
  934. offsetSeconds = 0;
  935. }
  936. }
  937. return decoded;
  938. }
  939. void Source::setMinVolume(float volume)
  940. {
  941. if (valid)
  942. alSourcef(source, AL_MIN_GAIN, volume);
  943. minVolume = volume;
  944. }
  945. float Source::getMinVolume() const
  946. {
  947. if (valid)
  948. {
  949. ALfloat f;
  950. alGetSourcef(source, AL_MIN_GAIN, &f);
  951. return f;
  952. }
  953. // In case the Source isn't playing.
  954. return this->minVolume;
  955. }
  956. void Source::setMaxVolume(float volume)
  957. {
  958. if (valid)
  959. alSourcef(source, AL_MAX_GAIN, volume);
  960. maxVolume = volume;
  961. }
  962. float Source::getMaxVolume() const
  963. {
  964. if (valid)
  965. {
  966. ALfloat f;
  967. alGetSourcef(source, AL_MAX_GAIN, &f);
  968. return f;
  969. }
  970. // In case the Source isn't playing.
  971. return maxVolume;
  972. }
  973. void Source::setReferenceDistance(float distance)
  974. {
  975. if (channels > 1)
  976. throw SpatialSupportException();
  977. if (valid)
  978. alSourcef(source, AL_REFERENCE_DISTANCE, distance);
  979. referenceDistance = distance;
  980. }
  981. float Source::getReferenceDistance() const
  982. {
  983. if (channels > 1)
  984. throw SpatialSupportException();
  985. if (valid)
  986. {
  987. ALfloat f;
  988. alGetSourcef(source, AL_REFERENCE_DISTANCE, &f);
  989. return f;
  990. }
  991. // In case the Source isn't playing.
  992. return referenceDistance;
  993. }
  994. void Source::setRolloffFactor(float factor)
  995. {
  996. if (channels > 1)
  997. throw SpatialSupportException();
  998. if (valid)
  999. alSourcef(source, AL_ROLLOFF_FACTOR, factor);
  1000. rolloffFactor = factor;
  1001. }
  1002. float Source::getRolloffFactor() const
  1003. {
  1004. if (channels > 1)
  1005. throw SpatialSupportException();
  1006. if (valid)
  1007. {
  1008. ALfloat f;
  1009. alGetSourcef(source, AL_ROLLOFF_FACTOR, &f);
  1010. return f;
  1011. }
  1012. // In case the Source isn't playing.
  1013. return rolloffFactor;
  1014. }
  1015. void Source::setMaxDistance(float distance)
  1016. {
  1017. if (channels > 1)
  1018. throw SpatialSupportException();
  1019. distance = std::min(distance, MAX_ATTENUATION_DISTANCE);
  1020. if (valid)
  1021. alSourcef(source, AL_MAX_DISTANCE, distance);
  1022. maxDistance = distance;
  1023. }
  1024. float Source::getMaxDistance() const
  1025. {
  1026. if (channels > 1)
  1027. throw SpatialSupportException();
  1028. if (valid)
  1029. {
  1030. ALfloat f;
  1031. alGetSourcef(source, AL_MAX_DISTANCE, &f);
  1032. return f;
  1033. }
  1034. // In case the Source isn't playing.
  1035. return maxDistance;
  1036. }
  1037. int Source::getChannels() const
  1038. {
  1039. return channels;
  1040. }
  1041. } // openal
  1042. } // audio
  1043. } // love