The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

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