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.

1186 lines
39KB

  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. namespace juce
  18. {
  19. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20. {
  21. return outputDeviceName == other.outputDeviceName
  22. && inputDeviceName == other.inputDeviceName
  23. && sampleRate == other.sampleRate
  24. && bufferSize == other.bufferSize
  25. && inputChannels == other.inputChannels
  26. && useDefaultInputChannels == other.useDefaultInputChannels
  27. && outputChannels == other.outputChannels
  28. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  29. }
  30. bool AudioDeviceManager::AudioDeviceSetup::operator!= (const AudioDeviceManager::AudioDeviceSetup& other) const
  31. {
  32. return ! operator== (other);
  33. }
  34. //==============================================================================
  35. class AudioDeviceManager::CallbackHandler : public AudioIODeviceCallback,
  36. public MidiInputCallback,
  37. public AudioIODeviceType::Listener
  38. {
  39. public:
  40. CallbackHandler (AudioDeviceManager& adm) noexcept : owner (adm) {}
  41. private:
  42. void audioDeviceIOCallback (const float** ins, int numIns, float** outs, int numOuts, int numSamples) override
  43. {
  44. owner.audioDeviceIOCallbackInt (ins, numIns, outs, numOuts, numSamples);
  45. }
  46. void audioDeviceAboutToStart (AudioIODevice* device) override
  47. {
  48. owner.audioDeviceAboutToStartInt (device);
  49. }
  50. void audioDeviceStopped() override
  51. {
  52. owner.audioDeviceStoppedInt();
  53. }
  54. void audioDeviceError (const String& message) override
  55. {
  56. owner.audioDeviceErrorInt (message);
  57. }
  58. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message) override
  59. {
  60. owner.handleIncomingMidiMessageInt (source, message);
  61. }
  62. void audioDeviceListChanged() override
  63. {
  64. owner.audioDeviceListChanged();
  65. }
  66. AudioDeviceManager& owner;
  67. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CallbackHandler)
  68. };
  69. //==============================================================================
  70. AudioDeviceManager::AudioDeviceManager()
  71. {
  72. callbackHandler.reset (new CallbackHandler (*this));
  73. }
  74. AudioDeviceManager::~AudioDeviceManager()
  75. {
  76. currentAudioDevice.reset();
  77. defaultMidiOutput.reset();
  78. }
  79. //==============================================================================
  80. void AudioDeviceManager::createDeviceTypesIfNeeded()
  81. {
  82. if (availableDeviceTypes.size() == 0)
  83. {
  84. OwnedArray<AudioIODeviceType> types;
  85. createAudioDeviceTypes (types);
  86. for (auto* t : types)
  87. addAudioDeviceType (std::unique_ptr<AudioIODeviceType> (t));
  88. types.clear (false);
  89. if (auto* first = availableDeviceTypes.getFirst())
  90. currentDeviceType = first->getTypeName();
  91. }
  92. }
  93. const OwnedArray<AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  94. {
  95. scanDevicesIfNeeded();
  96. return availableDeviceTypes;
  97. }
  98. void AudioDeviceManager::updateCurrentSetup()
  99. {
  100. if (currentAudioDevice != nullptr)
  101. {
  102. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  103. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  104. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  105. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  106. }
  107. }
  108. void AudioDeviceManager::audioDeviceListChanged()
  109. {
  110. if (currentAudioDevice != nullptr)
  111. {
  112. auto currentDeviceStillAvailable = [&]
  113. {
  114. auto currentTypeName = currentAudioDevice->getTypeName();
  115. auto currentDeviceName = currentAudioDevice->getName();
  116. for (auto* deviceType : availableDeviceTypes)
  117. {
  118. if (currentTypeName == deviceType->getTypeName())
  119. {
  120. for (auto& deviceName : deviceType->getDeviceNames (true))
  121. if (currentDeviceName == deviceName)
  122. return true;
  123. for (auto& deviceName : deviceType->getDeviceNames (false))
  124. if (currentDeviceName == deviceName)
  125. return true;
  126. }
  127. }
  128. return false;
  129. }();
  130. if (! currentDeviceStillAvailable)
  131. {
  132. closeAudioDevice();
  133. if (auto e = createStateXml())
  134. initialiseFromXML (*e, true, preferredDeviceName, &currentSetup);
  135. else
  136. initialiseDefault (preferredDeviceName, &currentSetup);
  137. }
  138. updateCurrentSetup();
  139. }
  140. sendChangeMessage();
  141. }
  142. //==============================================================================
  143. static void addIfNotNull (OwnedArray<AudioIODeviceType>& list, AudioIODeviceType* const device)
  144. {
  145. if (device != nullptr)
  146. list.add (device);
  147. }
  148. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray<AudioIODeviceType>& list)
  149. {
  150. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_WASAPI (WASAPIDeviceMode::shared));
  151. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_WASAPI (WASAPIDeviceMode::exclusive));
  152. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_WASAPI (WASAPIDeviceMode::sharedLowLatency));
  153. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_DirectSound());
  154. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_ASIO());
  155. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_CoreAudio());
  156. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_iOSAudio());
  157. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_Bela());
  158. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_ALSA());
  159. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_JACK());
  160. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_Oboe());
  161. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_OpenSLES());
  162. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_Android());
  163. }
  164. void AudioDeviceManager::addAudioDeviceType (std::unique_ptr<AudioIODeviceType> newDeviceType)
  165. {
  166. if (newDeviceType != nullptr)
  167. {
  168. jassert (lastDeviceTypeConfigs.size() == availableDeviceTypes.size());
  169. availableDeviceTypes.add (newDeviceType.release());
  170. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  171. availableDeviceTypes.getLast()->addListener (callbackHandler.get());
  172. }
  173. }
  174. void AudioDeviceManager::removeAudioDeviceType (AudioIODeviceType* deviceTypeToRemove)
  175. {
  176. if (deviceTypeToRemove != nullptr)
  177. {
  178. jassert (lastDeviceTypeConfigs.size() == availableDeviceTypes.size());
  179. auto index = availableDeviceTypes.indexOf (deviceTypeToRemove);
  180. if (auto removed = std::unique_ptr<AudioIODeviceType> (availableDeviceTypes.removeAndReturn (index)))
  181. {
  182. removed->removeListener (callbackHandler.get());
  183. lastDeviceTypeConfigs.remove (index, true);
  184. }
  185. }
  186. }
  187. static bool deviceListContains (AudioIODeviceType* type, bool isInput, const String& name)
  188. {
  189. for (auto& deviceName : type->getDeviceNames (isInput))
  190. if (deviceName.trim().equalsIgnoreCase (name.trim()))
  191. return true;
  192. return false;
  193. }
  194. //==============================================================================
  195. String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  196. const int numOutputChannelsNeeded,
  197. const XmlElement* const xml,
  198. const bool selectDefaultDeviceOnFailure,
  199. const String& preferredDefaultDeviceName,
  200. const AudioDeviceSetup* preferredSetupOptions)
  201. {
  202. scanDevicesIfNeeded();
  203. numInputChansNeeded = numInputChannelsNeeded;
  204. numOutputChansNeeded = numOutputChannelsNeeded;
  205. preferredDeviceName = preferredDefaultDeviceName;
  206. if (xml != nullptr && xml->hasTagName ("DEVICESETUP"))
  207. return initialiseFromXML (*xml, selectDefaultDeviceOnFailure,
  208. preferredDeviceName, preferredSetupOptions);
  209. return initialiseDefault (preferredDeviceName, preferredSetupOptions);
  210. }
  211. String AudioDeviceManager::initialiseDefault (const String& preferredDefaultDeviceName,
  212. const AudioDeviceSetup* preferredSetupOptions)
  213. {
  214. AudioDeviceSetup setup;
  215. if (preferredSetupOptions != nullptr)
  216. {
  217. setup = *preferredSetupOptions;
  218. }
  219. else if (preferredDefaultDeviceName.isNotEmpty())
  220. {
  221. for (auto* type : availableDeviceTypes)
  222. {
  223. for (auto& out : type->getDeviceNames (false))
  224. {
  225. if (out.matchesWildcard (preferredDefaultDeviceName, true))
  226. {
  227. setup.outputDeviceName = out;
  228. break;
  229. }
  230. }
  231. for (auto& in : type->getDeviceNames (true))
  232. {
  233. if (in.matchesWildcard (preferredDefaultDeviceName, true))
  234. {
  235. setup.inputDeviceName = in;
  236. break;
  237. }
  238. }
  239. }
  240. }
  241. insertDefaultDeviceNames (setup);
  242. return setAudioDeviceSetup (setup, false);
  243. }
  244. String AudioDeviceManager::initialiseFromXML (const XmlElement& xml,
  245. bool selectDefaultDeviceOnFailure,
  246. const String& preferredDefaultDeviceName,
  247. const AudioDeviceSetup* preferredSetupOptions)
  248. {
  249. lastExplicitSettings.reset (new XmlElement (xml));
  250. String error;
  251. AudioDeviceSetup setup;
  252. if (preferredSetupOptions != nullptr)
  253. setup = *preferredSetupOptions;
  254. if (xml.getStringAttribute ("audioDeviceName").isNotEmpty())
  255. {
  256. setup.inputDeviceName = setup.outputDeviceName
  257. = xml.getStringAttribute ("audioDeviceName");
  258. }
  259. else
  260. {
  261. setup.inputDeviceName = xml.getStringAttribute ("audioInputDeviceName");
  262. setup.outputDeviceName = xml.getStringAttribute ("audioOutputDeviceName");
  263. }
  264. currentDeviceType = xml.getStringAttribute ("deviceType");
  265. if (findType (currentDeviceType) == nullptr)
  266. {
  267. if (auto* type = findType (setup.inputDeviceName, setup.outputDeviceName))
  268. currentDeviceType = type->getTypeName();
  269. else if (auto* firstType = availableDeviceTypes.getFirst())
  270. currentDeviceType = firstType->getTypeName();
  271. }
  272. setup.bufferSize = xml.getIntAttribute ("audioDeviceBufferSize", setup.bufferSize);
  273. setup.sampleRate = xml.getDoubleAttribute ("audioDeviceRate", setup.sampleRate);
  274. setup.inputChannels .parseString (xml.getStringAttribute ("audioDeviceInChans", "11"), 2);
  275. setup.outputChannels.parseString (xml.getStringAttribute ("audioDeviceOutChans", "11"), 2);
  276. setup.useDefaultInputChannels = ! xml.hasAttribute ("audioDeviceInChans");
  277. setup.useDefaultOutputChannels = ! xml.hasAttribute ("audioDeviceOutChans");
  278. error = setAudioDeviceSetup (setup, true);
  279. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  280. error = initialise (numInputChansNeeded, numOutputChansNeeded, nullptr, false, preferredDefaultDeviceName);
  281. midiDeviceInfosFromXml.clear();
  282. enabledMidiInputs.clear();
  283. for (auto* c : xml.getChildWithTagNameIterator ("MIDIINPUT"))
  284. midiDeviceInfosFromXml.add ({ c->getStringAttribute ("name"), c->getStringAttribute ("identifier") });
  285. auto isIdentifierAvailable = [] (const Array<MidiDeviceInfo>& available, const String& identifier)
  286. {
  287. for (auto& device : available)
  288. if (device.identifier == identifier)
  289. return true;
  290. return false;
  291. };
  292. auto getUpdatedIdentifierForName = [&] (const Array<MidiDeviceInfo>& available, const String& name) -> String
  293. {
  294. for (auto& device : available)
  295. if (device.name == name)
  296. return device.identifier;
  297. return {};
  298. };
  299. auto inputs = MidiInput::getAvailableDevices();
  300. for (auto& info : midiDeviceInfosFromXml)
  301. {
  302. if (isIdentifierAvailable (inputs, info.identifier))
  303. {
  304. setMidiInputDeviceEnabled (info.identifier, true);
  305. }
  306. else
  307. {
  308. auto identifier = getUpdatedIdentifierForName (inputs, info.name);
  309. if (identifier.isNotEmpty())
  310. setMidiInputDeviceEnabled (identifier, true);
  311. }
  312. }
  313. MidiDeviceInfo defaultOutputDeviceInfo (xml.getStringAttribute ("defaultMidiOutput"),
  314. xml.getStringAttribute ("defaultMidiOutputDevice"));
  315. auto outputs = MidiOutput::getAvailableDevices();
  316. if (isIdentifierAvailable (outputs, defaultOutputDeviceInfo.identifier))
  317. {
  318. setDefaultMidiOutputDevice (defaultOutputDeviceInfo.identifier);
  319. }
  320. else
  321. {
  322. auto identifier = getUpdatedIdentifierForName (outputs, defaultOutputDeviceInfo.name);
  323. if (identifier.isNotEmpty())
  324. setDefaultMidiOutputDevice (identifier);
  325. }
  326. return error;
  327. }
  328. String AudioDeviceManager::initialiseWithDefaultDevices (int numInputChannelsNeeded,
  329. int numOutputChannelsNeeded)
  330. {
  331. lastExplicitSettings.reset();
  332. return initialise (numInputChannelsNeeded, numOutputChannelsNeeded,
  333. nullptr, false, {}, nullptr);
  334. }
  335. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  336. {
  337. if (auto* type = getCurrentDeviceTypeObject())
  338. {
  339. if (numOutputChansNeeded > 0 && setup.outputDeviceName.isEmpty())
  340. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  341. if (numInputChansNeeded > 0 && setup.inputDeviceName.isEmpty())
  342. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  343. }
  344. }
  345. std::unique_ptr<XmlElement> AudioDeviceManager::createStateXml() const
  346. {
  347. if (lastExplicitSettings != nullptr)
  348. return std::make_unique<XmlElement> (*lastExplicitSettings);
  349. return {};
  350. }
  351. //==============================================================================
  352. void AudioDeviceManager::scanDevicesIfNeeded()
  353. {
  354. if (listNeedsScanning)
  355. {
  356. listNeedsScanning = false;
  357. createDeviceTypesIfNeeded();
  358. for (auto* type : availableDeviceTypes)
  359. type->scanForDevices();
  360. }
  361. }
  362. AudioIODeviceType* AudioDeviceManager::findType (const String& typeName)
  363. {
  364. scanDevicesIfNeeded();
  365. for (auto* type : availableDeviceTypes)
  366. if (type->getTypeName() == typeName)
  367. return type;
  368. return {};
  369. }
  370. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  371. {
  372. scanDevicesIfNeeded();
  373. for (auto* type : availableDeviceTypes)
  374. if ((inputName.isNotEmpty() && deviceListContains (type, true, inputName))
  375. || (outputName.isNotEmpty() && deviceListContains (type, false, outputName)))
  376. return type;
  377. return {};
  378. }
  379. AudioDeviceManager::AudioDeviceSetup AudioDeviceManager::getAudioDeviceSetup() const
  380. {
  381. return currentSetup;
  382. }
  383. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup) const
  384. {
  385. setup = currentSetup;
  386. }
  387. void AudioDeviceManager::deleteCurrentDevice()
  388. {
  389. currentAudioDevice.reset();
  390. currentSetup.inputDeviceName.clear();
  391. currentSetup.outputDeviceName.clear();
  392. }
  393. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type, bool treatAsChosenDevice)
  394. {
  395. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  396. {
  397. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  398. && currentDeviceType != type)
  399. {
  400. if (currentAudioDevice != nullptr)
  401. {
  402. closeAudioDevice();
  403. Thread::sleep (1500); // allow a moment for OS devices to sort themselves out, to help
  404. // avoid things like DirectSound/ASIO clashes
  405. }
  406. currentDeviceType = type;
  407. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  408. insertDefaultDeviceNames (s);
  409. setAudioDeviceSetup (s, treatAsChosenDevice);
  410. sendChangeMessage();
  411. break;
  412. }
  413. }
  414. }
  415. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  416. {
  417. for (auto* type : availableDeviceTypes)
  418. if (type->getTypeName() == currentDeviceType)
  419. return type;
  420. return availableDeviceTypes.getFirst();
  421. }
  422. static void updateSetupChannels (AudioDeviceManager::AudioDeviceSetup& setup, int defaultNumIns, int defaultNumOuts)
  423. {
  424. auto updateChannels = [] (const String& deviceName, BigInteger& channels, int defaultNumChannels)
  425. {
  426. if (deviceName.isEmpty())
  427. {
  428. channels.clear();
  429. }
  430. else if (defaultNumChannels != -1)
  431. {
  432. channels.clear();
  433. channels.setRange (0, defaultNumChannels, true);
  434. }
  435. };
  436. updateChannels (setup.inputDeviceName, setup.inputChannels, setup.useDefaultInputChannels ? defaultNumIns : -1);
  437. updateChannels (setup.outputDeviceName, setup.outputChannels, setup.useDefaultOutputChannels ? defaultNumOuts : -1);
  438. }
  439. String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  440. bool treatAsChosenDevice)
  441. {
  442. jassert (&newSetup != &currentSetup); // this will have no effect
  443. if (newSetup != currentSetup)
  444. sendChangeMessage();
  445. else if (currentAudioDevice != nullptr)
  446. return {};
  447. stopDevice();
  448. if (getCurrentDeviceTypeObject() == nullptr
  449. || (newSetup.inputDeviceName.isEmpty() && newSetup.outputDeviceName.isEmpty()))
  450. {
  451. deleteCurrentDevice();
  452. if (treatAsChosenDevice)
  453. updateXml();
  454. return {};
  455. }
  456. String error;
  457. if (currentSetup.inputDeviceName != newSetup.inputDeviceName
  458. || currentSetup.outputDeviceName != newSetup.outputDeviceName
  459. || currentAudioDevice == nullptr)
  460. {
  461. deleteCurrentDevice();
  462. scanDevicesIfNeeded();
  463. auto* type = getCurrentDeviceTypeObject();
  464. if (newSetup.outputDeviceName.isNotEmpty() && ! deviceListContains (type, false, newSetup.outputDeviceName))
  465. return "No such device: " + newSetup.outputDeviceName;
  466. if (newSetup.inputDeviceName.isNotEmpty() && ! deviceListContains (type, true, newSetup.inputDeviceName))
  467. return "No such device: " + newSetup.inputDeviceName;
  468. currentAudioDevice.reset (type->createDevice (newSetup.outputDeviceName, newSetup.inputDeviceName));
  469. if (currentAudioDevice == nullptr)
  470. error = "Can't open the audio device!\n\n"
  471. "This may be because another application is currently using the same device - "
  472. "if so, you should close any other applications and try again!";
  473. else
  474. error = currentAudioDevice->getLastError();
  475. if (error.isNotEmpty())
  476. {
  477. deleteCurrentDevice();
  478. return error;
  479. }
  480. }
  481. currentSetup = newSetup;
  482. if (! currentSetup.useDefaultInputChannels) numInputChansNeeded = currentSetup.inputChannels.countNumberOfSetBits();
  483. if (! currentSetup.useDefaultOutputChannels) numOutputChansNeeded = currentSetup.outputChannels.countNumberOfSetBits();
  484. updateSetupChannels (currentSetup, numInputChansNeeded, numOutputChansNeeded);
  485. if (currentSetup.inputChannels.isZero() && currentSetup.outputChannels.isZero())
  486. {
  487. if (treatAsChosenDevice)
  488. updateXml();
  489. return {};
  490. }
  491. currentSetup.sampleRate = chooseBestSampleRate (currentSetup.sampleRate);
  492. currentSetup.bufferSize = chooseBestBufferSize (currentSetup.bufferSize);
  493. error = currentAudioDevice->open (currentSetup.inputChannels,
  494. currentSetup.outputChannels,
  495. currentSetup.sampleRate,
  496. currentSetup.bufferSize);
  497. if (error.isEmpty())
  498. {
  499. currentDeviceType = currentAudioDevice->getTypeName();
  500. currentAudioDevice->start (callbackHandler.get());
  501. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  502. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  503. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  504. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  505. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  506. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  507. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  508. if (treatAsChosenDevice)
  509. updateXml();
  510. }
  511. else
  512. {
  513. deleteCurrentDevice();
  514. }
  515. return error;
  516. }
  517. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  518. {
  519. jassert (currentAudioDevice != nullptr);
  520. auto rates = currentAudioDevice->getAvailableSampleRates();
  521. if (rate > 0 && rates.contains (rate))
  522. return rate;
  523. rate = currentAudioDevice->getCurrentSampleRate();
  524. if (rate > 0 && rates.contains (rate))
  525. return rate;
  526. double lowestAbove44 = 0.0;
  527. for (int i = rates.size(); --i >= 0;)
  528. {
  529. auto sr = rates[i];
  530. if (sr >= 44100.0 && (lowestAbove44 < 1.0 || sr < lowestAbove44))
  531. lowestAbove44 = sr;
  532. }
  533. if (lowestAbove44 > 0.0)
  534. return lowestAbove44;
  535. return rates[0];
  536. }
  537. int AudioDeviceManager::chooseBestBufferSize (int bufferSize) const
  538. {
  539. jassert (currentAudioDevice != nullptr);
  540. if (bufferSize > 0 && currentAudioDevice->getAvailableBufferSizes().contains (bufferSize))
  541. return bufferSize;
  542. return currentAudioDevice->getDefaultBufferSize();
  543. }
  544. void AudioDeviceManager::stopDevice()
  545. {
  546. if (currentAudioDevice != nullptr)
  547. currentAudioDevice->stop();
  548. testSound.reset();
  549. }
  550. void AudioDeviceManager::closeAudioDevice()
  551. {
  552. stopDevice();
  553. currentAudioDevice.reset();
  554. loadMeasurer.reset();
  555. }
  556. void AudioDeviceManager::restartLastAudioDevice()
  557. {
  558. if (currentAudioDevice == nullptr)
  559. {
  560. if (currentSetup.inputDeviceName.isEmpty()
  561. && currentSetup.outputDeviceName.isEmpty())
  562. {
  563. // This method will only reload the last device that was running
  564. // before closeAudioDevice() was called - you need to actually open
  565. // one first, with setAudioDeviceSetup().
  566. jassertfalse;
  567. return;
  568. }
  569. AudioDeviceSetup s (currentSetup);
  570. setAudioDeviceSetup (s, false);
  571. }
  572. }
  573. void AudioDeviceManager::updateXml()
  574. {
  575. lastExplicitSettings.reset (new XmlElement ("DEVICESETUP"));
  576. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  577. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  578. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  579. if (currentAudioDevice != nullptr)
  580. {
  581. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  582. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  583. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  584. if (! currentSetup.useDefaultInputChannels)
  585. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  586. if (! currentSetup.useDefaultOutputChannels)
  587. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  588. }
  589. for (auto& input : enabledMidiInputs)
  590. {
  591. auto* child = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  592. child->setAttribute ("name", input->getName());
  593. child->setAttribute ("identifier", input->getIdentifier());
  594. }
  595. if (midiDeviceInfosFromXml.size() > 0)
  596. {
  597. // Add any midi devices that have been enabled before, but which aren't currently
  598. // open because the device has been disconnected.
  599. auto availableMidiDevices = MidiInput::getAvailableDevices();
  600. for (auto& d : midiDeviceInfosFromXml)
  601. {
  602. if (! availableMidiDevices.contains (d))
  603. {
  604. auto* child = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  605. child->setAttribute ("name", d.name);
  606. child->setAttribute ("identifier", d.identifier);
  607. }
  608. }
  609. }
  610. if (defaultMidiOutputDeviceInfo != MidiDeviceInfo())
  611. {
  612. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputDeviceInfo.name);
  613. lastExplicitSettings->setAttribute ("defaultMidiOutputDevice", defaultMidiOutputDeviceInfo.identifier);
  614. }
  615. }
  616. //==============================================================================
  617. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  618. {
  619. {
  620. const ScopedLock sl (audioCallbackLock);
  621. if (callbacks.contains (newCallback))
  622. return;
  623. }
  624. if (currentAudioDevice != nullptr && newCallback != nullptr)
  625. newCallback->audioDeviceAboutToStart (currentAudioDevice.get());
  626. const ScopedLock sl (audioCallbackLock);
  627. callbacks.add (newCallback);
  628. }
  629. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callbackToRemove)
  630. {
  631. if (callbackToRemove != nullptr)
  632. {
  633. bool needsDeinitialising = currentAudioDevice != nullptr;
  634. {
  635. const ScopedLock sl (audioCallbackLock);
  636. needsDeinitialising = needsDeinitialising && callbacks.contains (callbackToRemove);
  637. callbacks.removeFirstMatchingValue (callbackToRemove);
  638. }
  639. if (needsDeinitialising)
  640. callbackToRemove->audioDeviceStopped();
  641. }
  642. }
  643. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  644. int numInputChannels,
  645. float** outputChannelData,
  646. int numOutputChannels,
  647. int numSamples)
  648. {
  649. const ScopedLock sl (audioCallbackLock);
  650. inputLevelGetter->updateLevel (inputChannelData, numInputChannels, numSamples);
  651. outputLevelGetter->updateLevel (const_cast<const float**> (outputChannelData), numOutputChannels, numSamples);
  652. if (callbacks.size() > 0)
  653. {
  654. AudioProcessLoadMeasurer::ScopedTimer timer (loadMeasurer);
  655. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  656. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  657. outputChannelData, numOutputChannels, numSamples);
  658. auto** tempChans = tempBuffer.getArrayOfWritePointers();
  659. for (int i = callbacks.size(); --i > 0;)
  660. {
  661. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  662. tempChans, numOutputChannels, numSamples);
  663. for (int chan = 0; chan < numOutputChannels; ++chan)
  664. {
  665. if (auto* src = tempChans [chan])
  666. if (auto* dst = outputChannelData [chan])
  667. for (int j = 0; j < numSamples; ++j)
  668. dst[j] += src[j];
  669. }
  670. }
  671. }
  672. else
  673. {
  674. for (int i = 0; i < numOutputChannels; ++i)
  675. zeromem (outputChannelData[i], (size_t) numSamples * sizeof (float));
  676. }
  677. if (testSound != nullptr)
  678. {
  679. auto numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  680. auto* src = testSound->getReadPointer (0, testSoundPosition);
  681. for (int i = 0; i < numOutputChannels; ++i)
  682. if (auto* dst = outputChannelData [i])
  683. for (int j = 0; j < numSamps; ++j)
  684. dst[j] += src[j];
  685. testSoundPosition += numSamps;
  686. if (testSoundPosition >= testSound->getNumSamples())
  687. testSound.reset();
  688. }
  689. }
  690. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  691. {
  692. loadMeasurer.reset (device->getCurrentSampleRate(),
  693. device->getCurrentBufferSizeSamples());
  694. {
  695. const ScopedLock sl (audioCallbackLock);
  696. for (int i = callbacks.size(); --i >= 0;)
  697. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  698. }
  699. updateCurrentSetup();
  700. sendChangeMessage();
  701. }
  702. void AudioDeviceManager::audioDeviceStoppedInt()
  703. {
  704. sendChangeMessage();
  705. const ScopedLock sl (audioCallbackLock);
  706. loadMeasurer.reset();
  707. for (int i = callbacks.size(); --i >= 0;)
  708. callbacks.getUnchecked(i)->audioDeviceStopped();
  709. }
  710. void AudioDeviceManager::audioDeviceErrorInt (const String& message)
  711. {
  712. const ScopedLock sl (audioCallbackLock);
  713. for (int i = callbacks.size(); --i >= 0;)
  714. callbacks.getUnchecked(i)->audioDeviceError (message);
  715. }
  716. double AudioDeviceManager::getCpuUsage() const
  717. {
  718. return loadMeasurer.getLoadAsProportion();
  719. }
  720. //==============================================================================
  721. void AudioDeviceManager::setMidiInputDeviceEnabled (const String& identifier, bool enabled)
  722. {
  723. if (enabled != isMidiInputDeviceEnabled (identifier))
  724. {
  725. if (enabled)
  726. {
  727. if (auto midiIn = MidiInput::openDevice (identifier, callbackHandler.get()))
  728. {
  729. enabledMidiInputs.push_back (std::move (midiIn));
  730. enabledMidiInputs.back()->start();
  731. }
  732. }
  733. else
  734. {
  735. auto removePredicate = [identifier] (const std::unique_ptr<MidiInput>& in) { return in->getIdentifier() == identifier; };
  736. enabledMidiInputs.erase (std::remove_if (std::begin (enabledMidiInputs), std::end (enabledMidiInputs), removePredicate),
  737. std::end (enabledMidiInputs));
  738. }
  739. updateXml();
  740. sendChangeMessage();
  741. }
  742. }
  743. bool AudioDeviceManager::isMidiInputDeviceEnabled (const String& identifier) const
  744. {
  745. for (auto& mi : enabledMidiInputs)
  746. if (mi->getIdentifier() == identifier)
  747. return true;
  748. return false;
  749. }
  750. void AudioDeviceManager::addMidiInputDeviceCallback (const String& identifier, MidiInputCallback* callbackToAdd)
  751. {
  752. removeMidiInputDeviceCallback (identifier, callbackToAdd);
  753. if (identifier.isEmpty() || isMidiInputDeviceEnabled (identifier))
  754. {
  755. const ScopedLock sl (midiCallbackLock);
  756. midiCallbacks.add ({ identifier, callbackToAdd });
  757. }
  758. }
  759. void AudioDeviceManager::removeMidiInputDeviceCallback (const String& identifier, MidiInputCallback* callbackToRemove)
  760. {
  761. for (int i = midiCallbacks.size(); --i >= 0;)
  762. {
  763. auto& mc = midiCallbacks.getReference (i);
  764. if (mc.callback == callbackToRemove && mc.deviceIdentifier == identifier)
  765. {
  766. const ScopedLock sl (midiCallbackLock);
  767. midiCallbacks.remove (i);
  768. }
  769. }
  770. }
  771. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message)
  772. {
  773. if (! message.isActiveSense())
  774. {
  775. const ScopedLock sl (midiCallbackLock);
  776. for (auto& mc : midiCallbacks)
  777. if (mc.deviceIdentifier.isEmpty() || mc.deviceIdentifier == source->getIdentifier())
  778. mc.callback->handleIncomingMidiMessage (source, message);
  779. }
  780. }
  781. //==============================================================================
  782. void AudioDeviceManager::setDefaultMidiOutputDevice (const String& identifier)
  783. {
  784. if (defaultMidiOutputDeviceInfo.identifier != identifier)
  785. {
  786. Array<AudioIODeviceCallback*> oldCallbacks;
  787. {
  788. const ScopedLock sl (audioCallbackLock);
  789. oldCallbacks.swapWith (callbacks);
  790. }
  791. if (currentAudioDevice != nullptr)
  792. for (int i = oldCallbacks.size(); --i >= 0;)
  793. oldCallbacks.getUnchecked (i)->audioDeviceStopped();
  794. defaultMidiOutput.reset();
  795. if (identifier.isNotEmpty())
  796. defaultMidiOutput = MidiOutput::openDevice (identifier);
  797. if (defaultMidiOutput != nullptr)
  798. defaultMidiOutputDeviceInfo = defaultMidiOutput->getDeviceInfo();
  799. else
  800. defaultMidiOutputDeviceInfo = {};
  801. if (currentAudioDevice != nullptr)
  802. for (auto* c : oldCallbacks)
  803. c->audioDeviceAboutToStart (currentAudioDevice.get());
  804. {
  805. const ScopedLock sl (audioCallbackLock);
  806. oldCallbacks.swapWith (callbacks);
  807. }
  808. updateXml();
  809. sendChangeMessage();
  810. }
  811. }
  812. //==============================================================================
  813. AudioDeviceManager::LevelMeter::LevelMeter() noexcept : level() {}
  814. void AudioDeviceManager::LevelMeter::updateLevel (const float* const* channelData, int numChannels, int numSamples) noexcept
  815. {
  816. if (getReferenceCount() <= 1)
  817. return;
  818. auto localLevel = level.get();
  819. if (numChannels > 0)
  820. {
  821. for (int j = 0; j < numSamples; ++j)
  822. {
  823. float s = 0;
  824. for (int i = 0; i < numChannels; ++i)
  825. s += std::abs (channelData[i][j]);
  826. s /= (float) numChannels;
  827. const float decayFactor = 0.99992f;
  828. if (s > localLevel)
  829. localLevel = s;
  830. else if (localLevel > 0.001f)
  831. localLevel *= decayFactor;
  832. else
  833. localLevel = 0;
  834. }
  835. }
  836. else
  837. {
  838. localLevel = 0;
  839. }
  840. level = localLevel;
  841. }
  842. double AudioDeviceManager::LevelMeter::getCurrentLevel() const noexcept
  843. {
  844. jassert (getReferenceCount() > 1);
  845. return level.get();
  846. }
  847. void AudioDeviceManager::playTestSound()
  848. {
  849. { // cunningly nested to swap, unlock and delete in that order.
  850. std::unique_ptr<AudioBuffer<float>> oldSound;
  851. {
  852. const ScopedLock sl (audioCallbackLock);
  853. std::swap (oldSound, testSound);
  854. }
  855. }
  856. testSoundPosition = 0;
  857. if (currentAudioDevice != nullptr)
  858. {
  859. auto sampleRate = currentAudioDevice->getCurrentSampleRate();
  860. auto soundLength = (int) sampleRate;
  861. double frequency = 440.0;
  862. float amplitude = 0.5f;
  863. auto phasePerSample = MathConstants<double>::twoPi / (sampleRate / frequency);
  864. std::unique_ptr<AudioBuffer<float>> newSound (new AudioBuffer<float> (1, soundLength));
  865. for (int i = 0; i < soundLength; ++i)
  866. newSound->setSample (0, i, amplitude * (float) std::sin (i * phasePerSample));
  867. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  868. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  869. {
  870. const ScopedLock sl (audioCallbackLock);
  871. std::swap (testSound, newSound);
  872. }
  873. }
  874. }
  875. int AudioDeviceManager::getXRunCount() const noexcept
  876. {
  877. auto deviceXRuns = (currentAudioDevice != nullptr ? currentAudioDevice->getXRunCount() : -1);
  878. return jmax (0, deviceXRuns) + loadMeasurer.getXRunCount();
  879. }
  880. //==============================================================================
  881. // Deprecated
  882. void AudioDeviceManager::setMidiInputEnabled (const String& name, const bool enabled)
  883. {
  884. for (auto& device : MidiInput::getAvailableDevices())
  885. {
  886. if (device.name == name)
  887. {
  888. setMidiInputDeviceEnabled (device.identifier, enabled);
  889. return;
  890. }
  891. }
  892. }
  893. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  894. {
  895. for (auto& device : MidiInput::getAvailableDevices())
  896. if (device.name == name)
  897. return isMidiInputDeviceEnabled (device.identifier);
  898. return false;
  899. }
  900. void AudioDeviceManager::addMidiInputCallback (const String& name, MidiInputCallback* callbackToAdd)
  901. {
  902. if (name.isEmpty())
  903. {
  904. addMidiInputDeviceCallback ({}, callbackToAdd);
  905. }
  906. else
  907. {
  908. for (auto& device : MidiInput::getAvailableDevices())
  909. {
  910. if (device.name == name)
  911. {
  912. addMidiInputDeviceCallback (device.identifier, callbackToAdd);
  913. return;
  914. }
  915. }
  916. }
  917. }
  918. void AudioDeviceManager::removeMidiInputCallback (const String& name, MidiInputCallback* callbackToRemove)
  919. {
  920. if (name.isEmpty())
  921. {
  922. removeMidiInputDeviceCallback ({}, callbackToRemove);
  923. }
  924. else
  925. {
  926. for (auto& device : MidiInput::getAvailableDevices())
  927. {
  928. if (device.name == name)
  929. {
  930. removeMidiInputDeviceCallback (device.identifier, callbackToRemove);
  931. return;
  932. }
  933. }
  934. }
  935. }
  936. void AudioDeviceManager::setDefaultMidiOutput (const String& name)
  937. {
  938. for (auto& device : MidiOutput::getAvailableDevices())
  939. {
  940. if (device.name == name)
  941. {
  942. setDefaultMidiOutputDevice (device.identifier);
  943. return;
  944. }
  945. }
  946. }
  947. } // namespace juce