Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1440 lines
60KB

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