SDL_openslES.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
  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. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. #ifdef SDL_AUDIO_DRIVER_OPENSLES
  20. // For more discussion of low latency audio on Android, see this:
  21. // https://googlesamples.github.io/android-audio-high-performance/guides/opensl_es.html
  22. #include "../SDL_sysaudio.h"
  23. #include "../SDL_audio_c.h"
  24. #include "SDL_openslES.h"
  25. #include "../../core/android/SDL_android.h"
  26. #include <SLES/OpenSLES.h>
  27. #include <SLES/OpenSLES_Android.h>
  28. #include <android/log.h>
  29. #define NUM_BUFFERS 2 // -- Don't lower this!
  30. struct SDL_PrivateAudioData
  31. {
  32. Uint8 *mixbuff;
  33. int next_buffer;
  34. Uint8 *pmixbuff[NUM_BUFFERS];
  35. SDL_Semaphore *playsem;
  36. };
  37. #if 0
  38. #define LOG_TAG "SDL_openslES"
  39. #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
  40. #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
  41. //#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE,LOG_TAG,__VA_ARGS__)
  42. #define LOGV(...)
  43. #else
  44. #define LOGE(...)
  45. #define LOGI(...)
  46. #define LOGV(...)
  47. #endif
  48. /*
  49. #define SL_SPEAKER_FRONT_LEFT ((SLuint32) 0x00000001)
  50. #define SL_SPEAKER_FRONT_RIGHT ((SLuint32) 0x00000002)
  51. #define SL_SPEAKER_FRONT_CENTER ((SLuint32) 0x00000004)
  52. #define SL_SPEAKER_LOW_FREQUENCY ((SLuint32) 0x00000008)
  53. #define SL_SPEAKER_BACK_LEFT ((SLuint32) 0x00000010)
  54. #define SL_SPEAKER_BACK_RIGHT ((SLuint32) 0x00000020)
  55. #define SL_SPEAKER_FRONT_LEFT_OF_CENTER ((SLuint32) 0x00000040)
  56. #define SL_SPEAKER_FRONT_RIGHT_OF_CENTER ((SLuint32) 0x00000080)
  57. #define SL_SPEAKER_BACK_CENTER ((SLuint32) 0x00000100)
  58. #define SL_SPEAKER_SIDE_LEFT ((SLuint32) 0x00000200)
  59. #define SL_SPEAKER_SIDE_RIGHT ((SLuint32) 0x00000400)
  60. #define SL_SPEAKER_TOP_CENTER ((SLuint32) 0x00000800)
  61. #define SL_SPEAKER_TOP_FRONT_LEFT ((SLuint32) 0x00001000)
  62. #define SL_SPEAKER_TOP_FRONT_CENTER ((SLuint32) 0x00002000)
  63. #define SL_SPEAKER_TOP_FRONT_RIGHT ((SLuint32) 0x00004000)
  64. #define SL_SPEAKER_TOP_BACK_LEFT ((SLuint32) 0x00008000)
  65. #define SL_SPEAKER_TOP_BACK_CENTER ((SLuint32) 0x00010000)
  66. #define SL_SPEAKER_TOP_BACK_RIGHT ((SLuint32) 0x00020000)
  67. */
  68. #define SL_ANDROID_SPEAKER_STEREO (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT)
  69. #define SL_ANDROID_SPEAKER_QUAD (SL_ANDROID_SPEAKER_STEREO | SL_SPEAKER_BACK_LEFT | SL_SPEAKER_BACK_RIGHT)
  70. #define SL_ANDROID_SPEAKER_5DOT1 (SL_ANDROID_SPEAKER_QUAD | SL_SPEAKER_FRONT_CENTER | SL_SPEAKER_LOW_FREQUENCY)
  71. #define SL_ANDROID_SPEAKER_7DOT1 (SL_ANDROID_SPEAKER_5DOT1 | SL_SPEAKER_SIDE_LEFT | SL_SPEAKER_SIDE_RIGHT)
  72. // engine interfaces
  73. static SLObjectItf engineObject = NULL;
  74. static SLEngineItf engineEngine = NULL;
  75. // output mix interfaces
  76. static SLObjectItf outputMixObject = NULL;
  77. // buffer queue player interfaces
  78. static SLObjectItf bqPlayerObject = NULL;
  79. static SLPlayItf bqPlayerPlay = NULL;
  80. static SLAndroidSimpleBufferQueueItf bqPlayerBufferQueue = NULL;
  81. #if 0
  82. static SLVolumeItf bqPlayerVolume;
  83. #endif
  84. // recorder interfaces
  85. static SLObjectItf recorderObject = NULL;
  86. static SLRecordItf recorderRecord = NULL;
  87. static SLAndroidSimpleBufferQueueItf recorderBufferQueue = NULL;
  88. #if 0
  89. static const char *sldevaudiorecorderstr = "SLES Audio Recorder";
  90. static const char *sldevaudioplayerstr = "SLES Audio Player";
  91. #define SLES_DEV_AUDIO_RECORDER sldevaudiorecorderstr
  92. #define SLES_DEV_AUDIO_PLAYER sldevaudioplayerstr
  93. static void OPENSLES_DetectDevices( int iscapture )
  94. {
  95. LOGI( "openSLES_DetectDevices()" );
  96. if ( iscapture )
  97. addfn( SLES_DEV_AUDIO_RECORDER );
  98. else
  99. addfn( SLES_DEV_AUDIO_PLAYER );
  100. }
  101. #endif
  102. static void OPENSLES_DestroyEngine(void)
  103. {
  104. LOGI("OPENSLES_DestroyEngine()");
  105. // destroy output mix object, and invalidate all associated interfaces
  106. if (outputMixObject != NULL) {
  107. (*outputMixObject)->Destroy(outputMixObject);
  108. outputMixObject = NULL;
  109. }
  110. // destroy engine object, and invalidate all associated interfaces
  111. if (engineObject != NULL) {
  112. (*engineObject)->Destroy(engineObject);
  113. engineObject = NULL;
  114. engineEngine = NULL;
  115. }
  116. }
  117. static int OPENSLES_CreateEngine(void)
  118. {
  119. const SLInterfaceID ids[1] = { SL_IID_VOLUME };
  120. const SLboolean req[1] = { SL_BOOLEAN_FALSE };
  121. SLresult result;
  122. LOGI("openSLES_CreateEngine()");
  123. // create engine
  124. result = slCreateEngine(&engineObject, 0, NULL, 0, NULL, NULL);
  125. if (SL_RESULT_SUCCESS != result) {
  126. LOGE("slCreateEngine failed: %d", result);
  127. goto error;
  128. }
  129. LOGI("slCreateEngine OK");
  130. // realize the engine
  131. result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE);
  132. if (SL_RESULT_SUCCESS != result) {
  133. LOGE("RealizeEngine failed: %d", result);
  134. goto error;
  135. }
  136. LOGI("RealizeEngine OK");
  137. // get the engine interface, which is needed in order to create other objects
  138. result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine);
  139. if (SL_RESULT_SUCCESS != result) {
  140. LOGE("EngineGetInterface failed: %d", result);
  141. goto error;
  142. }
  143. LOGI("EngineGetInterface OK");
  144. // create output mix
  145. result = (*engineEngine)->CreateOutputMix(engineEngine, &outputMixObject, 1, ids, req);
  146. if (SL_RESULT_SUCCESS != result) {
  147. LOGE("CreateOutputMix failed: %d", result);
  148. goto error;
  149. }
  150. LOGI("CreateOutputMix OK");
  151. // realize the output mix
  152. result = (*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE);
  153. if (SL_RESULT_SUCCESS != result) {
  154. LOGE("RealizeOutputMix failed: %d", result);
  155. goto error;
  156. }
  157. return 1;
  158. error:
  159. OPENSLES_DestroyEngine();
  160. return 0;
  161. }
  162. // this callback handler is called every time a buffer finishes recording
  163. static void bqRecorderCallback(SLAndroidSimpleBufferQueueItf bq, void *context)
  164. {
  165. struct SDL_PrivateAudioData *audiodata = (struct SDL_PrivateAudioData *)context;
  166. LOGV("SLES: Recording Callback");
  167. SDL_PostSemaphore(audiodata->playsem);
  168. }
  169. static void OPENSLES_DestroyPCMRecorder(SDL_AudioDevice *device)
  170. {
  171. struct SDL_PrivateAudioData *audiodata = device->hidden;
  172. SLresult result;
  173. // stop recording
  174. if (recorderRecord != NULL) {
  175. result = (*recorderRecord)->SetRecordState(recorderRecord, SL_RECORDSTATE_STOPPED);
  176. if (SL_RESULT_SUCCESS != result) {
  177. LOGE("SetRecordState stopped: %d", result);
  178. }
  179. }
  180. // destroy audio recorder object, and invalidate all associated interfaces
  181. if (recorderObject != NULL) {
  182. (*recorderObject)->Destroy(recorderObject);
  183. recorderObject = NULL;
  184. recorderRecord = NULL;
  185. recorderBufferQueue = NULL;
  186. }
  187. if (audiodata->playsem) {
  188. SDL_DestroySemaphore(audiodata->playsem);
  189. audiodata->playsem = NULL;
  190. }
  191. if (audiodata->mixbuff) {
  192. SDL_free(audiodata->mixbuff);
  193. }
  194. }
  195. static int OPENSLES_CreatePCMRecorder(SDL_AudioDevice *device)
  196. {
  197. struct SDL_PrivateAudioData *audiodata = device->hidden;
  198. SLDataFormat_PCM format_pcm;
  199. SLDataLocator_AndroidSimpleBufferQueue loc_bufq;
  200. SLDataSink audioSnk;
  201. SLDataLocator_IODevice loc_dev;
  202. SLDataSource audioSrc;
  203. const SLInterfaceID ids[1] = { SL_IID_ANDROIDSIMPLEBUFFERQUEUE };
  204. const SLboolean req[1] = { SL_BOOLEAN_TRUE };
  205. SLresult result;
  206. int i;
  207. if (!Android_JNI_RequestPermission("android.permission.RECORD_AUDIO")) {
  208. LOGE("This app doesn't have RECORD_AUDIO permission");
  209. return SDL_SetError("This app doesn't have RECORD_AUDIO permission");
  210. }
  211. // Just go with signed 16-bit audio as it's the most compatible
  212. device->spec.format = SDL_AUDIO_S16;
  213. device->spec.channels = 1;
  214. //device->spec.freq = SL_SAMPLINGRATE_16 / 1000;*/
  215. // Update the fragment size as size in bytes
  216. SDL_UpdatedAudioDeviceFormat(device);
  217. LOGI("Try to open %u hz %u bit chan %u %s samples %u",
  218. device->spec.freq, SDL_AUDIO_BITSIZE(device->spec.format),
  219. device->spec.channels, (device->spec.format & 0x1000) ? "BE" : "LE", device->sample_frames);
  220. // configure audio source
  221. loc_dev.locatorType = SL_DATALOCATOR_IODEVICE;
  222. loc_dev.deviceType = SL_IODEVICE_AUDIOINPUT;
  223. loc_dev.deviceID = SL_DEFAULTDEVICEID_AUDIOINPUT;
  224. loc_dev.device = NULL;
  225. audioSrc.pLocator = &loc_dev;
  226. audioSrc.pFormat = NULL;
  227. // configure audio sink
  228. loc_bufq.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE;
  229. loc_bufq.numBuffers = NUM_BUFFERS;
  230. format_pcm.formatType = SL_DATAFORMAT_PCM;
  231. format_pcm.numChannels = device->spec.channels;
  232. format_pcm.samplesPerSec = device->spec.freq * 1000; // / kilo Hz to milli Hz
  233. format_pcm.bitsPerSample = SDL_AUDIO_BITSIZE(device->spec.format);
  234. format_pcm.containerSize = SDL_AUDIO_BITSIZE(device->spec.format);
  235. format_pcm.endianness = SL_BYTEORDER_LITTLEENDIAN;
  236. format_pcm.channelMask = SL_SPEAKER_FRONT_CENTER;
  237. audioSnk.pLocator = &loc_bufq;
  238. audioSnk.pFormat = &format_pcm;
  239. // create audio recorder
  240. // (requires the RECORD_AUDIO permission)
  241. result = (*engineEngine)->CreateAudioRecorder(engineEngine, &recorderObject, &audioSrc, &audioSnk, 1, ids, req);
  242. if (SL_RESULT_SUCCESS != result) {
  243. LOGE("CreateAudioRecorder failed: %d", result);
  244. goto failed;
  245. }
  246. // realize the recorder
  247. result = (*recorderObject)->Realize(recorderObject, SL_BOOLEAN_FALSE);
  248. if (SL_RESULT_SUCCESS != result) {
  249. LOGE("RealizeAudioPlayer failed: %d", result);
  250. goto failed;
  251. }
  252. // get the record interface
  253. result = (*recorderObject)->GetInterface(recorderObject, SL_IID_RECORD, &recorderRecord);
  254. if (SL_RESULT_SUCCESS != result) {
  255. LOGE("SL_IID_RECORD interface get failed: %d", result);
  256. goto failed;
  257. }
  258. // get the buffer queue interface
  259. result = (*recorderObject)->GetInterface(recorderObject, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &recorderBufferQueue);
  260. if (SL_RESULT_SUCCESS != result) {
  261. LOGE("SL_IID_BUFFERQUEUE interface get failed: %d", result);
  262. goto failed;
  263. }
  264. // register callback on the buffer queue
  265. // context is '(SDL_PrivateAudioData *)device->hidden'
  266. result = (*recorderBufferQueue)->RegisterCallback(recorderBufferQueue, bqRecorderCallback, device->hidden);
  267. if (SL_RESULT_SUCCESS != result) {
  268. LOGE("RegisterCallback failed: %d", result);
  269. goto failed;
  270. }
  271. // Create the audio buffer semaphore
  272. audiodata->playsem = SDL_CreateSemaphore(0);
  273. if (!audiodata->playsem) {
  274. LOGE("cannot create Semaphore!");
  275. goto failed;
  276. }
  277. // Create the sound buffers
  278. audiodata->mixbuff = (Uint8 *)SDL_malloc(NUM_BUFFERS * device->buffer_size);
  279. if (audiodata->mixbuff == NULL) {
  280. LOGE("mixbuffer allocate - out of memory");
  281. goto failed;
  282. }
  283. for (i = 0; i < NUM_BUFFERS; i++) {
  284. audiodata->pmixbuff[i] = audiodata->mixbuff + i * device->buffer_size;
  285. }
  286. // in case already recording, stop recording and clear buffer queue
  287. result = (*recorderRecord)->SetRecordState(recorderRecord, SL_RECORDSTATE_STOPPED);
  288. if (SL_RESULT_SUCCESS != result) {
  289. LOGE("Record set state failed: %d", result);
  290. goto failed;
  291. }
  292. // enqueue empty buffers to be filled by the recorder
  293. for (i = 0; i < NUM_BUFFERS; i++) {
  294. result = (*recorderBufferQueue)->Enqueue(recorderBufferQueue, audiodata->pmixbuff[i], device->buffer_size);
  295. if (SL_RESULT_SUCCESS != result) {
  296. LOGE("Record enqueue buffers failed: %d", result);
  297. goto failed;
  298. }
  299. }
  300. // start recording
  301. result = (*recorderRecord)->SetRecordState(recorderRecord, SL_RECORDSTATE_RECORDING);
  302. if (SL_RESULT_SUCCESS != result) {
  303. LOGE("Record set state failed: %d", result);
  304. goto failed;
  305. }
  306. return 0;
  307. failed:
  308. return SDL_SetError("Open device failed!");
  309. }
  310. // this callback handler is called every time a buffer finishes playing
  311. static void bqPlayerCallback(SLAndroidSimpleBufferQueueItf bq, void *context)
  312. {
  313. struct SDL_PrivateAudioData *audiodata = (struct SDL_PrivateAudioData *)context;
  314. LOGV("SLES: Playback Callback");
  315. SDL_PostSemaphore(audiodata->playsem);
  316. }
  317. static void OPENSLES_DestroyPCMPlayer(SDL_AudioDevice *device)
  318. {
  319. struct SDL_PrivateAudioData *audiodata = device->hidden;
  320. // set the player's state to 'stopped'
  321. if (bqPlayerPlay != NULL) {
  322. const SLresult result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_STOPPED);
  323. if (SL_RESULT_SUCCESS != result) {
  324. LOGE("SetPlayState stopped failed: %d", result);
  325. }
  326. }
  327. // destroy buffer queue audio player object, and invalidate all associated interfaces
  328. if (bqPlayerObject != NULL) {
  329. (*bqPlayerObject)->Destroy(bqPlayerObject);
  330. bqPlayerObject = NULL;
  331. bqPlayerPlay = NULL;
  332. bqPlayerBufferQueue = NULL;
  333. }
  334. if (audiodata->playsem) {
  335. SDL_DestroySemaphore(audiodata->playsem);
  336. audiodata->playsem = NULL;
  337. }
  338. if (audiodata->mixbuff) {
  339. SDL_free(audiodata->mixbuff);
  340. }
  341. }
  342. static int OPENSLES_CreatePCMPlayer(SDL_AudioDevice *device)
  343. {
  344. /* If we want to add floating point audio support (requires API level 21)
  345. it can be done as described here:
  346. https://developer.android.com/ndk/guides/audio/opensl/android-extensions.html#floating-point
  347. */
  348. if (SDL_GetAndroidSDKVersion() >= 21) {
  349. const SDL_AudioFormat *closefmts = SDL_ClosestAudioFormats(device->spec.format);
  350. SDL_AudioFormat test_format;
  351. while ((test_format = *(closefmts++)) != 0) {
  352. if (SDL_AUDIO_ISSIGNED(test_format)) {
  353. break;
  354. }
  355. }
  356. if (!test_format) {
  357. // Didn't find a compatible format :
  358. LOGI("No compatible audio format, using signed 16-bit audio");
  359. test_format = SDL_AUDIO_S16;
  360. }
  361. device->spec.format = test_format;
  362. } else {
  363. // Just go with signed 16-bit audio as it's the most compatible
  364. device->spec.format = SDL_AUDIO_S16;
  365. }
  366. // Update the fragment size as size in bytes
  367. SDL_UpdatedAudioDeviceFormat(device);
  368. LOGI("Try to open %u hz %s %u bit chan %u %s samples %u",
  369. device->spec.freq, SDL_AUDIO_ISFLOAT(device->spec.format) ? "float" : "pcm", SDL_AUDIO_BITSIZE(device->spec.format),
  370. device->spec.channels, (device->spec.format & 0x1000) ? "BE" : "LE", device->sample_frames);
  371. // configure audio source
  372. SLDataLocator_AndroidSimpleBufferQueue loc_bufq;
  373. loc_bufq.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE;
  374. loc_bufq.numBuffers = NUM_BUFFERS;
  375. SLDataFormat_PCM format_pcm;
  376. format_pcm.formatType = SL_DATAFORMAT_PCM;
  377. format_pcm.numChannels = device->spec.channels;
  378. format_pcm.samplesPerSec = device->spec.freq * 1000; // / kilo Hz to milli Hz
  379. format_pcm.bitsPerSample = SDL_AUDIO_BITSIZE(device->spec.format);
  380. format_pcm.containerSize = SDL_AUDIO_BITSIZE(device->spec.format);
  381. if (SDL_AUDIO_ISBIGENDIAN(device->spec.format)) {
  382. format_pcm.endianness = SL_BYTEORDER_BIGENDIAN;
  383. } else {
  384. format_pcm.endianness = SL_BYTEORDER_LITTLEENDIAN;
  385. }
  386. switch (device->spec.channels) {
  387. case 1:
  388. format_pcm.channelMask = SL_SPEAKER_FRONT_LEFT;
  389. break;
  390. case 2:
  391. format_pcm.channelMask = SL_ANDROID_SPEAKER_STEREO;
  392. break;
  393. case 3:
  394. format_pcm.channelMask = SL_ANDROID_SPEAKER_STEREO | SL_SPEAKER_FRONT_CENTER;
  395. break;
  396. case 4:
  397. format_pcm.channelMask = SL_ANDROID_SPEAKER_QUAD;
  398. break;
  399. case 5:
  400. format_pcm.channelMask = SL_ANDROID_SPEAKER_QUAD | SL_SPEAKER_FRONT_CENTER;
  401. break;
  402. case 6:
  403. format_pcm.channelMask = SL_ANDROID_SPEAKER_5DOT1;
  404. break;
  405. case 7:
  406. format_pcm.channelMask = SL_ANDROID_SPEAKER_5DOT1 | SL_SPEAKER_BACK_CENTER;
  407. break;
  408. case 8:
  409. format_pcm.channelMask = SL_ANDROID_SPEAKER_7DOT1;
  410. break;
  411. default:
  412. // Unknown number of channels, fall back to stereo
  413. device->spec.channels = 2;
  414. format_pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
  415. break;
  416. }
  417. SLDataSink audioSnk;
  418. SLDataSource audioSrc;
  419. audioSrc.pFormat = (void *)&format_pcm;
  420. SLAndroidDataFormat_PCM_EX format_pcm_ex;
  421. if (SDL_AUDIO_ISFLOAT(device->spec.format)) {
  422. // Copy all setup into PCM EX structure
  423. format_pcm_ex.formatType = SL_ANDROID_DATAFORMAT_PCM_EX;
  424. format_pcm_ex.endianness = format_pcm.endianness;
  425. format_pcm_ex.channelMask = format_pcm.channelMask;
  426. format_pcm_ex.numChannels = format_pcm.numChannels;
  427. format_pcm_ex.sampleRate = format_pcm.samplesPerSec;
  428. format_pcm_ex.bitsPerSample = format_pcm.bitsPerSample;
  429. format_pcm_ex.containerSize = format_pcm.containerSize;
  430. format_pcm_ex.representation = SL_ANDROID_PCM_REPRESENTATION_FLOAT;
  431. audioSrc.pFormat = (void *)&format_pcm_ex;
  432. }
  433. audioSrc.pLocator = &loc_bufq;
  434. // configure audio sink
  435. SLDataLocator_OutputMix loc_outmix;
  436. loc_outmix.locatorType = SL_DATALOCATOR_OUTPUTMIX;
  437. loc_outmix.outputMix = outputMixObject;
  438. audioSnk.pLocator = &loc_outmix;
  439. audioSnk.pFormat = NULL;
  440. // create audio player
  441. const SLInterfaceID ids[2] = { SL_IID_ANDROIDSIMPLEBUFFERQUEUE, SL_IID_VOLUME };
  442. const SLboolean req[2] = { SL_BOOLEAN_TRUE, SL_BOOLEAN_FALSE };
  443. SLresult result;
  444. result = (*engineEngine)->CreateAudioPlayer(engineEngine, &bqPlayerObject, &audioSrc, &audioSnk, 2, ids, req);
  445. if (SL_RESULT_SUCCESS != result) {
  446. LOGE("CreateAudioPlayer failed: %d", result);
  447. goto failed;
  448. }
  449. // realize the player
  450. result = (*bqPlayerObject)->Realize(bqPlayerObject, SL_BOOLEAN_FALSE);
  451. if (SL_RESULT_SUCCESS != result) {
  452. LOGE("RealizeAudioPlayer failed: %d", result);
  453. goto failed;
  454. }
  455. // get the play interface
  456. result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_PLAY, &bqPlayerPlay);
  457. if (SL_RESULT_SUCCESS != result) {
  458. LOGE("SL_IID_PLAY interface get failed: %d", result);
  459. goto failed;
  460. }
  461. // get the buffer queue interface
  462. result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &bqPlayerBufferQueue);
  463. if (SL_RESULT_SUCCESS != result) {
  464. LOGE("SL_IID_BUFFERQUEUE interface get failed: %d", result);
  465. goto failed;
  466. }
  467. // register callback on the buffer queue
  468. // context is '(SDL_PrivateAudioData *)device->hidden'
  469. result = (*bqPlayerBufferQueue)->RegisterCallback(bqPlayerBufferQueue, bqPlayerCallback, device->hidden);
  470. if (SL_RESULT_SUCCESS != result) {
  471. LOGE("RegisterCallback failed: %d", result);
  472. goto failed;
  473. }
  474. #if 0
  475. // get the volume interface
  476. result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_VOLUME, &bqPlayerVolume);
  477. if (SL_RESULT_SUCCESS != result) {
  478. LOGE("SL_IID_VOLUME interface get failed: %d", result);
  479. // goto failed;
  480. }
  481. #endif
  482. struct SDL_PrivateAudioData *audiodata = device->hidden;
  483. // Create the audio buffer semaphore
  484. audiodata->playsem = SDL_CreateSemaphore(NUM_BUFFERS - 1);
  485. if (!audiodata->playsem) {
  486. LOGE("cannot create Semaphore!");
  487. goto failed;
  488. }
  489. // Create the sound buffers
  490. audiodata->mixbuff = (Uint8 *)SDL_malloc(NUM_BUFFERS * device->buffer_size);
  491. if (audiodata->mixbuff == NULL) {
  492. LOGE("mixbuffer allocate - out of memory");
  493. goto failed;
  494. }
  495. for (int i = 0; i < NUM_BUFFERS; i++) {
  496. audiodata->pmixbuff[i] = audiodata->mixbuff + i * device->buffer_size;
  497. }
  498. // set the player's state to playing
  499. result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_PLAYING);
  500. if (SL_RESULT_SUCCESS != result) {
  501. LOGE("Play set state failed: %d", result);
  502. goto failed;
  503. }
  504. return 0;
  505. failed:
  506. return -1;
  507. }
  508. static int OPENSLES_OpenDevice(SDL_AudioDevice *device)
  509. {
  510. device->hidden = (struct SDL_PrivateAudioData *)SDL_calloc(1, sizeof(*device->hidden));
  511. if (device->hidden == NULL) {
  512. return SDL_OutOfMemory();
  513. }
  514. if (device->iscapture) {
  515. LOGI("OPENSLES_OpenDevice() for capture");
  516. return OPENSLES_CreatePCMRecorder(device);
  517. } else {
  518. int ret;
  519. LOGI("OPENSLES_OpenDevice() for playing");
  520. ret = OPENSLES_CreatePCMPlayer(device);
  521. if (ret < 0) {
  522. // Another attempt to open the device with a lower frequency
  523. if (device->spec.freq > 48000) {
  524. OPENSLES_DestroyPCMPlayer(device);
  525. device->spec.freq = 48000;
  526. ret = OPENSLES_CreatePCMPlayer(device);
  527. }
  528. }
  529. if (ret != 0) {
  530. return SDL_SetError("Open device failed!");
  531. }
  532. }
  533. return 0;
  534. }
  535. static int OPENSLES_WaitDevice(SDL_AudioDevice *device)
  536. {
  537. struct SDL_PrivateAudioData *audiodata = device->hidden;
  538. LOGV("OPENSLES_WaitDevice()");
  539. // Wait for an audio chunk to finish
  540. return SDL_WaitSemaphore(audiodata->playsem);
  541. }
  542. static int OPENSLES_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
  543. {
  544. struct SDL_PrivateAudioData *audiodata = device->hidden;
  545. LOGV("======OPENSLES_PlayDevice()======");
  546. // Queue it up
  547. const SLresult result = (*bqPlayerBufferQueue)->Enqueue(bqPlayerBufferQueue, buffer, buflen);
  548. audiodata->next_buffer++;
  549. if (audiodata->next_buffer >= NUM_BUFFERS) {
  550. audiodata->next_buffer = 0;
  551. }
  552. // If Enqueue fails, callback won't be called.
  553. // Post the semaphore, not to run out of buffer
  554. if (SL_RESULT_SUCCESS != result) {
  555. SDL_PostSemaphore(audiodata->playsem);
  556. }
  557. return 0;
  558. }
  559. /// n playn sem
  560. // getbuf 0 - 1
  561. // fill buff 0 - 1
  562. // play 0 - 0 1
  563. // wait 1 0 0
  564. // getbuf 1 0 0
  565. // fill buff 1 0 0
  566. // play 0 0 0
  567. // wait
  568. //
  569. // okay..
  570. static Uint8 *OPENSLES_GetDeviceBuf(SDL_AudioDevice *device, int *bufsize)
  571. {
  572. struct SDL_PrivateAudioData *audiodata = device->hidden;
  573. LOGV("OPENSLES_GetDeviceBuf()");
  574. return audiodata->pmixbuff[audiodata->next_buffer];
  575. }
  576. static int OPENSLES_CaptureFromDevice(SDL_AudioDevice *device, void *buffer, int buflen)
  577. {
  578. struct SDL_PrivateAudioData *audiodata = device->hidden;
  579. // Copy it to the output buffer
  580. SDL_assert(buflen == device->buffer_size);
  581. SDL_memcpy(buffer, audiodata->pmixbuff[audiodata->next_buffer], device->buffer_size);
  582. // Re-enqueue the buffer
  583. const SLresult result = (*recorderBufferQueue)->Enqueue(recorderBufferQueue, audiodata->pmixbuff[audiodata->next_buffer], device->buffer_size);
  584. if (SL_RESULT_SUCCESS != result) {
  585. LOGE("Record enqueue buffers failed: %d", result);
  586. return -1;
  587. }
  588. audiodata->next_buffer++;
  589. if (audiodata->next_buffer >= NUM_BUFFERS) {
  590. audiodata->next_buffer = 0;
  591. }
  592. return device->buffer_size;
  593. }
  594. static void OPENSLES_CloseDevice(SDL_AudioDevice *device)
  595. {
  596. // struct SDL_PrivateAudioData *audiodata = device->hidden;
  597. if (device->hidden) {
  598. if (device->iscapture) {
  599. LOGI("OPENSLES_CloseDevice() for capture");
  600. OPENSLES_DestroyPCMRecorder(device);
  601. } else {
  602. LOGI("OPENSLES_CloseDevice() for playing");
  603. OPENSLES_DestroyPCMPlayer(device);
  604. }
  605. SDL_free(device->hidden);
  606. device->hidden = NULL;
  607. }
  608. }
  609. static SDL_bool OPENSLES_Init(SDL_AudioDriverImpl *impl)
  610. {
  611. LOGI("OPENSLES_Init() called");
  612. if (!OPENSLES_CreateEngine()) {
  613. return SDL_FALSE;
  614. }
  615. LOGI("OPENSLES_Init() - set pointers");
  616. // Set the function pointers
  617. // impl->DetectDevices = OPENSLES_DetectDevices;
  618. impl->ThreadInit = Android_AudioThreadInit;
  619. impl->OpenDevice = OPENSLES_OpenDevice;
  620. impl->WaitDevice = OPENSLES_WaitDevice;
  621. impl->PlayDevice = OPENSLES_PlayDevice;
  622. impl->GetDeviceBuf = OPENSLES_GetDeviceBuf;
  623. impl->WaitCaptureDevice = OPENSLES_WaitDevice;
  624. impl->CaptureFromDevice = OPENSLES_CaptureFromDevice;
  625. impl->CloseDevice = OPENSLES_CloseDevice;
  626. impl->Deinitialize = OPENSLES_DestroyEngine;
  627. // and the capabilities
  628. impl->HasCaptureSupport = SDL_TRUE;
  629. impl->OnlyHasDefaultOutputDevice = SDL_TRUE;
  630. impl->OnlyHasDefaultCaptureDevice = SDL_TRUE;
  631. LOGI("OPENSLES_Init() - success");
  632. // this audio target is available.
  633. return SDL_TRUE;
  634. }
  635. AudioBootStrap OPENSLES_bootstrap = {
  636. "openslES", "OpenSL ES audio driver", OPENSLES_Init, SDL_FALSE
  637. };
  638. void OPENSLES_ResumeDevices(void)
  639. {
  640. if (bqPlayerPlay != NULL) {
  641. // set the player's state to 'playing'
  642. SLresult result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_PLAYING);
  643. if (SL_RESULT_SUCCESS != result) {
  644. LOGE("OPENSLES_ResumeDevices failed: %d", result);
  645. }
  646. }
  647. }
  648. void OPENSLES_PauseDevices(void)
  649. {
  650. if (bqPlayerPlay != NULL) {
  651. // set the player's state to 'paused'
  652. SLresult result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_PAUSED);
  653. if (SL_RESULT_SUCCESS != result) {
  654. LOGE("OPENSLES_PauseDevices failed: %d", result);
  655. }
  656. }
  657. }
  658. #endif // SDL_AUDIO_DRIVER_OPENSLES