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.

1468 lines
61KB

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