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.

1160 lines
38KB

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