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.

445 lines
17KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  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. DECLARE_JNI_CLASS (AudioTrack, "android/media/AudioTrack");
  30. #undef JNI_CLASS_MEMBERS
  31. //==============================================================================
  32. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  33. STATICMETHOD (getMinBufferSize, "getMinBufferSize", "(III)I") \
  34. METHOD (constructor, "<init>", "(IIIII)V") \
  35. METHOD (getState, "getState", "()I") \
  36. METHOD (startRecording, "startRecording", "()V") \
  37. METHOD (stop, "stop", "()V") \
  38. METHOD (read, "read", "([SII)I") \
  39. METHOD (release, "release", "()V") \
  40. DECLARE_JNI_CLASS (AudioRecord, "android/media/AudioRecord");
  41. #undef JNI_CLASS_MEMBERS
  42. //==============================================================================
  43. enum
  44. {
  45. CHANNEL_OUT_STEREO = 12,
  46. CHANNEL_IN_STEREO = 12,
  47. CHANNEL_IN_MONO = 16,
  48. ENCODING_PCM_16BIT = 2,
  49. STREAM_MUSIC = 3,
  50. MODE_STREAM = 1,
  51. STATE_UNINITIALIZED = 0
  52. };
  53. const char* const javaAudioTypeName = "Android Audio";
  54. //==============================================================================
  55. class AndroidAudioIODevice : public AudioIODevice,
  56. public Thread
  57. {
  58. public:
  59. //==============================================================================
  60. AndroidAudioIODevice (const String& deviceName)
  61. : AudioIODevice (deviceName, javaAudioTypeName),
  62. Thread ("audio"),
  63. minBufferSizeOut (0), minBufferSizeIn (0), callback (0), sampleRate (0),
  64. numClientInputChannels (0), numDeviceInputChannels (0), numDeviceInputChannelsAvailable (2),
  65. numClientOutputChannels (0), numDeviceOutputChannels (0),
  66. actualBufferSize (0), isRunning (false),
  67. outputChannelBuffer (1, 1),
  68. inputChannelBuffer (1, 1)
  69. {
  70. JNIEnv* env = getEnv();
  71. sampleRate = env->CallStaticIntMethod (AudioTrack, AudioTrack.getNativeOutputSampleRate, MODE_STREAM);
  72. minBufferSizeOut = (int) env->CallStaticIntMethod (AudioTrack, AudioTrack.getMinBufferSize, sampleRate, CHANNEL_OUT_STEREO, ENCODING_PCM_16BIT);
  73. minBufferSizeIn = (int) env->CallStaticIntMethod (AudioRecord, AudioRecord.getMinBufferSize, sampleRate, CHANNEL_IN_STEREO, ENCODING_PCM_16BIT);
  74. if (minBufferSizeIn <= 0)
  75. {
  76. minBufferSizeIn = env->CallStaticIntMethod (AudioRecord, AudioRecord.getMinBufferSize, sampleRate, CHANNEL_IN_MONO, ENCODING_PCM_16BIT);
  77. if (minBufferSizeIn > 0)
  78. numDeviceInputChannelsAvailable = 1;
  79. else
  80. numDeviceInputChannelsAvailable = 0;
  81. }
  82. DBG ("Audio device - min buffers: " << minBufferSizeOut << ", " << minBufferSizeIn << "; "
  83. << sampleRate << " Hz; input chans: " << numDeviceInputChannelsAvailable);
  84. }
  85. ~AndroidAudioIODevice()
  86. {
  87. close();
  88. }
  89. StringArray getOutputChannelNames()
  90. {
  91. StringArray s;
  92. s.add ("Left");
  93. s.add ("Right");
  94. return s;
  95. }
  96. StringArray getInputChannelNames()
  97. {
  98. StringArray s;
  99. if (numDeviceInputChannelsAvailable == 2)
  100. {
  101. s.add ("Left");
  102. s.add ("Right");
  103. }
  104. else if (numDeviceInputChannelsAvailable == 1)
  105. {
  106. s.add ("Audio Input");
  107. }
  108. return s;
  109. }
  110. int getNumSampleRates() { return 1;}
  111. double getSampleRate (int index) { return sampleRate; }
  112. int getDefaultBufferSize() { return 2048; }
  113. int getNumBufferSizesAvailable() { return 50; }
  114. int getBufferSizeSamples (int index)
  115. {
  116. int n = 16;
  117. for (int i = 0; i < index; ++i)
  118. n += n < 64 ? 16
  119. : (n < 512 ? 32
  120. : (n < 1024 ? 64
  121. : (n < 2048 ? 128 : 256)));
  122. return n;
  123. }
  124. String open (const BigInteger& inputChannels,
  125. const BigInteger& outputChannels,
  126. double requestedSampleRate,
  127. int bufferSize)
  128. {
  129. close();
  130. if (sampleRate != (int) requestedSampleRate)
  131. return "Sample rate not allowed";
  132. lastError = String::empty;
  133. int preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  134. numDeviceInputChannels = 0;
  135. numDeviceOutputChannels = 0;
  136. activeOutputChans = outputChannels;
  137. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  138. numClientOutputChannels = activeOutputChans.countNumberOfSetBits();
  139. activeInputChans = inputChannels;
  140. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  141. numClientInputChannels = activeInputChans.countNumberOfSetBits();
  142. actualBufferSize = preferredBufferSize;
  143. inputChannelBuffer.setSize (2, actualBufferSize);
  144. inputChannelBuffer.clear();
  145. outputChannelBuffer.setSize (2, actualBufferSize);
  146. outputChannelBuffer.clear();
  147. JNIEnv* env = getEnv();
  148. if (numClientOutputChannels > 0)
  149. {
  150. numDeviceOutputChannels = 2;
  151. outputDevice = GlobalRef (env->NewObject (AudioTrack, AudioTrack.constructor,
  152. STREAM_MUSIC, sampleRate, CHANNEL_OUT_STEREO, ENCODING_PCM_16BIT,
  153. (jint) (minBufferSizeOut * numDeviceOutputChannels * sizeof (int16)), MODE_STREAM));
  154. if (env->CallIntMethod (outputDevice, AudioTrack.getState) != STATE_UNINITIALIZED)
  155. isRunning = true;
  156. else
  157. outputDevice.clear(); // failed to open the device
  158. }
  159. if (numClientInputChannels > 0 && numDeviceInputChannelsAvailable > 0)
  160. {
  161. numDeviceInputChannels = jmin (numClientInputChannels, numDeviceInputChannelsAvailable);
  162. inputDevice = GlobalRef (env->NewObject (AudioRecord, AudioRecord.constructor,
  163. 0 /* (default audio source) */, sampleRate,
  164. numDeviceInputChannelsAvailable > 1 ? CHANNEL_IN_STEREO : CHANNEL_IN_MONO,
  165. ENCODING_PCM_16BIT,
  166. (jint) (minBufferSizeIn * numDeviceInputChannels * sizeof (int16))));
  167. if (env->CallIntMethod (inputDevice, AudioRecord.getState) != STATE_UNINITIALIZED)
  168. isRunning = true;
  169. else
  170. inputDevice.clear(); // failed to open the device
  171. }
  172. if (isRunning)
  173. {
  174. if (outputDevice != nullptr)
  175. env->CallVoidMethod (outputDevice, AudioTrack.play);
  176. if (inputDevice != nullptr)
  177. env->CallVoidMethod (inputDevice, AudioRecord.startRecording);
  178. startThread (8);
  179. }
  180. else
  181. {
  182. closeDevices();
  183. }
  184. return lastError;
  185. }
  186. void close()
  187. {
  188. if (isRunning)
  189. {
  190. stopThread (2000);
  191. isRunning = false;
  192. closeDevices();
  193. }
  194. }
  195. int getOutputLatencyInSamples() { return (minBufferSizeOut * 3) / 4; }
  196. int getInputLatencyInSamples() { return (minBufferSizeIn * 3) / 4; }
  197. bool isOpen() { return isRunning; }
  198. int getCurrentBufferSizeSamples() { return actualBufferSize; }
  199. int getCurrentBitDepth() { return 16; }
  200. double getCurrentSampleRate() { return sampleRate; }
  201. BigInteger getActiveOutputChannels() const { return activeOutputChans; }
  202. BigInteger getActiveInputChannels() const { return activeInputChans; }
  203. String getLastError() { return lastError; }
  204. bool isPlaying() { return isRunning && callback != 0; }
  205. void start (AudioIODeviceCallback* newCallback)
  206. {
  207. if (isRunning && callback != newCallback)
  208. {
  209. if (newCallback != nullptr)
  210. newCallback->audioDeviceAboutToStart (this);
  211. const ScopedLock sl (callbackLock);
  212. callback = newCallback;
  213. }
  214. }
  215. void stop()
  216. {
  217. if (isRunning)
  218. {
  219. AudioIODeviceCallback* lastCallback;
  220. {
  221. const ScopedLock sl (callbackLock);
  222. lastCallback = callback;
  223. callback = nullptr;
  224. }
  225. if (lastCallback != nullptr)
  226. lastCallback->audioDeviceStopped();
  227. }
  228. }
  229. void run()
  230. {
  231. JNIEnv* env = getEnv();
  232. jshortArray audioBuffer = env->NewShortArray (actualBufferSize * jmax (numDeviceOutputChannels, numDeviceInputChannels));
  233. while (! threadShouldExit())
  234. {
  235. if (inputDevice != nullptr)
  236. {
  237. jint numRead = env->CallIntMethod (inputDevice, AudioRecord.read, audioBuffer, 0, actualBufferSize * numDeviceInputChannels);
  238. if (numRead < actualBufferSize * numDeviceInputChannels)
  239. {
  240. DBG ("Audio read under-run! " << numRead);
  241. }
  242. jshort* const src = env->GetShortArrayElements (audioBuffer, 0);
  243. for (int chan = 0; chan < inputChannelBuffer.getNumChannels(); ++chan)
  244. {
  245. AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> d (inputChannelBuffer.getSampleData (chan));
  246. if (chan < numDeviceInputChannels)
  247. {
  248. AudioData::Pointer <AudioData::Int16, AudioData::NativeEndian, AudioData::Interleaved, AudioData::Const> s (src + chan, numDeviceInputChannels);
  249. d.convertSamples (s, actualBufferSize);
  250. }
  251. else
  252. {
  253. d.clearSamples (actualBufferSize);
  254. }
  255. }
  256. env->ReleaseShortArrayElements (audioBuffer, src, 0);
  257. }
  258. if (threadShouldExit())
  259. break;
  260. {
  261. const ScopedLock sl (callbackLock);
  262. if (callback != nullptr)
  263. {
  264. callback->audioDeviceIOCallback ((const float**) inputChannelBuffer.getArrayOfChannels(), numClientInputChannels,
  265. outputChannelBuffer.getArrayOfChannels(), numClientOutputChannels,
  266. actualBufferSize);
  267. }
  268. else
  269. {
  270. outputChannelBuffer.clear();
  271. }
  272. }
  273. if (outputDevice != nullptr)
  274. {
  275. if (threadShouldExit())
  276. break;
  277. jshort* const dest = env->GetShortArrayElements (audioBuffer, 0);
  278. for (int chan = 0; chan < numDeviceOutputChannels; ++chan)
  279. {
  280. AudioData::Pointer <AudioData::Int16, AudioData::NativeEndian, AudioData::Interleaved, AudioData::NonConst> d (dest + chan, numDeviceOutputChannels);
  281. const float* const sourceChanData = outputChannelBuffer.getSampleData (jmin (chan, outputChannelBuffer.getNumChannels() - 1));
  282. AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> s (sourceChanData);
  283. d.convertSamples (s, actualBufferSize);
  284. }
  285. env->ReleaseShortArrayElements (audioBuffer, dest, 0);
  286. jint numWritten = env->CallIntMethod (outputDevice, AudioTrack.write, audioBuffer, 0, actualBufferSize * numDeviceOutputChannels);
  287. if (numWritten < actualBufferSize * numDeviceOutputChannels)
  288. {
  289. DBG ("Audio write underrun! " << numWritten);
  290. }
  291. }
  292. }
  293. }
  294. int minBufferSizeOut, minBufferSizeIn;
  295. private:
  296. //==================================================================================================
  297. CriticalSection callbackLock;
  298. AudioIODeviceCallback* callback;
  299. jint sampleRate;
  300. int numClientInputChannels, numDeviceInputChannels, numDeviceInputChannelsAvailable;
  301. int numClientOutputChannels, numDeviceOutputChannels;
  302. int actualBufferSize;
  303. bool isRunning;
  304. String lastError;
  305. BigInteger activeOutputChans, activeInputChans;
  306. GlobalRef outputDevice, inputDevice;
  307. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  308. void closeDevices()
  309. {
  310. if (outputDevice != nullptr)
  311. {
  312. outputDevice.callVoidMethod (AudioTrack.stop);
  313. outputDevice.callVoidMethod (AudioTrack.release);
  314. outputDevice.clear();
  315. }
  316. if (inputDevice != nullptr)
  317. {
  318. inputDevice.callVoidMethod (AudioRecord.stop);
  319. inputDevice.callVoidMethod (AudioRecord.release);
  320. inputDevice.clear();
  321. }
  322. }
  323. JUCE_DECLARE_NON_COPYABLE (AndroidAudioIODevice);
  324. };
  325. //==============================================================================
  326. class AndroidAudioIODeviceType : public AudioIODeviceType
  327. {
  328. public:
  329. AndroidAudioIODeviceType() : AudioIODeviceType (javaAudioTypeName) {}
  330. //==============================================================================
  331. void scanForDevices() {}
  332. StringArray getDeviceNames (bool wantInputNames) const { return StringArray (javaAudioTypeName); }
  333. int getDefaultDeviceIndex (bool forInput) const { return 0; }
  334. int getIndexOfDevice (AudioIODevice* device, bool asInput) const { return device != nullptr ? 0 : -1; }
  335. bool hasSeparateInputsAndOutputs() const { return false; }
  336. AudioIODevice* createDevice (const String& outputDeviceName,
  337. const String& inputDeviceName)
  338. {
  339. ScopedPointer<AndroidAudioIODevice> dev;
  340. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  341. {
  342. dev = new AndroidAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  343. : inputDeviceName);
  344. if (dev->getCurrentSampleRate() <= 0 || dev->getDefaultBufferSize() <= 0)
  345. dev = nullptr;
  346. }
  347. return dev.release();
  348. }
  349. private:
  350. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidAudioIODeviceType);
  351. };
  352. //==============================================================================
  353. extern bool isOpenSLAvailable();
  354. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_Android()
  355. {
  356. #if JUCE_USE_ANDROID_OPENSLES
  357. if (isOpenSLAvailable())
  358. return nullptr;
  359. #endif
  360. return new AndroidAudioIODeviceType();
  361. }