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.

1462 lines
60KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2018 - 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. #ifndef JUCE_OBOE_LOG_ENABLED
  18. #define JUCE_OBOE_LOG_ENABLED 1
  19. #endif
  20. #if JUCE_OBOE_LOG_ENABLED
  21. #define JUCE_OBOE_LOG(x) DBG(x)
  22. #else
  23. #define JUCE_OBOE_LOG(x) {}
  24. #endif
  25. namespace juce
  26. {
  27. template <typename OboeDataFormat> struct OboeAudioIODeviceBufferHelpers {};
  28. template<>
  29. struct OboeAudioIODeviceBufferHelpers<int16>
  30. {
  31. static oboe::AudioFormat oboeAudioFormat() { return oboe::AudioFormat::I16; }
  32. static constexpr int bitDepth() { return 16; }
  33. static void referAudioBufferDirectlyToOboeIfPossible (int16*, AudioBuffer<float>&, int) {}
  34. static void convertFromOboe (const int16* srcInterleaved, AudioBuffer<float>& audioBuffer, int numSamples)
  35. {
  36. for (int i = 0; i < audioBuffer.getNumChannels(); ++i)
  37. {
  38. using DstSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst>;
  39. using SrcSampleType = AudioData::Pointer<AudioData::Int16, AudioData::NativeEndian, AudioData::Interleaved, AudioData::Const>;
  40. DstSampleType dstData (audioBuffer.getWritePointer (i));
  41. SrcSampleType srcData (srcInterleaved + i, audioBuffer.getNumChannels());
  42. dstData.convertSamples (srcData, numSamples);
  43. }
  44. }
  45. static void convertToOboe (const AudioBuffer<float>& audioBuffer, int16* dstInterleaved, int numSamples)
  46. {
  47. for (int i = 0; i < audioBuffer.getNumChannels(); ++i)
  48. {
  49. using DstSampleType = AudioData::Pointer<AudioData::Int16, AudioData::NativeEndian, AudioData::Interleaved, AudioData::NonConst>;
  50. using SrcSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const>;
  51. DstSampleType dstData (dstInterleaved + i, audioBuffer.getNumChannels());
  52. SrcSampleType srcData (audioBuffer.getReadPointer (i));
  53. dstData.convertSamples (srcData, numSamples);
  54. }
  55. }
  56. };
  57. template<>
  58. struct OboeAudioIODeviceBufferHelpers<float>
  59. {
  60. static oboe::AudioFormat oboeAudioFormat() { return oboe::AudioFormat::Float; }
  61. static constexpr int bitDepth() { return 32; }
  62. static void referAudioBufferDirectlyToOboeIfPossible (float* nativeBuffer, AudioBuffer<float>& audioBuffer, int numSamples)
  63. {
  64. if (audioBuffer.getNumChannels() == 1)
  65. audioBuffer.setDataToReferTo (&nativeBuffer, 1, numSamples);
  66. }
  67. static void convertFromOboe (const float* srcInterleaved, AudioBuffer<float>& audioBuffer, int numSamples)
  68. {
  69. // No need to convert, we instructed the buffer to point to the src data directly already
  70. if (audioBuffer.getNumChannels() == 1)
  71. {
  72. jassert (audioBuffer.getWritePointer (0) == srcInterleaved);
  73. return;
  74. }
  75. for (int i = 0; i < audioBuffer.getNumChannels(); ++i)
  76. {
  77. using DstSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst>;
  78. using SrcSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::Interleaved, AudioData::Const>;
  79. DstSampleType dstData (audioBuffer.getWritePointer (i));
  80. SrcSampleType srcData (srcInterleaved + i, audioBuffer.getNumChannels());
  81. dstData.convertSamples (srcData, numSamples);
  82. }
  83. }
  84. static void convertToOboe (const AudioBuffer<float>& audioBuffer, float* dstInterleaved, int numSamples)
  85. {
  86. // No need to convert, we instructed the buffer to point to the src data directly already
  87. if (audioBuffer.getNumChannels() == 1)
  88. {
  89. jassert (audioBuffer.getReadPointer (0) == dstInterleaved);
  90. return;
  91. }
  92. for (int i = 0; i < audioBuffer.getNumChannels(); ++i)
  93. {
  94. using DstSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::Interleaved, AudioData::NonConst>;
  95. using SrcSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const>;
  96. DstSampleType dstData (dstInterleaved + i, audioBuffer.getNumChannels());
  97. SrcSampleType srcData (audioBuffer.getReadPointer (i));
  98. dstData.convertSamples (srcData, numSamples);
  99. }
  100. }
  101. };
  102. template <typename Type>
  103. static String getOboeString (const Type& value)
  104. {
  105. return String (oboe::convertToText (value));
  106. }
  107. //==============================================================================
  108. class OboeAudioIODevice : public AudioIODevice
  109. {
  110. public:
  111. //==============================================================================
  112. OboeAudioIODevice (const String& deviceName,
  113. int inputDeviceIdToUse,
  114. const Array<int>& supportedInputSampleRatesToUse,
  115. int maxNumInputChannelsToUse,
  116. int outputDeviceIdToUse,
  117. const Array<int>& supportedOutputSampleRatesToUse,
  118. int maxNumOutputChannelsToUse)
  119. : AudioIODevice (deviceName, oboeTypeName),
  120. inputDeviceId (inputDeviceIdToUse),
  121. supportedInputSampleRates (supportedInputSampleRatesToUse),
  122. maxNumInputChannels (maxNumInputChannelsToUse),
  123. outputDeviceId (outputDeviceIdToUse),
  124. supportedOutputSampleRates (supportedOutputSampleRatesToUse),
  125. maxNumOutputChannels (maxNumOutputChannelsToUse)
  126. {
  127. // At least an input or an output has to be supported by the device!
  128. jassert (inputDeviceId != -1 || outputDeviceId != -1);
  129. }
  130. ~OboeAudioIODevice()
  131. {
  132. close();
  133. }
  134. StringArray getOutputChannelNames() override { return getChannelNames (false); }
  135. StringArray getInputChannelNames() override { return getChannelNames (true); }
  136. Array<double> getAvailableSampleRates() override
  137. {
  138. Array<double> result;
  139. auto inputSampleRates = getAvailableSampleRates (true);
  140. auto outputSampleRates = getAvailableSampleRates (false);
  141. if (inputDeviceId == -1)
  142. {
  143. for (auto& sr : outputSampleRates)
  144. result.add (sr);
  145. }
  146. else if (outputDeviceId == -1)
  147. {
  148. for (auto& sr : inputSampleRates)
  149. result.add (sr);
  150. }
  151. else
  152. {
  153. // For best performance, the same sample rate should be used for input and output,
  154. for (auto& inputSampleRate : inputSampleRates)
  155. {
  156. if (outputSampleRates.contains (inputSampleRate))
  157. result.add (inputSampleRate);
  158. }
  159. }
  160. // either invalid device was requested or its input&output don't have compatible sample rate
  161. jassert (result.size() > 0);
  162. return result;
  163. }
  164. Array<int> getAvailableBufferSizes() override
  165. {
  166. // we need to offer the lowest possible buffer size which
  167. // is the native buffer size
  168. const int defaultNumMultiples = 8;
  169. const int nativeBufferSize = getNativeBufferSize();
  170. Array<int> bufferSizes;
  171. for (int i = 1; i < defaultNumMultiples; ++i)
  172. bufferSizes.add (i * nativeBufferSize);
  173. return bufferSizes;
  174. }
  175. String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  176. double requestedSampleRate, int bufferSize) override
  177. {
  178. close();
  179. lastError.clear();
  180. sampleRate = (int) requestedSampleRate;
  181. actualBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  182. // The device may report no max, claiming "no limits". Pick sensible defaults.
  183. int maxOutChans = maxNumOutputChannels > 0 ? maxNumOutputChannels : 2;
  184. int maxInChans = maxNumInputChannels > 0 ? maxNumInputChannels : 1;
  185. activeOutputChans = outputChannels;
  186. activeOutputChans.setRange (maxOutChans,
  187. activeOutputChans.getHighestBit() + 1 - maxOutChans,
  188. false);
  189. activeInputChans = inputChannels;
  190. activeInputChans.setRange (maxInChans,
  191. activeInputChans.getHighestBit() + 1 - maxInChans,
  192. false);
  193. int numOutputChans = activeOutputChans.countNumberOfSetBits();
  194. int numInputChans = activeInputChans.countNumberOfSetBits();
  195. if (numInputChans > 0 && (! RuntimePermissions::isGranted (RuntimePermissions::recordAudio)))
  196. {
  197. // If you hit this assert, you probably forgot to get RuntimePermissions::recordAudio
  198. // before trying to open an audio input device. This is not going to work!
  199. jassertfalse;
  200. lastError = "Error opening Oboe input device: the app was not granted android.permission.RECORD_AUDIO";
  201. }
  202. // At least one output channel should be set!
  203. jassert (numOutputChans >= 0);
  204. session.reset (OboeSessionBase::create (*this,
  205. inputDeviceId, outputDeviceId,
  206. numInputChans, numOutputChans,
  207. sampleRate, actualBufferSize));
  208. deviceOpen = session != nullptr;
  209. if (! deviceOpen)
  210. lastError = "Failed to create audio session";
  211. return lastError;
  212. }
  213. void close() override { stop(); }
  214. int getOutputLatencyInSamples() override { return session->getOutputLatencyInSamples(); }
  215. int getInputLatencyInSamples() override { return session->getInputLatencyInSamples(); }
  216. bool isOpen() override { return deviceOpen; }
  217. int getCurrentBufferSizeSamples() override { return actualBufferSize; }
  218. int getCurrentBitDepth() override { return session->getCurrentBitDepth(); }
  219. BigInteger getActiveOutputChannels() const override { return activeOutputChans; }
  220. BigInteger getActiveInputChannels() const override { return activeInputChans; }
  221. String getLastError() override { return lastError; }
  222. bool isPlaying() override { return callback.get() != nullptr; }
  223. int getXRunCount() const noexcept override { return session->getXRunCount(); }
  224. int getDefaultBufferSize() override
  225. {
  226. // Only on a Pro-Audio device will we set the lowest possible buffer size
  227. // by default. We need to be more conservative on other devices
  228. // as they may be low-latency, but still have a crappy CPU.
  229. return (isProAudioDevice() ? 1 : 6)
  230. * getNativeBufferSize();
  231. }
  232. double getCurrentSampleRate() override
  233. {
  234. return (sampleRate == 0.0 ? getNativeSampleRate() : sampleRate);
  235. }
  236. void start (AudioIODeviceCallback* newCallback) override
  237. {
  238. if (callback.get() != newCallback)
  239. {
  240. if (newCallback != nullptr)
  241. newCallback->audioDeviceAboutToStart (this);
  242. AudioIODeviceCallback* oldCallback = callback.get();
  243. if (oldCallback != nullptr)
  244. {
  245. // already running
  246. if (newCallback == nullptr)
  247. stop();
  248. else
  249. setCallback (newCallback);
  250. oldCallback->audioDeviceStopped();
  251. }
  252. else
  253. {
  254. jassert (newCallback != nullptr);
  255. // session hasn't started yet
  256. setCallback (newCallback);
  257. running = true;
  258. session->start();
  259. }
  260. callback = newCallback;
  261. }
  262. }
  263. void stop() override
  264. {
  265. if (session != nullptr)
  266. session->stop();
  267. running = false;
  268. setCallback (nullptr);
  269. }
  270. bool setAudioPreprocessingEnabled (bool) override
  271. {
  272. // Oboe does not expose this setting, yet it may use preprocessing
  273. // for older APIs running OpenSL
  274. return false;
  275. }
  276. static const char* const oboeTypeName;
  277. private:
  278. StringArray getChannelNames (bool forInput)
  279. {
  280. auto& deviceId = forInput ? inputDeviceId : outputDeviceId;
  281. auto& numChannels = forInput ? maxNumInputChannels : maxNumOutputChannels;
  282. // If the device id is unknown (on olders APIs) or if the device claims to
  283. // support "any" channel count, use a sensible default
  284. if (deviceId == -1 || numChannels == -1)
  285. return forInput ? StringArray ("Input") : StringArray ("Left", "Right");
  286. StringArray names;
  287. for (int i = 0; i < numChannels; ++i)
  288. names.add ("Channel " + String (i + 1));
  289. return names;
  290. }
  291. Array<int> getAvailableSampleRates (bool forInput)
  292. {
  293. auto& supportedSampleRates = forInput
  294. ? supportedInputSampleRates
  295. : supportedOutputSampleRates;
  296. if (! supportedSampleRates.isEmpty())
  297. return supportedSampleRates;
  298. // device claims that it supports "any" sample rate, use
  299. // standard ones then
  300. return getDefaultSampleRates();
  301. }
  302. static Array<int> getDefaultSampleRates()
  303. {
  304. static const int standardRates[] = { 8000, 11025, 12000, 16000,
  305. 22050, 24000, 32000, 44100, 48000 };
  306. Array<int> rates (standardRates, numElementsInArray (standardRates));
  307. // make sure the native sample rate is part of the list
  308. int native = (int) getNativeSampleRate();
  309. if (native != 0 && ! rates.contains (native))
  310. rates.add (native);
  311. return rates;
  312. }
  313. void setCallback (AudioIODeviceCallback* callbackToUse)
  314. {
  315. if (! running)
  316. {
  317. callback.set (callbackToUse);
  318. return;
  319. }
  320. // Setting nullptr callback is allowed only when playback is stopped.
  321. jassert (callbackToUse != nullptr);
  322. for (;;)
  323. {
  324. auto old = callback.get();
  325. if (old == callbackToUse)
  326. break;
  327. // If old is nullptr, then it means that it's currently being used!
  328. if (old != nullptr && callback.compareAndSetBool (callbackToUse, old))
  329. break;
  330. Thread::sleep (1);
  331. }
  332. }
  333. void process (const float** inputChannelData, int numInputChannels,
  334. float** outputChannelData, int numOutputChannels, int32_t numFrames)
  335. {
  336. if (auto* cb = callback.exchange (nullptr))
  337. {
  338. cb->audioDeviceIOCallback (inputChannelData, numInputChannels,
  339. outputChannelData, numOutputChannels, numFrames);
  340. callback.set (cb);
  341. }
  342. else
  343. {
  344. for (int i = 0; i < numOutputChannels; ++i)
  345. zeromem (outputChannelData[i], sizeof (float) * static_cast<size_t> (numFrames));
  346. }
  347. }
  348. //==============================================================================
  349. class OboeStream
  350. {
  351. public:
  352. OboeStream (int deviceId, oboe::Direction direction,
  353. oboe::SharingMode sharingMode,
  354. int channelCount, oboe::AudioFormat format,
  355. int32 sampleRate, int32 bufferSize,
  356. oboe::AudioStreamCallback* callback = nullptr)
  357. {
  358. open (deviceId, direction, sharingMode, channelCount,
  359. format, sampleRate, bufferSize, callback);
  360. }
  361. ~OboeStream()
  362. {
  363. close();
  364. delete stream;
  365. }
  366. bool openedOk() const noexcept
  367. {
  368. return openResult == oboe::Result::OK;
  369. }
  370. void start()
  371. {
  372. jassert (openedOk());
  373. if (openedOk() && stream != nullptr)
  374. {
  375. auto expectedState = oboe::StreamState::Starting;
  376. auto nextState = oboe::StreamState::Started;
  377. int64 timeoutNanos = 1000 * oboe::kNanosPerMillisecond;
  378. auto startResult = stream->requestStart();
  379. JUCE_OBOE_LOG ("Requested Oboe stream start with result: " + getOboeString (startResult));
  380. startResult = stream->waitForStateChange (expectedState, &nextState, timeoutNanos);
  381. JUCE_OBOE_LOG ("Starting Oboe stream with result: " + getOboeString (startResult);
  382. + "\nUses AAudio = " + String ((int) stream->usesAAudio())
  383. + "\nDirection = " + getOboeString (stream->getDirection())
  384. + "\nSharingMode = " + getOboeString (stream->getSharingMode())
  385. + "\nChannelCount = " + String (stream->getChannelCount())
  386. + "\nFormat = " + getOboeString (stream->getFormat())
  387. + "\nSampleRate = " + String (stream->getSampleRate())
  388. + "\nBufferSizeInFrames = " + String (stream->getBufferSizeInFrames())
  389. + "\nBufferCapacityInFrames = " + String (stream->getBufferCapacityInFrames())
  390. + "\nFramesPerBurst = " + String (stream->getFramesPerBurst())
  391. + "\nFramesPerCallback = " + String (stream->getFramesPerCallback())
  392. + "\nBytesPerFrame = " + String (stream->getBytesPerFrame())
  393. + "\nBytesPerSample = " + String (stream->getBytesPerSample())
  394. + "\nPerformanceMode = " + getOboeString (oboe::PerformanceMode::LowLatency)
  395. + "\ngetDeviceId = " + String (stream->getDeviceId()));
  396. }
  397. }
  398. oboe::AudioStream* getNativeStream() const
  399. {
  400. jassert (openedOk());
  401. return stream;
  402. }
  403. int getXRunCount() const
  404. {
  405. if (stream != nullptr)
  406. {
  407. auto count = stream->getXRunCount();
  408. if (count)
  409. return count.value();
  410. JUCE_OBOE_LOG ("Failed to get Xrun count: " + getOboeString (count.error()));
  411. }
  412. return 0;
  413. }
  414. private:
  415. void open (int deviceId, oboe::Direction direction,
  416. oboe::SharingMode sharingMode,
  417. int channelCount, oboe::AudioFormat format,
  418. int32 sampleRate, int32 bufferSize,
  419. oboe::AudioStreamCallback* callback = nullptr)
  420. {
  421. oboe::DefaultStreamValues::FramesPerBurst = getDefaultFramesPerBurst();
  422. oboe::AudioStreamBuilder builder;
  423. if (deviceId != -1)
  424. builder.setDeviceId (deviceId);
  425. // Note: letting OS to choose the buffer capacity & frames per callback.
  426. builder.setDirection (direction);
  427. builder.setSharingMode (sharingMode);
  428. builder.setChannelCount (channelCount);
  429. builder.setFormat (format);
  430. builder.setSampleRate (sampleRate);
  431. builder.setPerformanceMode (oboe::PerformanceMode::LowLatency);
  432. builder.setCallback (callback);
  433. JUCE_OBOE_LOG (String ("Preparing Oboe stream with params:")
  434. + "\nAAudio supported = " + String (int (builder.isAAudioSupported()))
  435. + "\nAPI = " + getOboeString (builder.getAudioApi())
  436. + "\nDeviceId = " + String (deviceId)
  437. + "\nDirection = " + getOboeString (direction)
  438. + "\nSharingMode = " + getOboeString (sharingMode)
  439. + "\nChannelCount = " + String (channelCount)
  440. + "\nFormat = " + getOboeString (format)
  441. + "\nSampleRate = " + String (sampleRate)
  442. + "\nPerformanceMode = " + getOboeString (oboe::PerformanceMode::LowLatency));
  443. openResult = builder.openStream (&stream);
  444. JUCE_OBOE_LOG ("Building Oboe stream with result: " + getOboeString (openResult)
  445. + "\nStream state = " + (stream != nullptr ? getOboeString (stream->getState()) : String ("?")));
  446. if (stream != nullptr && bufferSize != 0)
  447. {
  448. JUCE_OBOE_LOG ("Setting the bufferSizeInFrames to " + String (bufferSize));
  449. stream->setBufferSizeInFrames (bufferSize);
  450. }
  451. JUCE_OBOE_LOG (String ("Stream details:")
  452. + "\nUses AAudio = " + (stream != nullptr ? String ((int) stream->usesAAudio()) : String ("?"))
  453. + "\nDeviceId = " + (stream != nullptr ? String (stream->getDeviceId()) : String ("?"))
  454. + "\nDirection = " + (stream != nullptr ? getOboeString (stream->getDirection()) : String ("?"))
  455. + "\nSharingMode = " + (stream != nullptr ? getOboeString (stream->getSharingMode()) : String ("?"))
  456. + "\nChannelCount = " + (stream != nullptr ? String (stream->getChannelCount()) : String ("?"))
  457. + "\nFormat = " + (stream != nullptr ? getOboeString (stream->getFormat()) : String ("?"))
  458. + "\nSampleRate = " + (stream != nullptr ? String (stream->getSampleRate()) : String ("?"))
  459. + "\nBufferSizeInFrames = " + (stream != nullptr ? String (stream->getBufferSizeInFrames()) : String ("?"))
  460. + "\nBufferCapacityInFrames = " + (stream != nullptr ? String (stream->getBufferCapacityInFrames()) : String ("?"))
  461. + "\nFramesPerBurst = " + (stream != nullptr ? String (stream->getFramesPerBurst()) : String ("?"))
  462. + "\nFramesPerCallback = " + (stream != nullptr ? String (stream->getFramesPerCallback()) : String ("?"))
  463. + "\nBytesPerFrame = " + (stream != nullptr ? String (stream->getBytesPerFrame()) : String ("?"))
  464. + "\nBytesPerSample = " + (stream != nullptr ? String (stream->getBytesPerSample()) : String ("?"))
  465. + "\nPerformanceMode = " + getOboeString (oboe::PerformanceMode::LowLatency));
  466. }
  467. void close()
  468. {
  469. if (stream != nullptr)
  470. {
  471. oboe::Result result = stream->close();
  472. JUCE_OBOE_LOG ("Requested Oboe stream close with result: " + getOboeString (result));
  473. }
  474. }
  475. oboe::AudioStream* stream = nullptr;
  476. oboe::Result openResult;
  477. };
  478. //==============================================================================
  479. class OboeSessionBase : protected oboe::AudioStreamCallback
  480. {
  481. public:
  482. static OboeSessionBase* create (OboeAudioIODevice& owner,
  483. int inputDeviceId, int outputDeviceId,
  484. int numInputChannels, int numOutputChannels,
  485. int sampleRate, int bufferSize);
  486. virtual void start() = 0;
  487. virtual void stop() = 0;
  488. virtual int getOutputLatencyInSamples() = 0;
  489. virtual int getInputLatencyInSamples() = 0;
  490. bool openedOk() const noexcept
  491. {
  492. if (inputStream != nullptr && ! inputStream->openedOk())
  493. return false;
  494. return outputStream != nullptr && outputStream->openedOk();
  495. }
  496. int getCurrentBitDepth() const noexcept { return bitDepth; }
  497. int getXRunCount() const
  498. {
  499. int inputXRunCount = jmax (0, inputStream != nullptr ? inputStream->getXRunCount() : 0);
  500. int outputXRunCount = jmax (0, outputStream != nullptr ? outputStream->getXRunCount() : 0);
  501. return inputXRunCount + outputXRunCount;
  502. }
  503. protected:
  504. OboeSessionBase (OboeAudioIODevice& ownerToUse,
  505. int inputDeviceIdToUse, int outputDeviceIdToUse,
  506. int numInputChannelsToUse, int numOutputChannelsToUse,
  507. int sampleRateToUse, int bufferSizeToUse,
  508. oboe::AudioFormat streamFormatToUse,
  509. int bitDepthToUse)
  510. : owner (ownerToUse),
  511. inputDeviceId (inputDeviceIdToUse),
  512. outputDeviceId (outputDeviceIdToUse),
  513. numInputChannels (numInputChannelsToUse),
  514. numOutputChannels (numOutputChannelsToUse),
  515. sampleRate (sampleRateToUse),
  516. bufferSize (bufferSizeToUse),
  517. streamFormat (streamFormatToUse),
  518. bitDepth (bitDepthToUse),
  519. outputStream (new OboeStream (outputDeviceId,
  520. oboe::Direction::Output,
  521. oboe::SharingMode::Exclusive,
  522. numOutputChannels,
  523. streamFormatToUse,
  524. sampleRateToUse,
  525. bufferSizeToUse,
  526. this))
  527. {
  528. if (numInputChannels > 0)
  529. {
  530. inputStream.reset (new OboeStream (inputDeviceId,
  531. oboe::Direction::Input,
  532. oboe::SharingMode::Exclusive,
  533. numInputChannels,
  534. streamFormatToUse,
  535. sampleRateToUse,
  536. bufferSizeToUse,
  537. nullptr));
  538. if (inputStream->openedOk() && outputStream->openedOk())
  539. {
  540. // Input & output sample rates should match!
  541. jassert (inputStream->getNativeStream()->getSampleRate()
  542. == outputStream->getNativeStream()->getSampleRate());
  543. }
  544. checkStreamSetup (inputStream.get(), inputDeviceId, numInputChannels,
  545. sampleRate, bufferSize, streamFormat);
  546. }
  547. checkStreamSetup (outputStream.get(), outputDeviceId, numOutputChannels,
  548. sampleRate, bufferSize, streamFormat);
  549. }
  550. // Not strictly required as these should not change, but recommended by Google anyway
  551. void checkStreamSetup (OboeStream* stream, int deviceId, int numChannels, int sampleRate,
  552. int bufferSize, oboe::AudioFormat format)
  553. {
  554. if (auto* nativeStream = stream != nullptr ? stream->getNativeStream() : nullptr)
  555. {
  556. ignoreUnused (deviceId, numChannels, sampleRate, bufferSize);
  557. ignoreUnused (streamFormat, bitDepth);
  558. jassert (numChannels == nativeStream->getChannelCount());
  559. jassert (sampleRate == 0 || sampleRate == nativeStream->getSampleRate());
  560. jassert (format == nativeStream->getFormat());
  561. }
  562. }
  563. int getBufferCapacityInFrames (bool forInput) const
  564. {
  565. auto& ptr = forInput ? inputStream : outputStream;
  566. if (ptr == nullptr || ! ptr->openedOk())
  567. return 0;
  568. return ptr->getNativeStream()->getBufferCapacityInFrames();
  569. }
  570. OboeAudioIODevice& owner;
  571. int inputDeviceId, outputDeviceId;
  572. int numInputChannels, numOutputChannels;
  573. int sampleRate;
  574. int bufferSize;
  575. oboe::AudioFormat streamFormat;
  576. int bitDepth;
  577. std::unique_ptr<OboeStream> inputStream, outputStream;
  578. };
  579. //==============================================================================
  580. template <typename SampleType>
  581. class OboeSessionImpl : public OboeSessionBase
  582. {
  583. public:
  584. OboeSessionImpl (OboeAudioIODevice& ownerToUse,
  585. int inputDeviceId, int outputDeviceId,
  586. int numInputChannelsToUse, int numOutputChannelsToUse,
  587. int sampleRateToUse, int bufferSizeToUse)
  588. : OboeSessionBase (ownerToUse,
  589. inputDeviceId, outputDeviceId,
  590. numInputChannelsToUse, numOutputChannelsToUse,
  591. sampleRateToUse, bufferSizeToUse,
  592. OboeAudioIODeviceBufferHelpers<SampleType>::oboeAudioFormat(),
  593. OboeAudioIODeviceBufferHelpers<SampleType>::bitDepth()),
  594. inputStreamNativeBuffer (static_cast<size_t> (numInputChannelsToUse * getBufferCapacityInFrames (true))),
  595. inputStreamSampleBuffer (numInputChannels, getBufferCapacityInFrames (true)),
  596. outputStreamSampleBuffer (numOutputChannels, getBufferCapacityInFrames (false))
  597. {
  598. }
  599. void start() override
  600. {
  601. audioCallbackGuard.set (0);
  602. if (inputStream != nullptr)
  603. inputStream->start();
  604. outputStream->start();
  605. isInputLatencyDetectionSupported = isLatencyDetectionSupported (inputStream.get());
  606. isOutputLatencyDetectionSupported = isLatencyDetectionSupported (outputStream.get());
  607. }
  608. void stop() override
  609. {
  610. while (! audioCallbackGuard.compareAndSetBool (1, 0))
  611. Thread::sleep (1);
  612. inputStream = nullptr;
  613. outputStream = nullptr;
  614. audioCallbackGuard.set (0);
  615. }
  616. int getOutputLatencyInSamples() override { return outputLatency; }
  617. int getInputLatencyInSamples() override { return inputLatency; }
  618. private:
  619. bool isLatencyDetectionSupported (OboeStream* stream)
  620. {
  621. if (stream == nullptr || ! openedOk())
  622. return false;
  623. auto result = stream->getNativeStream()->getTimestamp (CLOCK_MONOTONIC, 0, 0);
  624. return result != oboe::Result::ErrorUnimplemented;
  625. }
  626. oboe::DataCallbackResult onAudioReady (oboe::AudioStream* stream, void* audioData, int32_t numFrames) override
  627. {
  628. if (audioCallbackGuard.compareAndSetBool (1, 0))
  629. {
  630. if (stream == nullptr)
  631. return oboe::DataCallbackResult::Stop;
  632. // only output stream should be the master stream receiving callbacks
  633. jassert (stream->getDirection() == oboe::Direction::Output && stream == outputStream->getNativeStream());
  634. //-----------------
  635. // Read input from Oboe
  636. inputStreamSampleBuffer.clear();
  637. inputStreamNativeBuffer.calloc (static_cast<size_t> (numInputChannels * bufferSize));
  638. if (inputStream != nullptr)
  639. {
  640. auto* nativeInputStream = inputStream->getNativeStream();
  641. if (nativeInputStream->getFormat() != oboe::AudioFormat::I16 && nativeInputStream->getFormat() != oboe::AudioFormat::Float)
  642. {
  643. JUCE_OBOE_LOG ("Unsupported input stream audio format: " + getOboeString (nativeInputStream->getFormat()));
  644. jassertfalse;
  645. return oboe::DataCallbackResult::Continue;
  646. }
  647. auto result = inputStream->getNativeStream()->read (inputStreamNativeBuffer.getData(), numFrames, 0);
  648. if (result)
  649. {
  650. OboeAudioIODeviceBufferHelpers<SampleType>::referAudioBufferDirectlyToOboeIfPossible (inputStreamNativeBuffer.get(),
  651. inputStreamSampleBuffer,
  652. result.value());
  653. OboeAudioIODeviceBufferHelpers<SampleType>::convertFromOboe (inputStreamNativeBuffer.get(), inputStreamSampleBuffer, result.value());
  654. }
  655. else
  656. {
  657. JUCE_OBOE_LOG ("Failed to read from input stream: " + getOboeString (result.error()));
  658. }
  659. if (isInputLatencyDetectionSupported)
  660. inputLatency = getLatencyFor (*inputStream);
  661. }
  662. //-----------------
  663. // Setup output buffer
  664. outputStreamSampleBuffer.clear();
  665. OboeAudioIODeviceBufferHelpers<SampleType>::referAudioBufferDirectlyToOboeIfPossible (static_cast<SampleType*> (audioData),
  666. outputStreamSampleBuffer,
  667. numFrames);
  668. //-----------------
  669. // Process
  670. // NB: the number of samples read from the input can potentially differ from numFrames.
  671. owner.process (inputStreamSampleBuffer.getArrayOfReadPointers(), numInputChannels,
  672. outputStreamSampleBuffer.getArrayOfWritePointers(), numOutputChannels,
  673. numFrames);
  674. //-----------------
  675. // Write output to Oboe
  676. OboeAudioIODeviceBufferHelpers<SampleType>::convertToOboe (outputStreamSampleBuffer, static_cast<SampleType*> (audioData), numFrames);
  677. if (isOutputLatencyDetectionSupported)
  678. outputLatency = getLatencyFor (*outputStream);
  679. audioCallbackGuard.set (0);
  680. }
  681. return oboe::DataCallbackResult::Continue;
  682. }
  683. void printStreamDebugInfo (oboe::AudioStream* stream)
  684. {
  685. ignoreUnused (stream);
  686. JUCE_OBOE_LOG ("\nUses AAudio = " + (stream != nullptr ? String ((int) stream->usesAAudio()) : String ("?"))
  687. + "\nDirection = " + (stream != nullptr ? getOboeString (stream->getDirection()) : String ("?"))
  688. + "\nSharingMode = " + (stream != nullptr ? getOboeString (stream->getSharingMode()) : String ("?"))
  689. + "\nChannelCount = " + (stream != nullptr ? String (stream->getChannelCount()) : String ("?"))
  690. + "\nFormat = " + (stream != nullptr ? getOboeString (stream->getFormat()) : String ("?"))
  691. + "\nSampleRate = " + (stream != nullptr ? String (stream->getSampleRate()) : String ("?"))
  692. + "\nBufferSizeInFrames = " + (stream != nullptr ? String (stream->getBufferSizeInFrames()) : String ("?"))
  693. + "\nBufferCapacityInFrames = " + (stream != nullptr ? String (stream->getBufferCapacityInFrames()) : String ("?"))
  694. + "\nFramesPerBurst = " + (stream != nullptr ? String (stream->getFramesPerBurst()) : String ("?"))
  695. + "\nFramesPerCallback = " + (stream != nullptr ? String (stream->getFramesPerCallback()) : String ("?"))
  696. + "\nBytesPerFrame = " + (stream != nullptr ? String (stream->getBytesPerFrame()) : String ("?"))
  697. + "\nBytesPerSample = " + (stream != nullptr ? String (stream->getBytesPerSample()) : String ("?"))
  698. + "\nPerformanceMode = " + getOboeString (oboe::PerformanceMode::LowLatency)
  699. + "\ngetDeviceId = " + (stream != nullptr ? String (stream->getDeviceId()) : String ("?")));
  700. }
  701. int getLatencyFor (OboeStream& stream)
  702. {
  703. auto& nativeStream = *stream.getNativeStream();
  704. if (auto latency = nativeStream.calculateLatencyMillis())
  705. return static_cast<int> ((latency.value() * sampleRate) / 1000);
  706. // Get the time that a known audio frame was presented.
  707. int64_t hardwareFrameIndex = 0;
  708. int64_t hardwareFrameHardwareTime = 0;
  709. auto result = nativeStream.getTimestamp (CLOCK_MONOTONIC,
  710. &hardwareFrameIndex,
  711. &hardwareFrameHardwareTime);
  712. if (result != oboe::Result::OK)
  713. return 0;
  714. // Get counter closest to the app.
  715. const bool isOutput = nativeStream.getDirection() == oboe::Direction::Output;
  716. const int64_t appFrameIndex = isOutput ? nativeStream.getFramesWritten() : nativeStream.getFramesRead();
  717. // Assume that the next frame will be processed at the current time
  718. using namespace std::chrono;
  719. int64_t appFrameAppTime = getCurrentTimeNanos();//duration_cast<nanoseconds> (steady_clock::now().time_since_epoch()).count();
  720. int64_t appFrameAppTime2 = duration_cast<nanoseconds> (steady_clock::now().time_since_epoch()).count();
  721. // Calculate the number of frames between app and hardware
  722. int64_t frameIndexDelta = appFrameIndex - hardwareFrameIndex;
  723. // Calculate the time which the next frame will be or was presented
  724. int64_t frameTimeDelta = (frameIndexDelta * oboe::kNanosPerSecond) / sampleRate;
  725. int64_t appFrameHardwareTime = hardwareFrameHardwareTime + frameTimeDelta;
  726. // Calculate latency as a difference in time between when the current frame is at the app
  727. // and when it is at the hardware.
  728. auto latencyNanos = isOutput ? (appFrameHardwareTime - appFrameAppTime) : (appFrameAppTime - appFrameHardwareTime);
  729. return static_cast<int> ((latencyNanos * sampleRate) / oboe::kNanosPerSecond);
  730. }
  731. int64_t getCurrentTimeNanos()
  732. {
  733. timespec time;
  734. if (clock_gettime (CLOCK_MONOTONIC, &time) < 0)
  735. return -1;
  736. return time.tv_sec * oboe::kNanosPerSecond + time.tv_nsec;
  737. }
  738. void onErrorBeforeClose (oboe::AudioStream* stream, oboe::Result error) override
  739. {
  740. // only output stream should be the master stream receiving callbacks
  741. jassert (stream->getDirection() == oboe::Direction::Output);
  742. JUCE_OBOE_LOG ("Oboe stream onErrorBeforeClose(): " + getOboeString (error));
  743. printStreamDebugInfo (stream);
  744. }
  745. void onErrorAfterClose (oboe::AudioStream* stream, oboe::Result error) override
  746. {
  747. // only output stream should be the master stream receiving callbacks
  748. jassert (stream->getDirection() == oboe::Direction::Output);
  749. JUCE_OBOE_LOG ("Oboe stream onErrorAfterClose(): " + getOboeString (error));
  750. if (error == oboe::Result::ErrorDisconnected)
  751. {
  752. if (streamRestartGuard.compareAndSetBool (1, 0))
  753. {
  754. // Close, recreate, and start the stream, not much use in current one.
  755. // Use default device id, to let the OS pick the best ID (since our was disconnected).
  756. while (! audioCallbackGuard.compareAndSetBool (1, 0))
  757. Thread::sleep (1);
  758. outputStream = nullptr;
  759. outputStream.reset (new OboeStream (-1,
  760. oboe::Direction::Output,
  761. oboe::SharingMode::Exclusive,
  762. numOutputChannels,
  763. streamFormat,
  764. sampleRate,
  765. bufferSize,
  766. this));
  767. outputStream->start();
  768. audioCallbackGuard.set (0);
  769. streamRestartGuard.set (0);
  770. }
  771. }
  772. }
  773. HeapBlock<SampleType> inputStreamNativeBuffer;
  774. AudioBuffer<float> inputStreamSampleBuffer,
  775. outputStreamSampleBuffer;
  776. Atomic<int> audioCallbackGuard { 0 },
  777. streamRestartGuard { 0 };
  778. bool isInputLatencyDetectionSupported = false;
  779. int inputLatency = -1;
  780. bool isOutputLatencyDetectionSupported = false;
  781. int outputLatency = -1;
  782. };
  783. //==============================================================================
  784. friend class OboeAudioIODeviceType;
  785. friend class OboeRealtimeThread;
  786. //==============================================================================
  787. int actualBufferSize = 0, sampleRate = 0;
  788. bool deviceOpen = false;
  789. String lastError;
  790. BigInteger activeOutputChans, activeInputChans;
  791. Atomic<AudioIODeviceCallback*> callback { nullptr };
  792. int inputDeviceId;
  793. Array<int> supportedInputSampleRates;
  794. int maxNumInputChannels;
  795. int outputDeviceId;
  796. Array<int> supportedOutputSampleRates;
  797. int maxNumOutputChannels;
  798. std::unique_ptr<OboeSessionBase> session;
  799. bool running = false;
  800. //==============================================================================
  801. static double getNativeSampleRate()
  802. {
  803. return audioManagerGetProperty ("android.media.property.OUTPUT_SAMPLE_RATE").getDoubleValue();
  804. }
  805. static int getNativeBufferSize()
  806. {
  807. auto val = audioManagerGetProperty ("android.media.property.OUTPUT_FRAMES_PER_BUFFER").getIntValue();
  808. return val > 0 ? val : 512;
  809. }
  810. static bool isProAudioDevice()
  811. {
  812. return androidHasSystemFeature ("android.hardware.audio.pro");
  813. }
  814. static int getDefaultFramesPerBurst()
  815. {
  816. // NB: this function only works for inbuilt speakers and headphones
  817. auto framesPerBurstString = javaString (audioManagerGetProperty ("android.media.property.OUTPUT_FRAMES_PER_BUFFER"));
  818. return framesPerBurstString != 0 ? getEnv()->CallStaticIntMethod (JavaInteger, JavaInteger.parseInt, framesPerBurstString.get(), 10) : 192;
  819. }
  820. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OboeAudioIODevice)
  821. };
  822. //==============================================================================
  823. OboeAudioIODevice::OboeSessionBase* OboeAudioIODevice::OboeSessionBase::create (OboeAudioIODevice& owner,
  824. int inputDeviceId,
  825. int outputDeviceId,
  826. int numInputChannels,
  827. int numOutputChannels,
  828. int sampleRate,
  829. int bufferSize)
  830. {
  831. std::unique_ptr<OboeSessionBase> session;
  832. auto sdkVersion = getAndroidSDKVersion();
  833. // SDK versions 21 and higher should natively support floating point...
  834. if (sdkVersion >= 21)
  835. {
  836. session.reset (new OboeSessionImpl<float> (owner, inputDeviceId, outputDeviceId,
  837. numInputChannels, numOutputChannels, sampleRate, bufferSize));
  838. // ...however, some devices lie so re-try without floating point
  839. if (session != nullptr && (! session->openedOk()))
  840. session.reset();
  841. }
  842. if (session == nullptr)
  843. {
  844. session.reset (new OboeSessionImpl<int16> (owner, inputDeviceId, outputDeviceId,
  845. numInputChannels, numOutputChannels, sampleRate, bufferSize));
  846. if (session != nullptr && (! session->openedOk()))
  847. session.reset();
  848. }
  849. return session.release();
  850. }
  851. //==============================================================================
  852. class OboeAudioIODeviceType : public AudioIODeviceType
  853. {
  854. public:
  855. OboeAudioIODeviceType()
  856. : AudioIODeviceType (OboeAudioIODevice::oboeTypeName)
  857. {
  858. // Not using scanForDevices() to maintain behaviour backwards compatible with older APIs
  859. checkAvailableDevices();
  860. }
  861. //==============================================================================
  862. void scanForDevices() override {}
  863. StringArray getDeviceNames (bool wantInputNames) const override
  864. {
  865. if (inputDevices.isEmpty() && outputDevices.isEmpty())
  866. return StringArray (OboeAudioIODevice::oboeTypeName);
  867. StringArray names;
  868. for (auto& device : wantInputNames ? inputDevices : outputDevices)
  869. names.add (device.name);
  870. return names;
  871. }
  872. int getDefaultDeviceIndex (bool forInput) const override
  873. {
  874. // No need to create a stream when only one default device is created.
  875. if (! supportsDevicesInfo())
  876. return 0;
  877. if (forInput && (! RuntimePermissions::isGranted (RuntimePermissions::recordAudio)))
  878. return 0;
  879. // Create stream with a default device ID and query the stream for its device ID
  880. using OboeStream = OboeAudioIODevice::OboeStream;
  881. OboeStream tempStream (-1,
  882. forInput ? oboe::Direction::Input : oboe::Direction::Output,
  883. oboe::SharingMode::Shared,
  884. forInput ? 1 : 2,
  885. getAndroidSDKVersion() >= 21 ? oboe::AudioFormat::Float : oboe::AudioFormat::I16,
  886. (int) OboeAudioIODevice::getNativeSampleRate(),
  887. OboeAudioIODevice::getNativeBufferSize(),
  888. nullptr);
  889. if (auto* nativeStream = tempStream.getNativeStream())
  890. {
  891. auto& devices = forInput ? inputDevices : outputDevices;
  892. for (int i = 0; i < devices.size(); ++i)
  893. if (devices.getReference (i).id == nativeStream->getDeviceId())
  894. return i;
  895. }
  896. return 0;
  897. }
  898. int getIndexOfDevice (AudioIODevice* device, bool asInput) const override
  899. {
  900. if (auto oboeDevice = static_cast<OboeAudioIODevice*> (device))
  901. {
  902. auto oboeDeviceId = asInput ? oboeDevice->inputDeviceId
  903. : oboeDevice->outputDeviceId;
  904. auto& devices = asInput ? inputDevices : outputDevices;
  905. for (int i = 0; i < devices.size(); ++i)
  906. if (devices.getReference (i).id == oboeDeviceId)
  907. return i;
  908. }
  909. return -1;
  910. }
  911. bool hasSeparateInputsAndOutputs() const override { return true; }
  912. AudioIODevice* createDevice (const String& outputDeviceName,
  913. const String& inputDeviceName) override
  914. {
  915. auto outputDeviceInfo = getDeviceInfoForName (outputDeviceName, false);
  916. auto inputDeviceInfo = getDeviceInfoForName (inputDeviceName, true);
  917. if (outputDeviceInfo.name.isEmpty() && inputDeviceInfo.name.isEmpty())
  918. {
  919. // Invalid device name passed. It must be one of the names returned by getDeviceNames().
  920. jassertfalse;
  921. return nullptr;
  922. }
  923. auto& name = outputDeviceInfo.name.isNotEmpty() ? outputDeviceInfo.name
  924. : inputDeviceInfo.name;
  925. return new OboeAudioIODevice (name,
  926. inputDeviceInfo.id, inputDeviceInfo.sampleRates,
  927. inputDeviceInfo.numChannels,
  928. outputDeviceInfo.id, outputDeviceInfo.sampleRates,
  929. outputDeviceInfo.numChannels);
  930. }
  931. static bool isOboeAvailable()
  932. {
  933. #if JUCE_USE_ANDROID_OBOE
  934. return true;
  935. #else
  936. return false;
  937. #endif
  938. }
  939. private:
  940. void checkAvailableDevices()
  941. {
  942. if (! supportsDevicesInfo())
  943. {
  944. auto sampleRates = OboeAudioIODevice::getDefaultSampleRates();
  945. inputDevices .add ({ OboeAudioIODevice::oboeTypeName, -1, sampleRates, 1 });
  946. outputDevices.add ({ OboeAudioIODevice::oboeTypeName, -1, sampleRates, 2 });
  947. return;
  948. }
  949. auto* env = getEnv();
  950. jclass audioManagerClass = env->FindClass ("android/media/AudioManager");
  951. // We should be really entering here only if API supports it.
  952. jassert (audioManagerClass != 0);
  953. if (audioManagerClass == 0)
  954. return;
  955. auto audioManager = LocalRef<jobject> (env->CallObjectMethod (getAppContext().get(),
  956. AndroidContext.getSystemService,
  957. javaString ("audio").get()));
  958. static jmethodID getDevicesMethod = env->GetMethodID (audioManagerClass, "getDevices",
  959. "(I)[Landroid/media/AudioDeviceInfo;");
  960. static constexpr int allDevices = 3;
  961. auto devices = LocalRef<jobjectArray> ((jobjectArray) env->CallObjectMethod (audioManager,
  962. getDevicesMethod,
  963. allDevices));
  964. const int numDevices = env->GetArrayLength (devices.get());
  965. for (int i = 0; i < numDevices; ++i)
  966. {
  967. auto device = LocalRef<jobject> ((jobject) env->GetObjectArrayElement (devices.get(), i));
  968. addDevice (device, env);
  969. }
  970. JUCE_OBOE_LOG ("-----InputDevices:");
  971. for (auto& device : inputDevices)
  972. {
  973. JUCE_OBOE_LOG ("name = " << device.name);
  974. JUCE_OBOE_LOG ("id = " << String (device.id));
  975. JUCE_OBOE_LOG ("sample rates size = " << String (device.sampleRates.size()));
  976. JUCE_OBOE_LOG ("num channels = " + String (device.numChannels));
  977. }
  978. JUCE_OBOE_LOG ("-----OutputDevices:");
  979. for (auto& device : outputDevices)
  980. {
  981. JUCE_OBOE_LOG ("name = " << device.name);
  982. JUCE_OBOE_LOG ("id = " << String (device.id));
  983. JUCE_OBOE_LOG ("sample rates size = " << String (device.sampleRates.size()));
  984. JUCE_OBOE_LOG ("num channels = " + String (device.numChannels));
  985. }
  986. }
  987. bool supportsDevicesInfo() const
  988. {
  989. static auto result = getAndroidSDKVersion() >= 23;
  990. return result;
  991. }
  992. void addDevice (const LocalRef<jobject>& device, JNIEnv* env)
  993. {
  994. auto deviceClass = LocalRef<jclass> ((jclass) env->FindClass ("android/media/AudioDeviceInfo"));
  995. jmethodID getProductNameMethod = env->GetMethodID (deviceClass, "getProductName",
  996. "()Ljava/lang/CharSequence;");
  997. jmethodID getTypeMethod = env->GetMethodID (deviceClass, "getType", "()I");
  998. jmethodID getIdMethod = env->GetMethodID (deviceClass, "getId", "()I");
  999. jmethodID getSampleRatesMethod = env->GetMethodID (deviceClass, "getSampleRates", "()[I");
  1000. jmethodID getChannelCountsMethod = env->GetMethodID (deviceClass, "getChannelCounts", "()[I");
  1001. jmethodID isSourceMethod = env->GetMethodID (deviceClass, "isSource", "()Z");
  1002. auto name = juceString ((jstring) env->CallObjectMethod (device, getProductNameMethod));
  1003. name << deviceTypeToString (env->CallIntMethod (device, getTypeMethod));
  1004. int id = env->CallIntMethod (device, getIdMethod);
  1005. auto jSampleRates = LocalRef<jintArray> ((jintArray) env->CallObjectMethod (device, getSampleRatesMethod));
  1006. auto sampleRates = jintArrayToJuceArray (jSampleRates);
  1007. auto jChannelCounts = LocalRef<jintArray> ((jintArray) env->CallObjectMethod (device, getChannelCountsMethod));
  1008. auto channelCounts = jintArrayToJuceArray (jChannelCounts);
  1009. int numChannels = channelCounts.isEmpty() ? -1 : channelCounts.getLast();
  1010. bool isInput = env->CallBooleanMethod (device, isSourceMethod);
  1011. auto& devices = isInput ? inputDevices : outputDevices;
  1012. devices.add ({ name, id, sampleRates, numChannels });
  1013. }
  1014. static const char* deviceTypeToString (int type)
  1015. {
  1016. switch (type)
  1017. {
  1018. case 0: return "";
  1019. case 1: return " built-in earphone speaker";
  1020. case 2: return " built-in speaker";
  1021. case 3: return " wired headset";
  1022. case 4: return " wired headphones";
  1023. case 5: return " line analog";
  1024. case 6: return " line digital";
  1025. case 7: return " Bluetooth device typically used for telephony";
  1026. case 8: return " Bluetooth device supporting the A2DP profile";
  1027. case 9: return " HDMI";
  1028. case 10: return " HDMI audio return channel";
  1029. case 11: return " USB device";
  1030. case 12: return " USB accessory";
  1031. case 13: return " DOCK";
  1032. case 14: return " FM";
  1033. case 15: return " built-in microphone";
  1034. case 16: return " FM tuner";
  1035. case 17: return " TV tuner";
  1036. case 18: return " telephony";
  1037. case 19: return " auxiliary line-level connectors";
  1038. case 20: return " IP";
  1039. case 21: return " BUS";
  1040. case 22: return " USB headset";
  1041. default: jassertfalse; return ""; // type not supported yet, needs to be added!
  1042. }
  1043. }
  1044. static Array<int> jintArrayToJuceArray (const LocalRef<jintArray>& jArray)
  1045. {
  1046. auto* env = getEnv();
  1047. jint* jArrayElems = env->GetIntArrayElements (jArray, 0);
  1048. int numElems = env->GetArrayLength (jArray);
  1049. Array<int> juceArray;
  1050. for (int s = 0; s < numElems; ++s)
  1051. juceArray.add (jArrayElems[s]);
  1052. env->ReleaseIntArrayElements (jArray, jArrayElems, 0);
  1053. return juceArray;
  1054. }
  1055. struct DeviceInfo
  1056. {
  1057. String name;
  1058. int id;
  1059. Array<int> sampleRates;
  1060. int numChannels;
  1061. };
  1062. DeviceInfo getDeviceInfoForName (const String& name, bool isInput)
  1063. {
  1064. if (name.isEmpty())
  1065. return {};
  1066. for (auto& device : isInput ? inputDevices : outputDevices)
  1067. if (device.name == name)
  1068. return device;
  1069. return {};
  1070. }
  1071. Array<DeviceInfo> inputDevices, outputDevices;
  1072. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OboeAudioIODeviceType)
  1073. };
  1074. const char* const OboeAudioIODevice::oboeTypeName = "Android Oboe";
  1075. //==============================================================================
  1076. bool isOboeAvailable() { return OboeAudioIODeviceType::isOboeAvailable(); }
  1077. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_Oboe()
  1078. {
  1079. return isOboeAvailable() ? new OboeAudioIODeviceType() : nullptr;
  1080. }
  1081. //==============================================================================
  1082. class OboeRealtimeThread : private oboe::AudioStreamCallback
  1083. {
  1084. using OboeStream = OboeAudioIODevice::OboeStream;
  1085. public:
  1086. OboeRealtimeThread()
  1087. : testStream (new OboeStream (-1,
  1088. oboe::Direction::Output,
  1089. oboe::SharingMode::Exclusive,
  1090. 1,
  1091. oboe::AudioFormat::Float,
  1092. (int) OboeAudioIODevice::getNativeSampleRate(),
  1093. OboeAudioIODevice::getNativeBufferSize(),
  1094. this)),
  1095. formatUsed (oboe::AudioFormat::Float)
  1096. {
  1097. // Fallback to I16 stream format if Float has not worked
  1098. if (! testStream->openedOk())
  1099. {
  1100. testStream.reset (new OboeStream (-1,
  1101. oboe::Direction::Output,
  1102. oboe::SharingMode::Exclusive,
  1103. 1,
  1104. oboe::AudioFormat::I16,
  1105. (int) OboeAudioIODevice::getNativeSampleRate(),
  1106. OboeAudioIODevice::getNativeBufferSize(),
  1107. this));
  1108. formatUsed = oboe::AudioFormat::I16;
  1109. }
  1110. parentThreadID = pthread_self();
  1111. pthread_cond_init (&threadReady, nullptr);
  1112. pthread_mutex_init (&threadReadyMutex, nullptr);
  1113. }
  1114. bool isOk() const
  1115. {
  1116. return testStream != nullptr && testStream->openedOk();
  1117. }
  1118. pthread_t startThread (void*(*entry)(void*), void* userPtr)
  1119. {
  1120. pthread_mutex_lock (&threadReadyMutex);
  1121. threadEntryProc = entry;
  1122. threadUserPtr = userPtr;
  1123. testStream->start();
  1124. pthread_cond_wait (&threadReady, &threadReadyMutex);
  1125. pthread_mutex_unlock (&threadReadyMutex);
  1126. return realtimeThreadID;
  1127. }
  1128. oboe::DataCallbackResult onAudioReady (oboe::AudioStream*, void*, int32_t) override
  1129. {
  1130. // When running with OpenSL, the first callback will come on the parent thread.
  1131. if (threadEntryProc != nullptr && ! pthread_equal (parentThreadID, pthread_self()))
  1132. {
  1133. pthread_mutex_lock (&threadReadyMutex);
  1134. realtimeThreadID = pthread_self();
  1135. pthread_cond_signal (&threadReady);
  1136. pthread_mutex_unlock (&threadReadyMutex);
  1137. threadEntryProc (threadUserPtr);
  1138. threadEntryProc = nullptr;
  1139. MessageManager::callAsync ([this] () { delete this; });
  1140. return oboe::DataCallbackResult::Stop;
  1141. }
  1142. return oboe::DataCallbackResult::Continue;
  1143. }
  1144. void onErrorBeforeClose (oboe::AudioStream*, oboe::Result error) override
  1145. {
  1146. JUCE_OBOE_LOG ("OboeRealtimeThread: Oboe stream onErrorBeforeClose(): " + getOboeString (error));
  1147. ignoreUnused (error);
  1148. jassertfalse; // Should never get here!
  1149. }
  1150. void onErrorAfterClose (oboe::AudioStream*, oboe::Result error) override
  1151. {
  1152. JUCE_OBOE_LOG ("OboeRealtimeThread: Oboe stream onErrorAfterClose(): " + getOboeString (error));
  1153. ignoreUnused (error);
  1154. jassertfalse; // Should never get here!
  1155. }
  1156. private:
  1157. //=============================================================================
  1158. void* (*threadEntryProc) (void*) = nullptr;
  1159. void* threadUserPtr = nullptr;
  1160. pthread_cond_t threadReady;
  1161. pthread_mutex_t threadReadyMutex;
  1162. pthread_t parentThreadID, realtimeThreadID;
  1163. std::unique_ptr<OboeStream> testStream;
  1164. oboe::AudioFormat formatUsed;
  1165. };
  1166. pthread_t juce_createRealtimeAudioThread (void* (*entry) (void*), void* userPtr)
  1167. {
  1168. std::unique_ptr<OboeRealtimeThread> thread (new OboeRealtimeThread());
  1169. if (! thread->isOk())
  1170. return {};
  1171. auto threadID = thread->startThread (entry, userPtr);
  1172. thread.release(); // the thread will de-allocate itself
  1173. return threadID;
  1174. }
  1175. } // namespace juce