🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

999 lines
34 KiB

  1. /*
  2. * Copyright (C) 2011 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /* This is an OpenAL backend for Android using the native audio APIs based on
  17. * OpenSL ES 1.0.1. It is based on source code for the native-audio sample app
  18. * bundled with NDK.
  19. */
  20. #include "config.h"
  21. #include "opensl.h"
  22. #include <stdlib.h>
  23. #include <jni.h>
  24. #include <new>
  25. #include <array>
  26. #include <cstring>
  27. #include <thread>
  28. #include <functional>
  29. #include "albit.h"
  30. #include "alnumeric.h"
  31. #include "core/device.h"
  32. #include "core/helpers.h"
  33. #include "core/logging.h"
  34. #include "opthelpers.h"
  35. #include "ringbuffer.h"
  36. #include "threads.h"
  37. #include <SLES/OpenSLES.h>
  38. #include <SLES/OpenSLES_Android.h>
  39. #include <SLES/OpenSLES_AndroidConfiguration.h>
  40. namespace {
  41. /* Helper macros */
  42. #define EXTRACT_VCALL_ARGS(...) __VA_ARGS__))
  43. #define VCALL(obj, func) ((*(obj))->func((obj), EXTRACT_VCALL_ARGS
  44. #define VCALL0(obj, func) ((*(obj))->func((obj) EXTRACT_VCALL_ARGS
  45. constexpr char opensl_device[] = "OpenSL";
  46. constexpr SLuint32 GetChannelMask(DevFmtChannels chans) noexcept
  47. {
  48. switch(chans)
  49. {
  50. case DevFmtMono: return SL_SPEAKER_FRONT_CENTER;
  51. case DevFmtStereo: return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
  52. case DevFmtQuad: return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT |
  53. SL_SPEAKER_BACK_LEFT | SL_SPEAKER_BACK_RIGHT;
  54. case DevFmtX51: return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT |
  55. SL_SPEAKER_FRONT_CENTER | SL_SPEAKER_LOW_FREQUENCY | SL_SPEAKER_SIDE_LEFT |
  56. SL_SPEAKER_SIDE_RIGHT;
  57. case DevFmtX61: return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT |
  58. SL_SPEAKER_FRONT_CENTER | SL_SPEAKER_LOW_FREQUENCY | SL_SPEAKER_BACK_CENTER |
  59. SL_SPEAKER_SIDE_LEFT | SL_SPEAKER_SIDE_RIGHT;
  60. case DevFmtX71:
  61. case DevFmtX3D71: return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT |
  62. SL_SPEAKER_FRONT_CENTER | SL_SPEAKER_LOW_FREQUENCY | SL_SPEAKER_BACK_LEFT |
  63. SL_SPEAKER_BACK_RIGHT | SL_SPEAKER_SIDE_LEFT | SL_SPEAKER_SIDE_RIGHT;
  64. case DevFmtAmbi3D:
  65. break;
  66. }
  67. return 0;
  68. }
  69. #ifdef SL_ANDROID_DATAFORMAT_PCM_EX
  70. constexpr SLuint32 GetTypeRepresentation(DevFmtType type) noexcept
  71. {
  72. switch(type)
  73. {
  74. case DevFmtUByte:
  75. case DevFmtUShort:
  76. case DevFmtUInt:
  77. return SL_ANDROID_PCM_REPRESENTATION_UNSIGNED_INT;
  78. case DevFmtByte:
  79. case DevFmtShort:
  80. case DevFmtInt:
  81. return SL_ANDROID_PCM_REPRESENTATION_SIGNED_INT;
  82. case DevFmtFloat:
  83. return SL_ANDROID_PCM_REPRESENTATION_FLOAT;
  84. }
  85. return 0;
  86. }
  87. #endif
  88. constexpr SLuint32 GetByteOrderEndianness() noexcept
  89. {
  90. if(al::endian::native == al::endian::little)
  91. return SL_BYTEORDER_LITTLEENDIAN;
  92. return SL_BYTEORDER_BIGENDIAN;
  93. }
  94. const char *res_str(SLresult result) noexcept
  95. {
  96. switch(result)
  97. {
  98. case SL_RESULT_SUCCESS: return "Success";
  99. case SL_RESULT_PRECONDITIONS_VIOLATED: return "Preconditions violated";
  100. case SL_RESULT_PARAMETER_INVALID: return "Parameter invalid";
  101. case SL_RESULT_MEMORY_FAILURE: return "Memory failure";
  102. case SL_RESULT_RESOURCE_ERROR: return "Resource error";
  103. case SL_RESULT_RESOURCE_LOST: return "Resource lost";
  104. case SL_RESULT_IO_ERROR: return "I/O error";
  105. case SL_RESULT_BUFFER_INSUFFICIENT: return "Buffer insufficient";
  106. case SL_RESULT_CONTENT_CORRUPTED: return "Content corrupted";
  107. case SL_RESULT_CONTENT_UNSUPPORTED: return "Content unsupported";
  108. case SL_RESULT_CONTENT_NOT_FOUND: return "Content not found";
  109. case SL_RESULT_PERMISSION_DENIED: return "Permission denied";
  110. case SL_RESULT_FEATURE_UNSUPPORTED: return "Feature unsupported";
  111. case SL_RESULT_INTERNAL_ERROR: return "Internal error";
  112. case SL_RESULT_UNKNOWN_ERROR: return "Unknown error";
  113. case SL_RESULT_OPERATION_ABORTED: return "Operation aborted";
  114. case SL_RESULT_CONTROL_LOST: return "Control lost";
  115. #ifdef SL_RESULT_READONLY
  116. case SL_RESULT_READONLY: return "ReadOnly";
  117. #endif
  118. #ifdef SL_RESULT_ENGINEOPTION_UNSUPPORTED
  119. case SL_RESULT_ENGINEOPTION_UNSUPPORTED: return "Engine option unsupported";
  120. #endif
  121. #ifdef SL_RESULT_SOURCE_SINK_INCOMPATIBLE
  122. case SL_RESULT_SOURCE_SINK_INCOMPATIBLE: return "Source/Sink incompatible";
  123. #endif
  124. }
  125. return "Unknown error code";
  126. }
  127. #define PRINTERR(x, s) do { \
  128. if UNLIKELY((x) != SL_RESULT_SUCCESS) \
  129. ERR("%s: %s\n", (s), res_str((x))); \
  130. } while(0)
  131. struct OpenSLPlayback final : public BackendBase {
  132. OpenSLPlayback(DeviceBase *device) noexcept : BackendBase{device} { }
  133. ~OpenSLPlayback() override;
  134. void process(SLAndroidSimpleBufferQueueItf bq) noexcept;
  135. static void processC(SLAndroidSimpleBufferQueueItf bq, void *context) noexcept
  136. { static_cast<OpenSLPlayback*>(context)->process(bq); }
  137. int mixerProc();
  138. void open(const char *name) override;
  139. bool reset() override;
  140. void start() override;
  141. void stop() override;
  142. ClockLatency getClockLatency() override;
  143. /* engine interfaces */
  144. SLObjectItf mEngineObj{nullptr};
  145. SLEngineItf mEngine{nullptr};
  146. /* output mix interfaces */
  147. SLObjectItf mOutputMix{nullptr};
  148. /* buffer queue player interfaces */
  149. SLObjectItf mBufferQueueObj{nullptr};
  150. RingBufferPtr mRing{nullptr};
  151. al::semaphore mSem;
  152. std::mutex mMutex;
  153. uint mFrameSize{0};
  154. std::atomic<bool> mKillNow{true};
  155. std::thread mThread;
  156. DEF_NEWDEL(OpenSLPlayback)
  157. };
  158. OpenSLPlayback::~OpenSLPlayback()
  159. {
  160. if(mBufferQueueObj)
  161. VCALL0(mBufferQueueObj,Destroy)();
  162. mBufferQueueObj = nullptr;
  163. if(mOutputMix)
  164. VCALL0(mOutputMix,Destroy)();
  165. mOutputMix = nullptr;
  166. if(mEngineObj)
  167. VCALL0(mEngineObj,Destroy)();
  168. mEngineObj = nullptr;
  169. mEngine = nullptr;
  170. }
  171. /* this callback handler is called every time a buffer finishes playing */
  172. void OpenSLPlayback::process(SLAndroidSimpleBufferQueueItf) noexcept
  173. {
  174. /* A note on the ringbuffer usage: The buffer queue seems to hold on to the
  175. * pointer passed to the Enqueue method, rather than copying the audio.
  176. * Consequently, the ringbuffer contains the audio that is currently queued
  177. * and waiting to play. This process() callback is called when a buffer is
  178. * finished, so we simply move the read pointer up to indicate the space is
  179. * available for writing again, and wake up the mixer thread to mix and
  180. * queue more audio.
  181. */
  182. mRing->readAdvance(1);
  183. mSem.post();
  184. }
  185. int OpenSLPlayback::mixerProc()
  186. {
  187. SetRTPriority();
  188. althrd_setname(MIXER_THREAD_NAME);
  189. SLPlayItf player;
  190. SLAndroidSimpleBufferQueueItf bufferQueue;
  191. SLresult result{VCALL(mBufferQueueObj,GetInterface)(SL_IID_ANDROIDSIMPLEBUFFERQUEUE,
  192. &bufferQueue)};
  193. PRINTERR(result, "bufferQueue->GetInterface SL_IID_ANDROIDSIMPLEBUFFERQUEUE");
  194. if(SL_RESULT_SUCCESS == result)
  195. {
  196. result = VCALL(mBufferQueueObj,GetInterface)(SL_IID_PLAY, &player);
  197. PRINTERR(result, "bufferQueue->GetInterface SL_IID_PLAY");
  198. }
  199. const size_t frame_step{mDevice->channelsFromFmt()};
  200. if(SL_RESULT_SUCCESS != result)
  201. mDevice->handleDisconnect("Failed to get playback buffer: 0x%08x", result);
  202. while(SL_RESULT_SUCCESS == result && !mKillNow.load(std::memory_order_acquire)
  203. && mDevice->Connected.load(std::memory_order_acquire))
  204. {
  205. if(mRing->writeSpace() == 0)
  206. {
  207. SLuint32 state{0};
  208. result = VCALL(player,GetPlayState)(&state);
  209. PRINTERR(result, "player->GetPlayState");
  210. if(SL_RESULT_SUCCESS == result && state != SL_PLAYSTATE_PLAYING)
  211. {
  212. result = VCALL(player,SetPlayState)(SL_PLAYSTATE_PLAYING);
  213. PRINTERR(result, "player->SetPlayState");
  214. }
  215. if(SL_RESULT_SUCCESS != result)
  216. {
  217. mDevice->handleDisconnect("Failed to start playback: 0x%08x", result);
  218. break;
  219. }
  220. if(mRing->writeSpace() == 0)
  221. {
  222. mSem.wait();
  223. continue;
  224. }
  225. }
  226. std::unique_lock<std::mutex> dlock{mMutex};
  227. auto data = mRing->getWriteVector();
  228. mDevice->renderSamples(data.first.buf,
  229. static_cast<uint>(data.first.len)*mDevice->UpdateSize, frame_step);
  230. if(data.second.len > 0)
  231. mDevice->renderSamples(data.second.buf,
  232. static_cast<uint>(data.second.len)*mDevice->UpdateSize, frame_step);
  233. size_t todo{data.first.len + data.second.len};
  234. mRing->writeAdvance(todo);
  235. dlock.unlock();
  236. for(size_t i{0};i < todo;i++)
  237. {
  238. if(!data.first.len)
  239. {
  240. data.first = data.second;
  241. data.second.buf = nullptr;
  242. data.second.len = 0;
  243. }
  244. result = VCALL(bufferQueue,Enqueue)(data.first.buf, mDevice->UpdateSize*mFrameSize);
  245. PRINTERR(result, "bufferQueue->Enqueue");
  246. if(SL_RESULT_SUCCESS != result)
  247. {
  248. mDevice->handleDisconnect("Failed to queue audio: 0x%08x", result);
  249. break;
  250. }
  251. data.first.len--;
  252. data.first.buf += mDevice->UpdateSize*mFrameSize;
  253. }
  254. }
  255. return 0;
  256. }
  257. void OpenSLPlayback::open(const char *name)
  258. {
  259. if(!name)
  260. name = opensl_device;
  261. else if(strcmp(name, opensl_device) != 0)
  262. throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%s\" not found",
  263. name};
  264. /* There's only one device, so if it's already open, there's nothing to do. */
  265. if(mEngineObj) return;
  266. // create engine
  267. SLresult result{slCreateEngine(&mEngineObj, 0, nullptr, 0, nullptr, nullptr)};
  268. PRINTERR(result, "slCreateEngine");
  269. if(SL_RESULT_SUCCESS == result)
  270. {
  271. result = VCALL(mEngineObj,Realize)(SL_BOOLEAN_FALSE);
  272. PRINTERR(result, "engine->Realize");
  273. }
  274. if(SL_RESULT_SUCCESS == result)
  275. {
  276. result = VCALL(mEngineObj,GetInterface)(SL_IID_ENGINE, &mEngine);
  277. PRINTERR(result, "engine->GetInterface");
  278. }
  279. if(SL_RESULT_SUCCESS == result)
  280. {
  281. result = VCALL(mEngine,CreateOutputMix)(&mOutputMix, 0, nullptr, nullptr);
  282. PRINTERR(result, "engine->CreateOutputMix");
  283. }
  284. if(SL_RESULT_SUCCESS == result)
  285. {
  286. result = VCALL(mOutputMix,Realize)(SL_BOOLEAN_FALSE);
  287. PRINTERR(result, "outputMix->Realize");
  288. }
  289. if(SL_RESULT_SUCCESS != result)
  290. {
  291. if(mOutputMix)
  292. VCALL0(mOutputMix,Destroy)();
  293. mOutputMix = nullptr;
  294. if(mEngineObj)
  295. VCALL0(mEngineObj,Destroy)();
  296. mEngineObj = nullptr;
  297. mEngine = nullptr;
  298. throw al::backend_exception{al::backend_error::DeviceError,
  299. "Failed to initialize OpenSL device: 0x%08x", result};
  300. }
  301. mDevice->DeviceName = name;
  302. }
  303. bool OpenSLPlayback::reset()
  304. {
  305. SLresult result;
  306. if(mBufferQueueObj)
  307. VCALL0(mBufferQueueObj,Destroy)();
  308. mBufferQueueObj = nullptr;
  309. mRing = nullptr;
  310. #if 0
  311. if(!mDevice->Flags.get<FrequencyRequest>())
  312. {
  313. /* FIXME: Disabled until I figure out how to get the Context needed for
  314. * the getSystemService call.
  315. */
  316. JNIEnv *env = Android_GetJNIEnv();
  317. jobject jctx = Android_GetContext();
  318. /* Get necessary stuff for using java.lang.Integer,
  319. * android.content.Context, and android.media.AudioManager.
  320. */
  321. jclass int_cls = JCALL(env,FindClass)("java/lang/Integer");
  322. jmethodID int_parseint = JCALL(env,GetStaticMethodID)(int_cls,
  323. "parseInt", "(Ljava/lang/String;)I"
  324. );
  325. TRACE("Integer: %p, parseInt: %p\n", int_cls, int_parseint);
  326. jclass ctx_cls = JCALL(env,FindClass)("android/content/Context");
  327. jfieldID ctx_audsvc = JCALL(env,GetStaticFieldID)(ctx_cls,
  328. "AUDIO_SERVICE", "Ljava/lang/String;"
  329. );
  330. jmethodID ctx_getSysSvc = JCALL(env,GetMethodID)(ctx_cls,
  331. "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;"
  332. );
  333. TRACE("Context: %p, AUDIO_SERVICE: %p, getSystemService: %p\n",
  334. ctx_cls, ctx_audsvc, ctx_getSysSvc);
  335. jclass audmgr_cls = JCALL(env,FindClass)("android/media/AudioManager");
  336. jfieldID audmgr_prop_out_srate = JCALL(env,GetStaticFieldID)(audmgr_cls,
  337. "PROPERTY_OUTPUT_SAMPLE_RATE", "Ljava/lang/String;"
  338. );
  339. jmethodID audmgr_getproperty = JCALL(env,GetMethodID)(audmgr_cls,
  340. "getProperty", "(Ljava/lang/String;)Ljava/lang/String;"
  341. );
  342. TRACE("AudioManager: %p, PROPERTY_OUTPUT_SAMPLE_RATE: %p, getProperty: %p\n",
  343. audmgr_cls, audmgr_prop_out_srate, audmgr_getproperty);
  344. const char *strchars;
  345. jstring strobj;
  346. /* Now make the calls. */
  347. //AudioManager audMgr = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
  348. strobj = JCALL(env,GetStaticObjectField)(ctx_cls, ctx_audsvc);
  349. jobject audMgr = JCALL(env,CallObjectMethod)(jctx, ctx_getSysSvc, strobj);
  350. strchars = JCALL(env,GetStringUTFChars)(strobj, nullptr);
  351. TRACE("Context.getSystemService(%s) = %p\n", strchars, audMgr);
  352. JCALL(env,ReleaseStringUTFChars)(strobj, strchars);
  353. //String srateStr = audMgr.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE);
  354. strobj = JCALL(env,GetStaticObjectField)(audmgr_cls, audmgr_prop_out_srate);
  355. jstring srateStr = JCALL(env,CallObjectMethod)(audMgr, audmgr_getproperty, strobj);
  356. strchars = JCALL(env,GetStringUTFChars)(strobj, nullptr);
  357. TRACE("audMgr.getProperty(%s) = %p\n", strchars, srateStr);
  358. JCALL(env,ReleaseStringUTFChars)(strobj, strchars);
  359. //int sampleRate = Integer.parseInt(srateStr);
  360. sampleRate = JCALL(env,CallStaticIntMethod)(int_cls, int_parseint, srateStr);
  361. strchars = JCALL(env,GetStringUTFChars)(srateStr, nullptr);
  362. TRACE("Got system sample rate %uhz (%s)\n", sampleRate, strchars);
  363. JCALL(env,ReleaseStringUTFChars)(srateStr, strchars);
  364. if(!sampleRate) sampleRate = device->Frequency;
  365. else sampleRate = maxu(sampleRate, MIN_OUTPUT_RATE);
  366. }
  367. #endif
  368. mDevice->FmtChans = DevFmtStereo;
  369. mDevice->FmtType = DevFmtShort;
  370. setDefaultWFXChannelOrder();
  371. mFrameSize = mDevice->frameSizeFromFmt();
  372. const std::array<SLInterfaceID,2> ids{{ SL_IID_ANDROIDSIMPLEBUFFERQUEUE, SL_IID_ANDROIDCONFIGURATION }};
  373. const std::array<SLboolean,2> reqs{{ SL_BOOLEAN_TRUE, SL_BOOLEAN_FALSE }};
  374. SLDataLocator_OutputMix loc_outmix{};
  375. loc_outmix.locatorType = SL_DATALOCATOR_OUTPUTMIX;
  376. loc_outmix.outputMix = mOutputMix;
  377. SLDataSink audioSnk{};
  378. audioSnk.pLocator = &loc_outmix;
  379. audioSnk.pFormat = nullptr;
  380. SLDataLocator_AndroidSimpleBufferQueue loc_bufq{};
  381. loc_bufq.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE;
  382. loc_bufq.numBuffers = mDevice->BufferSize / mDevice->UpdateSize;
  383. SLDataSource audioSrc{};
  384. #ifdef SL_ANDROID_DATAFORMAT_PCM_EX
  385. SLAndroidDataFormat_PCM_EX format_pcm_ex{};
  386. format_pcm_ex.formatType = SL_ANDROID_DATAFORMAT_PCM_EX;
  387. format_pcm_ex.numChannels = mDevice->channelsFromFmt();
  388. format_pcm_ex.sampleRate = mDevice->Frequency * 1000;
  389. format_pcm_ex.bitsPerSample = mDevice->bytesFromFmt() * 8;
  390. format_pcm_ex.containerSize = format_pcm_ex.bitsPerSample;
  391. format_pcm_ex.channelMask = GetChannelMask(mDevice->FmtChans);
  392. format_pcm_ex.endianness = GetByteOrderEndianness();
  393. format_pcm_ex.representation = GetTypeRepresentation(mDevice->FmtType);
  394. audioSrc.pLocator = &loc_bufq;
  395. audioSrc.pFormat = &format_pcm_ex;
  396. result = VCALL(mEngine,CreateAudioPlayer)(&mBufferQueueObj, &audioSrc, &audioSnk, ids.size(),
  397. ids.data(), reqs.data());
  398. if(SL_RESULT_SUCCESS != result)
  399. #endif
  400. {
  401. /* Alter sample type according to what SLDataFormat_PCM can support. */
  402. switch(mDevice->FmtType)
  403. {
  404. case DevFmtByte: mDevice->FmtType = DevFmtUByte; break;
  405. case DevFmtUInt: mDevice->FmtType = DevFmtInt; break;
  406. case DevFmtFloat:
  407. case DevFmtUShort: mDevice->FmtType = DevFmtShort; break;
  408. case DevFmtUByte:
  409. case DevFmtShort:
  410. case DevFmtInt:
  411. break;
  412. }
  413. SLDataFormat_PCM format_pcm{};
  414. format_pcm.formatType = SL_DATAFORMAT_PCM;
  415. format_pcm.numChannels = mDevice->channelsFromFmt();
  416. format_pcm.samplesPerSec = mDevice->Frequency * 1000;
  417. format_pcm.bitsPerSample = mDevice->bytesFromFmt() * 8;
  418. format_pcm.containerSize = format_pcm.bitsPerSample;
  419. format_pcm.channelMask = GetChannelMask(mDevice->FmtChans);
  420. format_pcm.endianness = GetByteOrderEndianness();
  421. audioSrc.pLocator = &loc_bufq;
  422. audioSrc.pFormat = &format_pcm;
  423. result = VCALL(mEngine,CreateAudioPlayer)(&mBufferQueueObj, &audioSrc, &audioSnk, ids.size(),
  424. ids.data(), reqs.data());
  425. PRINTERR(result, "engine->CreateAudioPlayer");
  426. }
  427. if(SL_RESULT_SUCCESS == result)
  428. {
  429. /* Set the stream type to "media" (games, music, etc), if possible. */
  430. SLAndroidConfigurationItf config;
  431. result = VCALL(mBufferQueueObj,GetInterface)(SL_IID_ANDROIDCONFIGURATION, &config);
  432. PRINTERR(result, "bufferQueue->GetInterface SL_IID_ANDROIDCONFIGURATION");
  433. if(SL_RESULT_SUCCESS == result)
  434. {
  435. SLint32 streamType = SL_ANDROID_STREAM_MEDIA;
  436. result = VCALL(config,SetConfiguration)(SL_ANDROID_KEY_STREAM_TYPE, &streamType,
  437. sizeof(streamType));
  438. PRINTERR(result, "config->SetConfiguration");
  439. }
  440. /* Clear any error since this was optional. */
  441. result = SL_RESULT_SUCCESS;
  442. }
  443. if(SL_RESULT_SUCCESS == result)
  444. {
  445. result = VCALL(mBufferQueueObj,Realize)(SL_BOOLEAN_FALSE);
  446. PRINTERR(result, "bufferQueue->Realize");
  447. }
  448. if(SL_RESULT_SUCCESS == result)
  449. {
  450. const uint num_updates{mDevice->BufferSize / mDevice->UpdateSize};
  451. mRing = RingBuffer::Create(num_updates, mFrameSize*mDevice->UpdateSize, true);
  452. }
  453. if(SL_RESULT_SUCCESS != result)
  454. {
  455. if(mBufferQueueObj)
  456. VCALL0(mBufferQueueObj,Destroy)();
  457. mBufferQueueObj = nullptr;
  458. return false;
  459. }
  460. return true;
  461. }
  462. void OpenSLPlayback::start()
  463. {
  464. mRing->reset();
  465. SLAndroidSimpleBufferQueueItf bufferQueue;
  466. SLresult result{VCALL(mBufferQueueObj,GetInterface)(SL_IID_ANDROIDSIMPLEBUFFERQUEUE,
  467. &bufferQueue)};
  468. PRINTERR(result, "bufferQueue->GetInterface");
  469. if(SL_RESULT_SUCCESS == result)
  470. {
  471. result = VCALL(bufferQueue,RegisterCallback)(&OpenSLPlayback::processC, this);
  472. PRINTERR(result, "bufferQueue->RegisterCallback");
  473. }
  474. if(SL_RESULT_SUCCESS != result)
  475. throw al::backend_exception{al::backend_error::DeviceError,
  476. "Failed to register callback: 0x%08x", result};
  477. try {
  478. mKillNow.store(false, std::memory_order_release);
  479. mThread = std::thread(std::mem_fn(&OpenSLPlayback::mixerProc), this);
  480. }
  481. catch(std::exception& e) {
  482. throw al::backend_exception{al::backend_error::DeviceError,
  483. "Failed to start mixing thread: %s", e.what()};
  484. }
  485. }
  486. void OpenSLPlayback::stop()
  487. {
  488. if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable())
  489. return;
  490. mSem.post();
  491. mThread.join();
  492. SLPlayItf player;
  493. SLresult result{VCALL(mBufferQueueObj,GetInterface)(SL_IID_PLAY, &player)};
  494. PRINTERR(result, "bufferQueue->GetInterface");
  495. if(SL_RESULT_SUCCESS == result)
  496. {
  497. result = VCALL(player,SetPlayState)(SL_PLAYSTATE_STOPPED);
  498. PRINTERR(result, "player->SetPlayState");
  499. }
  500. SLAndroidSimpleBufferQueueItf bufferQueue;
  501. result = VCALL(mBufferQueueObj,GetInterface)(SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &bufferQueue);
  502. PRINTERR(result, "bufferQueue->GetInterface");
  503. if(SL_RESULT_SUCCESS == result)
  504. {
  505. result = VCALL0(bufferQueue,Clear)();
  506. PRINTERR(result, "bufferQueue->Clear");
  507. }
  508. if(SL_RESULT_SUCCESS == result)
  509. {
  510. result = VCALL(bufferQueue,RegisterCallback)(nullptr, nullptr);
  511. PRINTERR(result, "bufferQueue->RegisterCallback");
  512. }
  513. if(SL_RESULT_SUCCESS == result)
  514. {
  515. SLAndroidSimpleBufferQueueState state;
  516. do {
  517. std::this_thread::yield();
  518. result = VCALL(bufferQueue,GetState)(&state);
  519. } while(SL_RESULT_SUCCESS == result && state.count > 0);
  520. PRINTERR(result, "bufferQueue->GetState");
  521. mRing.reset();
  522. }
  523. }
  524. ClockLatency OpenSLPlayback::getClockLatency()
  525. {
  526. ClockLatency ret;
  527. std::lock_guard<std::mutex> _{mMutex};
  528. ret.ClockTime = GetDeviceClockTime(mDevice);
  529. ret.Latency = std::chrono::seconds{mRing->readSpace() * mDevice->UpdateSize};
  530. ret.Latency /= mDevice->Frequency;
  531. return ret;
  532. }
  533. struct OpenSLCapture final : public BackendBase {
  534. OpenSLCapture(DeviceBase *device) noexcept : BackendBase{device} { }
  535. ~OpenSLCapture() override;
  536. void process(SLAndroidSimpleBufferQueueItf bq) noexcept;
  537. static void processC(SLAndroidSimpleBufferQueueItf bq, void *context) noexcept
  538. { static_cast<OpenSLCapture*>(context)->process(bq); }
  539. void open(const char *name) override;
  540. void start() override;
  541. void stop() override;
  542. void captureSamples(al::byte *buffer, uint samples) override;
  543. uint availableSamples() override;
  544. /* engine interfaces */
  545. SLObjectItf mEngineObj{nullptr};
  546. SLEngineItf mEngine;
  547. /* recording interfaces */
  548. SLObjectItf mRecordObj{nullptr};
  549. RingBufferPtr mRing{nullptr};
  550. uint mSplOffset{0u};
  551. uint mFrameSize{0};
  552. DEF_NEWDEL(OpenSLCapture)
  553. };
  554. OpenSLCapture::~OpenSLCapture()
  555. {
  556. if(mRecordObj)
  557. VCALL0(mRecordObj,Destroy)();
  558. mRecordObj = nullptr;
  559. if(mEngineObj)
  560. VCALL0(mEngineObj,Destroy)();
  561. mEngineObj = nullptr;
  562. mEngine = nullptr;
  563. }
  564. void OpenSLCapture::process(SLAndroidSimpleBufferQueueItf) noexcept
  565. {
  566. /* A new chunk has been written into the ring buffer, advance it. */
  567. mRing->writeAdvance(1);
  568. }
  569. void OpenSLCapture::open(const char* name)
  570. {
  571. if(!name)
  572. name = opensl_device;
  573. else if(strcmp(name, opensl_device) != 0)
  574. throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%s\" not found",
  575. name};
  576. SLresult result{slCreateEngine(&mEngineObj, 0, nullptr, 0, nullptr, nullptr)};
  577. PRINTERR(result, "slCreateEngine");
  578. if(SL_RESULT_SUCCESS == result)
  579. {
  580. result = VCALL(mEngineObj,Realize)(SL_BOOLEAN_FALSE);
  581. PRINTERR(result, "engine->Realize");
  582. }
  583. if(SL_RESULT_SUCCESS == result)
  584. {
  585. result = VCALL(mEngineObj,GetInterface)(SL_IID_ENGINE, &mEngine);
  586. PRINTERR(result, "engine->GetInterface");
  587. }
  588. if(SL_RESULT_SUCCESS == result)
  589. {
  590. mFrameSize = mDevice->frameSizeFromFmt();
  591. /* Ensure the total length is at least 100ms */
  592. uint length{maxu(mDevice->BufferSize, mDevice->Frequency/10)};
  593. /* Ensure the per-chunk length is at least 10ms, and no more than 50ms. */
  594. uint update_len{clampu(mDevice->BufferSize/3, mDevice->Frequency/100,
  595. mDevice->Frequency/100*5)};
  596. uint num_updates{(length+update_len-1) / update_len};
  597. mRing = RingBuffer::Create(num_updates, update_len*mFrameSize, false);
  598. mDevice->UpdateSize = update_len;
  599. mDevice->BufferSize = static_cast<uint>(mRing->writeSpace() * update_len);
  600. }
  601. if(SL_RESULT_SUCCESS == result)
  602. {
  603. const std::array<SLInterfaceID,2> ids{{ SL_IID_ANDROIDSIMPLEBUFFERQUEUE, SL_IID_ANDROIDCONFIGURATION }};
  604. const std::array<SLboolean,2> reqs{{ SL_BOOLEAN_TRUE, SL_BOOLEAN_FALSE }};
  605. SLDataLocator_IODevice loc_dev{};
  606. loc_dev.locatorType = SL_DATALOCATOR_IODEVICE;
  607. loc_dev.deviceType = SL_IODEVICE_AUDIOINPUT;
  608. loc_dev.deviceID = SL_DEFAULTDEVICEID_AUDIOINPUT;
  609. loc_dev.device = nullptr;
  610. SLDataSource audioSrc{};
  611. audioSrc.pLocator = &loc_dev;
  612. audioSrc.pFormat = nullptr;
  613. SLDataLocator_AndroidSimpleBufferQueue loc_bq{};
  614. loc_bq.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE;
  615. loc_bq.numBuffers = mDevice->BufferSize / mDevice->UpdateSize;
  616. SLDataSink audioSnk{};
  617. #ifdef SL_ANDROID_DATAFORMAT_PCM_EX
  618. SLAndroidDataFormat_PCM_EX format_pcm_ex{};
  619. format_pcm_ex.formatType = SL_ANDROID_DATAFORMAT_PCM_EX;
  620. format_pcm_ex.numChannels = mDevice->channelsFromFmt();
  621. format_pcm_ex.sampleRate = mDevice->Frequency * 1000;
  622. format_pcm_ex.bitsPerSample = mDevice->bytesFromFmt() * 8;
  623. format_pcm_ex.containerSize = format_pcm_ex.bitsPerSample;
  624. format_pcm_ex.channelMask = GetChannelMask(mDevice->FmtChans);
  625. format_pcm_ex.endianness = GetByteOrderEndianness();
  626. format_pcm_ex.representation = GetTypeRepresentation(mDevice->FmtType);
  627. audioSnk.pLocator = &loc_bq;
  628. audioSnk.pFormat = &format_pcm_ex;
  629. result = VCALL(mEngine,CreateAudioRecorder)(&mRecordObj, &audioSrc, &audioSnk,
  630. ids.size(), ids.data(), reqs.data());
  631. if(SL_RESULT_SUCCESS != result)
  632. #endif
  633. {
  634. /* Fallback to SLDataFormat_PCM only if it supports the desired
  635. * sample type.
  636. */
  637. if(mDevice->FmtType == DevFmtUByte || mDevice->FmtType == DevFmtShort
  638. || mDevice->FmtType == DevFmtInt)
  639. {
  640. SLDataFormat_PCM format_pcm{};
  641. format_pcm.formatType = SL_DATAFORMAT_PCM;
  642. format_pcm.numChannels = mDevice->channelsFromFmt();
  643. format_pcm.samplesPerSec = mDevice->Frequency * 1000;
  644. format_pcm.bitsPerSample = mDevice->bytesFromFmt() * 8;
  645. format_pcm.containerSize = format_pcm.bitsPerSample;
  646. format_pcm.channelMask = GetChannelMask(mDevice->FmtChans);
  647. format_pcm.endianness = GetByteOrderEndianness();
  648. audioSnk.pLocator = &loc_bq;
  649. audioSnk.pFormat = &format_pcm;
  650. result = VCALL(mEngine,CreateAudioRecorder)(&mRecordObj, &audioSrc, &audioSnk,
  651. ids.size(), ids.data(), reqs.data());
  652. }
  653. PRINTERR(result, "engine->CreateAudioRecorder");
  654. }
  655. }
  656. if(SL_RESULT_SUCCESS == result)
  657. {
  658. /* Set the record preset to "generic", if possible. */
  659. SLAndroidConfigurationItf config;
  660. result = VCALL(mRecordObj,GetInterface)(SL_IID_ANDROIDCONFIGURATION, &config);
  661. PRINTERR(result, "recordObj->GetInterface SL_IID_ANDROIDCONFIGURATION");
  662. if(SL_RESULT_SUCCESS == result)
  663. {
  664. SLuint32 preset = SL_ANDROID_RECORDING_PRESET_GENERIC;
  665. result = VCALL(config,SetConfiguration)(SL_ANDROID_KEY_RECORDING_PRESET, &preset,
  666. sizeof(preset));
  667. PRINTERR(result, "config->SetConfiguration");
  668. }
  669. /* Clear any error since this was optional. */
  670. result = SL_RESULT_SUCCESS;
  671. }
  672. if(SL_RESULT_SUCCESS == result)
  673. {
  674. result = VCALL(mRecordObj,Realize)(SL_BOOLEAN_FALSE);
  675. PRINTERR(result, "recordObj->Realize");
  676. }
  677. SLAndroidSimpleBufferQueueItf bufferQueue;
  678. if(SL_RESULT_SUCCESS == result)
  679. {
  680. result = VCALL(mRecordObj,GetInterface)(SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &bufferQueue);
  681. PRINTERR(result, "recordObj->GetInterface");
  682. }
  683. if(SL_RESULT_SUCCESS == result)
  684. {
  685. result = VCALL(bufferQueue,RegisterCallback)(&OpenSLCapture::processC, this);
  686. PRINTERR(result, "bufferQueue->RegisterCallback");
  687. }
  688. if(SL_RESULT_SUCCESS == result)
  689. {
  690. const uint chunk_size{mDevice->UpdateSize * mFrameSize};
  691. const auto silence = (mDevice->FmtType == DevFmtUByte) ? al::byte{0x80} : al::byte{0};
  692. auto data = mRing->getWriteVector();
  693. std::fill_n(data.first.buf, data.first.len*chunk_size, silence);
  694. std::fill_n(data.second.buf, data.second.len*chunk_size, silence);
  695. for(size_t i{0u};i < data.first.len && SL_RESULT_SUCCESS == result;i++)
  696. {
  697. result = VCALL(bufferQueue,Enqueue)(data.first.buf + chunk_size*i, chunk_size);
  698. PRINTERR(result, "bufferQueue->Enqueue");
  699. }
  700. for(size_t i{0u};i < data.second.len && SL_RESULT_SUCCESS == result;i++)
  701. {
  702. result = VCALL(bufferQueue,Enqueue)(data.second.buf + chunk_size*i, chunk_size);
  703. PRINTERR(result, "bufferQueue->Enqueue");
  704. }
  705. }
  706. if(SL_RESULT_SUCCESS != result)
  707. {
  708. if(mRecordObj)
  709. VCALL0(mRecordObj,Destroy)();
  710. mRecordObj = nullptr;
  711. if(mEngineObj)
  712. VCALL0(mEngineObj,Destroy)();
  713. mEngineObj = nullptr;
  714. mEngine = nullptr;
  715. throw al::backend_exception{al::backend_error::DeviceError,
  716. "Failed to initialize OpenSL device: 0x%08x", result};
  717. }
  718. mDevice->DeviceName = name;
  719. }
  720. void OpenSLCapture::start()
  721. {
  722. SLRecordItf record;
  723. SLresult result{VCALL(mRecordObj,GetInterface)(SL_IID_RECORD, &record)};
  724. PRINTERR(result, "recordObj->GetInterface");
  725. if(SL_RESULT_SUCCESS == result)
  726. {
  727. result = VCALL(record,SetRecordState)(SL_RECORDSTATE_RECORDING);
  728. PRINTERR(result, "record->SetRecordState");
  729. }
  730. if(SL_RESULT_SUCCESS != result)
  731. throw al::backend_exception{al::backend_error::DeviceError,
  732. "Failed to start capture: 0x%08x", result};
  733. }
  734. void OpenSLCapture::stop()
  735. {
  736. SLRecordItf record;
  737. SLresult result{VCALL(mRecordObj,GetInterface)(SL_IID_RECORD, &record)};
  738. PRINTERR(result, "recordObj->GetInterface");
  739. if(SL_RESULT_SUCCESS == result)
  740. {
  741. result = VCALL(record,SetRecordState)(SL_RECORDSTATE_PAUSED);
  742. PRINTERR(result, "record->SetRecordState");
  743. }
  744. }
  745. void OpenSLCapture::captureSamples(al::byte *buffer, uint samples)
  746. {
  747. const uint update_size{mDevice->UpdateSize};
  748. const uint chunk_size{update_size * mFrameSize};
  749. /* Read the desired samples from the ring buffer then advance its read
  750. * pointer.
  751. */
  752. size_t adv_count{0};
  753. auto rdata = mRing->getReadVector();
  754. for(uint i{0};i < samples;)
  755. {
  756. const uint rem{minu(samples - i, update_size - mSplOffset)};
  757. std::copy_n(rdata.first.buf + mSplOffset*size_t{mFrameSize}, rem*size_t{mFrameSize},
  758. buffer + i*size_t{mFrameSize});
  759. mSplOffset += rem;
  760. if(mSplOffset == update_size)
  761. {
  762. /* Finished a chunk, reset the offset and advance the read pointer. */
  763. mSplOffset = 0;
  764. ++adv_count;
  765. rdata.first.len -= 1;
  766. if(!rdata.first.len)
  767. rdata.first = rdata.second;
  768. else
  769. rdata.first.buf += chunk_size;
  770. }
  771. i += rem;
  772. }
  773. SLAndroidSimpleBufferQueueItf bufferQueue{};
  774. if(likely(mDevice->Connected.load(std::memory_order_acquire)))
  775. {
  776. const SLresult result{VCALL(mRecordObj,GetInterface)(SL_IID_ANDROIDSIMPLEBUFFERQUEUE,
  777. &bufferQueue)};
  778. PRINTERR(result, "recordObj->GetInterface");
  779. if(unlikely(SL_RESULT_SUCCESS != result))
  780. {
  781. mDevice->handleDisconnect("Failed to get capture buffer queue: 0x%08x", result);
  782. bufferQueue = nullptr;
  783. }
  784. }
  785. if(unlikely(!bufferQueue) || adv_count == 0)
  786. return;
  787. /* For each buffer chunk that was fully read, queue another writable buffer
  788. * chunk to keep the OpenSL queue full. This is rather convulated, as a
  789. * result of the ring buffer holding more elements than are writable at a
  790. * given time. The end of the write vector increments when the read pointer
  791. * advances, which will "expose" a previously unwritable element. So for
  792. * every element that we've finished reading, we queue that many elements
  793. * from the end of the write vector.
  794. */
  795. mRing->readAdvance(adv_count);
  796. SLresult result{SL_RESULT_SUCCESS};
  797. auto wdata = mRing->getWriteVector();
  798. if(likely(adv_count > wdata.second.len))
  799. {
  800. auto len1 = std::min(wdata.first.len, adv_count-wdata.second.len);
  801. auto buf1 = wdata.first.buf + chunk_size*(wdata.first.len-len1);
  802. for(size_t i{0u};i < len1 && SL_RESULT_SUCCESS == result;i++)
  803. {
  804. result = VCALL(bufferQueue,Enqueue)(buf1 + chunk_size*i, chunk_size);
  805. PRINTERR(result, "bufferQueue->Enqueue");
  806. }
  807. }
  808. if(wdata.second.len > 0)
  809. {
  810. auto len2 = std::min(wdata.second.len, adv_count);
  811. auto buf2 = wdata.second.buf + chunk_size*(wdata.second.len-len2);
  812. for(size_t i{0u};i < len2 && SL_RESULT_SUCCESS == result;i++)
  813. {
  814. result = VCALL(bufferQueue,Enqueue)(buf2 + chunk_size*i, chunk_size);
  815. PRINTERR(result, "bufferQueue->Enqueue");
  816. }
  817. }
  818. }
  819. uint OpenSLCapture::availableSamples()
  820. { return static_cast<uint>(mRing->readSpace()*mDevice->UpdateSize - mSplOffset); }
  821. } // namespace
  822. bool OSLBackendFactory::init() { return true; }
  823. bool OSLBackendFactory::querySupport(BackendType type)
  824. { return (type == BackendType::Playback || type == BackendType::Capture); }
  825. std::string OSLBackendFactory::probe(BackendType type)
  826. {
  827. std::string outnames;
  828. switch(type)
  829. {
  830. case BackendType::Playback:
  831. case BackendType::Capture:
  832. /* Includes null char. */
  833. outnames.append(opensl_device, sizeof(opensl_device));
  834. break;
  835. }
  836. return outnames;
  837. }
  838. BackendPtr OSLBackendFactory::createBackend(DeviceBase *device, BackendType type)
  839. {
  840. if(type == BackendType::Playback)
  841. return BackendPtr{new OpenSLPlayback{device}};
  842. if(type == BackendType::Capture)
  843. return BackendPtr{new OpenSLCapture{device}};
  844. return nullptr;
  845. }
  846. BackendFactory &OSLBackendFactory::getFactory()
  847. {
  848. static OSLBackendFactory factory{};
  849. return factory;
  850. }