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.

421 lines
16KB

  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 (play, "play", "()V") \
  24. METHOD (stop, "stop", "()V") \
  25. METHOD (release, "release", "()V") \
  26. METHOD (flush, "flush", "()V") \
  27. METHOD (write, "write", "([SII)I") \
  28. DECLARE_JNI_CLASS (AudioTrack, "android/media/AudioTrack");
  29. #undef JNI_CLASS_MEMBERS
  30. //==============================================================================
  31. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  32. STATICMETHOD (getMinBufferSize, "getMinBufferSize", "(III)I") \
  33. METHOD (constructor, "<init>", "(IIIII)V"); \
  34. METHOD (startRecording, "startRecording", "()V"); \
  35. METHOD (stop, "stop", "()V"); \
  36. METHOD (read, "read", "([SII)I"); \
  37. METHOD (release, "release", "()V"); \
  38. DECLARE_JNI_CLASS (AudioRecord, "android/media/AudioRecord");
  39. #undef JNI_CLASS_MEMBERS
  40. //==============================================================================
  41. #define CHANNEL_OUT_STEREO ((jint) 12)
  42. #define CHANNEL_IN_STEREO ((jint) 12)
  43. #define CHANNEL_IN_MONO ((jint) 16)
  44. #define ENCODING_PCM_16BIT ((jint) 2)
  45. #define STREAM_MUSIC ((jint) 3)
  46. #define MODE_STREAM ((jint) 1)
  47. //==============================================================================
  48. class AndroidAudioIODevice : public AudioIODevice,
  49. public Thread
  50. {
  51. public:
  52. //==============================================================================
  53. AndroidAudioIODevice (const String& deviceName)
  54. : AudioIODevice (deviceName, "Audio"),
  55. Thread ("audio"),
  56. callback (0), sampleRate (0),
  57. numClientInputChannels (0), numDeviceInputChannels (0), numDeviceInputChannelsAvailable (2),
  58. numClientOutputChannels (0), numDeviceOutputChannels (0),
  59. minbufferSize (0), actualBufferSize (0),
  60. isRunning (false),
  61. outputChannelBuffer (1, 1),
  62. inputChannelBuffer (1, 1)
  63. {
  64. JNIEnv* env = getEnv();
  65. sampleRate = env->CallStaticIntMethod (AudioTrack, AudioTrack.getNativeOutputSampleRate, MODE_STREAM);
  66. const jint outMinBuffer = env->CallStaticIntMethod (AudioTrack, AudioTrack.getMinBufferSize, sampleRate, CHANNEL_OUT_STEREO, ENCODING_PCM_16BIT);
  67. jint inMinBuffer = env->CallStaticIntMethod (AudioRecord, AudioRecord.getMinBufferSize, sampleRate, CHANNEL_IN_STEREO, ENCODING_PCM_16BIT);
  68. if (inMinBuffer <= 0)
  69. {
  70. inMinBuffer = env->CallStaticIntMethod (AudioRecord, AudioRecord.getMinBufferSize, sampleRate, CHANNEL_IN_MONO, ENCODING_PCM_16BIT);
  71. if (inMinBuffer > 0)
  72. numDeviceInputChannelsAvailable = 1;
  73. else
  74. numDeviceInputChannelsAvailable = 0;
  75. }
  76. minbufferSize = jmax (outMinBuffer, inMinBuffer) / 4;
  77. DBG ("Audio device - min buffers: " << outMinBuffer << ", " << inMinBuffer << "; "
  78. << sampleRate << " Hz; input chans: " << numDeviceInputChannelsAvailable);
  79. }
  80. ~AndroidAudioIODevice()
  81. {
  82. close();
  83. }
  84. StringArray getOutputChannelNames()
  85. {
  86. StringArray s;
  87. s.add ("Left");
  88. s.add ("Right");
  89. return s;
  90. }
  91. StringArray getInputChannelNames()
  92. {
  93. StringArray s;
  94. if (numDeviceInputChannelsAvailable == 2)
  95. {
  96. s.add ("Left");
  97. s.add ("Right");
  98. }
  99. else if (numDeviceInputChannelsAvailable == 1)
  100. {
  101. s.add ("Audio Input");
  102. }
  103. return s;
  104. }
  105. int getNumSampleRates() { return 1;}
  106. double getSampleRate (int index) { return sampleRate; }
  107. int getDefaultBufferSize() { return minbufferSize; }
  108. int getNumBufferSizesAvailable() { return 10; }
  109. int getBufferSizeSamples (int index) { return getDefaultBufferSize() + index * 128; }
  110. String open (const BigInteger& inputChannels,
  111. const BigInteger& outputChannels,
  112. double requestedSampleRate,
  113. int bufferSize)
  114. {
  115. close();
  116. if (sampleRate != (int) requestedSampleRate)
  117. return "Sample rate not allowed";
  118. lastError = String::empty;
  119. int preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : jmax (minbufferSize, bufferSize);
  120. numDeviceInputChannels = 0;
  121. numDeviceOutputChannels = 0;
  122. activeOutputChans = outputChannels;
  123. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  124. numClientOutputChannels = activeOutputChans.countNumberOfSetBits();
  125. activeInputChans = inputChannels;
  126. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  127. numClientInputChannels = activeInputChans.countNumberOfSetBits();
  128. actualBufferSize = preferredBufferSize;
  129. inputChannelBuffer.setSize (actualBufferSize, 2);
  130. outputChannelBuffer.setSize (actualBufferSize, 2);
  131. inputChannelBuffer.clear();
  132. outputChannelBuffer.clear();
  133. JNIEnv* env = getEnv();
  134. if (numClientOutputChannels > 0)
  135. {
  136. numDeviceOutputChannels = 2;
  137. outputDevice = GlobalRef (env->NewObject (AudioTrack, AudioTrack.constructor,
  138. STREAM_MUSIC, sampleRate, CHANNEL_OUT_STEREO, ENCODING_PCM_16BIT,
  139. (jint) (actualBufferSize * numDeviceOutputChannels * sizeof (float)), MODE_STREAM));
  140. isRunning = true;
  141. }
  142. if (numClientInputChannels > 0 && numDeviceInputChannelsAvailable > 0)
  143. {
  144. numDeviceInputChannels = jmin (numClientInputChannels, numDeviceInputChannelsAvailable);
  145. inputDevice = GlobalRef (env->NewObject (AudioRecord, AudioRecord.constructor,
  146. 0 /* (default audio source) */, sampleRate,
  147. numDeviceInputChannelsAvailable > 1 ? CHANNEL_IN_STEREO : CHANNEL_IN_MONO,
  148. ENCODING_PCM_16BIT,
  149. (jint) (actualBufferSize * numDeviceInputChannels * sizeof (float))));
  150. isRunning = true;
  151. }
  152. if (isRunning)
  153. {
  154. if (outputDevice != nullptr)
  155. env->CallVoidMethod (outputDevice, AudioTrack.play);
  156. if (inputDevice != nullptr)
  157. env->CallVoidMethod (inputDevice, AudioRecord.startRecording);
  158. startThread (8);
  159. }
  160. else
  161. {
  162. closeDevices();
  163. }
  164. return lastError;
  165. }
  166. void close()
  167. {
  168. if (isRunning)
  169. {
  170. stopThread (2000);
  171. isRunning = false;
  172. closeDevices();
  173. }
  174. }
  175. int getOutputLatencyInSamples() { return 0; } // TODO
  176. int getInputLatencyInSamples() { return 0; } // TODO
  177. bool isOpen() { return isRunning; }
  178. int getCurrentBufferSizeSamples() { return actualBufferSize; }
  179. int getCurrentBitDepth() { return 16; }
  180. double getCurrentSampleRate() { return sampleRate; }
  181. BigInteger getActiveOutputChannels() const { return activeOutputChans; }
  182. BigInteger getActiveInputChannels() const { return activeInputChans; }
  183. String getLastError() { return lastError; }
  184. bool isPlaying() { return isRunning && callback != 0; }
  185. void start (AudioIODeviceCallback* newCallback)
  186. {
  187. if (isRunning && callback != newCallback)
  188. {
  189. if (newCallback != nullptr)
  190. newCallback->audioDeviceAboutToStart (this);
  191. const ScopedLock sl (callbackLock);
  192. callback = newCallback;
  193. }
  194. }
  195. void stop()
  196. {
  197. if (isRunning)
  198. {
  199. AudioIODeviceCallback* lastCallback;
  200. {
  201. const ScopedLock sl (callbackLock);
  202. lastCallback = callback;
  203. callback = nullptr;
  204. }
  205. if (lastCallback != nullptr)
  206. lastCallback->audioDeviceStopped();
  207. }
  208. }
  209. void run()
  210. {
  211. JNIEnv* env = getEnv();
  212. jshortArray audioBuffer = env->NewShortArray (actualBufferSize * jmax (numDeviceOutputChannels, numDeviceInputChannels));
  213. while (! threadShouldExit())
  214. {
  215. if (inputDevice != nullptr)
  216. {
  217. jint numRead = env->CallIntMethod (inputDevice, AudioRecord.read, audioBuffer, 0, actualBufferSize * numDeviceInputChannels);
  218. if (numRead < actualBufferSize * numDeviceInputChannels)
  219. {
  220. DBG ("Audio read under-run! " << numRead);
  221. }
  222. jshort* const src = env->GetShortArrayElements (audioBuffer, 0);
  223. for (int chan = 0; chan < inputChannelBuffer.getNumChannels(); ++chan)
  224. {
  225. AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> d (inputChannelBuffer.getSampleData (chan));
  226. if (chan < numDeviceInputChannels)
  227. {
  228. AudioData::Pointer <AudioData::Int16, AudioData::NativeEndian, AudioData::Interleaved, AudioData::Const> s (src + chan, numDeviceInputChannels);
  229. d.convertSamples (s, actualBufferSize);
  230. }
  231. else
  232. {
  233. d.clearSamples (actualBufferSize);
  234. }
  235. }
  236. env->ReleaseShortArrayElements (audioBuffer, src, 0);
  237. }
  238. if (threadShouldExit())
  239. break;
  240. {
  241. const ScopedLock sl (callbackLock);
  242. if (callback != nullptr)
  243. {
  244. callback->audioDeviceIOCallback ((const float**) inputChannelBuffer.getArrayOfChannels(), numClientInputChannels,
  245. outputChannelBuffer.getArrayOfChannels(), numClientOutputChannels,
  246. actualBufferSize);
  247. }
  248. else
  249. {
  250. outputChannelBuffer.clear();
  251. }
  252. }
  253. if (outputDevice != nullptr)
  254. {
  255. if (threadShouldExit())
  256. break;
  257. jshort* const dest = env->GetShortArrayElements (audioBuffer, 0);
  258. for (int chan = 0; chan < numDeviceOutputChannels; ++chan)
  259. {
  260. AudioData::Pointer <AudioData::Int16, AudioData::NativeEndian, AudioData::Interleaved, AudioData::NonConst> d (dest + chan, numDeviceOutputChannels);
  261. const float* const sourceChanData = outputChannelBuffer.getSampleData (jmin (chan, outputChannelBuffer.getNumChannels() - 1));
  262. AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> s (sourceChanData);
  263. d.convertSamples (s, actualBufferSize);
  264. }
  265. env->ReleaseShortArrayElements (audioBuffer, dest, 0);
  266. jint numWritten = env->CallIntMethod (outputDevice, AudioTrack.write, audioBuffer, 0, actualBufferSize * numDeviceOutputChannels);
  267. if (numWritten < actualBufferSize * numDeviceOutputChannels)
  268. {
  269. DBG ("Audio write underrun! " << numWritten);
  270. }
  271. }
  272. }
  273. }
  274. private:
  275. //==================================================================================================
  276. CriticalSection callbackLock;
  277. AudioIODeviceCallback* callback;
  278. jint sampleRate;
  279. int numClientInputChannels, numDeviceInputChannels, numDeviceInputChannelsAvailable;
  280. int numClientOutputChannels, numDeviceOutputChannels;
  281. int minbufferSize, actualBufferSize;
  282. bool isRunning;
  283. String lastError;
  284. BigInteger activeOutputChans, activeInputChans;
  285. GlobalRef outputDevice, inputDevice;
  286. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  287. void closeDevices()
  288. {
  289. if (outputDevice != nullptr)
  290. {
  291. outputDevice.callVoidMethod (AudioTrack.stop);
  292. outputDevice.callVoidMethod (AudioTrack.release);
  293. outputDevice.clear();
  294. }
  295. if (inputDevice != nullptr)
  296. {
  297. inputDevice.callVoidMethod (AudioRecord.stop);
  298. inputDevice.callVoidMethod (AudioRecord.release);
  299. inputDevice.clear();
  300. }
  301. }
  302. JUCE_DECLARE_NON_COPYABLE (AndroidAudioIODevice);
  303. };
  304. //==============================================================================
  305. class AndroidAudioIODeviceType : public AudioIODeviceType
  306. {
  307. public:
  308. AndroidAudioIODeviceType()
  309. : AudioIODeviceType ("Android Audio")
  310. {
  311. }
  312. //==============================================================================
  313. void scanForDevices() {}
  314. int getDefaultDeviceIndex (bool forInput) const { return 0; }
  315. int getIndexOfDevice (AudioIODevice* device, bool asInput) const { return device != nullptr ? 0 : -1; }
  316. bool hasSeparateInputsAndOutputs() const { return false; }
  317. StringArray getDeviceNames (bool wantInputNames) const
  318. {
  319. StringArray s;
  320. s.add ("Android Audio");
  321. return s;
  322. }
  323. AudioIODevice* createDevice (const String& outputDeviceName,
  324. const String& inputDeviceName)
  325. {
  326. ScopedPointer<AndroidAudioIODevice> dev;
  327. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  328. {
  329. dev = new AndroidAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  330. : inputDeviceName);
  331. if (dev->getCurrentSampleRate() <= 0 || dev->getDefaultBufferSize() <= 0)
  332. dev = nullptr;
  333. }
  334. return dev.release();
  335. }
  336. private:
  337. //==============================================================================
  338. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidAudioIODeviceType);
  339. };
  340. //==============================================================================
  341. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_Android()
  342. {
  343. return new AndroidAudioIODeviceType();
  344. }