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.

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