Audio plugin host https://kx.studio/carla
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.

1304 lines
51KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  20. DECLARE_JNI_CLASS (AndroidAudioManager, "android/media/AudioManager")
  21. #undef JNI_CLASS_MEMBERS
  22. //==============================================================================
  23. #ifndef SL_ANDROID_DATAFORMAT_PCM_EX
  24. #define SL_ANDROID_DATAFORMAT_PCM_EX ((SLuint32) 0x00000004)
  25. #endif
  26. #ifndef SL_ANDROID_PCM_REPRESENTATION_FLOAT
  27. #define SL_ANDROID_PCM_REPRESENTATION_FLOAT ((SLuint32) 0x00000003)
  28. #endif
  29. #ifndef SL_ANDROID_RECORDING_PRESET_UNPROCESSED
  30. #define SL_ANDROID_RECORDING_PRESET_UNPROCESSED ((SLuint32) 0x00000005)
  31. #endif
  32. //==============================================================================
  33. struct PCMDataFormatEx : SLDataFormat_PCM
  34. {
  35. SLuint32 representation;
  36. };
  37. //==============================================================================
  38. template <typename T> struct IntfIID;
  39. template <> struct IntfIID<SLObjectItf_> { static SLInterfaceID_ iid; };
  40. template <> struct IntfIID<SLEngineItf_> { static SLInterfaceID_ iid; };
  41. template <> struct IntfIID<SLOutputMixItf_> { static SLInterfaceID_ iid; };
  42. template <> struct IntfIID<SLPlayItf_> { static SLInterfaceID_ iid; };
  43. template <> struct IntfIID<SLRecordItf_> { static SLInterfaceID_ iid; };
  44. template <> struct IntfIID<SLAndroidSimpleBufferQueueItf_> { static SLInterfaceID_ iid; };
  45. template <> struct IntfIID<SLAndroidConfigurationItf_> { static SLInterfaceID_ iid; };
  46. SLInterfaceID_ IntfIID<SLObjectItf_>::iid = { 0x79216360, 0xddd7, 0x11db, 0xac16, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b} };
  47. SLInterfaceID_ IntfIID<SLEngineItf_>::iid = { 0x8d97c260, 0xddd4, 0x11db, 0x958f, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b} };
  48. SLInterfaceID_ IntfIID<SLOutputMixItf_>::iid = { 0x97750f60, 0xddd7, 0x11db, 0x92b1, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b} };
  49. SLInterfaceID_ IntfIID<SLPlayItf_>::iid = { 0xef0bd9c0, 0xddd7, 0x11db, 0xbf49, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b} };
  50. SLInterfaceID_ IntfIID<SLRecordItf_>::iid = { 0xc5657aa0, 0xdddb, 0x11db, 0x82f7, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b} };
  51. SLInterfaceID_ IntfIID<SLAndroidSimpleBufferQueueItf_>::iid = { 0x198e4940, 0xc5d7, 0x11df, 0xa2a6, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b} };
  52. SLInterfaceID_ IntfIID<SLAndroidConfigurationItf_>::iid = { 0x89f6a7e0, 0xbeac, 0x11df, 0x8b5c, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b} };
  53. template <typename SLObjectType>
  54. static void destroyObject (SLObjectType object)
  55. {
  56. if (object != nullptr && *object != nullptr)
  57. (*object)->Destroy (object);
  58. }
  59. struct SLObjectItfFree
  60. {
  61. void operator() (SLObjectItf obj) const noexcept
  62. {
  63. destroyObject (obj);
  64. }
  65. };
  66. //==============================================================================
  67. // Some life-time and type management of OpenSL objects
  68. class SlObjectRef
  69. {
  70. public:
  71. //==============================================================================
  72. SlObjectRef() noexcept {}
  73. SlObjectRef (const SlObjectRef& obj) noexcept : cb (obj.cb) {}
  74. SlObjectRef (SlObjectRef&& obj) noexcept : cb (std::move (obj.cb)) { obj.cb = nullptr; }
  75. explicit SlObjectRef (SLObjectItf o) : cb (new ControlBlock (o)) {}
  76. //==============================================================================
  77. SlObjectRef& operator= (const SlObjectRef& r) noexcept { cb = r.cb; return *this; }
  78. SlObjectRef& operator= (SlObjectRef&& r) noexcept { cb = std::move (r.cb); r.cb = nullptr; return *this; }
  79. SlObjectRef& operator= (std::nullptr_t) noexcept { cb = nullptr; return *this; }
  80. //==============================================================================
  81. const SLObjectItf_* operator*() noexcept { return *cb->ptr.get(); }
  82. SLObjectItf operator->() noexcept { return (cb == nullptr ? nullptr : cb->ptr.get()); }
  83. operator SLObjectItf() noexcept { return (cb == nullptr ? nullptr : cb->ptr.get()); }
  84. //==============================================================================
  85. bool operator== (nullptr_t) const noexcept { return (cb == nullptr || cb->ptr == nullptr); }
  86. bool operator!= (nullptr_t) const noexcept { return (cb != nullptr && cb->ptr != nullptr); }
  87. private:
  88. //==============================================================================
  89. struct ControlBlock : ReferenceCountedObject
  90. {
  91. ControlBlock() = default;
  92. ControlBlock (SLObjectItf o) : ptr (o) {}
  93. std::unique_ptr<const SLObjectItf_* const, SLObjectItfFree> ptr;
  94. };
  95. ReferenceCountedObjectPtr<ControlBlock> cb;
  96. };
  97. template <typename T>
  98. class SlRef : public SlObjectRef
  99. {
  100. public:
  101. //==============================================================================
  102. SlRef() noexcept {}
  103. SlRef (const SlRef& r) noexcept : SlObjectRef (r), type (r.type) {}
  104. SlRef (SlRef&& r) noexcept : SlObjectRef (std::move (r)), type (r.type) { r.type = nullptr; }
  105. //==============================================================================
  106. SlRef& operator= (const SlRef& r) noexcept { SlObjectRef::operator= (r); type = r.type; return *this; }
  107. SlRef& operator= (SlRef&& r) noexcept { SlObjectRef::operator= (std::move (r)); type = r.type; r.type = nullptr; return *this; }
  108. SlRef& operator= (std::nullptr_t) noexcept { SlObjectRef::operator= (nullptr); type = nullptr; return *this; }
  109. //==============================================================================
  110. T* const operator*() noexcept { return *type; }
  111. T* const* operator->() noexcept { return type; }
  112. operator T* const*() noexcept { return type; }
  113. //==============================================================================
  114. static SlRef cast (SlObjectRef& base) { return SlRef (base); }
  115. static SlRef cast (SlObjectRef&& base) { return SlRef (std::move (base)); }
  116. private:
  117. SlRef (SlObjectRef& base) : SlObjectRef (base)
  118. {
  119. if (auto obj = SlObjectRef::operator->())
  120. {
  121. auto err = (*obj)->GetInterface (obj, &IntfIID<T>::iid, &type);
  122. if (type != nullptr && err == SL_RESULT_SUCCESS)
  123. return;
  124. }
  125. *this = nullptr;
  126. }
  127. SlRef (SlObjectRef&& base) : SlObjectRef (std::move (base))
  128. {
  129. if (auto obj = SlObjectRef::operator->())
  130. {
  131. auto err = (*obj)->GetInterface (obj, &IntfIID<T>::iid, &type);
  132. base = nullptr;
  133. if (type != nullptr && err == SL_RESULT_SUCCESS)
  134. return;
  135. }
  136. *this = nullptr;
  137. }
  138. T* const* type = nullptr;
  139. };
  140. //==============================================================================
  141. template <typename T> struct BufferHelpers {};
  142. template <>
  143. struct BufferHelpers<int16>
  144. {
  145. enum { isFloatingPoint = 0 };
  146. static void initPCMDataFormat (PCMDataFormatEx& dataFormat, int numChannels, double sampleRate)
  147. {
  148. dataFormat.formatType = SL_DATAFORMAT_PCM;
  149. dataFormat.numChannels = (SLuint32) numChannels;
  150. dataFormat.samplesPerSec = (SLuint32) (sampleRate * 1000);
  151. dataFormat.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;
  152. dataFormat.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16;
  153. dataFormat.channelMask = (numChannels == 1) ? SL_SPEAKER_FRONT_CENTER :
  154. (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT);
  155. dataFormat.endianness = SL_BYTEORDER_LITTLEENDIAN;
  156. dataFormat.representation = 0;
  157. }
  158. static void prepareCallbackBuffer (AudioBuffer<float>&, int16*) {}
  159. static void convertFromOpenSL (const int16* srcInterleaved, AudioBuffer<float>& audioBuffer)
  160. {
  161. for (int i = 0; i < audioBuffer.getNumChannels(); ++i)
  162. {
  163. using DstSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst>;
  164. using SrcSampleType = AudioData::Pointer<AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>;
  165. DstSampleType dstData (audioBuffer.getWritePointer (i));
  166. SrcSampleType srcData (srcInterleaved + i, audioBuffer.getNumChannels());
  167. dstData.convertSamples (srcData, audioBuffer.getNumSamples());
  168. }
  169. }
  170. static void convertToOpenSL (const AudioBuffer<float>& audioBuffer, int16* dstInterleaved)
  171. {
  172. for (int i = 0; i < audioBuffer.getNumChannels(); ++i)
  173. {
  174. using DstSampleType = AudioData::Pointer<AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst>;
  175. using SrcSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const>;
  176. DstSampleType dstData (dstInterleaved + i, audioBuffer.getNumChannels());
  177. SrcSampleType srcData (audioBuffer.getReadPointer (i));
  178. dstData.convertSamples (srcData, audioBuffer.getNumSamples());
  179. }
  180. }
  181. };
  182. template <>
  183. struct BufferHelpers<float>
  184. {
  185. enum { isFloatingPoint = 1 };
  186. static void initPCMDataFormat (PCMDataFormatEx& dataFormat, int numChannels, double sampleRate)
  187. {
  188. dataFormat.formatType = SL_ANDROID_DATAFORMAT_PCM_EX;
  189. dataFormat.numChannels = (SLuint32) numChannels;
  190. dataFormat.samplesPerSec = (SLuint32) (sampleRate * 1000);
  191. dataFormat.bitsPerSample = 32;
  192. dataFormat.containerSize = 32;
  193. dataFormat.channelMask = (numChannels == 1) ? SL_SPEAKER_FRONT_CENTER :
  194. (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT);
  195. dataFormat.endianness = SL_BYTEORDER_LITTLEENDIAN;
  196. dataFormat.representation = SL_ANDROID_PCM_REPRESENTATION_FLOAT;
  197. }
  198. static void prepareCallbackBuffer (AudioBuffer<float>& audioBuffer, float* native)
  199. {
  200. if (audioBuffer.getNumChannels() == 1)
  201. audioBuffer.setDataToReferTo (&native, 1, audioBuffer.getNumSamples());
  202. }
  203. static void convertFromOpenSL (const float* srcInterleaved, AudioBuffer<float>& audioBuffer)
  204. {
  205. if (audioBuffer.getNumChannels() == 1)
  206. {
  207. jassert (srcInterleaved == audioBuffer.getWritePointer (0));
  208. return;
  209. }
  210. for (int i = 0; i < audioBuffer.getNumChannels(); ++i)
  211. {
  212. using DstSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst>;
  213. using SrcSampleType = AudioData::Pointer<AudioData::Float32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>;
  214. DstSampleType dstData (audioBuffer.getWritePointer (i));
  215. SrcSampleType srcData (srcInterleaved + i, audioBuffer.getNumChannels());
  216. dstData.convertSamples (srcData, audioBuffer.getNumSamples());
  217. }
  218. }
  219. static void convertToOpenSL (const AudioBuffer<float>& audioBuffer, float* dstInterleaved)
  220. {
  221. if (audioBuffer.getNumChannels() == 1)
  222. {
  223. jassert (dstInterleaved == audioBuffer.getReadPointer (0));
  224. return;
  225. }
  226. for (int i = 0; i < audioBuffer.getNumChannels(); ++i)
  227. {
  228. using DstSampleType = AudioData::Pointer<AudioData::Float32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst>;
  229. using SrcSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const>;
  230. DstSampleType dstData (dstInterleaved + i, audioBuffer.getNumChannels());
  231. SrcSampleType srcData (audioBuffer.getReadPointer (i));
  232. dstData.convertSamples (srcData, audioBuffer.getNumSamples());
  233. }
  234. }
  235. };
  236. //==============================================================================
  237. using CreateEngineFunc = SLresult (*) (SLObjectItf*, SLuint32, const SLEngineOption*,
  238. SLuint32, const SLInterfaceID*, const SLboolean*);
  239. struct OpenSLEngineHolder
  240. {
  241. OpenSLEngineHolder()
  242. {
  243. if (auto createEngine = (CreateEngineFunc) slLibrary.getFunction ("slCreateEngine"))
  244. {
  245. SLObjectItf obj = nullptr;
  246. auto err = createEngine (&obj, 0, nullptr, 0, nullptr, nullptr);
  247. if (err != SL_RESULT_SUCCESS || obj == nullptr || *obj == nullptr
  248. || (*obj)->Realize (obj, 0) != SL_RESULT_SUCCESS)
  249. {
  250. destroyObject (obj);
  251. }
  252. engine = SlRef<SLEngineItf_>::cast (SlObjectRef (obj));
  253. }
  254. }
  255. DynamicLibrary slLibrary { "libOpenSLES.so" };
  256. SlRef<SLEngineItf_> engine;
  257. };
  258. OpenSLEngineHolder& getEngineHolder()
  259. {
  260. static OpenSLEngineHolder holder;
  261. return holder;
  262. }
  263. //==============================================================================
  264. class SLRealtimeThread;
  265. //==============================================================================
  266. class OpenSLAudioIODevice : public AudioIODevice
  267. {
  268. public:
  269. //==============================================================================
  270. template <typename T>
  271. class OpenSLSessionT;
  272. //==============================================================================
  273. // CRTP
  274. template <typename T, class Child, typename RunnerObjectType>
  275. struct OpenSLQueueRunner
  276. {
  277. OpenSLQueueRunner (OpenSLSessionT<T>& sessionToUse, int numChannelsToUse)
  278. : owner (sessionToUse),
  279. numChannels (numChannelsToUse),
  280. nativeBuffer (static_cast<size_t> (numChannels * owner.bufferSize * owner.numBuffers)),
  281. scratchBuffer (numChannelsToUse, owner.bufferSize),
  282. sampleBuffer (scratchBuffer.getArrayOfWritePointers(), numChannelsToUse, owner.bufferSize)
  283. {}
  284. ~OpenSLQueueRunner()
  285. {
  286. if (config != nullptr && javaProxy != nullptr)
  287. {
  288. javaProxy.clear();
  289. (*config)->ReleaseJavaProxy (config, /*SL_ANDROID_JAVA_PROXY_ROUTING*/1);
  290. }
  291. }
  292. bool init()
  293. {
  294. runner = crtp().createPlayerOrRecorder();
  295. if (runner == nullptr)
  296. return false;
  297. const bool supportsJavaProxy = (getAndroidSDKVersion() >= 24);
  298. if (supportsJavaProxy)
  299. {
  300. // may return nullptr on some platforms - that's ok
  301. config = SlRef<SLAndroidConfigurationItf_>::cast (runner);
  302. if (config != nullptr)
  303. {
  304. jobject audioRoutingJni;
  305. auto status = (*config)->AcquireJavaProxy (config, /*SL_ANDROID_JAVA_PROXY_ROUTING*/1,
  306. &audioRoutingJni);
  307. if (status == SL_RESULT_SUCCESS && audioRoutingJni != nullptr)
  308. javaProxy = GlobalRef (LocalRef<jobject>(getEnv()->NewLocalRef (audioRoutingJni)));
  309. }
  310. }
  311. queue = SlRef<SLAndroidSimpleBufferQueueItf_>::cast (runner);
  312. if (queue == nullptr)
  313. return false;
  314. return ((*queue)->RegisterCallback (queue, staticFinished, this) == SL_RESULT_SUCCESS);
  315. }
  316. void clear()
  317. {
  318. nextBlock.set (0);
  319. numBlocksOut.set (0);
  320. zeromem (nativeBuffer.get(), static_cast<size_t> (owner.bufferSize * numChannels * owner.numBuffers) * sizeof (T));
  321. scratchBuffer.clear();
  322. (*queue)->Clear (queue);
  323. }
  324. void enqueueBuffer()
  325. {
  326. (*queue)->Enqueue (queue, getCurrentBuffer(), static_cast<SLuint32> (getBufferSizeInSamples() * sizeof (T)));
  327. ++numBlocksOut;
  328. }
  329. bool isBufferAvailable() const { return (numBlocksOut.get() < owner.numBuffers); }
  330. T* getNextBuffer() { nextBlock.set((nextBlock.get() + 1) % owner.numBuffers); return getCurrentBuffer(); }
  331. T* getCurrentBuffer() { return nativeBuffer.get() + (static_cast<size_t> (nextBlock.get()) * getBufferSizeInSamples()); }
  332. size_t getBufferSizeInSamples() const { return static_cast<size_t> (owner.bufferSize * numChannels); }
  333. void finished (SLAndroidSimpleBufferQueueItf)
  334. {
  335. --numBlocksOut;
  336. owner.doSomeWorkOnAudioThread();
  337. }
  338. static void staticFinished (SLAndroidSimpleBufferQueueItf caller, void *pContext)
  339. {
  340. reinterpret_cast<OpenSLQueueRunner*> (pContext)->finished (caller);
  341. }
  342. // get the "this" pointer for CRTP
  343. Child& crtp() { return * ((Child*) this); }
  344. const Child& crtp() const { return * ((Child*) this); }
  345. OpenSLSessionT<T>& owner;
  346. SlRef<RunnerObjectType> runner;
  347. SlRef<SLAndroidSimpleBufferQueueItf_> queue;
  348. SlRef<SLAndroidConfigurationItf_> config;
  349. GlobalRef javaProxy;
  350. int numChannels;
  351. HeapBlock<T> nativeBuffer;
  352. AudioBuffer<float> scratchBuffer, sampleBuffer;
  353. Atomic<int> nextBlock { 0 }, numBlocksOut { 0 };
  354. };
  355. //==============================================================================
  356. template <typename T>
  357. struct OpenSLQueueRunnerPlayer : OpenSLQueueRunner<T, OpenSLQueueRunnerPlayer<T>, SLPlayItf_>
  358. {
  359. using Base = OpenSLQueueRunner<T, OpenSLQueueRunnerPlayer<T>, SLPlayItf_>;
  360. OpenSLQueueRunnerPlayer (OpenSLSessionT<T>& sessionToUse, int numChannelsToUse)
  361. : Base (sessionToUse, numChannelsToUse)
  362. {}
  363. SlRef<SLPlayItf_> createPlayerOrRecorder()
  364. {
  365. SLDataLocator_AndroidSimpleBufferQueue queueLocator = { SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, static_cast<SLuint32> (Base::owner.numBuffers) };
  366. SLDataLocator_OutputMix outputMix = { SL_DATALOCATOR_OUTPUTMIX, Base::owner.outputMix };
  367. PCMDataFormatEx dataFormat;
  368. BufferHelpers<T>::initPCMDataFormat (dataFormat, Base::numChannels, Base::owner.sampleRate);
  369. SLDataSource source = { &queueLocator, &dataFormat };
  370. SLDataSink sink = { &outputMix, nullptr };
  371. SLInterfaceID queueInterfaces[] = { &IntfIID<SLAndroidSimpleBufferQueueItf_>::iid, &IntfIID<SLAndroidConfigurationItf_>::iid };
  372. SLboolean interfaceRequired[] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_FALSE};
  373. SLObjectItf obj = nullptr;
  374. auto& holder = getEngineHolder();
  375. if (auto e = *holder.engine)
  376. {
  377. auto status = e->CreateAudioPlayer (holder.engine, &obj, &source, &sink, 2,
  378. queueInterfaces, interfaceRequired);
  379. if (status != SL_RESULT_SUCCESS || obj == nullptr || (*obj)->Realize(obj, 0) != SL_RESULT_SUCCESS)
  380. {
  381. destroyObject (obj);
  382. return {};
  383. }
  384. }
  385. return SlRef<SLPlayItf_>::cast (SlObjectRef (obj));
  386. }
  387. void setState (bool running) { (*Base::runner)->SetPlayState (Base::runner, running ? SL_PLAYSTATE_PLAYING : SL_PLAYSTATE_STOPPED); }
  388. };
  389. template <typename T>
  390. struct OpenSLQueueRunnerRecorder : public OpenSLQueueRunner<T, OpenSLQueueRunnerRecorder<T>, SLRecordItf_>
  391. {
  392. using Base = OpenSLQueueRunner<T, OpenSLQueueRunnerRecorder<T>, SLRecordItf_>;
  393. OpenSLQueueRunnerRecorder (OpenSLSessionT<T>& sessionToUse, int numChannelsToUse)
  394. : Base (sessionToUse, numChannelsToUse)
  395. {}
  396. SlRef<SLRecordItf_> createPlayerOrRecorder()
  397. {
  398. SLDataLocator_IODevice ioDeviceLocator = { SL_DATALOCATOR_IODEVICE, SL_IODEVICE_AUDIOINPUT, SL_DEFAULTDEVICEID_AUDIOINPUT, nullptr };
  399. SLDataLocator_AndroidSimpleBufferQueue queueLocator = { SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, static_cast<SLuint32> (Base::owner.numBuffers) };
  400. PCMDataFormatEx dataFormat;
  401. BufferHelpers<T>::initPCMDataFormat (dataFormat, Base::numChannels, Base::owner.sampleRate);
  402. SLDataSource source = { &ioDeviceLocator, nullptr };
  403. SLDataSink sink = { &queueLocator, &dataFormat };
  404. SLInterfaceID queueInterfaces[] = { &IntfIID<SLAndroidSimpleBufferQueueItf_>::iid, &IntfIID<SLAndroidConfigurationItf_>::iid };
  405. SLboolean interfaceRequired[] = { SL_BOOLEAN_TRUE, SL_BOOLEAN_FALSE };
  406. SLObjectItf obj = nullptr;
  407. auto& holder = getEngineHolder();
  408. if (auto e = *holder.engine)
  409. {
  410. auto status = e->CreateAudioRecorder (holder.engine, &obj, &source, &sink, 2, queueInterfaces, interfaceRequired);
  411. if (status != SL_RESULT_SUCCESS || obj == nullptr || (*obj)->Realize (obj, 0) != SL_RESULT_SUCCESS)
  412. {
  413. destroyObject (obj);
  414. return {};
  415. }
  416. }
  417. return SlRef<SLRecordItf_>::cast (SlObjectRef (obj));
  418. }
  419. bool setAudioPreprocessingEnabled (bool shouldEnable)
  420. {
  421. if (Base::config != nullptr)
  422. {
  423. const bool supportsUnprocessed = (getAndroidSDKVersion() >= 25);
  424. const SLuint32 recordingPresetValue
  425. = (shouldEnable ? SL_ANDROID_RECORDING_PRESET_GENERIC
  426. : (supportsUnprocessed ? SL_ANDROID_RECORDING_PRESET_UNPROCESSED
  427. : SL_ANDROID_RECORDING_PRESET_VOICE_RECOGNITION));
  428. auto status = (*Base::config)->SetConfiguration (Base::config, SL_ANDROID_KEY_RECORDING_PRESET,
  429. &recordingPresetValue, sizeof (recordingPresetValue));
  430. return (status == SL_RESULT_SUCCESS);
  431. }
  432. return false;
  433. }
  434. void setState (bool running) { (*Base::runner)->SetRecordState (Base::runner, running ? SL_RECORDSTATE_RECORDING
  435. : SL_RECORDSTATE_STOPPED); }
  436. };
  437. //==============================================================================
  438. class OpenSLSession
  439. {
  440. public:
  441. OpenSLSession (int numInputChannels, int numOutputChannels,
  442. double samleRateToUse, int bufferSizeToUse,
  443. int numBuffersToUse)
  444. : inputChannels (numInputChannels), outputChannels (numOutputChannels),
  445. sampleRate (samleRateToUse), bufferSize (bufferSizeToUse), numBuffers (numBuffersToUse)
  446. {
  447. jassert (numInputChannels > 0 || numOutputChannels > 0);
  448. if (outputChannels > 0)
  449. {
  450. auto& holder = getEngineHolder();
  451. SLObjectItf obj = nullptr;
  452. auto err = (*holder.engine)->CreateOutputMix (holder.engine, &obj, 0, nullptr, nullptr);
  453. if (err != SL_RESULT_SUCCESS || obj == nullptr || *obj == nullptr
  454. || (*obj)->Realize (obj, 0) != SL_RESULT_SUCCESS)
  455. {
  456. destroyObject (obj);
  457. return;
  458. }
  459. outputMix = SlRef<SLOutputMixItf_>::cast (SlObjectRef (obj));
  460. }
  461. }
  462. virtual ~OpenSLSession() {}
  463. virtual bool openedOK() const { return (outputChannels == 0 || outputMix != nullptr); }
  464. virtual void start() { stop(); jassert (callback.get() != nullptr); running = true; }
  465. virtual void stop() { running = false; }
  466. virtual bool setAudioPreprocessingEnabled (bool shouldEnable) = 0;
  467. virtual bool supportsFloatingPoint() const noexcept = 0;
  468. virtual int getXRunCount() const noexcept = 0;
  469. void setCallback (AudioIODeviceCallback* callbackToUse)
  470. {
  471. if (! running)
  472. {
  473. callback.set (callbackToUse);
  474. return;
  475. }
  476. // don't set callback to null! stop the playback instead!
  477. jassert (callbackToUse != nullptr);
  478. // spin-lock until we can set the callback
  479. for (;;)
  480. {
  481. auto old = callback.get();
  482. if (old == callbackToUse)
  483. break;
  484. if (callback.compareAndSetBool (callbackToUse, old))
  485. break;
  486. Thread::sleep (1);
  487. }
  488. }
  489. void process (const float** inputChannelData, float** outputChannelData)
  490. {
  491. if (auto* cb = callback.exchange (nullptr))
  492. {
  493. cb->audioDeviceIOCallback (inputChannelData, inputChannels, outputChannelData, outputChannels, bufferSize);
  494. callback.set (cb);
  495. }
  496. else
  497. {
  498. for (int i = 0; i < outputChannels; ++i)
  499. zeromem (outputChannelData[i], sizeof(float) * static_cast<size_t> (bufferSize));
  500. }
  501. }
  502. static OpenSLSession* create (int numInputChannels, int numOutputChannels,
  503. double samleRateToUse, int bufferSizeToUse,
  504. int numBuffersToUse);
  505. //==============================================================================
  506. int inputChannels, outputChannels;
  507. double sampleRate;
  508. int bufferSize, numBuffers;
  509. bool running = false, audioProcessingEnabled = true;
  510. SlRef<SLOutputMixItf_> outputMix;
  511. Atomic<AudioIODeviceCallback*> callback { nullptr };
  512. };
  513. template <typename T>
  514. class OpenSLSessionT : public OpenSLSession
  515. {
  516. public:
  517. OpenSLSessionT (int numInputChannels, int numOutputChannels,
  518. double samleRateToUse, int bufferSizeToUse,
  519. int numBuffersToUse)
  520. : OpenSLSession (numInputChannels, numOutputChannels,
  521. samleRateToUse, bufferSizeToUse, numBuffersToUse)
  522. {
  523. jassert (numInputChannels > 0 || numOutputChannels > 0);
  524. if (OpenSLSession::openedOK())
  525. {
  526. if (inputChannels > 0)
  527. {
  528. recorder.reset (new OpenSLQueueRunnerRecorder<T> (*this, inputChannels));
  529. if (! recorder->init())
  530. {
  531. recorder = nullptr;
  532. return;
  533. }
  534. }
  535. if (outputChannels > 0)
  536. {
  537. player.reset (new OpenSLQueueRunnerPlayer<T> (*this, outputChannels));
  538. if (! player->init())
  539. {
  540. player = nullptr;
  541. return;
  542. }
  543. const bool supportsUnderrunCount = (getAndroidSDKVersion() >= 24);
  544. getUnderrunCount = supportsUnderrunCount ? getEnv()->GetMethodID (AudioTrack, "getUnderrunCount", "()I") : nullptr;
  545. }
  546. }
  547. }
  548. bool openedOK() const override
  549. {
  550. return OpenSLSession::openedOK() && (inputChannels == 0 || recorder != nullptr)
  551. && (outputChannels == 0 || player != nullptr);
  552. }
  553. void start() override
  554. {
  555. OpenSLSession::start();
  556. guard.set (0);
  557. if (inputChannels > 0)
  558. recorder->clear();
  559. if (outputChannels > 0)
  560. player->clear();
  561. // first enqueue all buffers
  562. for (int i = 0; i < numBuffers; ++i)
  563. doSomeWorkOnAudioThread();
  564. if (inputChannels > 0)
  565. recorder->setState (true);
  566. if (outputChannels > 0)
  567. player->setState (true);
  568. }
  569. void stop() override
  570. {
  571. OpenSLSession::stop();
  572. while (! guard.compareAndSetBool (1, 0))
  573. Thread::sleep (1);
  574. if (inputChannels > 0)
  575. recorder->setState (false);
  576. if (outputChannels > 0)
  577. player->setState (false);
  578. guard.set (0);
  579. }
  580. bool setAudioPreprocessingEnabled (bool shouldEnable) override
  581. {
  582. if (shouldEnable != audioProcessingEnabled)
  583. {
  584. audioProcessingEnabled = shouldEnable;
  585. if (recorder != nullptr)
  586. return recorder->setAudioPreprocessingEnabled (audioProcessingEnabled);
  587. }
  588. return true;
  589. }
  590. int getXRunCount() const noexcept override
  591. {
  592. if (player != nullptr && player->javaProxy != nullptr && getUnderrunCount != nullptr)
  593. return getEnv()->CallIntMethod (player->javaProxy, getUnderrunCount);
  594. return -1;
  595. }
  596. bool supportsFloatingPoint() const noexcept override { return (BufferHelpers<T>::isFloatingPoint != 0); }
  597. void doSomeWorkOnAudioThread()
  598. {
  599. // only the player or the recorder should enter this section at any time
  600. if (guard.compareAndSetBool (1, 0))
  601. {
  602. // are there enough buffers available to process some audio
  603. if ((inputChannels == 0 || recorder->isBufferAvailable()) && (outputChannels == 0 || player->isBufferAvailable()))
  604. {
  605. T* recorderBuffer = (inputChannels > 0 ? recorder->getNextBuffer() : nullptr);
  606. T* playerBuffer = (outputChannels > 0 ? player->getNextBuffer() : nullptr);
  607. const float** inputChannelData = nullptr;
  608. float** outputChannelData = nullptr;
  609. if (recorderBuffer != nullptr)
  610. {
  611. BufferHelpers<T>::prepareCallbackBuffer (recorder->sampleBuffer, recorderBuffer);
  612. BufferHelpers<T>::convertFromOpenSL (recorderBuffer, recorder->sampleBuffer);
  613. inputChannelData = recorder->sampleBuffer.getArrayOfReadPointers();
  614. }
  615. if (playerBuffer != nullptr)
  616. {
  617. BufferHelpers<T>::prepareCallbackBuffer (player->sampleBuffer, playerBuffer);
  618. outputChannelData = player->sampleBuffer.getArrayOfWritePointers();
  619. }
  620. process (inputChannelData, outputChannelData);
  621. if (recorderBuffer != nullptr)
  622. recorder->enqueueBuffer();
  623. if (playerBuffer != nullptr)
  624. {
  625. BufferHelpers<T>::convertToOpenSL (player->sampleBuffer, playerBuffer);
  626. player->enqueueBuffer();
  627. }
  628. }
  629. guard.set (0);
  630. }
  631. }
  632. //==============================================================================
  633. std::unique_ptr<OpenSLQueueRunnerPlayer<T>> player;
  634. std::unique_ptr<OpenSLQueueRunnerRecorder<T>> recorder;
  635. Atomic<int> guard;
  636. jmethodID getUnderrunCount = nullptr;
  637. };
  638. //==============================================================================
  639. OpenSLAudioIODevice (const String& deviceName) : AudioIODevice (deviceName, openSLTypeName)
  640. {
  641. // OpenSL has piss-poor support for determining latency, so the only way I can find to
  642. // get a number for this is by asking the AudioTrack/AudioRecord classes..
  643. AndroidAudioIODevice javaDevice (deviceName);
  644. // this is a total guess about how to calculate the latency, but seems to vaguely agree
  645. // with the devices I've tested.. YMMV
  646. inputLatency = (javaDevice.minBufferSizeIn * 2) / 3;
  647. outputLatency = (javaDevice.minBufferSizeOut * 2) / 3;
  648. const int64 longestLatency = jmax (inputLatency, outputLatency);
  649. const int64 totalLatency = inputLatency + outputLatency;
  650. inputLatency = (int) ((longestLatency * inputLatency) / totalLatency) & ~15;
  651. outputLatency = (int) ((longestLatency * outputLatency) / totalLatency) & ~15;
  652. // You can only create this class if you are sure that your hardware supports OpenSL
  653. jassert (getEngineHolder().slLibrary.getNativeHandle() != nullptr);
  654. }
  655. ~OpenSLAudioIODevice() override
  656. {
  657. close();
  658. }
  659. bool openedOk() const { return session != nullptr; }
  660. StringArray getOutputChannelNames() override
  661. {
  662. StringArray s;
  663. s.add ("Left");
  664. s.add ("Right");
  665. return s;
  666. }
  667. StringArray getInputChannelNames() override
  668. {
  669. StringArray s;
  670. s.add ("Audio Input");
  671. return s;
  672. }
  673. Array<double> getAvailableSampleRates() override
  674. {
  675. // see https://developer.android.com/ndk/guides/audio/opensl-for-android.html
  676. static const double rates[] = { 8000.0, 11025.0, 12000.0, 16000.0,
  677. 22050.0, 24000.0, 32000.0, 44100.0, 48000.0 };
  678. Array<double> retval (rates, numElementsInArray (rates));
  679. // make sure the native sample rate is part of the list
  680. double native = AndroidHighPerformanceAudioHelpers::getNativeSampleRate();
  681. if (native != 0.0 && ! retval.contains (native))
  682. retval.add (native);
  683. return retval;
  684. }
  685. Array<int> getAvailableBufferSizes() override
  686. {
  687. return AndroidHighPerformanceAudioHelpers::getAvailableBufferSizes (AndroidHighPerformanceAudioHelpers::getNativeBufferSizeHint(),
  688. getAvailableSampleRates());
  689. }
  690. String open (const BigInteger& inputChannels,
  691. const BigInteger& outputChannels,
  692. double requestedSampleRate,
  693. int bufferSize) override
  694. {
  695. close();
  696. lastError.clear();
  697. sampleRate = (int) (requestedSampleRate > 0 ? requestedSampleRate : AndroidHighPerformanceAudioHelpers::getNativeSampleRate());
  698. auto preferredBufferSize = (bufferSize > 0) ? bufferSize : getDefaultBufferSize();
  699. audioBuffersToEnqueue = [this, preferredBufferSize]
  700. {
  701. using namespace AndroidHighPerformanceAudioHelpers;
  702. auto nativeBufferSize = getNativeBufferSizeHint();
  703. if (canUseHighPerformanceAudioPath (nativeBufferSize, preferredBufferSize, sampleRate))
  704. return preferredBufferSize / nativeBufferSize;
  705. return 1;
  706. }();
  707. actualBufferSize = preferredBufferSize / audioBuffersToEnqueue;
  708. jassert ((actualBufferSize * audioBuffersToEnqueue) == preferredBufferSize);
  709. activeOutputChans = outputChannels;
  710. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  711. auto numOutputChannels = activeOutputChans.countNumberOfSetBits();
  712. activeInputChans = inputChannels;
  713. activeInputChans.setRange (1, activeInputChans.getHighestBit(), false);
  714. auto numInputChannels = activeInputChans.countNumberOfSetBits();
  715. if (numInputChannels > 0 && (! RuntimePermissions::isGranted (RuntimePermissions::recordAudio)))
  716. {
  717. // If you hit this assert, you probably forgot to get RuntimePermissions::recordAudio
  718. // before trying to open an audio input device. This is not going to work!
  719. jassertfalse;
  720. lastError = "Error opening OpenSL input device: the app was not granted android.permission.RECORD_AUDIO";
  721. }
  722. session.reset (OpenSLSession::create (numInputChannels, numOutputChannels,
  723. sampleRate, actualBufferSize, audioBuffersToEnqueue));
  724. if (session != nullptr)
  725. {
  726. session->setAudioPreprocessingEnabled (audioProcessingEnabled);
  727. }
  728. else
  729. {
  730. if (numInputChannels > 0 && numOutputChannels > 0 && RuntimePermissions::isGranted (RuntimePermissions::recordAudio))
  731. {
  732. // New versions of the Android emulator do not seem to support audio input anymore on OS X
  733. activeInputChans = BigInteger(0);
  734. numInputChannels = 0;
  735. session.reset (OpenSLSession::create (numInputChannels, numOutputChannels,
  736. sampleRate, actualBufferSize, audioBuffersToEnqueue));
  737. }
  738. }
  739. DBG ("OpenSL: numInputChannels = " << numInputChannels
  740. << ", numOutputChannels = " << numOutputChannels
  741. << ", nativeBufferSize = " << AndroidHighPerformanceAudioHelpers::getNativeBufferSizeHint()
  742. << ", nativeSampleRate = " << AndroidHighPerformanceAudioHelpers::getNativeSampleRate()
  743. << ", actualBufferSize = " << actualBufferSize
  744. << ", audioBuffersToEnqueue = " << audioBuffersToEnqueue
  745. << ", sampleRate = " << sampleRate
  746. << ", supportsFloatingPoint = " << (session != nullptr && session->supportsFloatingPoint() ? "true" : "false"));
  747. if (session == nullptr)
  748. lastError = "Unknown error initializing opensl session";
  749. deviceOpen = (session != nullptr);
  750. return lastError;
  751. }
  752. void close() override
  753. {
  754. stop();
  755. session = nullptr;
  756. callback = nullptr;
  757. }
  758. int getOutputLatencyInSamples() override { return outputLatency; }
  759. int getInputLatencyInSamples() override { return inputLatency; }
  760. bool isOpen() override { return deviceOpen; }
  761. int getCurrentBufferSizeSamples() override { return actualBufferSize * audioBuffersToEnqueue; }
  762. int getCurrentBitDepth() override { return (session != nullptr && session->supportsFloatingPoint() ? 32 : 16); }
  763. BigInteger getActiveOutputChannels() const override { return activeOutputChans; }
  764. BigInteger getActiveInputChannels() const override { return activeInputChans; }
  765. String getLastError() override { return lastError; }
  766. bool isPlaying() override { return callback != nullptr; }
  767. int getXRunCount() const noexcept override { return (session != nullptr ? session->getXRunCount() : -1); }
  768. int getDefaultBufferSize() override
  769. {
  770. return AndroidHighPerformanceAudioHelpers::getDefaultBufferSize (AndroidHighPerformanceAudioHelpers::getNativeBufferSizeHint(),
  771. getCurrentSampleRate());
  772. }
  773. double getCurrentSampleRate() override
  774. {
  775. return (sampleRate == 0.0 ? AndroidHighPerformanceAudioHelpers::getNativeSampleRate() : sampleRate);
  776. }
  777. void start (AudioIODeviceCallback* newCallback) override
  778. {
  779. if (session != nullptr && callback != newCallback)
  780. {
  781. auto oldCallback = callback;
  782. if (newCallback != nullptr)
  783. newCallback->audioDeviceAboutToStart (this);
  784. if (oldCallback != nullptr)
  785. {
  786. // already running
  787. if (newCallback == nullptr)
  788. stop();
  789. else
  790. session->setCallback (newCallback);
  791. oldCallback->audioDeviceStopped();
  792. }
  793. else
  794. {
  795. jassert (newCallback != nullptr);
  796. // session hasn't started yet
  797. session->setCallback (newCallback);
  798. session->start();
  799. }
  800. callback = newCallback;
  801. }
  802. }
  803. void stop() override
  804. {
  805. if (session != nullptr && callback != nullptr)
  806. {
  807. callback = nullptr;
  808. session->stop();
  809. session->setCallback (nullptr);
  810. }
  811. }
  812. bool setAudioPreprocessingEnabled (bool shouldAudioProcessingBeEnabled) override
  813. {
  814. audioProcessingEnabled = shouldAudioProcessingBeEnabled;
  815. if (session != nullptr)
  816. session->setAudioPreprocessingEnabled (audioProcessingEnabled);
  817. return true;
  818. }
  819. static const char* const openSLTypeName;
  820. private:
  821. //==============================================================================
  822. friend class SLRealtimeThread;
  823. //==============================================================================
  824. int actualBufferSize = 0, sampleRate = 0, audioBuffersToEnqueue = 0;
  825. int inputLatency, outputLatency;
  826. bool deviceOpen = false, audioProcessingEnabled = true;
  827. String lastError;
  828. BigInteger activeOutputChans, activeInputChans;
  829. AudioIODeviceCallback* callback = nullptr;
  830. std::unique_ptr<OpenSLSession> session;
  831. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenSLAudioIODevice)
  832. };
  833. OpenSLAudioIODevice::OpenSLSession* OpenSLAudioIODevice::OpenSLSession::create (int numInputChannels, int numOutputChannels,
  834. double samleRateToUse, int bufferSizeToUse,
  835. int numBuffersToUse)
  836. {
  837. std::unique_ptr<OpenSLSession> retval;
  838. auto sdkVersion = getAndroidSDKVersion();
  839. // SDK versions 21 and higher should natively support floating point...
  840. if (sdkVersion >= 21)
  841. {
  842. retval.reset (new OpenSLSessionT<float> (numInputChannels, numOutputChannels, samleRateToUse,
  843. bufferSizeToUse, numBuffersToUse));
  844. // ...however, some devices lie so re-try without floating point
  845. if (retval != nullptr && (! retval->openedOK()))
  846. retval = nullptr;
  847. }
  848. if (retval == nullptr)
  849. {
  850. retval.reset (new OpenSLSessionT<int16> (numInputChannels, numOutputChannels, samleRateToUse,
  851. bufferSizeToUse, numBuffersToUse));
  852. if (retval != nullptr && (! retval->openedOK()))
  853. retval = nullptr;
  854. }
  855. return retval.release();
  856. }
  857. //==============================================================================
  858. class OpenSLAudioDeviceType : public AudioIODeviceType
  859. {
  860. public:
  861. OpenSLAudioDeviceType() : AudioIODeviceType (OpenSLAudioIODevice::openSLTypeName) {}
  862. //==============================================================================
  863. void scanForDevices() override {}
  864. StringArray getDeviceNames (bool) const override { return StringArray (OpenSLAudioIODevice::openSLTypeName); }
  865. int getDefaultDeviceIndex (bool) const override { return 0; }
  866. int getIndexOfDevice (AudioIODevice* device, bool) const override { return device != nullptr ? 0 : -1; }
  867. bool hasSeparateInputsAndOutputs() const override { return false; }
  868. AudioIODevice* createDevice (const String& outputDeviceName,
  869. const String& inputDeviceName) override
  870. {
  871. std::unique_ptr<OpenSLAudioIODevice> dev;
  872. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  873. dev.reset (new OpenSLAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  874. : inputDeviceName));
  875. return dev.release();
  876. }
  877. static bool isOpenSLAvailable()
  878. {
  879. DynamicLibrary library;
  880. return library.open ("libOpenSLES.so");
  881. }
  882. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenSLAudioDeviceType)
  883. };
  884. const char* const OpenSLAudioIODevice::openSLTypeName = "Android OpenSL";
  885. //==============================================================================
  886. bool isOpenSLAvailable() { return OpenSLAudioDeviceType::isOpenSLAvailable(); }
  887. //==============================================================================
  888. class SLRealtimeThread
  889. {
  890. public:
  891. static constexpr int numBuffers = 4;
  892. SLRealtimeThread()
  893. {
  894. if (auto createEngine = (CreateEngineFunc) slLibrary.getFunction ("slCreateEngine"))
  895. {
  896. SLObjectItf obj = nullptr;
  897. auto err = createEngine (&obj, 0, nullptr, 0, nullptr, nullptr);
  898. if (err != SL_RESULT_SUCCESS || obj == nullptr || *obj == nullptr)
  899. return;
  900. if ((*obj)->Realize (obj, 0) != SL_RESULT_SUCCESS)
  901. {
  902. destroyObject (obj);
  903. return;
  904. }
  905. engine = SlRef<SLEngineItf_>::cast (SlObjectRef (obj));
  906. if (engine == nullptr)
  907. {
  908. destroyObject (obj);
  909. return;
  910. }
  911. obj = nullptr;
  912. err = (*engine)->CreateOutputMix (engine, &obj, 0, nullptr, nullptr);
  913. if (err != SL_RESULT_SUCCESS || obj == nullptr || (*obj)->Realize (obj, 0) != SL_RESULT_SUCCESS)
  914. {
  915. destroyObject (obj);
  916. return;
  917. }
  918. outputMix = SlRef<SLOutputMixItf_>::cast (SlObjectRef (obj));
  919. if (outputMix == nullptr)
  920. {
  921. destroyObject (obj);
  922. return;
  923. }
  924. SLDataLocator_AndroidSimpleBufferQueue queueLocator = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, static_cast<SLuint32> (numBuffers)};
  925. SLDataLocator_OutputMix outputMixLocator = {SL_DATALOCATOR_OUTPUTMIX, outputMix};
  926. PCMDataFormatEx dataFormat;
  927. BufferHelpers<int16>::initPCMDataFormat (dataFormat, 1, AndroidHighPerformanceAudioHelpers::getNativeSampleRate());
  928. SLDataSource source = { &queueLocator, &dataFormat };
  929. SLDataSink sink = { &outputMixLocator, nullptr };
  930. SLInterfaceID queueInterfaces[] = { &IntfIID<SLAndroidSimpleBufferQueueItf_>::iid };
  931. SLboolean trueFlag = SL_BOOLEAN_TRUE;
  932. obj = nullptr;
  933. err = (*engine)->CreateAudioPlayer (engine, &obj, &source, &sink, 1, queueInterfaces, &trueFlag);
  934. if (err != SL_RESULT_SUCCESS || obj == nullptr)
  935. return;
  936. if ((*obj)->Realize (obj, 0) != SL_RESULT_SUCCESS)
  937. {
  938. destroyObject (obj);
  939. return;
  940. }
  941. player = SlRef<SLPlayItf_>::cast (SlObjectRef (obj));
  942. if (player == nullptr)
  943. {
  944. destroyObject (obj);
  945. return;
  946. }
  947. queue = SlRef<SLAndroidSimpleBufferQueueItf_>::cast (player);
  948. if (queue == nullptr)
  949. return;
  950. if ((*queue)->RegisterCallback (queue, staticFinished, this) != SL_RESULT_SUCCESS)
  951. {
  952. queue = nullptr;
  953. return;
  954. }
  955. pthread_cond_init (&threadReady, nullptr);
  956. pthread_mutex_init (&threadReadyMutex, nullptr);
  957. }
  958. }
  959. bool isOk() const { return queue != nullptr; }
  960. pthread_t startThread (void* (*entry) (void*), void* userPtr)
  961. {
  962. memset (buffer.get(), 0, static_cast<size_t> (sizeof (int16) * static_cast<size_t> (bufferSize * numBuffers)));
  963. for (int i = 0; i < numBuffers; ++i)
  964. {
  965. int16* dst = buffer.get() + (bufferSize * i);
  966. (*queue)->Enqueue (queue, dst, static_cast<SLuint32> (static_cast<size_t> (bufferSize) * sizeof (int16)));
  967. }
  968. pthread_mutex_lock (&threadReadyMutex);
  969. threadEntryProc = entry;
  970. threadUserPtr = userPtr;
  971. (*player)->SetPlayState (player, SL_PLAYSTATE_PLAYING);
  972. pthread_cond_wait (&threadReady, &threadReadyMutex);
  973. pthread_mutex_unlock (&threadReadyMutex);
  974. return threadID;
  975. }
  976. void finished()
  977. {
  978. if (threadEntryProc != nullptr)
  979. {
  980. pthread_mutex_lock (&threadReadyMutex);
  981. threadID = pthread_self();
  982. pthread_cond_signal (&threadReady);
  983. pthread_mutex_unlock (&threadReadyMutex);
  984. threadEntryProc (threadUserPtr);
  985. threadEntryProc = nullptr;
  986. (*player)->SetPlayState (player, SL_PLAYSTATE_STOPPED);
  987. MessageManager::callAsync ([this]() { delete this; });
  988. }
  989. }
  990. private:
  991. //==============================================================================
  992. static void staticFinished (SLAndroidSimpleBufferQueueItf, void* context)
  993. {
  994. static_cast<SLRealtimeThread*> (context)->finished();
  995. }
  996. //==============================================================================
  997. DynamicLibrary slLibrary { "libOpenSLES.so" };
  998. SlRef<SLEngineItf_> engine;
  999. SlRef<SLOutputMixItf_> outputMix;
  1000. SlRef<SLPlayItf_> player;
  1001. SlRef<SLAndroidSimpleBufferQueueItf_> queue;
  1002. int bufferSize = AndroidHighPerformanceAudioHelpers::getNativeBufferSizeHint();
  1003. HeapBlock<int16> buffer { HeapBlock<int16> (static_cast<size_t> (1 * bufferSize * numBuffers)) };
  1004. void* (*threadEntryProc) (void*) = nullptr;
  1005. void* threadUserPtr = nullptr;
  1006. pthread_cond_t threadReady;
  1007. pthread_mutex_t threadReadyMutex;
  1008. pthread_t threadID;
  1009. };
  1010. //==============================================================================
  1011. pthread_t juce_createRealtimeAudioThread (void* (*entry) (void*), void* userPtr)
  1012. {
  1013. auto thread = std::make_unique<SLRealtimeThread>();
  1014. if (! thread->isOk())
  1015. return {};
  1016. auto threadID = thread->startThread (entry, userPtr);
  1017. // the thread will de-allocate itself
  1018. thread.release();
  1019. return threadID;
  1020. }
  1021. } // namespace juce