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.

488 lines
18KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  20. STATICMETHOD (getMinBufferSize, "getMinBufferSize", "(III)I") \
  21. STATICMETHOD (getNativeOutputSampleRate, "getNativeOutputSampleRate", "(I)I") \
  22. METHOD (constructor, "<init>", "(IIIIII)V") \
  23. METHOD (getState, "getState", "()I") \
  24. METHOD (play, "play", "()V") \
  25. METHOD (stop, "stop", "()V") \
  26. METHOD (release, "release", "()V") \
  27. METHOD (flush, "flush", "()V") \
  28. METHOD (write, "write", "([SII)I") \
  29. METHOD (getUnderrunCount, "getUnderrunCount", "()I") \
  30. DECLARE_JNI_CLASS (AudioTrack, "android/media/AudioTrack");
  31. #undef JNI_CLASS_MEMBERS
  32. //==============================================================================
  33. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  34. STATICMETHOD (getMinBufferSize, "getMinBufferSize", "(III)I") \
  35. METHOD (constructor, "<init>", "(IIIII)V") \
  36. METHOD (getState, "getState", "()I") \
  37. METHOD (startRecording, "startRecording", "()V") \
  38. METHOD (stop, "stop", "()V") \
  39. METHOD (read, "read", "([SII)I") \
  40. METHOD (release, "release", "()V") \
  41. DECLARE_JNI_CLASS (AudioRecord, "android/media/AudioRecord");
  42. #undef JNI_CLASS_MEMBERS
  43. //==============================================================================
  44. enum
  45. {
  46. CHANNEL_OUT_STEREO = 12,
  47. CHANNEL_IN_STEREO = 12,
  48. CHANNEL_IN_MONO = 16,
  49. ENCODING_PCM_16BIT = 2,
  50. STREAM_MUSIC = 3,
  51. MODE_STREAM = 1,
  52. STATE_UNINITIALIZED = 0
  53. };
  54. const char* const javaAudioTypeName = "Android Audio";
  55. //==============================================================================
  56. class AndroidAudioIODevice : public AudioIODevice,
  57. public Thread
  58. {
  59. public:
  60. //==============================================================================
  61. AndroidAudioIODevice (const String& deviceName)
  62. : AudioIODevice (deviceName, javaAudioTypeName),
  63. Thread ("audio"),
  64. minBufferSizeOut (0), minBufferSizeIn (0), callback (0), sampleRate (0),
  65. numClientInputChannels (0), numDeviceInputChannels (0), numDeviceInputChannelsAvailable (2),
  66. numClientOutputChannels (0), numDeviceOutputChannels (0),
  67. actualBufferSize (0), isRunning (false),
  68. inputChannelBuffer (1, 1),
  69. outputChannelBuffer (1, 1)
  70. {
  71. JNIEnv* env = getEnv();
  72. sampleRate = env->CallStaticIntMethod (AudioTrack, AudioTrack.getNativeOutputSampleRate, MODE_STREAM);
  73. minBufferSizeOut = (int) env->CallStaticIntMethod (AudioTrack, AudioTrack.getMinBufferSize, sampleRate, CHANNEL_OUT_STEREO, ENCODING_PCM_16BIT);
  74. minBufferSizeIn = (int) env->CallStaticIntMethod (AudioRecord, AudioRecord.getMinBufferSize, sampleRate, CHANNEL_IN_STEREO, ENCODING_PCM_16BIT);
  75. if (minBufferSizeIn <= 0)
  76. {
  77. minBufferSizeIn = env->CallStaticIntMethod (AudioRecord, AudioRecord.getMinBufferSize, sampleRate, CHANNEL_IN_MONO, ENCODING_PCM_16BIT);
  78. if (minBufferSizeIn > 0)
  79. numDeviceInputChannelsAvailable = 1;
  80. else
  81. numDeviceInputChannelsAvailable = 0;
  82. }
  83. DBG ("Audio device - min buffers: " << minBufferSizeOut << ", " << minBufferSizeIn << "; "
  84. << sampleRate << " Hz; input chans: " << numDeviceInputChannelsAvailable);
  85. }
  86. ~AndroidAudioIODevice()
  87. {
  88. close();
  89. }
  90. StringArray getOutputChannelNames() override
  91. {
  92. StringArray s;
  93. s.add ("Left");
  94. s.add ("Right");
  95. return s;
  96. }
  97. StringArray getInputChannelNames() override
  98. {
  99. StringArray s;
  100. if (numDeviceInputChannelsAvailable == 2)
  101. {
  102. s.add ("Left");
  103. s.add ("Right");
  104. }
  105. else if (numDeviceInputChannelsAvailable == 1)
  106. {
  107. s.add ("Audio Input");
  108. }
  109. return s;
  110. }
  111. Array<double> getAvailableSampleRates() override
  112. {
  113. Array<double> r;
  114. r.add ((double) sampleRate);
  115. return r;
  116. }
  117. Array<int> getAvailableBufferSizes() override
  118. {
  119. Array<int> b;
  120. int n = 16;
  121. for (int i = 0; i < 50; ++i)
  122. {
  123. b.add (n);
  124. n += n < 64 ? 16
  125. : (n < 512 ? 32
  126. : (n < 1024 ? 64
  127. : (n < 2048 ? 128 : 256)));
  128. }
  129. return b;
  130. }
  131. int getDefaultBufferSize() override { return 2048; }
  132. String open (const BigInteger& inputChannels,
  133. const BigInteger& outputChannels,
  134. double requestedSampleRate,
  135. int bufferSize) override
  136. {
  137. close();
  138. if (sampleRate != (int) requestedSampleRate)
  139. return "Sample rate not allowed";
  140. lastError.clear();
  141. int preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  142. numDeviceInputChannels = 0;
  143. numDeviceOutputChannels = 0;
  144. activeOutputChans = outputChannels;
  145. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  146. numClientOutputChannels = activeOutputChans.countNumberOfSetBits();
  147. activeInputChans = inputChannels;
  148. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  149. numClientInputChannels = activeInputChans.countNumberOfSetBits();
  150. actualBufferSize = preferredBufferSize;
  151. inputChannelBuffer.setSize (2, actualBufferSize);
  152. inputChannelBuffer.clear();
  153. outputChannelBuffer.setSize (2, actualBufferSize);
  154. outputChannelBuffer.clear();
  155. JNIEnv* env = getEnv();
  156. if (numClientOutputChannels > 0)
  157. {
  158. numDeviceOutputChannels = 2;
  159. outputDevice = GlobalRef (env->NewObject (AudioTrack, AudioTrack.constructor,
  160. STREAM_MUSIC, sampleRate, CHANNEL_OUT_STEREO, ENCODING_PCM_16BIT,
  161. (jint) (minBufferSizeOut * numDeviceOutputChannels * static_cast<int> (sizeof (int16))), MODE_STREAM));
  162. int outputDeviceState = env->CallIntMethod (outputDevice, AudioTrack.getState);
  163. if (outputDeviceState > 0)
  164. {
  165. isRunning = true;
  166. }
  167. else
  168. {
  169. // failed to open the device
  170. outputDevice.clear();
  171. lastError = "Error opening audio output device: android.media.AudioTrack failed with state = " + String (outputDeviceState);
  172. }
  173. }
  174. if (numClientInputChannels > 0 && numDeviceInputChannelsAvailable > 0)
  175. {
  176. if (! RuntimePermissions::isGranted (RuntimePermissions::recordAudio))
  177. {
  178. // If you hit this assert, you probably forgot to get RuntimePermissions::recordAudio
  179. // before trying to open an audio input device. This is not going to work!
  180. jassertfalse;
  181. inputDevice.clear();
  182. lastError = "Error opening audio input device: the app was not granted android.permission.RECORD_AUDIO";
  183. }
  184. else
  185. {
  186. numDeviceInputChannels = jmin (numClientInputChannels, numDeviceInputChannelsAvailable);
  187. inputDevice = GlobalRef (env->NewObject (AudioRecord, AudioRecord.constructor,
  188. 0 /* (default audio source) */, sampleRate,
  189. numDeviceInputChannelsAvailable > 1 ? CHANNEL_IN_STEREO : CHANNEL_IN_MONO,
  190. ENCODING_PCM_16BIT,
  191. (jint) (minBufferSizeIn * numDeviceInputChannels * static_cast<int> (sizeof (int16)))));
  192. int inputDeviceState = env->CallIntMethod (inputDevice, AudioRecord.getState);
  193. if (inputDeviceState > 0)
  194. {
  195. isRunning = true;
  196. }
  197. else
  198. {
  199. // failed to open the device
  200. inputDevice.clear();
  201. lastError = "Error opening audio input device: android.media.AudioRecord failed with state = " + String (inputDeviceState);
  202. }
  203. }
  204. }
  205. if (isRunning)
  206. {
  207. if (outputDevice != nullptr)
  208. env->CallVoidMethod (outputDevice, AudioTrack.play);
  209. if (inputDevice != nullptr)
  210. env->CallVoidMethod (inputDevice, AudioRecord.startRecording);
  211. startThread (8);
  212. }
  213. else
  214. {
  215. closeDevices();
  216. }
  217. return lastError;
  218. }
  219. void close() override
  220. {
  221. if (isRunning)
  222. {
  223. stopThread (2000);
  224. isRunning = false;
  225. closeDevices();
  226. }
  227. }
  228. int getOutputLatencyInSamples() override { return (minBufferSizeOut * 3) / 4; }
  229. int getInputLatencyInSamples() override { return (minBufferSizeIn * 3) / 4; }
  230. bool isOpen() override { return isRunning; }
  231. int getCurrentBufferSizeSamples() override { return actualBufferSize; }
  232. int getCurrentBitDepth() override { return 16; }
  233. double getCurrentSampleRate() override { return sampleRate; }
  234. BigInteger getActiveOutputChannels() const override { return activeOutputChans; }
  235. BigInteger getActiveInputChannels() const override { return activeInputChans; }
  236. String getLastError() override { return lastError; }
  237. bool isPlaying() override { return isRunning && callback != 0; }
  238. int getXRunCount() const noexcept override
  239. {
  240. if (outputDevice != nullptr)
  241. return getEnv()->CallIntMethod (outputDevice, AudioTrack.getUnderrunCount);
  242. return -1;
  243. }
  244. void start (AudioIODeviceCallback* newCallback) override
  245. {
  246. if (isRunning && callback != newCallback)
  247. {
  248. if (newCallback != nullptr)
  249. newCallback->audioDeviceAboutToStart (this);
  250. const ScopedLock sl (callbackLock);
  251. callback = newCallback;
  252. }
  253. }
  254. void stop() override
  255. {
  256. if (isRunning)
  257. {
  258. AudioIODeviceCallback* lastCallback;
  259. {
  260. const ScopedLock sl (callbackLock);
  261. lastCallback = callback;
  262. callback = nullptr;
  263. }
  264. if (lastCallback != nullptr)
  265. lastCallback->audioDeviceStopped();
  266. }
  267. }
  268. void run() override
  269. {
  270. JNIEnv* env = getEnv();
  271. jshortArray audioBuffer = env->NewShortArray (actualBufferSize * jmax (numDeviceOutputChannels, numDeviceInputChannels));
  272. while (! threadShouldExit())
  273. {
  274. if (inputDevice != nullptr)
  275. {
  276. jint numRead = env->CallIntMethod (inputDevice, AudioRecord.read, audioBuffer, 0, actualBufferSize * numDeviceInputChannels);
  277. if (numRead < actualBufferSize * numDeviceInputChannels)
  278. {
  279. DBG ("Audio read under-run! " << numRead);
  280. }
  281. jshort* const src = env->GetShortArrayElements (audioBuffer, 0);
  282. for (int chan = 0; chan < inputChannelBuffer.getNumChannels(); ++chan)
  283. {
  284. AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> d (inputChannelBuffer.getWritePointer (chan));
  285. if (chan < numDeviceInputChannels)
  286. {
  287. AudioData::Pointer <AudioData::Int16, AudioData::NativeEndian, AudioData::Interleaved, AudioData::Const> s (src + chan, numDeviceInputChannels);
  288. d.convertSamples (s, actualBufferSize);
  289. }
  290. else
  291. {
  292. d.clearSamples (actualBufferSize);
  293. }
  294. }
  295. env->ReleaseShortArrayElements (audioBuffer, src, 0);
  296. }
  297. if (threadShouldExit())
  298. break;
  299. {
  300. const ScopedLock sl (callbackLock);
  301. if (callback != nullptr)
  302. {
  303. callback->audioDeviceIOCallback (inputChannelBuffer.getArrayOfReadPointers(), numClientInputChannels,
  304. outputChannelBuffer.getArrayOfWritePointers(), numClientOutputChannels,
  305. actualBufferSize);
  306. }
  307. else
  308. {
  309. outputChannelBuffer.clear();
  310. }
  311. }
  312. if (outputDevice != nullptr)
  313. {
  314. if (threadShouldExit())
  315. break;
  316. jshort* const dest = env->GetShortArrayElements (audioBuffer, 0);
  317. for (int chan = 0; chan < numDeviceOutputChannels; ++chan)
  318. {
  319. AudioData::Pointer <AudioData::Int16, AudioData::NativeEndian, AudioData::Interleaved, AudioData::NonConst> d (dest + chan, numDeviceOutputChannels);
  320. const float* const sourceChanData = outputChannelBuffer.getReadPointer (jmin (chan, outputChannelBuffer.getNumChannels() - 1));
  321. AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> s (sourceChanData);
  322. d.convertSamples (s, actualBufferSize);
  323. }
  324. env->ReleaseShortArrayElements (audioBuffer, dest, 0);
  325. jint numWritten = env->CallIntMethod (outputDevice, AudioTrack.write, audioBuffer, 0, actualBufferSize * numDeviceOutputChannels);
  326. if (numWritten < actualBufferSize * numDeviceOutputChannels)
  327. {
  328. DBG ("Audio write underrun! " << numWritten);
  329. }
  330. }
  331. }
  332. }
  333. int minBufferSizeOut, minBufferSizeIn;
  334. private:
  335. //==============================================================================
  336. CriticalSection callbackLock;
  337. AudioIODeviceCallback* callback;
  338. jint sampleRate;
  339. int numClientInputChannels, numDeviceInputChannels, numDeviceInputChannelsAvailable;
  340. int numClientOutputChannels, numDeviceOutputChannels;
  341. int actualBufferSize;
  342. bool isRunning;
  343. String lastError;
  344. BigInteger activeOutputChans, activeInputChans;
  345. GlobalRef outputDevice, inputDevice;
  346. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  347. void closeDevices()
  348. {
  349. if (outputDevice != nullptr)
  350. {
  351. outputDevice.callVoidMethod (AudioTrack.stop);
  352. outputDevice.callVoidMethod (AudioTrack.release);
  353. outputDevice.clear();
  354. }
  355. if (inputDevice != nullptr)
  356. {
  357. inputDevice.callVoidMethod (AudioRecord.stop);
  358. inputDevice.callVoidMethod (AudioRecord.release);
  359. inputDevice.clear();
  360. }
  361. }
  362. JUCE_DECLARE_NON_COPYABLE (AndroidAudioIODevice)
  363. };
  364. //==============================================================================
  365. class AndroidAudioIODeviceType : public AudioIODeviceType
  366. {
  367. public:
  368. AndroidAudioIODeviceType() : AudioIODeviceType (javaAudioTypeName) {}
  369. //==============================================================================
  370. void scanForDevices() {}
  371. StringArray getDeviceNames (bool) const { return StringArray (javaAudioTypeName); }
  372. int getDefaultDeviceIndex (bool) const { return 0; }
  373. int getIndexOfDevice (AudioIODevice* device, bool) const { return device != nullptr ? 0 : -1; }
  374. bool hasSeparateInputsAndOutputs() const { return false; }
  375. AudioIODevice* createDevice (const String& outputDeviceName,
  376. const String& inputDeviceName)
  377. {
  378. ScopedPointer<AndroidAudioIODevice> dev;
  379. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  380. {
  381. dev = new AndroidAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  382. : inputDeviceName);
  383. if (dev->getCurrentSampleRate() <= 0 || dev->getDefaultBufferSize() <= 0)
  384. dev = nullptr;
  385. }
  386. return dev.release();
  387. }
  388. private:
  389. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidAudioIODeviceType)
  390. };
  391. //==============================================================================
  392. extern bool isOpenSLAvailable();
  393. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_Android()
  394. {
  395. #if JUCE_USE_ANDROID_OPENSLES
  396. if (isOpenSLAvailable())
  397. return nullptr;
  398. #endif
  399. return new AndroidAudioIODeviceType();
  400. }
  401. } // namespace juce