SLESSoundWorld.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. /*
  2. Copyright (c) 2013 Daniele Bartolini, Michele Rossi
  3. Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
  4. Permission is hereby granted, free of charge, to any person
  5. obtaining a copy of this software and associated documentation
  6. files (the "Software"), to deal in the Software without
  7. restriction, including without limitation the rights to use,
  8. copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the
  10. Software is furnished to do so, subject to the following
  11. conditions:
  12. The above copyright notice and this permission notice shall be
  13. included in all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  16. OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  19. WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  20. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  21. OTHER DEALINGS IN THE SOFTWARE.
  22. */
  23. #include <SLES/OpenSLES.h>
  24. #include <SLES/OpenSLES_Android.h>
  25. #include "SoundWorld.h"
  26. #include "IdArray.h"
  27. #include "Allocator.h"
  28. #include "Vector3.h"
  29. #include "Matrix4x4.h"
  30. #include "Resource.h"
  31. #include "Device.h"
  32. #include "ResourceManager.h"
  33. #include "SoundResource.h"
  34. #include "ContainerTypes.h"
  35. #include "TempAllocator.h"
  36. #include "Queue.h"
  37. namespace crown
  38. {
  39. //-----------------------------------------------------------------------------
  40. #if defined(CROWN_DEBUG) || defined(CROWN_DEVELOPMENT)
  41. static const char* sles_error_to_string(SLresult result)
  42. {
  43. switch (result)
  44. {
  45. case SL_RESULT_SUCCESS: return "SL_RESULT_SUCCESS";
  46. case SL_RESULT_PARAMETER_INVALID: return "SL_RESULT_PARAMETER_INVALID";
  47. case SL_RESULT_MEMORY_FAILURE: return "SL_RESULT_MEMORY_FAILURE";
  48. case SL_RESULT_FEATURE_UNSUPPORTED: return "SL_RESULT_FEATURE_UNSUPPORTED";
  49. case SL_RESULT_RESOURCE_ERROR: return "SL_RESULT_RESOURCE_ERROR";
  50. case SL_RESULT_IO_ERROR: return "SL_RESULT_IO_ERROR";
  51. case SL_RESULT_PRECONDITIONS_VIOLATED: return "SL_RESULT_PRECONDITIONS_VIOLATED";
  52. case SL_RESULT_CONTENT_CORRUPTED: return "SL_RESULT_CONTENT_CORRUPTED";
  53. case SL_RESULT_CONTENT_UNSUPPORTED: return "SL_RESULT_CONTENT_UNSUPPORTED";
  54. case SL_RESULT_CONTENT_NOT_FOUND: return "SL_RESULT_CONTENT_NOT_FOUND";
  55. case SL_RESULT_PERMISSION_DENIED: return "SL_RESULT_PERMISSION_DENIED";
  56. case SL_RESULT_BUFFER_INSUFFICIENT: return "SL_RESULT_BUFFER_INSUFFICIENT";
  57. default: return "UNKNOWN_SL_ERROR";
  58. }
  59. }
  60. #define SL_CHECK(function)\
  61. do { SLresult result = function;\
  62. CE_ASSERT(result == SL_RESULT_SUCCESS, "OpenSL|ES error: %s", sles_error_to_string(result)); } while (0)
  63. #else
  64. #define SL_CHECK(function) function;
  65. #endif
  66. namespace audio_system
  67. {
  68. static SLObjectItf s_sl_engine;
  69. static SLEngineItf s_sl_engine_itf;
  70. static SLObjectItf s_sl_output_mix;
  71. void init()
  72. {
  73. const SLInterfaceID ids[] = {SL_IID_ENGINE};
  74. const SLboolean reqs[] = {SL_BOOLEAN_TRUE};
  75. const SLEngineOption opts[] = { (SLuint32) SL_ENGINEOPTION_THREADSAFE, (SLuint32) SL_BOOLEAN_TRUE };
  76. // Create OpenSL engine
  77. SL_CHECK(slCreateEngine(&s_sl_engine, 1, opts, 1, ids, reqs));
  78. SL_CHECK((*s_sl_engine)->Realize(s_sl_engine, SL_BOOLEAN_FALSE));
  79. // Obtain OpenSL engine interface
  80. SL_CHECK((*s_sl_engine)->GetInterface(s_sl_engine, SL_IID_ENGINE, &s_sl_engine_itf));
  81. // Create global output mix
  82. const SLInterfaceID ids1[] = {SL_IID_VOLUME};
  83. const SLboolean reqs1[] = {SL_BOOLEAN_FALSE};
  84. SL_CHECK((*s_sl_engine_itf)->CreateOutputMix(s_sl_engine_itf, &s_sl_output_mix, 1, ids1, reqs1));
  85. SL_CHECK((*s_sl_output_mix)->Realize(s_sl_output_mix, SL_BOOLEAN_FALSE));
  86. }
  87. void shutdown()
  88. {
  89. (*s_sl_output_mix)->Destroy(s_sl_output_mix);
  90. (*s_sl_engine)->Destroy(s_sl_engine);
  91. }
  92. } // namespace audio_system
  93. namespace sles_sound_world
  94. {
  95. // Queue of instances to stop at next update()
  96. static Queue<SoundInstanceId>* s_stop_queue = NULL;
  97. void init()
  98. {
  99. s_stop_queue = CE_NEW(default_allocator(), Queue<SoundInstanceId>)(default_allocator());
  100. }
  101. void shutdown()
  102. {
  103. CE_DELETE(default_allocator(), s_stop_queue);
  104. }
  105. static void player_callback(SLPlayItf caller, void* context, SLuint32 event)
  106. {
  107. SoundInstanceId id;
  108. id.decode((uint32_t) context);
  109. queue::push_back(*s_stop_queue, id);
  110. }
  111. static SLmillibel gain_to_attenuation(SLVolumeItf vol_itf, float volume)
  112. {
  113. SLmillibel volume_mb;
  114. if (volume <= 0.02f) return SL_MILLIBEL_MIN;
  115. else if (volume >= 1.0f)
  116. {
  117. (*vol_itf)->GetMaxVolumeLevel(vol_itf, &volume_mb);
  118. return volume_mb;
  119. }
  120. volume_mb = M_LN2 / log(1.0f / (1.0f - volume)) * -1000.0f;
  121. if (volume_mb > 0) volume_mb = SL_MILLIBEL_MIN;
  122. return volume_mb;
  123. }
  124. }
  125. //-----------------------------------------------------------------------------
  126. struct SoundInstance
  127. {
  128. void create(SLEngineItf engine, SLObjectItf output_mix, SoundInstanceId id, SoundResource* sr)
  129. {
  130. m_resource = sr;
  131. m_finished = false;
  132. m_id = id;
  133. // Configures buffer queue
  134. SLDataLocator_AndroidSimpleBufferQueue buffer_queue = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2};
  135. // Configures audio format
  136. SLDataFormat_PCM format_pcm;
  137. format_pcm.formatType = SL_DATAFORMAT_PCM;
  138. // Sets channels
  139. switch (sr->channels())
  140. {
  141. case 1:
  142. {
  143. format_pcm.numChannels = 1;
  144. format_pcm.channelMask = SL_SPEAKER_FRONT_CENTER;
  145. break;
  146. }
  147. case 2:
  148. {
  149. format_pcm.numChannels = 2;
  150. format_pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
  151. break;
  152. }
  153. default:
  154. {
  155. CE_FATAL("Oops, wrong number of channels");
  156. break;
  157. }
  158. }
  159. // Sets sample rate
  160. switch (sr->sample_rate())
  161. {
  162. case 8000: format_pcm.samplesPerSec = SL_SAMPLINGRATE_8; break;
  163. case 11025: format_pcm.samplesPerSec = SL_SAMPLINGRATE_11_025; break;
  164. case 16000: format_pcm.samplesPerSec = SL_SAMPLINGRATE_16; break;
  165. case 22050: format_pcm.samplesPerSec = SL_SAMPLINGRATE_22_05; break;
  166. case 24000: format_pcm.samplesPerSec = SL_SAMPLINGRATE_24; break;
  167. case 32000: format_pcm.samplesPerSec = SL_SAMPLINGRATE_32; break;
  168. case 44100: format_pcm.samplesPerSec = SL_SAMPLINGRATE_44_1; break;
  169. case 48000: format_pcm.samplesPerSec = SL_SAMPLINGRATE_48; break;
  170. case 64000: format_pcm.samplesPerSec = SL_SAMPLINGRATE_64; break;
  171. case 88200: format_pcm.samplesPerSec = SL_SAMPLINGRATE_88_2; break;
  172. case 96000: format_pcm.samplesPerSec = SL_SAMPLINGRATE_96; break;
  173. case 192000: format_pcm.samplesPerSec = SL_SAMPLINGRATE_192; break;
  174. default: CE_FATAL("Oops, sample rate not supported"); break;
  175. }
  176. format_pcm.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;
  177. format_pcm.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16;
  178. format_pcm.endianness = SL_BYTEORDER_LITTLEENDIAN;
  179. // Configures audio source
  180. SLDataSource audio_source;
  181. audio_source.pLocator = &buffer_queue;
  182. audio_source.pFormat = &format_pcm;
  183. // Configures audio output mix
  184. SLDataLocator_OutputMix out_mix;
  185. out_mix.locatorType = SL_DATALOCATOR_OUTPUTMIX;
  186. out_mix.outputMix = output_mix;
  187. // Configures audio sink
  188. SLDataSink audio_sink;
  189. audio_sink.pLocator = &out_mix;
  190. audio_sink.pFormat = NULL;
  191. // Creates sound player
  192. const SLInterfaceID ids[] = {SL_IID_PLAY, SL_IID_BUFFERQUEUE, SL_IID_VOLUME};
  193. const SLboolean reqs[] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE};
  194. SL_CHECK((*engine)->CreateAudioPlayer(engine, &m_player, &audio_source, &audio_sink, 3, ids, reqs));
  195. SL_CHECK((*m_player)->Realize(m_player, SL_BOOLEAN_FALSE));
  196. SL_CHECK((*m_player)->GetInterface(m_player, SL_IID_BUFFERQUEUE, &m_player_bufferqueue));
  197. //(*m_player_bufferqueue)->RegisterCallback(m_player_bufferqueue, SoundInstance::buffer_callback, this);
  198. (*play_itf())->SetCallbackEventsMask(play_itf(), SL_PLAYEVENT_HEADATEND);
  199. (*play_itf())->RegisterCallback(play_itf(), sles_sound_world::player_callback, (void*) id.encode());
  200. // Manage simple sound or stream
  201. // m_streaming = sr->sound_type() == SoundType::OGG;
  202. // if (m_streaming)
  203. // {
  204. // m_decoder.init((char*)sr->data(), sr->size());
  205. // m_decoder.stream();
  206. // (*m_player_bufferqueue)->Enqueue(m_player_bufferqueue, m_decoder.data(), m_decoder.size());
  207. // }
  208. // else
  209. {
  210. (*m_player_bufferqueue)->Enqueue(m_player_bufferqueue, sr->data(), sr->size());
  211. }
  212. }
  213. void destroy()
  214. {
  215. // if (m_streaming)
  216. // {
  217. // m_decoder.shutdown();
  218. // }
  219. stop();
  220. (*m_player_bufferqueue)->Clear(m_player_bufferqueue);
  221. (*m_player)->AbortAsyncOperation(m_player);
  222. (*m_player)->Destroy(m_player);
  223. }
  224. void reload(SoundResource* new_sr)
  225. {
  226. }
  227. void play(bool loop, float volume)
  228. {
  229. set_volume(volume);
  230. SL_CHECK((*play_itf())->SetPlayState(play_itf(), SL_PLAYSTATE_PLAYING));
  231. }
  232. void pause()
  233. {
  234. SL_CHECK((*play_itf())->SetPlayState(play_itf(), SL_PLAYSTATE_PAUSED));
  235. }
  236. void resume()
  237. {
  238. SL_CHECK((*play_itf())->SetPlayState(play_itf(), SL_PLAYSTATE_PLAYING));
  239. }
  240. void stop()
  241. {
  242. SL_CHECK((*play_itf())->SetPlayState(play_itf(), SL_PLAYSTATE_STOPPED));
  243. }
  244. bool is_playing()
  245. {
  246. SLuint32 state;
  247. SL_CHECK((*play_itf())->GetPlayState(play_itf(), &state));
  248. return state == SL_PLAYSTATE_PLAYING;
  249. }
  250. bool finished()
  251. {
  252. return m_finished;
  253. }
  254. void set_volume(float volume)
  255. {
  256. SLVolumeItf vol;
  257. SL_CHECK((*m_player)->GetInterface(m_player, SL_IID_VOLUME, &vol));
  258. SL_CHECK((*vol)->SetVolumeLevel(vol, sles_sound_world::gain_to_attenuation(vol, volume)));
  259. }
  260. void set_range(float range)
  261. {
  262. }
  263. void set_position(const Vector3& pos)
  264. {
  265. }
  266. static void buffer_callback(SLAndroidSimpleBufferQueueItf caller, void* context)
  267. {
  268. SoundInstance* s = (SoundInstance*) context;
  269. // if (s->is_playing())
  270. // {
  271. // s->m_processed_buffers++;
  272. // if (s->m_decoder.stream())
  273. // {
  274. // (*s->m_player_bufferqueue)->Enqueue(s->m_player_bufferqueue, s->m_decoder.data(), s->m_decoder.size());
  275. // }
  276. // else if (s->m_looping)
  277. // {
  278. // s->m_decoder.rewind();
  279. // s->m_decoder.stream();
  280. // (*s->m_player_bufferqueue)->Enqueue(s->m_player_bufferqueue, s->m_decoder.data(), s->m_decoder.size());
  281. // }
  282. // else
  283. // {
  284. // s->pause();
  285. // }
  286. // }
  287. }
  288. SoundResource* resource()
  289. {
  290. return m_resource;
  291. }
  292. SLPlayItf play_itf()
  293. {
  294. SLPlayItf play;
  295. SL_CHECK((*m_player)->GetInterface(m_player, SL_IID_PLAY, &play));
  296. return play;
  297. }
  298. public:
  299. SoundInstanceId m_id;
  300. SoundResource* m_resource;
  301. SLObjectItf m_player;
  302. SLAndroidSimpleBufferQueueItf m_player_bufferqueue;
  303. uint32_t m_processed_buffers;
  304. bool m_finished;
  305. // OggDecoder m_decoder;
  306. };
  307. class SLESSoundWorld : public SoundWorld
  308. {
  309. public:
  310. SLESSoundWorld()
  311. {
  312. sles_sound_world::init();
  313. }
  314. virtual ~SLESSoundWorld()
  315. {
  316. sles_sound_world::shutdown();
  317. }
  318. virtual SoundInstanceId play(const char* name, bool loop, float volume, const Vector3& /*pos*/)
  319. {
  320. return play((SoundResource*) device()->resource_manager()->get(SOUND_EXTENSION, name), loop, volume);
  321. }
  322. SoundInstanceId play(SoundResource* sr, bool loop, float volume)
  323. {
  324. SoundInstance dummy;
  325. SoundInstanceId id = id_array::create(m_playing_sounds, dummy);
  326. SoundInstance& instance = id_array::get(m_playing_sounds, id);
  327. instance.create(audio_system::s_sl_engine_itf, audio_system::s_sl_output_mix, id, sr);
  328. instance.play(loop, volume);
  329. return id;
  330. }
  331. virtual void stop(SoundInstanceId id)
  332. {
  333. id_array::get(m_playing_sounds, id).destroy();
  334. id_array::destroy(m_playing_sounds, id);
  335. }
  336. virtual bool is_playing(SoundInstanceId id)
  337. {
  338. return id_array::has(m_playing_sounds, id) && id_array::get(m_playing_sounds, id).is_playing();
  339. }
  340. virtual void stop_all()
  341. {
  342. for (uint32_t i = 0; i < id_array::size(m_playing_sounds); i++)
  343. {
  344. m_playing_sounds[i].stop();
  345. }
  346. }
  347. virtual void pause_all()
  348. {
  349. for (uint32_t i = 0; i < id_array::size(m_playing_sounds); i++)
  350. {
  351. m_playing_sounds[i].pause();
  352. }
  353. }
  354. virtual void resume_all()
  355. {
  356. for (uint32_t i = 0; i < id_array::size(m_playing_sounds); i++)
  357. {
  358. m_playing_sounds[i].resume();
  359. }
  360. }
  361. virtual void set_sound_positions(uint32_t count, const SoundInstanceId* ids, const Vector3* positions)
  362. {
  363. for (uint32_t i = 0; i < id_array::size(m_playing_sounds); i++)
  364. {
  365. m_playing_sounds[i].set_position(positions[i]);
  366. }
  367. }
  368. virtual void set_sound_ranges(uint32_t count, const SoundInstanceId* ids, const float* ranges)
  369. {
  370. for (uint32_t i = 0; i < id_array::size(m_playing_sounds); i++)
  371. {
  372. m_playing_sounds[i].set_range(ranges[i]);
  373. }
  374. }
  375. virtual void set_sound_volumes(uint32_t count, const SoundInstanceId* ids, const float* volumes)
  376. {
  377. for (uint32_t i = 0; i < id_array::size(m_playing_sounds); i++)
  378. {
  379. m_playing_sounds[i].set_volume(volumes[i]);
  380. }
  381. }
  382. virtual void reload_sounds(SoundResource* old_sr, SoundResource* new_sr)
  383. {
  384. for (uint32_t i = 0; i < id_array::size(m_playing_sounds); i++)
  385. {
  386. if (m_playing_sounds[i].resource() == old_sr)
  387. {
  388. m_playing_sounds[i].reload(new_sr);
  389. }
  390. }
  391. }
  392. virtual void set_listener_pose(const Matrix4x4& pose)
  393. {
  394. m_listener_pose = pose;
  395. }
  396. virtual void update()
  397. {
  398. const uint32_t num_to_stop = queue::size(*sles_sound_world::s_stop_queue);
  399. for (uint32_t i = 0; i < num_to_stop; i++)
  400. {
  401. const SoundInstanceId id = queue::front(*sles_sound_world::s_stop_queue);
  402. queue::pop_front(*sles_sound_world::s_stop_queue);
  403. if (!id_array::has(m_playing_sounds, id)) continue;
  404. stop(id);
  405. }
  406. }
  407. private:
  408. IdArray<CE_MAX_SOUND_INSTANCES, SoundInstance> m_playing_sounds;
  409. Matrix4x4 m_listener_pose;
  410. };
  411. SoundWorld* SoundWorld::create(Allocator& a)
  412. {
  413. return CE_NEW(a, SLESSoundWorld)();
  414. }
  415. void SoundWorld::destroy(Allocator& a, SoundWorld* sw)
  416. {
  417. CE_DELETE(a, sw);
  418. }
  419. } // namespace crown