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.

1390 lines
55KB

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