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.

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