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.

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