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.

1136 lines
37KB

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