opensl.cpp 31 KB

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