Audio plugin host https://kx.studio/carla
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.

483 lines
19KB

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