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.

1407 lines
56KB

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