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.

1286 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. while (! guard.compareAndSetBool (1, 0))
  521. Thread::sleep (1);
  522. if (inputChannels > 0)
  523. recorder->setState (false);
  524. if (outputChannels > 0)
  525. player->setState (false);
  526. guard.set (0);
  527. }
  528. bool setAudioPreprocessingEnabled (bool shouldEnable) override
  529. {
  530. if (shouldEnable != audioProcessingEnabled)
  531. {
  532. audioProcessingEnabled = shouldEnable;
  533. if (recorder != nullptr)
  534. return recorder->setAudioPreprocessingEnabled (audioProcessingEnabled);
  535. }
  536. return true;
  537. }
  538. bool supportsFloatingPoint() const noexcept override { return (BufferHelpers<T>::isFloatingPoint != 0); }
  539. void doSomeWorkOnAudioThread()
  540. {
  541. // only the player or the recorder should enter this section at any time
  542. if (guard.compareAndSetBool (1, 0))
  543. {
  544. // are there enough buffers avaialable to process some audio
  545. if ((inputChannels == 0 || recorder->isBufferAvailable()) && (outputChannels == 0 || player->isBufferAvailable()))
  546. {
  547. T* recorderBuffer = (inputChannels > 0 ? recorder->getNextBuffer() : nullptr);
  548. T* playerBuffer = (outputChannels > 0 ? player->getNextBuffer() : nullptr);
  549. const float** inputChannelData = nullptr;
  550. float** outputChannelData = nullptr;
  551. if (recorderBuffer != nullptr)
  552. {
  553. BufferHelpers<T>::prepareCallbackBuffer (recorder->sampleBuffer, recorderBuffer);
  554. BufferHelpers<T>::convertFromOpenSL (recorderBuffer, recorder->sampleBuffer);
  555. inputChannelData = recorder->sampleBuffer.getArrayOfReadPointers();
  556. }
  557. if (playerBuffer != nullptr)
  558. {
  559. BufferHelpers<T>::prepareCallbackBuffer (player->sampleBuffer, playerBuffer);
  560. outputChannelData = player->sampleBuffer.getArrayOfWritePointers();
  561. }
  562. process (inputChannelData, outputChannelData);
  563. if (recorderBuffer != nullptr)
  564. recorder->enqueueBuffer();
  565. if (playerBuffer != nullptr)
  566. {
  567. BufferHelpers<T>::convertToOpenSL (player->sampleBuffer, playerBuffer);
  568. player->enqueueBuffer();
  569. }
  570. }
  571. guard.set (0);
  572. }
  573. }
  574. //==============================================================================
  575. ScopedPointer<OpenSLQueueRunnerPlayer<T> > player;
  576. ScopedPointer<OpenSLQueueRunnerRecorder<T> > recorder;
  577. Atomic<int> guard;
  578. };
  579. //==============================================================================
  580. OpenSLAudioIODevice (const String& deviceName)
  581. : AudioIODevice (deviceName, openSLTypeName),
  582. actualBufferSize (0), sampleRate (0),
  583. audioProcessingEnabled (true),
  584. callback (nullptr)
  585. {
  586. // OpenSL has piss-poor support for determining latency, so the only way I can find to
  587. // get a number for this is by asking the AudioTrack/AudioRecord classes..
  588. AndroidAudioIODevice javaDevice (deviceName);
  589. // this is a total guess about how to calculate the latency, but seems to vaguely agree
  590. // with the devices I've tested.. YMMV
  591. inputLatency = (javaDevice.minBufferSizeIn * 2) / 3;
  592. outputLatency = (javaDevice.minBufferSizeOut * 2) / 3;
  593. const int64 longestLatency = jmax (inputLatency, outputLatency);
  594. const int64 totalLatency = inputLatency + outputLatency;
  595. inputLatency = (int) ((longestLatency * inputLatency) / totalLatency) & ~15;
  596. outputLatency = (int) ((longestLatency * outputLatency) / totalLatency) & ~15;
  597. bool success = slLibrary.open ("libOpenSLES.so");
  598. // You can only create this class if you are sure that your hardware supports OpenSL
  599. jassert (success);
  600. ignoreUnused (success);
  601. }
  602. ~OpenSLAudioIODevice()
  603. {
  604. close();
  605. }
  606. bool openedOk() const { return session != nullptr; }
  607. StringArray getOutputChannelNames() override
  608. {
  609. StringArray s;
  610. s.add ("Left");
  611. s.add ("Right");
  612. return s;
  613. }
  614. StringArray getInputChannelNames() override
  615. {
  616. StringArray s;
  617. s.add ("Audio Input");
  618. return s;
  619. }
  620. Array<double> getAvailableSampleRates() override
  621. {
  622. //see https://developer.android.com/ndk/guides/audio/opensl-for-android.html
  623. static const double rates[] = { 8000.0, 11025.0, 12000.0, 16000.0,
  624. 22050.0, 24000.0, 32000.0, 44100.0, 48000.0 };
  625. Array<double> retval (rates, numElementsInArray (rates));
  626. // make sure the native sample rate is pafrt of the list
  627. double native = getNativeSampleRate();
  628. if (native != 0.0 && ! retval.contains (native))
  629. retval.add (native);
  630. return retval;
  631. }
  632. Array<int> getAvailableBufferSizes() override
  633. {
  634. // we need to offer the lowest possible buffer size which
  635. // is the native buffer size
  636. const int defaultNumMultiples = 8;
  637. const int nativeBufferSize = getNativeBufferSize();
  638. Array<int> retval;
  639. for (int i = 1; i < defaultNumMultiples; ++i)
  640. retval.add (i * nativeBufferSize);
  641. return retval;
  642. }
  643. String open (const BigInteger& inputChannels,
  644. const BigInteger& outputChannels,
  645. double requestedSampleRate,
  646. int bufferSize) override
  647. {
  648. close();
  649. lastError.clear();
  650. sampleRate = (int) requestedSampleRate;
  651. int preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  652. activeOutputChans = outputChannels;
  653. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  654. int numOutputChannels = activeOutputChans.countNumberOfSetBits();
  655. activeInputChans = inputChannels;
  656. activeInputChans.setRange (1, activeInputChans.getHighestBit(), false);
  657. int numInputChannels = activeInputChans.countNumberOfSetBits();
  658. actualBufferSize = preferredBufferSize;
  659. const int audioBuffersToEnqueue = hasLowLatencyAudioPath() ? buffersToEnqueueForLowLatency
  660. : buffersToEnqueueSlowAudio;
  661. if (numInputChannels > 0 && (! RuntimePermissions::isGranted (RuntimePermissions::recordAudio)))
  662. {
  663. // If you hit this assert, you probably forgot to get RuntimePermissions::recordAudio
  664. // before trying to open an audio input device. This is not going to work!
  665. jassertfalse;
  666. lastError = "Error opening OpenSL input device: the app was not granted android.permission.RECORD_AUDIO";
  667. }
  668. session = OpenSLSession::create (slLibrary, numInputChannels, numOutputChannels,
  669. sampleRate, actualBufferSize, audioBuffersToEnqueue);
  670. if (session != nullptr)
  671. session->setAudioPreprocessingEnabled (audioProcessingEnabled);
  672. else
  673. {
  674. if (numInputChannels > 0 && numOutputChannels > 0 && RuntimePermissions::isGranted (RuntimePermissions::recordAudio))
  675. {
  676. // New versions of the Android emulator do not seem to support audio input anymore on OS X
  677. activeInputChans = BigInteger(0);
  678. numInputChannels = 0;
  679. session = OpenSLSession::create(slLibrary, numInputChannels, numOutputChannels,
  680. sampleRate, actualBufferSize, audioBuffersToEnqueue);
  681. }
  682. }
  683. DBG ("OpenSL: numInputChannels = " << numInputChannels
  684. << ", numOutputChannels = " << numOutputChannels
  685. << ", nativeBufferSize = " << getNativeBufferSize()
  686. << ", nativeSampleRate = " << getNativeSampleRate()
  687. << ", actualBufferSize = " << actualBufferSize
  688. << ", audioBuffersToEnqueue = " << audioBuffersToEnqueue
  689. << ", sampleRate = " << sampleRate
  690. << ", supportsFloatingPoint = " << (session != nullptr && session->supportsFloatingPoint() ? "true" : "false"));
  691. if (session == nullptr)
  692. lastError = "Unknown error initializing opensl session";
  693. deviceOpen = (session != nullptr);
  694. return lastError;
  695. }
  696. void close() override
  697. {
  698. stop();
  699. session = nullptr;
  700. callback = nullptr;
  701. }
  702. int getOutputLatencyInSamples() override { return outputLatency; }
  703. int getInputLatencyInSamples() override { return inputLatency; }
  704. bool isOpen() override { return deviceOpen; }
  705. int getCurrentBufferSizeSamples() override { return actualBufferSize; }
  706. int getCurrentBitDepth() override { return (session != nullptr && session->supportsFloatingPoint() ? 32 : 16); }
  707. BigInteger getActiveOutputChannels() const override { return activeOutputChans; }
  708. BigInteger getActiveInputChannels() const override { return activeInputChans; }
  709. String getLastError() override { return lastError; }
  710. bool isPlaying() override { return callback != nullptr; }
  711. int getDefaultBufferSize() override
  712. {
  713. // Only on a Pro-Audio device will we set the lowest possible buffer size
  714. // by default. We need to be more conservative on other devices
  715. // as they may be low-latency, but still have a crappy CPU.
  716. return (isProAudioDevice() ? 1 : 6)
  717. * defaultBufferSizeIsMultipleOfNative * getNativeBufferSize();
  718. }
  719. double getCurrentSampleRate() override
  720. {
  721. return (sampleRate == 0.0 ? getNativeSampleRate() : sampleRate);
  722. }
  723. void start (AudioIODeviceCallback* newCallback) override
  724. {
  725. if (session != nullptr && callback != newCallback)
  726. {
  727. AudioIODeviceCallback* oldCallback = callback;
  728. if (newCallback != nullptr)
  729. newCallback->audioDeviceAboutToStart (this);
  730. if (oldCallback != nullptr)
  731. {
  732. // already running
  733. if (newCallback == nullptr)
  734. stop();
  735. else
  736. session->setCallback (newCallback);
  737. oldCallback->audioDeviceStopped();
  738. }
  739. else
  740. {
  741. jassert (newCallback != nullptr);
  742. // session hasn't started yet
  743. session->setCallback (newCallback);
  744. session->start();
  745. }
  746. callback = newCallback;
  747. }
  748. }
  749. void stop() override
  750. {
  751. if (session != nullptr && callback != nullptr)
  752. {
  753. callback = nullptr;
  754. session->stop();
  755. session->setCallback (nullptr);
  756. }
  757. }
  758. bool setAudioPreprocessingEnabled (bool shouldAudioProcessingBeEnabled) override
  759. {
  760. audioProcessingEnabled = shouldAudioProcessingBeEnabled;
  761. if (session != nullptr)
  762. session->setAudioPreprocessingEnabled (audioProcessingEnabled);
  763. return true;
  764. }
  765. static const char* const openSLTypeName;
  766. private:
  767. //==============================================================================
  768. friend class SLRealtimeThread;
  769. //==============================================================================
  770. DynamicLibrary slLibrary;
  771. int actualBufferSize, sampleRate;
  772. int inputLatency, outputLatency;
  773. bool deviceOpen, audioProcessingEnabled;
  774. String lastError;
  775. BigInteger activeOutputChans, activeInputChans;
  776. AudioIODeviceCallback* callback;
  777. ScopedPointer<OpenSLSession> session;
  778. enum
  779. {
  780. // The number of buffers to enqueue needs to be at least two for the audio to use the low-latency
  781. // audio path (see "Performance" section in ndk/docs/Additional_library_docs/opensles/index.html)
  782. buffersToEnqueueForLowLatency = 4,
  783. buffersToEnqueueSlowAudio = 8,
  784. defaultBufferSizeIsMultipleOfNative = 1
  785. };
  786. //==============================================================================
  787. static String audioManagerGetProperty (const String& property)
  788. {
  789. const LocalRef<jstring> jProperty (javaString (property));
  790. const LocalRef<jstring> text ((jstring) android.activity.callObjectMethod (JuceAppActivity.audioManagerGetProperty,
  791. jProperty.get()));
  792. if (text.get() != 0)
  793. return juceString (text);
  794. return {};
  795. }
  796. static bool androidHasSystemFeature (const String& property)
  797. {
  798. const LocalRef<jstring> jProperty (javaString (property));
  799. return android.activity.callBooleanMethod (JuceAppActivity.hasSystemFeature, jProperty.get());
  800. }
  801. static double getNativeSampleRate()
  802. {
  803. return audioManagerGetProperty ("android.media.property.OUTPUT_SAMPLE_RATE").getDoubleValue();
  804. }
  805. static int getNativeBufferSize()
  806. {
  807. const int val = audioManagerGetProperty ("android.media.property.OUTPUT_FRAMES_PER_BUFFER").getIntValue();
  808. return val > 0 ? val : 512;
  809. }
  810. static bool isProAudioDevice()
  811. {
  812. return androidHasSystemFeature ("android.hardware.audio.pro");
  813. }
  814. static bool hasLowLatencyAudioPath()
  815. {
  816. return androidHasSystemFeature ("android.hardware.audio.low_latency");
  817. }
  818. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenSLAudioIODevice)
  819. };
  820. OpenSLAudioIODevice::OpenSLSession* OpenSLAudioIODevice::OpenSLSession::create (DynamicLibrary& slLibrary,
  821. int numInputChannels, int numOutputChannels,
  822. double samleRateToUse, int bufferSizeToUse,
  823. int numBuffersToUse)
  824. {
  825. ScopedPointer<OpenSLSession> retval;
  826. auto sdkVersion = getEnv()->GetStaticIntField (AndroidBuildVersion, AndroidBuildVersion.SDK_INT);
  827. // SDK versions 21 and higher should natively support floating point...
  828. if (sdkVersion >= 21)
  829. {
  830. retval = new OpenSLSessionT<float> (slLibrary, numInputChannels, numOutputChannels, samleRateToUse,
  831. bufferSizeToUse, numBuffersToUse);
  832. // ...however, some devices lie so re-try without floating point
  833. if (retval != nullptr && (! retval->openedOK()))
  834. retval = nullptr;
  835. }
  836. if (retval == nullptr)
  837. {
  838. retval = new OpenSLSessionT<int16> (slLibrary, numInputChannels, numOutputChannels, samleRateToUse,
  839. bufferSizeToUse, numBuffersToUse);
  840. if (retval != nullptr && (! retval->openedOK()))
  841. retval = nullptr;
  842. }
  843. return retval.release();
  844. }
  845. //==============================================================================
  846. class OpenSLAudioDeviceType : public AudioIODeviceType
  847. {
  848. public:
  849. OpenSLAudioDeviceType() : AudioIODeviceType (OpenSLAudioIODevice::openSLTypeName) {}
  850. //==============================================================================
  851. void scanForDevices() override {}
  852. StringArray getDeviceNames (bool) const override { return StringArray (OpenSLAudioIODevice::openSLTypeName); }
  853. int getDefaultDeviceIndex (bool) const override { return 0; }
  854. int getIndexOfDevice (AudioIODevice* device, bool) const override { return device != nullptr ? 0 : -1; }
  855. bool hasSeparateInputsAndOutputs() const override { return false; }
  856. AudioIODevice* createDevice (const String& outputDeviceName,
  857. const String& inputDeviceName) override
  858. {
  859. ScopedPointer<OpenSLAudioIODevice> dev;
  860. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  861. dev = new OpenSLAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  862. : inputDeviceName);
  863. return dev.release();
  864. }
  865. static bool isOpenSLAvailable()
  866. {
  867. DynamicLibrary library;
  868. return library.open ("libOpenSLES.so");
  869. }
  870. private:
  871. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenSLAudioDeviceType)
  872. };
  873. const char* const OpenSLAudioIODevice::openSLTypeName = "Android OpenSL";
  874. //==============================================================================
  875. bool isOpenSLAvailable() { return OpenSLAudioDeviceType::isOpenSLAvailable(); }
  876. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_OpenSLES()
  877. {
  878. return isOpenSLAvailable() ? new OpenSLAudioDeviceType() : nullptr;
  879. }
  880. //==============================================================================
  881. class SLRealtimeThread
  882. {
  883. public:
  884. static constexpr int numBuffers = 4;
  885. SLRealtimeThread()
  886. {
  887. if (auto createEngine = (OpenSLAudioIODevice::OpenSLSession::CreateEngineFunc) slLibrary.getFunction ("slCreateEngine"))
  888. {
  889. SLObjectItf obj = nullptr;
  890. auto err = createEngine (&obj, 0, nullptr, 0, nullptr, nullptr);
  891. if (err != SL_RESULT_SUCCESS || obj == nullptr)
  892. return;
  893. if ((*obj)->Realize (obj, 0) != SL_RESULT_SUCCESS)
  894. {
  895. (*obj)->Destroy (obj);
  896. return;
  897. }
  898. engine = SlRef<SLEngineItf_>::cast (SlObjectRef (obj));
  899. if (engine == nullptr)
  900. {
  901. (*obj)->Destroy (obj);
  902. return;
  903. }
  904. obj = nullptr;
  905. err = (*engine)->CreateOutputMix (engine, &obj, 0, nullptr, nullptr);
  906. if (err != SL_RESULT_SUCCESS || obj == nullptr || (*obj)->Realize (obj, 0) != SL_RESULT_SUCCESS)
  907. {
  908. (*obj)->Destroy (obj);
  909. return;
  910. }
  911. outputMix = SlRef<SLOutputMixItf_>::cast (SlObjectRef (obj));
  912. if (outputMix == nullptr)
  913. {
  914. (*obj)->Destroy (obj);
  915. return;
  916. }
  917. SLDataLocator_AndroidSimpleBufferQueue queueLocator = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, static_cast<SLuint32> (numBuffers)};
  918. SLDataLocator_OutputMix outputMixLocator = {SL_DATALOCATOR_OUTPUTMIX, outputMix};
  919. PCMDataFormatEx dataFormat;
  920. BufferHelpers<int16>::initPCMDataFormat (dataFormat, 1, OpenSLAudioIODevice::getNativeSampleRate());
  921. SLDataSource source = { &queueLocator, &dataFormat };
  922. SLDataSink sink = { &outputMixLocator, nullptr };
  923. SLInterfaceID queueInterfaces[] = { &IntfIID<SLAndroidSimpleBufferQueueItf_>::iid };
  924. SLboolean trueFlag = SL_BOOLEAN_TRUE;
  925. obj = nullptr;
  926. err = (*engine)->CreateAudioPlayer (engine, &obj, &source, &sink, 1, queueInterfaces, &trueFlag);
  927. if (err != SL_RESULT_SUCCESS || obj == nullptr)
  928. return;
  929. if ((*obj)->Realize (obj, 0) != SL_RESULT_SUCCESS)
  930. {
  931. (*obj)->Destroy (obj);
  932. return;
  933. }
  934. player = SlRef<SLPlayItf_>::cast (SlObjectRef (obj));
  935. if (player == nullptr)
  936. {
  937. (*obj)->Destroy (obj);
  938. return;
  939. }
  940. queue = SlRef<SLAndroidSimpleBufferQueueItf_>::cast (player);
  941. if (queue == nullptr)
  942. return;
  943. if ((*queue)->RegisterCallback (queue, staticFinished, this) != SL_RESULT_SUCCESS)
  944. {
  945. queue = nullptr;
  946. return;
  947. }
  948. pthread_cond_init (&threadReady, nullptr);
  949. pthread_mutex_init (&threadReadyMutex, nullptr);
  950. }
  951. }
  952. bool isOK() const { return queue != nullptr; }
  953. pthread_t startThread (void* (*entry) (void*), void* userPtr)
  954. {
  955. memset (buffer.getData(), 0, static_cast<size_t> (sizeof (int16) * static_cast<size_t> (bufferSize * numBuffers)));
  956. for (int i = 0; i < numBuffers; ++i)
  957. {
  958. int16* dst = buffer.getData() + (bufferSize * i);
  959. (*queue)->Enqueue (queue, dst, static_cast<SLuint32> (static_cast<size_t> (bufferSize) * sizeof (int16)));
  960. }
  961. pthread_mutex_lock (&threadReadyMutex);
  962. threadEntryProc = entry;
  963. threadUserPtr = userPtr;
  964. (*player)->SetPlayState (player, SL_PLAYSTATE_PLAYING);
  965. pthread_cond_wait (&threadReady, &threadReadyMutex);
  966. pthread_mutex_unlock (&threadReadyMutex);
  967. return threadID;
  968. }
  969. void finished()
  970. {
  971. if (threadEntryProc != nullptr)
  972. {
  973. pthread_mutex_lock (&threadReadyMutex);
  974. threadID = pthread_self();
  975. pthread_cond_signal (&threadReady);
  976. pthread_mutex_unlock (&threadReadyMutex);
  977. threadEntryProc (threadUserPtr);
  978. threadEntryProc = nullptr;
  979. (*player)->SetPlayState (player, SL_PLAYSTATE_STOPPED);
  980. MessageManager::callAsync ([this] () { delete this; });
  981. }
  982. }
  983. private:
  984. //=============================================================================
  985. static void staticFinished (SLAndroidSimpleBufferQueueItf, void* context)
  986. {
  987. static_cast<SLRealtimeThread*> (context)->finished();
  988. }
  989. //=============================================================================
  990. DynamicLibrary slLibrary { "libOpenSLES.so" };
  991. SlRef<SLEngineItf_> engine;
  992. SlRef<SLOutputMixItf_> outputMix;
  993. SlRef<SLPlayItf_> player;
  994. SlRef<SLAndroidSimpleBufferQueueItf_> queue;
  995. int bufferSize = OpenSLAudioIODevice::getNativeBufferSize();
  996. HeapBlock<int16> buffer { HeapBlock<int16> (static_cast<size_t> (1 * bufferSize * numBuffers)) };
  997. void* (*threadEntryProc) (void*) = nullptr;
  998. void* threadUserPtr = nullptr;
  999. pthread_cond_t threadReady;
  1000. pthread_mutex_t threadReadyMutex;
  1001. pthread_t threadID;
  1002. };
  1003. pthread_t juce_createRealtimeAudioThread (void* (*entry) (void*), void* userPtr)
  1004. {
  1005. ScopedPointer<SLRealtimeThread> thread (new SLRealtimeThread);
  1006. if (! thread->isOK())
  1007. return 0;
  1008. pthread_t threadID = thread->startThread (entry, userPtr);
  1009. // the thread will de-allocate itself
  1010. thread.release();
  1011. return threadID;
  1012. }