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.

1317 lines
52KB

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