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.

1281 lines
51KB

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