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.

1088 lines
45KB

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