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.

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