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.

1833 lines
64KB

  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. template <typename Setup>
  20. static auto getSetupInfo (Setup& s, bool isInput)
  21. {
  22. struct SetupInfo
  23. {
  24. // double brackets so that we get the expression type, i.e. a (possibly const) reference
  25. decltype ((s.inputDeviceName)) name;
  26. decltype ((s.inputChannels)) channels;
  27. decltype ((s.useDefaultInputChannels)) useDefault;
  28. };
  29. return isInput ? SetupInfo { s.inputDeviceName, s.inputChannels, s.useDefaultInputChannels }
  30. : SetupInfo { s.outputDeviceName, s.outputChannels, s.useDefaultOutputChannels };
  31. }
  32. static auto tie (const AudioDeviceManager::AudioDeviceSetup& s)
  33. {
  34. return std::tie (s.outputDeviceName,
  35. s.inputDeviceName,
  36. s.sampleRate,
  37. s.bufferSize,
  38. s.inputChannels,
  39. s.useDefaultInputChannels,
  40. s.outputChannels,
  41. s.useDefaultOutputChannels);
  42. }
  43. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  44. {
  45. return tie (*this) == tie (other);
  46. }
  47. bool AudioDeviceManager::AudioDeviceSetup::operator!= (const AudioDeviceManager::AudioDeviceSetup& other) const
  48. {
  49. return tie (*this) != tie (other);
  50. }
  51. //==============================================================================
  52. class AudioDeviceManager::CallbackHandler : public AudioIODeviceCallback,
  53. public MidiInputCallback,
  54. public AudioIODeviceType::Listener
  55. {
  56. public:
  57. CallbackHandler (AudioDeviceManager& adm) noexcept : owner (adm) {}
  58. private:
  59. void audioDeviceIOCallback (const float** ins, int numIns, float** outs, int numOuts, int numSamples) override
  60. {
  61. owner.audioDeviceIOCallbackInt (ins, numIns, outs, numOuts, numSamples);
  62. }
  63. void audioDeviceAboutToStart (AudioIODevice* device) override
  64. {
  65. owner.audioDeviceAboutToStartInt (device);
  66. }
  67. void audioDeviceStopped() override
  68. {
  69. owner.audioDeviceStoppedInt();
  70. }
  71. void audioDeviceError (const String& message) override
  72. {
  73. owner.audioDeviceErrorInt (message);
  74. }
  75. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message) override
  76. {
  77. owner.handleIncomingMidiMessageInt (source, message);
  78. }
  79. void audioDeviceListChanged() override
  80. {
  81. owner.audioDeviceListChanged();
  82. }
  83. AudioDeviceManager& owner;
  84. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CallbackHandler)
  85. };
  86. //==============================================================================
  87. AudioDeviceManager::AudioDeviceManager()
  88. {
  89. callbackHandler.reset (new CallbackHandler (*this));
  90. }
  91. AudioDeviceManager::~AudioDeviceManager()
  92. {
  93. currentAudioDevice.reset();
  94. defaultMidiOutput.reset();
  95. }
  96. //==============================================================================
  97. void AudioDeviceManager::createDeviceTypesIfNeeded()
  98. {
  99. if (availableDeviceTypes.size() == 0)
  100. {
  101. OwnedArray<AudioIODeviceType> types;
  102. createAudioDeviceTypes (types);
  103. for (auto* t : types)
  104. addAudioDeviceType (std::unique_ptr<AudioIODeviceType> (t));
  105. types.clear (false);
  106. for (auto* type : availableDeviceTypes)
  107. type->scanForDevices();
  108. pickCurrentDeviceTypeWithDevices();
  109. }
  110. }
  111. void AudioDeviceManager::pickCurrentDeviceTypeWithDevices()
  112. {
  113. const auto deviceTypeHasDevices = [] (const AudioIODeviceType* ptr)
  114. {
  115. return ! ptr->getDeviceNames (true) .isEmpty()
  116. || ! ptr->getDeviceNames (false).isEmpty();
  117. };
  118. if (auto* type = findType (currentDeviceType))
  119. if (deviceTypeHasDevices (type))
  120. return;
  121. const auto iter = std::find_if (availableDeviceTypes.begin(),
  122. availableDeviceTypes.end(),
  123. deviceTypeHasDevices);
  124. if (iter != availableDeviceTypes.end())
  125. currentDeviceType = (*iter)->getTypeName();
  126. }
  127. const OwnedArray<AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  128. {
  129. scanDevicesIfNeeded();
  130. return availableDeviceTypes;
  131. }
  132. void AudioDeviceManager::updateCurrentSetup()
  133. {
  134. if (currentAudioDevice != nullptr)
  135. {
  136. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  137. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  138. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  139. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  140. }
  141. }
  142. void AudioDeviceManager::audioDeviceListChanged()
  143. {
  144. if (currentAudioDevice != nullptr)
  145. {
  146. auto currentDeviceStillAvailable = [&]
  147. {
  148. auto currentTypeName = currentAudioDevice->getTypeName();
  149. auto currentDeviceName = currentAudioDevice->getName();
  150. for (auto* deviceType : availableDeviceTypes)
  151. {
  152. if (currentTypeName == deviceType->getTypeName())
  153. {
  154. for (auto& deviceName : deviceType->getDeviceNames (true))
  155. if (currentDeviceName == deviceName)
  156. return true;
  157. for (auto& deviceName : deviceType->getDeviceNames (false))
  158. if (currentDeviceName == deviceName)
  159. return true;
  160. }
  161. }
  162. return false;
  163. }();
  164. if (! currentDeviceStillAvailable)
  165. {
  166. closeAudioDevice();
  167. if (auto e = createStateXml())
  168. initialiseFromXML (*e, true, preferredDeviceName, &currentSetup);
  169. else
  170. initialiseDefault (preferredDeviceName, &currentSetup);
  171. }
  172. updateCurrentSetup();
  173. }
  174. sendChangeMessage();
  175. }
  176. //==============================================================================
  177. static void addIfNotNull (OwnedArray<AudioIODeviceType>& list, AudioIODeviceType* const device)
  178. {
  179. if (device != nullptr)
  180. list.add (device);
  181. }
  182. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray<AudioIODeviceType>& list)
  183. {
  184. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_WASAPI (WASAPIDeviceMode::shared));
  185. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_WASAPI (WASAPIDeviceMode::exclusive));
  186. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_WASAPI (WASAPIDeviceMode::sharedLowLatency));
  187. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_DirectSound());
  188. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_ASIO());
  189. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_CoreAudio());
  190. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_iOSAudio());
  191. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_Bela());
  192. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_ALSA());
  193. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_JACK());
  194. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_Oboe());
  195. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_OpenSLES());
  196. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_Android());
  197. }
  198. void AudioDeviceManager::addAudioDeviceType (std::unique_ptr<AudioIODeviceType> newDeviceType)
  199. {
  200. if (newDeviceType != nullptr)
  201. {
  202. jassert (lastDeviceTypeConfigs.size() == availableDeviceTypes.size());
  203. availableDeviceTypes.add (newDeviceType.release());
  204. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  205. availableDeviceTypes.getLast()->addListener (callbackHandler.get());
  206. }
  207. }
  208. void AudioDeviceManager::removeAudioDeviceType (AudioIODeviceType* deviceTypeToRemove)
  209. {
  210. if (deviceTypeToRemove != nullptr)
  211. {
  212. jassert (lastDeviceTypeConfigs.size() == availableDeviceTypes.size());
  213. auto index = availableDeviceTypes.indexOf (deviceTypeToRemove);
  214. if (auto removed = std::unique_ptr<AudioIODeviceType> (availableDeviceTypes.removeAndReturn (index)))
  215. {
  216. removed->removeListener (callbackHandler.get());
  217. lastDeviceTypeConfigs.remove (index, true);
  218. }
  219. }
  220. }
  221. static bool deviceListContains (AudioIODeviceType* type, bool isInput, const String& name)
  222. {
  223. for (auto& deviceName : type->getDeviceNames (isInput))
  224. if (deviceName.trim().equalsIgnoreCase (name.trim()))
  225. return true;
  226. return false;
  227. }
  228. //==============================================================================
  229. String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  230. const int numOutputChannelsNeeded,
  231. const XmlElement* const xml,
  232. const bool selectDefaultDeviceOnFailure,
  233. const String& preferredDefaultDeviceName,
  234. const AudioDeviceSetup* preferredSetupOptions)
  235. {
  236. scanDevicesIfNeeded();
  237. pickCurrentDeviceTypeWithDevices();
  238. numInputChansNeeded = numInputChannelsNeeded;
  239. numOutputChansNeeded = numOutputChannelsNeeded;
  240. preferredDeviceName = preferredDefaultDeviceName;
  241. if (xml != nullptr && xml->hasTagName ("DEVICESETUP"))
  242. return initialiseFromXML (*xml, selectDefaultDeviceOnFailure,
  243. preferredDeviceName, preferredSetupOptions);
  244. return initialiseDefault (preferredDeviceName, preferredSetupOptions);
  245. }
  246. String AudioDeviceManager::initialiseDefault (const String& preferredDefaultDeviceName,
  247. const AudioDeviceSetup* preferredSetupOptions)
  248. {
  249. AudioDeviceSetup setup;
  250. if (preferredSetupOptions != nullptr)
  251. {
  252. setup = *preferredSetupOptions;
  253. }
  254. else if (preferredDefaultDeviceName.isNotEmpty())
  255. {
  256. const auto nameMatches = [&preferredDefaultDeviceName] (const String& name)
  257. {
  258. return name.matchesWildcard (preferredDefaultDeviceName, true);
  259. };
  260. struct WildcardMatch
  261. {
  262. String value;
  263. bool successful;
  264. };
  265. const auto getWildcardMatch = [&nameMatches] (const StringArray& names)
  266. {
  267. const auto iter = std::find_if (names.begin(), names.end(), nameMatches);
  268. return WildcardMatch { iter != names.end() ? *iter : String(), iter != names.end() };
  269. };
  270. struct WildcardMatches
  271. {
  272. WildcardMatch input, output;
  273. };
  274. const auto getMatchesForType = [&getWildcardMatch] (const AudioIODeviceType* type)
  275. {
  276. return WildcardMatches { getWildcardMatch (type->getDeviceNames (true)),
  277. getWildcardMatch (type->getDeviceNames (false)) };
  278. };
  279. struct SearchResult
  280. {
  281. String type, input, output;
  282. };
  283. const auto result = [&]
  284. {
  285. // First, look for a device type with an input and output which matches the preferred name
  286. for (auto* type : availableDeviceTypes)
  287. {
  288. const auto matches = getMatchesForType (type);
  289. if (matches.input.successful && matches.output.successful)
  290. return SearchResult { type->getTypeName(), matches.input.value, matches.output.value };
  291. }
  292. // No device type has matching ins and outs, so fall back to a device where either the
  293. // input or output match
  294. for (auto* type : availableDeviceTypes)
  295. {
  296. const auto matches = getMatchesForType (type);
  297. if (matches.input.successful || matches.output.successful)
  298. return SearchResult { type->getTypeName(), matches.input.value, matches.output.value };
  299. }
  300. // No devices match the query, so just use the default devices from the current type
  301. return SearchResult { currentDeviceType, {}, {} };
  302. }();
  303. currentDeviceType = result.type;
  304. setup.inputDeviceName = result.input;
  305. setup.outputDeviceName = result.output;
  306. }
  307. insertDefaultDeviceNames (setup);
  308. return setAudioDeviceSetup (setup, false);
  309. }
  310. String AudioDeviceManager::initialiseFromXML (const XmlElement& xml,
  311. bool selectDefaultDeviceOnFailure,
  312. const String& preferredDefaultDeviceName,
  313. const AudioDeviceSetup* preferredSetupOptions)
  314. {
  315. lastExplicitSettings.reset (new XmlElement (xml));
  316. String error;
  317. AudioDeviceSetup setup;
  318. if (preferredSetupOptions != nullptr)
  319. setup = *preferredSetupOptions;
  320. if (xml.getStringAttribute ("audioDeviceName").isNotEmpty())
  321. {
  322. setup.inputDeviceName = setup.outputDeviceName
  323. = xml.getStringAttribute ("audioDeviceName");
  324. }
  325. else
  326. {
  327. setup.inputDeviceName = xml.getStringAttribute ("audioInputDeviceName");
  328. setup.outputDeviceName = xml.getStringAttribute ("audioOutputDeviceName");
  329. }
  330. currentDeviceType = xml.getStringAttribute ("deviceType");
  331. if (findType (currentDeviceType) == nullptr)
  332. {
  333. if (auto* type = findType (setup.inputDeviceName, setup.outputDeviceName))
  334. currentDeviceType = type->getTypeName();
  335. else if (auto* firstType = availableDeviceTypes.getFirst())
  336. currentDeviceType = firstType->getTypeName();
  337. }
  338. setup.bufferSize = xml.getIntAttribute ("audioDeviceBufferSize", setup.bufferSize);
  339. setup.sampleRate = xml.getDoubleAttribute ("audioDeviceRate", setup.sampleRate);
  340. setup.inputChannels .parseString (xml.getStringAttribute ("audioDeviceInChans", "11"), 2);
  341. setup.outputChannels.parseString (xml.getStringAttribute ("audioDeviceOutChans", "11"), 2);
  342. setup.useDefaultInputChannels = ! xml.hasAttribute ("audioDeviceInChans");
  343. setup.useDefaultOutputChannels = ! xml.hasAttribute ("audioDeviceOutChans");
  344. error = setAudioDeviceSetup (setup, true);
  345. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  346. error = initialise (numInputChansNeeded, numOutputChansNeeded, nullptr, false, preferredDefaultDeviceName);
  347. midiDeviceInfosFromXml.clear();
  348. enabledMidiInputs.clear();
  349. for (auto* c : xml.getChildWithTagNameIterator ("MIDIINPUT"))
  350. midiDeviceInfosFromXml.add ({ c->getStringAttribute ("name"), c->getStringAttribute ("identifier") });
  351. auto isIdentifierAvailable = [] (const Array<MidiDeviceInfo>& available, const String& identifier)
  352. {
  353. for (auto& device : available)
  354. if (device.identifier == identifier)
  355. return true;
  356. return false;
  357. };
  358. auto getUpdatedIdentifierForName = [&] (const Array<MidiDeviceInfo>& available, const String& name) -> String
  359. {
  360. for (auto& device : available)
  361. if (device.name == name)
  362. return device.identifier;
  363. return {};
  364. };
  365. auto inputs = MidiInput::getAvailableDevices();
  366. for (auto& info : midiDeviceInfosFromXml)
  367. {
  368. if (isIdentifierAvailable (inputs, info.identifier))
  369. {
  370. setMidiInputDeviceEnabled (info.identifier, true);
  371. }
  372. else
  373. {
  374. auto identifier = getUpdatedIdentifierForName (inputs, info.name);
  375. if (identifier.isNotEmpty())
  376. setMidiInputDeviceEnabled (identifier, true);
  377. }
  378. }
  379. MidiDeviceInfo defaultOutputDeviceInfo (xml.getStringAttribute ("defaultMidiOutput"),
  380. xml.getStringAttribute ("defaultMidiOutputDevice"));
  381. auto outputs = MidiOutput::getAvailableDevices();
  382. if (isIdentifierAvailable (outputs, defaultOutputDeviceInfo.identifier))
  383. {
  384. setDefaultMidiOutputDevice (defaultOutputDeviceInfo.identifier);
  385. }
  386. else
  387. {
  388. auto identifier = getUpdatedIdentifierForName (outputs, defaultOutputDeviceInfo.name);
  389. if (identifier.isNotEmpty())
  390. setDefaultMidiOutputDevice (identifier);
  391. }
  392. return error;
  393. }
  394. String AudioDeviceManager::initialiseWithDefaultDevices (int numInputChannelsNeeded,
  395. int numOutputChannelsNeeded)
  396. {
  397. lastExplicitSettings.reset();
  398. return initialise (numInputChannelsNeeded, numOutputChannelsNeeded,
  399. nullptr, false, {}, nullptr);
  400. }
  401. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  402. {
  403. if (auto* type = getCurrentDeviceTypeObject())
  404. {
  405. for (const auto isInput : { false, true })
  406. {
  407. const auto numChannelsNeeded = isInput ? numInputChansNeeded : numOutputChansNeeded;
  408. const auto info = getSetupInfo (setup, isInput);
  409. if (numChannelsNeeded > 0 && info.name.isEmpty())
  410. info.name = type->getDeviceNames (isInput) [type->getDefaultDeviceIndex (isInput)];
  411. }
  412. }
  413. }
  414. std::unique_ptr<XmlElement> AudioDeviceManager::createStateXml() const
  415. {
  416. if (lastExplicitSettings != nullptr)
  417. return std::make_unique<XmlElement> (*lastExplicitSettings);
  418. return {};
  419. }
  420. //==============================================================================
  421. void AudioDeviceManager::scanDevicesIfNeeded()
  422. {
  423. if (listNeedsScanning)
  424. {
  425. listNeedsScanning = false;
  426. createDeviceTypesIfNeeded();
  427. for (auto* type : availableDeviceTypes)
  428. type->scanForDevices();
  429. }
  430. }
  431. AudioIODeviceType* AudioDeviceManager::findType (const String& typeName)
  432. {
  433. scanDevicesIfNeeded();
  434. for (auto* type : availableDeviceTypes)
  435. if (type->getTypeName() == typeName)
  436. return type;
  437. return {};
  438. }
  439. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  440. {
  441. scanDevicesIfNeeded();
  442. for (auto* type : availableDeviceTypes)
  443. if ((inputName.isNotEmpty() && deviceListContains (type, true, inputName))
  444. || (outputName.isNotEmpty() && deviceListContains (type, false, outputName)))
  445. return type;
  446. return {};
  447. }
  448. AudioDeviceManager::AudioDeviceSetup AudioDeviceManager::getAudioDeviceSetup() const
  449. {
  450. return currentSetup;
  451. }
  452. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup) const
  453. {
  454. setup = currentSetup;
  455. }
  456. void AudioDeviceManager::deleteCurrentDevice()
  457. {
  458. currentAudioDevice.reset();
  459. currentSetup.inputDeviceName.clear();
  460. currentSetup.outputDeviceName.clear();
  461. }
  462. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type, bool treatAsChosenDevice)
  463. {
  464. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  465. {
  466. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  467. && currentDeviceType != type)
  468. {
  469. if (currentAudioDevice != nullptr)
  470. {
  471. closeAudioDevice();
  472. Thread::sleep (1500); // allow a moment for OS devices to sort themselves out, to help
  473. // avoid things like DirectSound/ASIO clashes
  474. }
  475. currentDeviceType = type;
  476. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  477. insertDefaultDeviceNames (s);
  478. setAudioDeviceSetup (s, treatAsChosenDevice);
  479. sendChangeMessage();
  480. break;
  481. }
  482. }
  483. }
  484. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  485. {
  486. for (auto* type : availableDeviceTypes)
  487. if (type->getTypeName() == currentDeviceType)
  488. return type;
  489. return availableDeviceTypes.getFirst();
  490. }
  491. static void updateSetupChannels (AudioDeviceManager::AudioDeviceSetup& setup, int defaultNumIns, int defaultNumOuts)
  492. {
  493. auto updateChannels = [] (const String& deviceName, BigInteger& channels, int defaultNumChannels)
  494. {
  495. if (deviceName.isEmpty())
  496. {
  497. channels.clear();
  498. }
  499. else if (defaultNumChannels != -1)
  500. {
  501. channels.clear();
  502. channels.setRange (0, defaultNumChannels, true);
  503. }
  504. };
  505. updateChannels (setup.inputDeviceName, setup.inputChannels, setup.useDefaultInputChannels ? defaultNumIns : -1);
  506. updateChannels (setup.outputDeviceName, setup.outputChannels, setup.useDefaultOutputChannels ? defaultNumOuts : -1);
  507. }
  508. String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  509. bool treatAsChosenDevice)
  510. {
  511. jassert (&newSetup != &currentSetup); // this will have no effect
  512. if (newSetup != currentSetup)
  513. sendChangeMessage();
  514. else if (currentAudioDevice != nullptr)
  515. return {};
  516. stopDevice();
  517. if (getCurrentDeviceTypeObject() == nullptr
  518. || (newSetup.inputDeviceName.isEmpty() && newSetup.outputDeviceName.isEmpty()))
  519. {
  520. deleteCurrentDevice();
  521. if (treatAsChosenDevice)
  522. updateXml();
  523. return {};
  524. }
  525. String error;
  526. const auto needsNewDevice = currentSetup.inputDeviceName != newSetup.inputDeviceName
  527. || currentSetup.outputDeviceName != newSetup.outputDeviceName
  528. || currentAudioDevice == nullptr;
  529. if (needsNewDevice)
  530. {
  531. deleteCurrentDevice();
  532. scanDevicesIfNeeded();
  533. auto* type = getCurrentDeviceTypeObject();
  534. for (const auto isInput : { false, true })
  535. {
  536. const auto name = getSetupInfo (newSetup, isInput).name;
  537. if (name.isNotEmpty() && ! deviceListContains (type, isInput, name))
  538. return "No such device: " + name;
  539. }
  540. currentAudioDevice.reset (type->createDevice (newSetup.outputDeviceName, newSetup.inputDeviceName));
  541. if (currentAudioDevice == nullptr)
  542. error = "Can't open the audio device!\n\n"
  543. "This may be because another application is currently using the same device - "
  544. "if so, you should close any other applications and try again!";
  545. else
  546. error = currentAudioDevice->getLastError();
  547. if (error.isNotEmpty())
  548. {
  549. deleteCurrentDevice();
  550. return error;
  551. }
  552. }
  553. currentSetup = newSetup;
  554. if (! currentSetup.useDefaultInputChannels) numInputChansNeeded = currentSetup.inputChannels.countNumberOfSetBits();
  555. if (! currentSetup.useDefaultOutputChannels) numOutputChansNeeded = currentSetup.outputChannels.countNumberOfSetBits();
  556. updateSetupChannels (currentSetup, numInputChansNeeded, numOutputChansNeeded);
  557. if (currentSetup.inputChannels.isZero() && currentSetup.outputChannels.isZero())
  558. {
  559. if (treatAsChosenDevice)
  560. updateXml();
  561. return {};
  562. }
  563. currentSetup.sampleRate = chooseBestSampleRate (currentSetup.sampleRate);
  564. currentSetup.bufferSize = chooseBestBufferSize (currentSetup.bufferSize);
  565. error = currentAudioDevice->open (currentSetup.inputChannels,
  566. currentSetup.outputChannels,
  567. currentSetup.sampleRate,
  568. currentSetup.bufferSize);
  569. if (error.isEmpty())
  570. {
  571. currentDeviceType = currentAudioDevice->getTypeName();
  572. currentAudioDevice->start (callbackHandler.get());
  573. updateCurrentSetup();
  574. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  575. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  576. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  577. if (treatAsChosenDevice)
  578. updateXml();
  579. }
  580. else
  581. {
  582. deleteCurrentDevice();
  583. }
  584. return error;
  585. }
  586. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  587. {
  588. jassert (currentAudioDevice != nullptr);
  589. auto rates = currentAudioDevice->getAvailableSampleRates();
  590. if (rate > 0 && rates.contains (rate))
  591. return rate;
  592. rate = currentAudioDevice->getCurrentSampleRate();
  593. if (rate > 0 && rates.contains (rate))
  594. return rate;
  595. double lowestAbove44 = 0.0;
  596. for (int i = rates.size(); --i >= 0;)
  597. {
  598. auto sr = rates[i];
  599. if (sr >= 44100.0 && (lowestAbove44 < 1.0 || sr < lowestAbove44))
  600. lowestAbove44 = sr;
  601. }
  602. if (lowestAbove44 > 0.0)
  603. return lowestAbove44;
  604. return rates[0];
  605. }
  606. int AudioDeviceManager::chooseBestBufferSize (int bufferSize) const
  607. {
  608. jassert (currentAudioDevice != nullptr);
  609. if (bufferSize > 0 && currentAudioDevice->getAvailableBufferSizes().contains (bufferSize))
  610. return bufferSize;
  611. return currentAudioDevice->getDefaultBufferSize();
  612. }
  613. void AudioDeviceManager::stopDevice()
  614. {
  615. if (currentAudioDevice != nullptr)
  616. currentAudioDevice->stop();
  617. testSound.reset();
  618. }
  619. void AudioDeviceManager::closeAudioDevice()
  620. {
  621. stopDevice();
  622. currentAudioDevice.reset();
  623. loadMeasurer.reset();
  624. }
  625. void AudioDeviceManager::restartLastAudioDevice()
  626. {
  627. if (currentAudioDevice == nullptr)
  628. {
  629. if (currentSetup.inputDeviceName.isEmpty()
  630. && currentSetup.outputDeviceName.isEmpty())
  631. {
  632. // This method will only reload the last device that was running
  633. // before closeAudioDevice() was called - you need to actually open
  634. // one first, with setAudioDeviceSetup().
  635. jassertfalse;
  636. return;
  637. }
  638. AudioDeviceSetup s (currentSetup);
  639. setAudioDeviceSetup (s, false);
  640. }
  641. }
  642. void AudioDeviceManager::updateXml()
  643. {
  644. lastExplicitSettings.reset (new XmlElement ("DEVICESETUP"));
  645. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  646. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  647. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  648. if (currentAudioDevice != nullptr)
  649. {
  650. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  651. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  652. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  653. if (! currentSetup.useDefaultInputChannels)
  654. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  655. if (! currentSetup.useDefaultOutputChannels)
  656. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  657. }
  658. for (auto& input : enabledMidiInputs)
  659. {
  660. auto* child = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  661. child->setAttribute ("name", input->getName());
  662. child->setAttribute ("identifier", input->getIdentifier());
  663. }
  664. if (midiDeviceInfosFromXml.size() > 0)
  665. {
  666. // Add any midi devices that have been enabled before, but which aren't currently
  667. // open because the device has been disconnected.
  668. auto availableMidiDevices = MidiInput::getAvailableDevices();
  669. for (auto& d : midiDeviceInfosFromXml)
  670. {
  671. if (! availableMidiDevices.contains (d))
  672. {
  673. auto* child = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  674. child->setAttribute ("name", d.name);
  675. child->setAttribute ("identifier", d.identifier);
  676. }
  677. }
  678. }
  679. if (defaultMidiOutputDeviceInfo != MidiDeviceInfo())
  680. {
  681. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputDeviceInfo.name);
  682. lastExplicitSettings->setAttribute ("defaultMidiOutputDevice", defaultMidiOutputDeviceInfo.identifier);
  683. }
  684. }
  685. //==============================================================================
  686. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  687. {
  688. {
  689. const ScopedLock sl (audioCallbackLock);
  690. if (callbacks.contains (newCallback))
  691. return;
  692. }
  693. if (currentAudioDevice != nullptr && newCallback != nullptr)
  694. newCallback->audioDeviceAboutToStart (currentAudioDevice.get());
  695. const ScopedLock sl (audioCallbackLock);
  696. callbacks.add (newCallback);
  697. }
  698. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callbackToRemove)
  699. {
  700. if (callbackToRemove != nullptr)
  701. {
  702. bool needsDeinitialising = currentAudioDevice != nullptr;
  703. {
  704. const ScopedLock sl (audioCallbackLock);
  705. needsDeinitialising = needsDeinitialising && callbacks.contains (callbackToRemove);
  706. callbacks.removeFirstMatchingValue (callbackToRemove);
  707. }
  708. if (needsDeinitialising)
  709. callbackToRemove->audioDeviceStopped();
  710. }
  711. }
  712. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  713. int numInputChannels,
  714. float** outputChannelData,
  715. int numOutputChannels,
  716. int numSamples)
  717. {
  718. const ScopedLock sl (audioCallbackLock);
  719. inputLevelGetter->updateLevel (inputChannelData, numInputChannels, numSamples);
  720. if (callbacks.size() > 0)
  721. {
  722. AudioProcessLoadMeasurer::ScopedTimer timer (loadMeasurer, numSamples);
  723. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  724. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  725. outputChannelData, numOutputChannels, numSamples);
  726. auto** tempChans = tempBuffer.getArrayOfWritePointers();
  727. for (int i = callbacks.size(); --i > 0;)
  728. {
  729. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  730. tempChans, numOutputChannels, numSamples);
  731. for (int chan = 0; chan < numOutputChannels; ++chan)
  732. {
  733. if (auto* src = tempChans [chan])
  734. if (auto* dst = outputChannelData [chan])
  735. for (int j = 0; j < numSamples; ++j)
  736. dst[j] += src[j];
  737. }
  738. }
  739. }
  740. else
  741. {
  742. for (int i = 0; i < numOutputChannels; ++i)
  743. zeromem (outputChannelData[i], (size_t) numSamples * sizeof (float));
  744. }
  745. if (testSound != nullptr)
  746. {
  747. auto numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  748. auto* src = testSound->getReadPointer (0, testSoundPosition);
  749. for (int i = 0; i < numOutputChannels; ++i)
  750. if (auto* dst = outputChannelData [i])
  751. for (int j = 0; j < numSamps; ++j)
  752. dst[j] += src[j];
  753. testSoundPosition += numSamps;
  754. if (testSoundPosition >= testSound->getNumSamples())
  755. testSound.reset();
  756. }
  757. outputLevelGetter->updateLevel (const_cast<const float**> (outputChannelData), numOutputChannels, numSamples);
  758. }
  759. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  760. {
  761. loadMeasurer.reset (device->getCurrentSampleRate(),
  762. device->getCurrentBufferSizeSamples());
  763. updateCurrentSetup();
  764. {
  765. const ScopedLock sl (audioCallbackLock);
  766. for (int i = callbacks.size(); --i >= 0;)
  767. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  768. }
  769. sendChangeMessage();
  770. }
  771. void AudioDeviceManager::audioDeviceStoppedInt()
  772. {
  773. sendChangeMessage();
  774. const ScopedLock sl (audioCallbackLock);
  775. loadMeasurer.reset();
  776. for (int i = callbacks.size(); --i >= 0;)
  777. callbacks.getUnchecked(i)->audioDeviceStopped();
  778. }
  779. void AudioDeviceManager::audioDeviceErrorInt (const String& message)
  780. {
  781. const ScopedLock sl (audioCallbackLock);
  782. for (int i = callbacks.size(); --i >= 0;)
  783. callbacks.getUnchecked(i)->audioDeviceError (message);
  784. }
  785. double AudioDeviceManager::getCpuUsage() const
  786. {
  787. return loadMeasurer.getLoadAsProportion();
  788. }
  789. //==============================================================================
  790. void AudioDeviceManager::setMidiInputDeviceEnabled (const String& identifier, bool enabled)
  791. {
  792. if (enabled != isMidiInputDeviceEnabled (identifier))
  793. {
  794. if (enabled)
  795. {
  796. if (auto midiIn = MidiInput::openDevice (identifier, callbackHandler.get()))
  797. {
  798. enabledMidiInputs.push_back (std::move (midiIn));
  799. enabledMidiInputs.back()->start();
  800. }
  801. }
  802. else
  803. {
  804. auto removePredicate = [identifier] (const std::unique_ptr<MidiInput>& in) { return in->getIdentifier() == identifier; };
  805. enabledMidiInputs.erase (std::remove_if (std::begin (enabledMidiInputs), std::end (enabledMidiInputs), removePredicate),
  806. std::end (enabledMidiInputs));
  807. }
  808. updateXml();
  809. sendChangeMessage();
  810. }
  811. }
  812. bool AudioDeviceManager::isMidiInputDeviceEnabled (const String& identifier) const
  813. {
  814. for (auto& mi : enabledMidiInputs)
  815. if (mi->getIdentifier() == identifier)
  816. return true;
  817. return false;
  818. }
  819. void AudioDeviceManager::addMidiInputDeviceCallback (const String& identifier, MidiInputCallback* callbackToAdd)
  820. {
  821. removeMidiInputDeviceCallback (identifier, callbackToAdd);
  822. if (identifier.isEmpty() || isMidiInputDeviceEnabled (identifier))
  823. {
  824. const ScopedLock sl (midiCallbackLock);
  825. midiCallbacks.add ({ identifier, callbackToAdd });
  826. }
  827. }
  828. void AudioDeviceManager::removeMidiInputDeviceCallback (const String& identifier, MidiInputCallback* callbackToRemove)
  829. {
  830. for (int i = midiCallbacks.size(); --i >= 0;)
  831. {
  832. auto& mc = midiCallbacks.getReference (i);
  833. if (mc.callback == callbackToRemove && mc.deviceIdentifier == identifier)
  834. {
  835. const ScopedLock sl (midiCallbackLock);
  836. midiCallbacks.remove (i);
  837. }
  838. }
  839. }
  840. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message)
  841. {
  842. if (! message.isActiveSense())
  843. {
  844. const ScopedLock sl (midiCallbackLock);
  845. for (auto& mc : midiCallbacks)
  846. if (mc.deviceIdentifier.isEmpty() || mc.deviceIdentifier == source->getIdentifier())
  847. mc.callback->handleIncomingMidiMessage (source, message);
  848. }
  849. }
  850. //==============================================================================
  851. void AudioDeviceManager::setDefaultMidiOutputDevice (const String& identifier)
  852. {
  853. if (defaultMidiOutputDeviceInfo.identifier != identifier)
  854. {
  855. Array<AudioIODeviceCallback*> oldCallbacks;
  856. {
  857. const ScopedLock sl (audioCallbackLock);
  858. oldCallbacks.swapWith (callbacks);
  859. }
  860. if (currentAudioDevice != nullptr)
  861. for (int i = oldCallbacks.size(); --i >= 0;)
  862. oldCallbacks.getUnchecked (i)->audioDeviceStopped();
  863. defaultMidiOutput.reset();
  864. if (identifier.isNotEmpty())
  865. defaultMidiOutput = MidiOutput::openDevice (identifier);
  866. if (defaultMidiOutput != nullptr)
  867. defaultMidiOutputDeviceInfo = defaultMidiOutput->getDeviceInfo();
  868. else
  869. defaultMidiOutputDeviceInfo = {};
  870. if (currentAudioDevice != nullptr)
  871. for (auto* c : oldCallbacks)
  872. c->audioDeviceAboutToStart (currentAudioDevice.get());
  873. {
  874. const ScopedLock sl (audioCallbackLock);
  875. oldCallbacks.swapWith (callbacks);
  876. }
  877. updateXml();
  878. sendChangeMessage();
  879. }
  880. }
  881. //==============================================================================
  882. AudioDeviceManager::LevelMeter::LevelMeter() noexcept : level() {}
  883. void AudioDeviceManager::LevelMeter::updateLevel (const float* const* channelData, int numChannels, int numSamples) noexcept
  884. {
  885. if (getReferenceCount() <= 1)
  886. return;
  887. auto localLevel = level.get();
  888. if (numChannels > 0)
  889. {
  890. for (int j = 0; j < numSamples; ++j)
  891. {
  892. float s = 0;
  893. for (int i = 0; i < numChannels; ++i)
  894. s += std::abs (channelData[i][j]);
  895. s /= (float) numChannels;
  896. const float decayFactor = 0.99992f;
  897. if (s > localLevel)
  898. localLevel = s;
  899. else if (localLevel > 0.001f)
  900. localLevel *= decayFactor;
  901. else
  902. localLevel = 0;
  903. }
  904. }
  905. else
  906. {
  907. localLevel = 0;
  908. }
  909. level = localLevel;
  910. }
  911. double AudioDeviceManager::LevelMeter::getCurrentLevel() const noexcept
  912. {
  913. jassert (getReferenceCount() > 1);
  914. return level.get();
  915. }
  916. void AudioDeviceManager::playTestSound()
  917. {
  918. { // cunningly nested to swap, unlock and delete in that order.
  919. std::unique_ptr<AudioBuffer<float>> oldSound;
  920. {
  921. const ScopedLock sl (audioCallbackLock);
  922. std::swap (oldSound, testSound);
  923. }
  924. }
  925. testSoundPosition = 0;
  926. if (currentAudioDevice != nullptr)
  927. {
  928. auto sampleRate = currentAudioDevice->getCurrentSampleRate();
  929. auto soundLength = (int) sampleRate;
  930. double frequency = 440.0;
  931. float amplitude = 0.5f;
  932. auto phasePerSample = MathConstants<double>::twoPi / (sampleRate / frequency);
  933. std::unique_ptr<AudioBuffer<float>> newSound (new AudioBuffer<float> (1, soundLength));
  934. for (int i = 0; i < soundLength; ++i)
  935. newSound->setSample (0, i, amplitude * (float) std::sin (i * phasePerSample));
  936. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  937. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  938. {
  939. const ScopedLock sl (audioCallbackLock);
  940. std::swap (testSound, newSound);
  941. }
  942. }
  943. }
  944. int AudioDeviceManager::getXRunCount() const noexcept
  945. {
  946. auto deviceXRuns = (currentAudioDevice != nullptr ? currentAudioDevice->getXRunCount() : -1);
  947. return jmax (0, deviceXRuns) + loadMeasurer.getXRunCount();
  948. }
  949. //==============================================================================
  950. // Deprecated
  951. void AudioDeviceManager::setMidiInputEnabled (const String& name, const bool enabled)
  952. {
  953. for (auto& device : MidiInput::getAvailableDevices())
  954. {
  955. if (device.name == name)
  956. {
  957. setMidiInputDeviceEnabled (device.identifier, enabled);
  958. return;
  959. }
  960. }
  961. }
  962. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  963. {
  964. for (auto& device : MidiInput::getAvailableDevices())
  965. if (device.name == name)
  966. return isMidiInputDeviceEnabled (device.identifier);
  967. return false;
  968. }
  969. void AudioDeviceManager::addMidiInputCallback (const String& name, MidiInputCallback* callbackToAdd)
  970. {
  971. if (name.isEmpty())
  972. {
  973. addMidiInputDeviceCallback ({}, callbackToAdd);
  974. }
  975. else
  976. {
  977. for (auto& device : MidiInput::getAvailableDevices())
  978. {
  979. if (device.name == name)
  980. {
  981. addMidiInputDeviceCallback (device.identifier, callbackToAdd);
  982. return;
  983. }
  984. }
  985. }
  986. }
  987. void AudioDeviceManager::removeMidiInputCallback (const String& name, MidiInputCallback* callbackToRemove)
  988. {
  989. if (name.isEmpty())
  990. {
  991. removeMidiInputDeviceCallback ({}, callbackToRemove);
  992. }
  993. else
  994. {
  995. for (auto& device : MidiInput::getAvailableDevices())
  996. {
  997. if (device.name == name)
  998. {
  999. removeMidiInputDeviceCallback (device.identifier, callbackToRemove);
  1000. return;
  1001. }
  1002. }
  1003. }
  1004. }
  1005. void AudioDeviceManager::setDefaultMidiOutput (const String& name)
  1006. {
  1007. for (auto& device : MidiOutput::getAvailableDevices())
  1008. {
  1009. if (device.name == name)
  1010. {
  1011. setDefaultMidiOutputDevice (device.identifier);
  1012. return;
  1013. }
  1014. }
  1015. }
  1016. //==============================================================================
  1017. //==============================================================================
  1018. #if JUCE_UNIT_TESTS
  1019. class AudioDeviceManagerTests : public UnitTest
  1020. {
  1021. public:
  1022. AudioDeviceManagerTests() : UnitTest ("AudioDeviceManager", UnitTestCategories::audio) {}
  1023. void runTest() override
  1024. {
  1025. beginTest ("When the AudioDeviceSetup has non-empty device names, initialise uses the requested devices");
  1026. {
  1027. AudioDeviceManager manager;
  1028. initialiseManager (manager);
  1029. expectEquals (manager.getAvailableDeviceTypes().size(), 2);
  1030. AudioDeviceManager::AudioDeviceSetup setup;
  1031. setup.outputDeviceName = "z";
  1032. setup.inputDeviceName = "c";
  1033. expect (manager.initialise (2, 2, nullptr, true, String{}, &setup).isEmpty());
  1034. const auto& newSetup = manager.getAudioDeviceSetup();
  1035. expectEquals (newSetup.outputDeviceName, setup.outputDeviceName);
  1036. expectEquals (newSetup.inputDeviceName, setup.inputDeviceName);
  1037. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1038. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 2);
  1039. }
  1040. beginTest ("When the AudioDeviceSetup has empty device names, initialise picks suitable default devices");
  1041. {
  1042. AudioDeviceManager manager;
  1043. initialiseManager (manager);
  1044. AudioDeviceManager::AudioDeviceSetup setup;
  1045. expect (manager.initialise (2, 2, nullptr, true, String{}, &setup).isEmpty());
  1046. const auto& newSetup = manager.getAudioDeviceSetup();
  1047. expectEquals (newSetup.outputDeviceName, String ("x"));
  1048. expectEquals (newSetup.inputDeviceName, String ("a"));
  1049. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1050. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 2);
  1051. }
  1052. beginTest ("When the preferred device name matches an input and an output on the same type, that type is used");
  1053. {
  1054. AudioDeviceManager manager;
  1055. initialiseManagerWithDifferentDeviceNames (manager);
  1056. expect (manager.initialise (2, 2, nullptr, true, "bar *").isEmpty());
  1057. expectEquals (manager.getCurrentAudioDeviceType(), String ("bar"));
  1058. const auto& newSetup = manager.getAudioDeviceSetup();
  1059. expectEquals (newSetup.outputDeviceName, String ("bar out a"));
  1060. expectEquals (newSetup.inputDeviceName, String ("bar in a"));
  1061. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1062. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 2);
  1063. expect (manager.getCurrentAudioDevice() != nullptr);
  1064. }
  1065. beginTest ("When the preferred device name matches either an input and an output, but not both, that type is used");
  1066. {
  1067. AudioDeviceManager manager;
  1068. initialiseManagerWithDifferentDeviceNames (manager);
  1069. expect (manager.initialise (2, 2, nullptr, true, "bar out b").isEmpty());
  1070. expectEquals (manager.getCurrentAudioDeviceType(), String ("bar"));
  1071. const auto& newSetup = manager.getAudioDeviceSetup();
  1072. expectEquals (newSetup.outputDeviceName, String ("bar out b"));
  1073. expectEquals (newSetup.inputDeviceName, String ("bar in a"));
  1074. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1075. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 2);
  1076. expect (manager.getCurrentAudioDevice() != nullptr);
  1077. }
  1078. beginTest ("When the preferred device name does not match any inputs or outputs, defaults are used");
  1079. {
  1080. AudioDeviceManager manager;
  1081. initialiseManagerWithDifferentDeviceNames (manager);
  1082. expect (manager.initialise (2, 2, nullptr, true, "unmatchable").isEmpty());
  1083. expectEquals (manager.getCurrentAudioDeviceType(), String ("foo"));
  1084. const auto& newSetup = manager.getAudioDeviceSetup();
  1085. expectEquals (newSetup.outputDeviceName, String ("foo out a"));
  1086. expectEquals (newSetup.inputDeviceName, String ("foo in a"));
  1087. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1088. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 2);
  1089. expect (manager.getCurrentAudioDevice() != nullptr);
  1090. }
  1091. beginTest ("When first device type has no devices, a device type with devices is used instead");
  1092. {
  1093. AudioDeviceManager manager;
  1094. initialiseManagerWithEmptyDeviceType (manager);
  1095. AudioDeviceManager::AudioDeviceSetup setup;
  1096. expect (manager.initialise (2, 2, nullptr, true, {}, &setup).isEmpty());
  1097. const auto& newSetup = manager.getAudioDeviceSetup();
  1098. expectEquals (newSetup.outputDeviceName, String ("x"));
  1099. expectEquals (newSetup.inputDeviceName, String ("a"));
  1100. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1101. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 2);
  1102. }
  1103. beginTest ("If a device type has been explicitly set to a type with devices, "
  1104. "initialisation should respect this choice");
  1105. {
  1106. AudioDeviceManager manager;
  1107. initialiseManagerWithEmptyDeviceType (manager);
  1108. manager.setCurrentAudioDeviceType (mockBName, true);
  1109. AudioDeviceManager::AudioDeviceSetup setup;
  1110. expect (manager.initialise (2, 2, nullptr, true, {}, &setup).isEmpty());
  1111. expectEquals (manager.getCurrentAudioDeviceType(), mockBName);
  1112. }
  1113. beginTest ("If a device type has been explicitly set to a type without devices, "
  1114. "initialisation should pick a type with devices instead");
  1115. {
  1116. AudioDeviceManager manager;
  1117. initialiseManagerWithEmptyDeviceType (manager);
  1118. manager.setCurrentAudioDeviceType (emptyName, true);
  1119. AudioDeviceManager::AudioDeviceSetup setup;
  1120. expect (manager.initialise (2, 2, nullptr, true, {}, &setup).isEmpty());
  1121. expectEquals (manager.getCurrentAudioDeviceType(), mockAName);
  1122. }
  1123. beginTest ("Carry out a long sequence of configuration changes");
  1124. {
  1125. AudioDeviceManager manager;
  1126. initialiseManagerWithEmptyDeviceType (manager);
  1127. initialiseWithDefaultDevices (manager);
  1128. disableInputChannelsButLeaveDeviceOpen (manager);
  1129. selectANewInputDevice (manager);
  1130. disableInputDevice (manager);
  1131. reenableInputDeviceWithNoChannels (manager);
  1132. enableInputChannels (manager);
  1133. disableInputChannelsButLeaveDeviceOpen (manager);
  1134. switchDeviceType (manager);
  1135. enableInputChannels (manager);
  1136. closeDeviceByRequestingEmptyNames (manager);
  1137. }
  1138. beginTest ("AudioDeviceManager updates its current settings before notifying callbacks when device restarts itself");
  1139. {
  1140. AudioDeviceManager manager;
  1141. auto deviceType = std::make_unique<MockDeviceType> ("foo",
  1142. StringArray { "foo in a", "foo in b" },
  1143. StringArray { "foo out a", "foo out b" });
  1144. auto* ptr = deviceType.get();
  1145. manager.addAudioDeviceType (std::move (deviceType));
  1146. AudioDeviceManager::AudioDeviceSetup setup;
  1147. setup.sampleRate = 48000.0;
  1148. setup.bufferSize = 256;
  1149. setup.inputDeviceName = "foo in a";
  1150. setup.outputDeviceName = "foo out a";
  1151. setup.useDefaultInputChannels = true;
  1152. setup.useDefaultOutputChannels = true;
  1153. manager.setAudioDeviceSetup (setup, true);
  1154. const auto currentSetup = manager.getAudioDeviceSetup();
  1155. expectEquals (currentSetup.sampleRate, setup.sampleRate);
  1156. expectEquals (currentSetup.bufferSize, setup.bufferSize);
  1157. MockCallback callback;
  1158. manager.addAudioCallback (&callback);
  1159. constexpr auto newSr = 10000.0;
  1160. constexpr auto newBs = 1024;
  1161. auto numCalls = 0;
  1162. // Compilers disagree about whether newSr and newBs need to be captured
  1163. callback.aboutToStart = [&]
  1164. {
  1165. ++numCalls;
  1166. const auto current = manager.getAudioDeviceSetup();
  1167. expectEquals (current.sampleRate, newSr);
  1168. expectEquals (current.bufferSize, newBs);
  1169. };
  1170. ptr->restartDevices (newSr, newBs);
  1171. expectEquals (numCalls, 1);
  1172. }
  1173. }
  1174. private:
  1175. void initialiseWithDefaultDevices (AudioDeviceManager& manager)
  1176. {
  1177. manager.initialiseWithDefaultDevices (2, 2);
  1178. const auto& setup = manager.getAudioDeviceSetup();
  1179. expectEquals (setup.inputChannels.countNumberOfSetBits(), 2);
  1180. expectEquals (setup.outputChannels.countNumberOfSetBits(), 2);
  1181. expect (setup.useDefaultInputChannels);
  1182. expect (setup.useDefaultOutputChannels);
  1183. expect (manager.getCurrentAudioDevice() != nullptr);
  1184. }
  1185. void disableInputChannelsButLeaveDeviceOpen (AudioDeviceManager& manager)
  1186. {
  1187. auto setup = manager.getAudioDeviceSetup();
  1188. setup.inputChannels.clear();
  1189. setup.useDefaultInputChannels = false;
  1190. expect (manager.setAudioDeviceSetup (setup, true).isEmpty());
  1191. const auto newSetup = manager.getAudioDeviceSetup();
  1192. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 0);
  1193. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1194. expect (! newSetup.useDefaultInputChannels);
  1195. expect (newSetup.useDefaultOutputChannels);
  1196. expectEquals (newSetup.inputDeviceName, setup.inputDeviceName);
  1197. expectEquals (newSetup.outputDeviceName, setup.outputDeviceName);
  1198. expect (manager.getCurrentAudioDevice() != nullptr);
  1199. }
  1200. void selectANewInputDevice (AudioDeviceManager& manager)
  1201. {
  1202. auto setup = manager.getAudioDeviceSetup();
  1203. setup.inputDeviceName = "b";
  1204. expect (manager.setAudioDeviceSetup (setup, true).isEmpty());
  1205. const auto newSetup = manager.getAudioDeviceSetup();
  1206. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 0);
  1207. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1208. expect (! newSetup.useDefaultInputChannels);
  1209. expect (newSetup.useDefaultOutputChannels);
  1210. expectEquals (newSetup.inputDeviceName, setup.inputDeviceName);
  1211. expectEquals (newSetup.outputDeviceName, setup.outputDeviceName);
  1212. expect (manager.getCurrentAudioDevice() != nullptr);
  1213. }
  1214. void disableInputDevice (AudioDeviceManager& manager)
  1215. {
  1216. auto setup = manager.getAudioDeviceSetup();
  1217. setup.inputDeviceName = "";
  1218. expect (manager.setAudioDeviceSetup (setup, true).isEmpty());
  1219. const auto newSetup = manager.getAudioDeviceSetup();
  1220. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 0);
  1221. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1222. expect (! newSetup.useDefaultInputChannels);
  1223. expect (newSetup.useDefaultOutputChannels);
  1224. expectEquals (newSetup.inputDeviceName, setup.inputDeviceName);
  1225. expectEquals (newSetup.outputDeviceName, setup.outputDeviceName);
  1226. expect (manager.getCurrentAudioDevice() != nullptr);
  1227. }
  1228. void reenableInputDeviceWithNoChannels (AudioDeviceManager& manager)
  1229. {
  1230. auto setup = manager.getAudioDeviceSetup();
  1231. setup.inputDeviceName = "a";
  1232. expect (manager.setAudioDeviceSetup (setup, true).isEmpty());
  1233. const auto newSetup = manager.getAudioDeviceSetup();
  1234. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 0);
  1235. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1236. expect (! newSetup.useDefaultInputChannels);
  1237. expect (newSetup.useDefaultOutputChannels);
  1238. expectEquals (newSetup.inputDeviceName, setup.inputDeviceName);
  1239. expectEquals (newSetup.outputDeviceName, setup.outputDeviceName);
  1240. expect (manager.getCurrentAudioDevice() != nullptr);
  1241. }
  1242. void enableInputChannels (AudioDeviceManager& manager)
  1243. {
  1244. auto setup = manager.getAudioDeviceSetup();
  1245. setup.inputDeviceName = manager.getCurrentDeviceTypeObject()->getDeviceNames (true)[0];
  1246. setup.inputChannels = 3;
  1247. setup.useDefaultInputChannels = false;
  1248. expect (manager.setAudioDeviceSetup (setup, true).isEmpty());
  1249. const auto newSetup = manager.getAudioDeviceSetup();
  1250. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 2);
  1251. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1252. expect (! newSetup.useDefaultInputChannels);
  1253. expect (newSetup.useDefaultOutputChannels);
  1254. expectEquals (newSetup.inputDeviceName, setup.inputDeviceName);
  1255. expectEquals (newSetup.outputDeviceName, setup.outputDeviceName);
  1256. expect (manager.getCurrentAudioDevice() != nullptr);
  1257. }
  1258. void switchDeviceType (AudioDeviceManager& manager)
  1259. {
  1260. const auto oldSetup = manager.getAudioDeviceSetup();
  1261. expectEquals (manager.getCurrentAudioDeviceType(), String (mockAName));
  1262. manager.setCurrentAudioDeviceType (mockBName, true);
  1263. expectEquals (manager.getCurrentAudioDeviceType(), String (mockBName));
  1264. const auto newSetup = manager.getAudioDeviceSetup();
  1265. expect (newSetup.outputDeviceName.isNotEmpty());
  1266. // We had no channels enabled, which means we don't need to open a new input device
  1267. expect (newSetup.inputDeviceName.isEmpty());
  1268. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 0);
  1269. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1270. expect (manager.getCurrentAudioDevice() != nullptr);
  1271. }
  1272. void closeDeviceByRequestingEmptyNames (AudioDeviceManager& manager)
  1273. {
  1274. auto setup = manager.getAudioDeviceSetup();
  1275. setup.inputDeviceName = "";
  1276. setup.outputDeviceName = "";
  1277. expect (manager.setAudioDeviceSetup (setup, true).isEmpty());
  1278. const auto newSetup = manager.getAudioDeviceSetup();
  1279. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 2);
  1280. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1281. expect (newSetup.inputDeviceName.isEmpty());
  1282. expect (newSetup.outputDeviceName.isEmpty());
  1283. expect (manager.getCurrentAudioDevice() == nullptr);
  1284. }
  1285. const String mockAName = "mockA";
  1286. const String mockBName = "mockB";
  1287. const String emptyName = "empty";
  1288. struct Restartable
  1289. {
  1290. virtual ~Restartable() = default;
  1291. virtual void restart (double newSr, int newBs) = 0;
  1292. };
  1293. class MockDevice : public AudioIODevice,
  1294. private Restartable
  1295. {
  1296. public:
  1297. MockDevice (ListenerList<Restartable>& l, String typeNameIn, String outNameIn, String inNameIn)
  1298. : AudioIODevice ("mock", typeNameIn), listeners (l), outName (outNameIn), inName (inNameIn)
  1299. {
  1300. listeners.add (this);
  1301. }
  1302. ~MockDevice() override
  1303. {
  1304. listeners.remove (this);
  1305. }
  1306. StringArray getOutputChannelNames() override { return { "o1", "o2", "o3" }; }
  1307. StringArray getInputChannelNames() override { return { "i1", "i2", "i3" }; }
  1308. Array<double> getAvailableSampleRates() override { return { 44100.0, 48000.0 }; }
  1309. Array<int> getAvailableBufferSizes() override { return { 128, 256 }; }
  1310. int getDefaultBufferSize() override { return 128; }
  1311. String open (const BigInteger& inputs, const BigInteger& outputs, double sr, int bs) override
  1312. {
  1313. inChannels = inputs;
  1314. outChannels = outputs;
  1315. sampleRate = sr;
  1316. blockSize = bs;
  1317. on = true;
  1318. return {};
  1319. }
  1320. void close() override { on = false; }
  1321. bool isOpen() override { return on; }
  1322. void start (AudioIODeviceCallback* c) override
  1323. {
  1324. callback = c;
  1325. callback->audioDeviceAboutToStart (this);
  1326. playing = true;
  1327. }
  1328. void stop() override
  1329. {
  1330. playing = false;
  1331. callback->audioDeviceStopped();
  1332. }
  1333. bool isPlaying() override { return playing; }
  1334. String getLastError() override { return {}; }
  1335. int getCurrentBufferSizeSamples() override { return blockSize; }
  1336. double getCurrentSampleRate() override { return sampleRate; }
  1337. int getCurrentBitDepth() override { return 16; }
  1338. BigInteger getActiveOutputChannels() const override { return outChannels; }
  1339. BigInteger getActiveInputChannels() const override { return inChannels; }
  1340. int getOutputLatencyInSamples() override { return 0; }
  1341. int getInputLatencyInSamples() override { return 0; }
  1342. private:
  1343. void restart (double newSr, int newBs) override
  1344. {
  1345. stop();
  1346. close();
  1347. open (inChannels, outChannels, newSr, newBs);
  1348. start (callback);
  1349. }
  1350. ListenerList<Restartable>& listeners;
  1351. AudioIODeviceCallback* callback = nullptr;
  1352. String outName, inName;
  1353. BigInteger outChannels, inChannels;
  1354. double sampleRate = 0.0;
  1355. int blockSize = 0;
  1356. bool on = false, playing = false;
  1357. };
  1358. class MockDeviceType : public AudioIODeviceType
  1359. {
  1360. public:
  1361. explicit MockDeviceType (String kind)
  1362. : MockDeviceType (std::move (kind), { "a", "b", "c" }, { "x", "y", "z" }) {}
  1363. MockDeviceType (String kind, StringArray inputNames, StringArray outputNames)
  1364. : AudioIODeviceType (std::move (kind)),
  1365. inNames (std::move (inputNames)),
  1366. outNames (std::move (outputNames)) {}
  1367. ~MockDeviceType() override
  1368. {
  1369. // A Device outlived its DeviceType!
  1370. jassert (listeners.isEmpty());
  1371. }
  1372. void scanForDevices() override {}
  1373. StringArray getDeviceNames (bool isInput) const override
  1374. {
  1375. return getNames (isInput);
  1376. }
  1377. int getDefaultDeviceIndex (bool) const override { return 0; }
  1378. int getIndexOfDevice (AudioIODevice* device, bool isInput) const override
  1379. {
  1380. return getNames (isInput).indexOf (device->getName());
  1381. }
  1382. bool hasSeparateInputsAndOutputs() const override { return true; }
  1383. AudioIODevice* createDevice (const String& outputName, const String& inputName) override
  1384. {
  1385. if (inNames.contains (inputName) || outNames.contains (outputName))
  1386. return new MockDevice (listeners, getTypeName(), outputName, inputName);
  1387. return nullptr;
  1388. }
  1389. // Call this to emulate the device restarting itself with new settings.
  1390. // This might happen e.g. when a user changes the ASIO settings.
  1391. void restartDevices (double newSr, int newBs)
  1392. {
  1393. listeners.call ([&] (auto& l) { return l.restart (newSr, newBs); });
  1394. }
  1395. private:
  1396. const StringArray& getNames (bool isInput) const { return isInput ? inNames : outNames; }
  1397. const StringArray inNames, outNames;
  1398. ListenerList<Restartable> listeners;
  1399. };
  1400. class MockCallback : public AudioIODeviceCallback
  1401. {
  1402. public:
  1403. std::function<void()> callback;
  1404. std::function<void()> aboutToStart;
  1405. std::function<void()> stopped;
  1406. std::function<void()> error;
  1407. void audioDeviceIOCallback (const float**, int, float**, int, int) override { NullCheckedInvocation::invoke (callback); }
  1408. void audioDeviceAboutToStart (AudioIODevice*) override { NullCheckedInvocation::invoke (aboutToStart); }
  1409. void audioDeviceStopped() override { NullCheckedInvocation::invoke (stopped); }
  1410. void audioDeviceError (const String&) override { NullCheckedInvocation::invoke (error); }
  1411. };
  1412. void initialiseManager (AudioDeviceManager& manager)
  1413. {
  1414. manager.addAudioDeviceType (std::make_unique<MockDeviceType> (mockAName));
  1415. manager.addAudioDeviceType (std::make_unique<MockDeviceType> (mockBName));
  1416. }
  1417. void initialiseManagerWithEmptyDeviceType (AudioDeviceManager& manager)
  1418. {
  1419. manager.addAudioDeviceType (std::make_unique<MockDeviceType> (emptyName, StringArray{}, StringArray{}));
  1420. initialiseManager (manager);
  1421. }
  1422. void initialiseManagerWithDifferentDeviceNames (AudioDeviceManager& manager)
  1423. {
  1424. manager.addAudioDeviceType (std::make_unique<MockDeviceType> ("foo",
  1425. StringArray { "foo in a", "foo in b" },
  1426. StringArray { "foo out a", "foo out b" }));
  1427. manager.addAudioDeviceType (std::make_unique<MockDeviceType> ("bar",
  1428. StringArray { "bar in a", "bar in b" },
  1429. StringArray { "bar out a", "bar out b" }));
  1430. }
  1431. };
  1432. static AudioDeviceManagerTests audioDeviceManagerTests;
  1433. #endif
  1434. } // namespace juce