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

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