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.

1730 lines
60KB

  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. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  574. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  575. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  576. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  577. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  578. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  579. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  580. if (treatAsChosenDevice)
  581. updateXml();
  582. }
  583. else
  584. {
  585. deleteCurrentDevice();
  586. }
  587. return error;
  588. }
  589. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  590. {
  591. jassert (currentAudioDevice != nullptr);
  592. auto rates = currentAudioDevice->getAvailableSampleRates();
  593. if (rate > 0 && rates.contains (rate))
  594. return rate;
  595. rate = currentAudioDevice->getCurrentSampleRate();
  596. if (rate > 0 && rates.contains (rate))
  597. return rate;
  598. double lowestAbove44 = 0.0;
  599. for (int i = rates.size(); --i >= 0;)
  600. {
  601. auto sr = rates[i];
  602. if (sr >= 44100.0 && (lowestAbove44 < 1.0 || sr < lowestAbove44))
  603. lowestAbove44 = sr;
  604. }
  605. if (lowestAbove44 > 0.0)
  606. return lowestAbove44;
  607. return rates[0];
  608. }
  609. int AudioDeviceManager::chooseBestBufferSize (int bufferSize) const
  610. {
  611. jassert (currentAudioDevice != nullptr);
  612. if (bufferSize > 0 && currentAudioDevice->getAvailableBufferSizes().contains (bufferSize))
  613. return bufferSize;
  614. return currentAudioDevice->getDefaultBufferSize();
  615. }
  616. void AudioDeviceManager::stopDevice()
  617. {
  618. if (currentAudioDevice != nullptr)
  619. currentAudioDevice->stop();
  620. testSound.reset();
  621. }
  622. void AudioDeviceManager::closeAudioDevice()
  623. {
  624. stopDevice();
  625. currentAudioDevice.reset();
  626. loadMeasurer.reset();
  627. }
  628. void AudioDeviceManager::restartLastAudioDevice()
  629. {
  630. if (currentAudioDevice == nullptr)
  631. {
  632. if (currentSetup.inputDeviceName.isEmpty()
  633. && currentSetup.outputDeviceName.isEmpty())
  634. {
  635. // This method will only reload the last device that was running
  636. // before closeAudioDevice() was called - you need to actually open
  637. // one first, with setAudioDeviceSetup().
  638. jassertfalse;
  639. return;
  640. }
  641. AudioDeviceSetup s (currentSetup);
  642. setAudioDeviceSetup (s, false);
  643. }
  644. }
  645. void AudioDeviceManager::updateXml()
  646. {
  647. lastExplicitSettings.reset (new XmlElement ("DEVICESETUP"));
  648. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  649. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  650. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  651. if (currentAudioDevice != nullptr)
  652. {
  653. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  654. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  655. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  656. if (! currentSetup.useDefaultInputChannels)
  657. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  658. if (! currentSetup.useDefaultOutputChannels)
  659. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  660. }
  661. for (auto& input : enabledMidiInputs)
  662. {
  663. auto* child = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  664. child->setAttribute ("name", input->getName());
  665. child->setAttribute ("identifier", input->getIdentifier());
  666. }
  667. if (midiDeviceInfosFromXml.size() > 0)
  668. {
  669. // Add any midi devices that have been enabled before, but which aren't currently
  670. // open because the device has been disconnected.
  671. auto availableMidiDevices = MidiInput::getAvailableDevices();
  672. for (auto& d : midiDeviceInfosFromXml)
  673. {
  674. if (! availableMidiDevices.contains (d))
  675. {
  676. auto* child = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  677. child->setAttribute ("name", d.name);
  678. child->setAttribute ("identifier", d.identifier);
  679. }
  680. }
  681. }
  682. if (defaultMidiOutputDeviceInfo != MidiDeviceInfo())
  683. {
  684. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputDeviceInfo.name);
  685. lastExplicitSettings->setAttribute ("defaultMidiOutputDevice", defaultMidiOutputDeviceInfo.identifier);
  686. }
  687. }
  688. //==============================================================================
  689. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  690. {
  691. {
  692. const ScopedLock sl (audioCallbackLock);
  693. if (callbacks.contains (newCallback))
  694. return;
  695. }
  696. if (currentAudioDevice != nullptr && newCallback != nullptr)
  697. newCallback->audioDeviceAboutToStart (currentAudioDevice.get());
  698. const ScopedLock sl (audioCallbackLock);
  699. callbacks.add (newCallback);
  700. }
  701. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callbackToRemove)
  702. {
  703. if (callbackToRemove != nullptr)
  704. {
  705. bool needsDeinitialising = currentAudioDevice != nullptr;
  706. {
  707. const ScopedLock sl (audioCallbackLock);
  708. needsDeinitialising = needsDeinitialising && callbacks.contains (callbackToRemove);
  709. callbacks.removeFirstMatchingValue (callbackToRemove);
  710. }
  711. if (needsDeinitialising)
  712. callbackToRemove->audioDeviceStopped();
  713. }
  714. }
  715. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  716. int numInputChannels,
  717. float** outputChannelData,
  718. int numOutputChannels,
  719. int numSamples)
  720. {
  721. const ScopedLock sl (audioCallbackLock);
  722. inputLevelGetter->updateLevel (inputChannelData, numInputChannels, numSamples);
  723. if (callbacks.size() > 0)
  724. {
  725. AudioProcessLoadMeasurer::ScopedTimer timer (loadMeasurer, numSamples);
  726. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  727. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  728. outputChannelData, numOutputChannels, numSamples);
  729. auto** tempChans = tempBuffer.getArrayOfWritePointers();
  730. for (int i = callbacks.size(); --i > 0;)
  731. {
  732. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  733. tempChans, numOutputChannels, numSamples);
  734. for (int chan = 0; chan < numOutputChannels; ++chan)
  735. {
  736. if (auto* src = tempChans [chan])
  737. if (auto* dst = outputChannelData [chan])
  738. for (int j = 0; j < numSamples; ++j)
  739. dst[j] += src[j];
  740. }
  741. }
  742. }
  743. else
  744. {
  745. for (int i = 0; i < numOutputChannels; ++i)
  746. zeromem (outputChannelData[i], (size_t) numSamples * sizeof (float));
  747. }
  748. if (testSound != nullptr)
  749. {
  750. auto numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  751. auto* src = testSound->getReadPointer (0, testSoundPosition);
  752. for (int i = 0; i < numOutputChannels; ++i)
  753. if (auto* dst = outputChannelData [i])
  754. for (int j = 0; j < numSamps; ++j)
  755. dst[j] += src[j];
  756. testSoundPosition += numSamps;
  757. if (testSoundPosition >= testSound->getNumSamples())
  758. testSound.reset();
  759. }
  760. outputLevelGetter->updateLevel (const_cast<const float**> (outputChannelData), numOutputChannels, numSamples);
  761. }
  762. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  763. {
  764. loadMeasurer.reset (device->getCurrentSampleRate(),
  765. device->getCurrentBufferSizeSamples());
  766. {
  767. const ScopedLock sl (audioCallbackLock);
  768. for (int i = callbacks.size(); --i >= 0;)
  769. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  770. }
  771. updateCurrentSetup();
  772. sendChangeMessage();
  773. }
  774. void AudioDeviceManager::audioDeviceStoppedInt()
  775. {
  776. sendChangeMessage();
  777. const ScopedLock sl (audioCallbackLock);
  778. loadMeasurer.reset();
  779. for (int i = callbacks.size(); --i >= 0;)
  780. callbacks.getUnchecked(i)->audioDeviceStopped();
  781. }
  782. void AudioDeviceManager::audioDeviceErrorInt (const String& message)
  783. {
  784. const ScopedLock sl (audioCallbackLock);
  785. for (int i = callbacks.size(); --i >= 0;)
  786. callbacks.getUnchecked(i)->audioDeviceError (message);
  787. }
  788. double AudioDeviceManager::getCpuUsage() const
  789. {
  790. return loadMeasurer.getLoadAsProportion();
  791. }
  792. //==============================================================================
  793. void AudioDeviceManager::setMidiInputDeviceEnabled (const String& identifier, bool enabled)
  794. {
  795. if (enabled != isMidiInputDeviceEnabled (identifier))
  796. {
  797. if (enabled)
  798. {
  799. if (auto midiIn = MidiInput::openDevice (identifier, callbackHandler.get()))
  800. {
  801. enabledMidiInputs.push_back (std::move (midiIn));
  802. enabledMidiInputs.back()->start();
  803. }
  804. }
  805. else
  806. {
  807. auto removePredicate = [identifier] (const std::unique_ptr<MidiInput>& in) { return in->getIdentifier() == identifier; };
  808. enabledMidiInputs.erase (std::remove_if (std::begin (enabledMidiInputs), std::end (enabledMidiInputs), removePredicate),
  809. std::end (enabledMidiInputs));
  810. }
  811. updateXml();
  812. sendChangeMessage();
  813. }
  814. }
  815. bool AudioDeviceManager::isMidiInputDeviceEnabled (const String& identifier) const
  816. {
  817. for (auto& mi : enabledMidiInputs)
  818. if (mi->getIdentifier() == identifier)
  819. return true;
  820. return false;
  821. }
  822. void AudioDeviceManager::addMidiInputDeviceCallback (const String& identifier, MidiInputCallback* callbackToAdd)
  823. {
  824. removeMidiInputDeviceCallback (identifier, callbackToAdd);
  825. if (identifier.isEmpty() || isMidiInputDeviceEnabled (identifier))
  826. {
  827. const ScopedLock sl (midiCallbackLock);
  828. midiCallbacks.add ({ identifier, callbackToAdd });
  829. }
  830. }
  831. void AudioDeviceManager::removeMidiInputDeviceCallback (const String& identifier, MidiInputCallback* callbackToRemove)
  832. {
  833. for (int i = midiCallbacks.size(); --i >= 0;)
  834. {
  835. auto& mc = midiCallbacks.getReference (i);
  836. if (mc.callback == callbackToRemove && mc.deviceIdentifier == identifier)
  837. {
  838. const ScopedLock sl (midiCallbackLock);
  839. midiCallbacks.remove (i);
  840. }
  841. }
  842. }
  843. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message)
  844. {
  845. if (! message.isActiveSense())
  846. {
  847. const ScopedLock sl (midiCallbackLock);
  848. for (auto& mc : midiCallbacks)
  849. if (mc.deviceIdentifier.isEmpty() || mc.deviceIdentifier == source->getIdentifier())
  850. mc.callback->handleIncomingMidiMessage (source, message);
  851. }
  852. }
  853. //==============================================================================
  854. void AudioDeviceManager::setDefaultMidiOutputDevice (const String& identifier)
  855. {
  856. if (defaultMidiOutputDeviceInfo.identifier != identifier)
  857. {
  858. Array<AudioIODeviceCallback*> oldCallbacks;
  859. {
  860. const ScopedLock sl (audioCallbackLock);
  861. oldCallbacks.swapWith (callbacks);
  862. }
  863. if (currentAudioDevice != nullptr)
  864. for (int i = oldCallbacks.size(); --i >= 0;)
  865. oldCallbacks.getUnchecked (i)->audioDeviceStopped();
  866. defaultMidiOutput.reset();
  867. if (identifier.isNotEmpty())
  868. defaultMidiOutput = MidiOutput::openDevice (identifier);
  869. if (defaultMidiOutput != nullptr)
  870. defaultMidiOutputDeviceInfo = defaultMidiOutput->getDeviceInfo();
  871. else
  872. defaultMidiOutputDeviceInfo = {};
  873. if (currentAudioDevice != nullptr)
  874. for (auto* c : oldCallbacks)
  875. c->audioDeviceAboutToStart (currentAudioDevice.get());
  876. {
  877. const ScopedLock sl (audioCallbackLock);
  878. oldCallbacks.swapWith (callbacks);
  879. }
  880. updateXml();
  881. sendChangeMessage();
  882. }
  883. }
  884. //==============================================================================
  885. AudioDeviceManager::LevelMeter::LevelMeter() noexcept : level() {}
  886. void AudioDeviceManager::LevelMeter::updateLevel (const float* const* channelData, int numChannels, int numSamples) noexcept
  887. {
  888. if (getReferenceCount() <= 1)
  889. return;
  890. auto localLevel = level.get();
  891. if (numChannels > 0)
  892. {
  893. for (int j = 0; j < numSamples; ++j)
  894. {
  895. float s = 0;
  896. for (int i = 0; i < numChannels; ++i)
  897. s += std::abs (channelData[i][j]);
  898. s /= (float) numChannels;
  899. const float decayFactor = 0.99992f;
  900. if (s > localLevel)
  901. localLevel = s;
  902. else if (localLevel > 0.001f)
  903. localLevel *= decayFactor;
  904. else
  905. localLevel = 0;
  906. }
  907. }
  908. else
  909. {
  910. localLevel = 0;
  911. }
  912. level = localLevel;
  913. }
  914. double AudioDeviceManager::LevelMeter::getCurrentLevel() const noexcept
  915. {
  916. jassert (getReferenceCount() > 1);
  917. return level.get();
  918. }
  919. void AudioDeviceManager::playTestSound()
  920. {
  921. { // cunningly nested to swap, unlock and delete in that order.
  922. std::unique_ptr<AudioBuffer<float>> oldSound;
  923. {
  924. const ScopedLock sl (audioCallbackLock);
  925. std::swap (oldSound, testSound);
  926. }
  927. }
  928. testSoundPosition = 0;
  929. if (currentAudioDevice != nullptr)
  930. {
  931. auto sampleRate = currentAudioDevice->getCurrentSampleRate();
  932. auto soundLength = (int) sampleRate;
  933. double frequency = 440.0;
  934. float amplitude = 0.5f;
  935. auto phasePerSample = MathConstants<double>::twoPi / (sampleRate / frequency);
  936. std::unique_ptr<AudioBuffer<float>> newSound (new AudioBuffer<float> (1, soundLength));
  937. for (int i = 0; i < soundLength; ++i)
  938. newSound->setSample (0, i, amplitude * (float) std::sin (i * phasePerSample));
  939. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  940. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  941. {
  942. const ScopedLock sl (audioCallbackLock);
  943. std::swap (testSound, newSound);
  944. }
  945. }
  946. }
  947. int AudioDeviceManager::getXRunCount() const noexcept
  948. {
  949. auto deviceXRuns = (currentAudioDevice != nullptr ? currentAudioDevice->getXRunCount() : -1);
  950. return jmax (0, deviceXRuns) + loadMeasurer.getXRunCount();
  951. }
  952. //==============================================================================
  953. // Deprecated
  954. void AudioDeviceManager::setMidiInputEnabled (const String& name, const bool enabled)
  955. {
  956. for (auto& device : MidiInput::getAvailableDevices())
  957. {
  958. if (device.name == name)
  959. {
  960. setMidiInputDeviceEnabled (device.identifier, enabled);
  961. return;
  962. }
  963. }
  964. }
  965. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  966. {
  967. for (auto& device : MidiInput::getAvailableDevices())
  968. if (device.name == name)
  969. return isMidiInputDeviceEnabled (device.identifier);
  970. return false;
  971. }
  972. void AudioDeviceManager::addMidiInputCallback (const String& name, MidiInputCallback* callbackToAdd)
  973. {
  974. if (name.isEmpty())
  975. {
  976. addMidiInputDeviceCallback ({}, callbackToAdd);
  977. }
  978. else
  979. {
  980. for (auto& device : MidiInput::getAvailableDevices())
  981. {
  982. if (device.name == name)
  983. {
  984. addMidiInputDeviceCallback (device.identifier, callbackToAdd);
  985. return;
  986. }
  987. }
  988. }
  989. }
  990. void AudioDeviceManager::removeMidiInputCallback (const String& name, MidiInputCallback* callbackToRemove)
  991. {
  992. if (name.isEmpty())
  993. {
  994. removeMidiInputDeviceCallback ({}, callbackToRemove);
  995. }
  996. else
  997. {
  998. for (auto& device : MidiInput::getAvailableDevices())
  999. {
  1000. if (device.name == name)
  1001. {
  1002. removeMidiInputDeviceCallback (device.identifier, callbackToRemove);
  1003. return;
  1004. }
  1005. }
  1006. }
  1007. }
  1008. void AudioDeviceManager::setDefaultMidiOutput (const String& name)
  1009. {
  1010. for (auto& device : MidiOutput::getAvailableDevices())
  1011. {
  1012. if (device.name == name)
  1013. {
  1014. setDefaultMidiOutputDevice (device.identifier);
  1015. return;
  1016. }
  1017. }
  1018. }
  1019. //==============================================================================
  1020. //==============================================================================
  1021. #if JUCE_UNIT_TESTS
  1022. class AudioDeviceManagerTests : public UnitTest
  1023. {
  1024. public:
  1025. AudioDeviceManagerTests() : UnitTest ("AudioDeviceManager", UnitTestCategories::audio) {}
  1026. void runTest() override
  1027. {
  1028. beginTest ("When the AudioDeviceSetup has non-empty device names, initialise uses the requested devices");
  1029. {
  1030. AudioDeviceManager manager;
  1031. initialiseManager (manager);
  1032. expectEquals (manager.getAvailableDeviceTypes().size(), 2);
  1033. AudioDeviceManager::AudioDeviceSetup setup;
  1034. setup.outputDeviceName = "z";
  1035. setup.inputDeviceName = "c";
  1036. expect (manager.initialise (2, 2, nullptr, true, String{}, &setup).isEmpty());
  1037. const auto& newSetup = manager.getAudioDeviceSetup();
  1038. expectEquals (newSetup.outputDeviceName, setup.outputDeviceName);
  1039. expectEquals (newSetup.inputDeviceName, setup.inputDeviceName);
  1040. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1041. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 2);
  1042. }
  1043. beginTest ("When the AudioDeviceSetup has empty device names, initialise picks suitable default devices");
  1044. {
  1045. AudioDeviceManager manager;
  1046. initialiseManager (manager);
  1047. AudioDeviceManager::AudioDeviceSetup setup;
  1048. expect (manager.initialise (2, 2, nullptr, true, String{}, &setup).isEmpty());
  1049. const auto& newSetup = manager.getAudioDeviceSetup();
  1050. expectEquals (newSetup.outputDeviceName, String ("x"));
  1051. expectEquals (newSetup.inputDeviceName, String ("a"));
  1052. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1053. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 2);
  1054. }
  1055. beginTest ("When the preferred device name matches an input and an output on the same type, that type is used");
  1056. {
  1057. AudioDeviceManager manager;
  1058. initialiseManagerWithDifferentDeviceNames (manager);
  1059. expect (manager.initialise (2, 2, nullptr, true, "bar *").isEmpty());
  1060. expectEquals (manager.getCurrentAudioDeviceType(), String ("bar"));
  1061. const auto& newSetup = manager.getAudioDeviceSetup();
  1062. expectEquals (newSetup.outputDeviceName, String ("bar out a"));
  1063. expectEquals (newSetup.inputDeviceName, String ("bar in a"));
  1064. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1065. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 2);
  1066. expect (manager.getCurrentAudioDevice() != nullptr);
  1067. }
  1068. beginTest ("When the preferred device name matches either an input and an output, but not both, that type is used");
  1069. {
  1070. AudioDeviceManager manager;
  1071. initialiseManagerWithDifferentDeviceNames (manager);
  1072. expect (manager.initialise (2, 2, nullptr, true, "bar out b").isEmpty());
  1073. expectEquals (manager.getCurrentAudioDeviceType(), String ("bar"));
  1074. const auto& newSetup = manager.getAudioDeviceSetup();
  1075. expectEquals (newSetup.outputDeviceName, String ("bar out b"));
  1076. expectEquals (newSetup.inputDeviceName, String ("bar in a"));
  1077. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1078. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 2);
  1079. expect (manager.getCurrentAudioDevice() != nullptr);
  1080. }
  1081. beginTest ("When the preferred device name does not match any inputs or outputs, defaults are used");
  1082. {
  1083. AudioDeviceManager manager;
  1084. initialiseManagerWithDifferentDeviceNames (manager);
  1085. expect (manager.initialise (2, 2, nullptr, true, "unmatchable").isEmpty());
  1086. expectEquals (manager.getCurrentAudioDeviceType(), String ("foo"));
  1087. const auto& newSetup = manager.getAudioDeviceSetup();
  1088. expectEquals (newSetup.outputDeviceName, String ("foo out a"));
  1089. expectEquals (newSetup.inputDeviceName, String ("foo in a"));
  1090. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1091. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 2);
  1092. expect (manager.getCurrentAudioDevice() != nullptr);
  1093. }
  1094. beginTest ("When first device type has no devices, a device type with devices is used instead");
  1095. {
  1096. AudioDeviceManager manager;
  1097. initialiseManagerWithEmptyDeviceType (manager);
  1098. AudioDeviceManager::AudioDeviceSetup setup;
  1099. expect (manager.initialise (2, 2, nullptr, true, {}, &setup).isEmpty());
  1100. const auto& newSetup = manager.getAudioDeviceSetup();
  1101. expectEquals (newSetup.outputDeviceName, String ("x"));
  1102. expectEquals (newSetup.inputDeviceName, String ("a"));
  1103. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1104. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 2);
  1105. }
  1106. beginTest ("If a device type has been explicitly set to a type with devices, "
  1107. "initialisation should respect this choice");
  1108. {
  1109. AudioDeviceManager manager;
  1110. initialiseManagerWithEmptyDeviceType (manager);
  1111. manager.setCurrentAudioDeviceType (mockBName, true);
  1112. AudioDeviceManager::AudioDeviceSetup setup;
  1113. expect (manager.initialise (2, 2, nullptr, true, {}, &setup).isEmpty());
  1114. expectEquals (manager.getCurrentAudioDeviceType(), mockBName);
  1115. }
  1116. beginTest ("If a device type has been explicitly set to a type without devices, "
  1117. "initialisation should pick a type with devices instead");
  1118. {
  1119. AudioDeviceManager manager;
  1120. initialiseManagerWithEmptyDeviceType (manager);
  1121. manager.setCurrentAudioDeviceType (emptyName, true);
  1122. AudioDeviceManager::AudioDeviceSetup setup;
  1123. expect (manager.initialise (2, 2, nullptr, true, {}, &setup).isEmpty());
  1124. expectEquals (manager.getCurrentAudioDeviceType(), mockAName);
  1125. }
  1126. beginTest ("Carry out a long sequence of configuration changes");
  1127. {
  1128. AudioDeviceManager manager;
  1129. initialiseManagerWithEmptyDeviceType (manager);
  1130. initialiseWithDefaultDevices (manager);
  1131. disableInputChannelsButLeaveDeviceOpen (manager);
  1132. selectANewInputDevice (manager);
  1133. disableInputDevice (manager);
  1134. reenableInputDeviceWithNoChannels (manager);
  1135. enableInputChannels (manager);
  1136. disableInputChannelsButLeaveDeviceOpen (manager);
  1137. switchDeviceType (manager);
  1138. enableInputChannels (manager);
  1139. closeDeviceByRequestingEmptyNames (manager);
  1140. }
  1141. }
  1142. private:
  1143. void initialiseWithDefaultDevices (AudioDeviceManager& manager)
  1144. {
  1145. manager.initialiseWithDefaultDevices (2, 2);
  1146. const auto& setup = manager.getAudioDeviceSetup();
  1147. expectEquals (setup.inputChannels.countNumberOfSetBits(), 2);
  1148. expectEquals (setup.outputChannels.countNumberOfSetBits(), 2);
  1149. expect (setup.useDefaultInputChannels);
  1150. expect (setup.useDefaultOutputChannels);
  1151. expect (manager.getCurrentAudioDevice() != nullptr);
  1152. }
  1153. void disableInputChannelsButLeaveDeviceOpen (AudioDeviceManager& manager)
  1154. {
  1155. auto setup = manager.getAudioDeviceSetup();
  1156. setup.inputChannels.clear();
  1157. setup.useDefaultInputChannels = false;
  1158. expect (manager.setAudioDeviceSetup (setup, true).isEmpty());
  1159. const auto newSetup = manager.getAudioDeviceSetup();
  1160. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 0);
  1161. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1162. expect (! newSetup.useDefaultInputChannels);
  1163. expect (newSetup.useDefaultOutputChannels);
  1164. expectEquals (newSetup.inputDeviceName, setup.inputDeviceName);
  1165. expectEquals (newSetup.outputDeviceName, setup.outputDeviceName);
  1166. expect (manager.getCurrentAudioDevice() != nullptr);
  1167. }
  1168. void selectANewInputDevice (AudioDeviceManager& manager)
  1169. {
  1170. auto setup = manager.getAudioDeviceSetup();
  1171. setup.inputDeviceName = "b";
  1172. expect (manager.setAudioDeviceSetup (setup, true).isEmpty());
  1173. const auto newSetup = manager.getAudioDeviceSetup();
  1174. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 0);
  1175. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1176. expect (! newSetup.useDefaultInputChannels);
  1177. expect (newSetup.useDefaultOutputChannels);
  1178. expectEquals (newSetup.inputDeviceName, setup.inputDeviceName);
  1179. expectEquals (newSetup.outputDeviceName, setup.outputDeviceName);
  1180. expect (manager.getCurrentAudioDevice() != nullptr);
  1181. }
  1182. void disableInputDevice (AudioDeviceManager& manager)
  1183. {
  1184. auto setup = manager.getAudioDeviceSetup();
  1185. setup.inputDeviceName = "";
  1186. expect (manager.setAudioDeviceSetup (setup, true).isEmpty());
  1187. const auto newSetup = manager.getAudioDeviceSetup();
  1188. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 0);
  1189. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1190. expect (! newSetup.useDefaultInputChannels);
  1191. expect (newSetup.useDefaultOutputChannels);
  1192. expectEquals (newSetup.inputDeviceName, setup.inputDeviceName);
  1193. expectEquals (newSetup.outputDeviceName, setup.outputDeviceName);
  1194. expect (manager.getCurrentAudioDevice() != nullptr);
  1195. }
  1196. void reenableInputDeviceWithNoChannels (AudioDeviceManager& manager)
  1197. {
  1198. auto setup = manager.getAudioDeviceSetup();
  1199. setup.inputDeviceName = "a";
  1200. expect (manager.setAudioDeviceSetup (setup, true).isEmpty());
  1201. const auto newSetup = manager.getAudioDeviceSetup();
  1202. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 0);
  1203. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1204. expect (! newSetup.useDefaultInputChannels);
  1205. expect (newSetup.useDefaultOutputChannels);
  1206. expectEquals (newSetup.inputDeviceName, setup.inputDeviceName);
  1207. expectEquals (newSetup.outputDeviceName, setup.outputDeviceName);
  1208. expect (manager.getCurrentAudioDevice() != nullptr);
  1209. }
  1210. void enableInputChannels (AudioDeviceManager& manager)
  1211. {
  1212. auto setup = manager.getAudioDeviceSetup();
  1213. setup.inputDeviceName = manager.getCurrentDeviceTypeObject()->getDeviceNames (true)[0];
  1214. setup.inputChannels = 3;
  1215. setup.useDefaultInputChannels = false;
  1216. expect (manager.setAudioDeviceSetup (setup, true).isEmpty());
  1217. const auto newSetup = manager.getAudioDeviceSetup();
  1218. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 2);
  1219. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1220. expect (! newSetup.useDefaultInputChannels);
  1221. expect (newSetup.useDefaultOutputChannels);
  1222. expectEquals (newSetup.inputDeviceName, setup.inputDeviceName);
  1223. expectEquals (newSetup.outputDeviceName, setup.outputDeviceName);
  1224. expect (manager.getCurrentAudioDevice() != nullptr);
  1225. }
  1226. void switchDeviceType (AudioDeviceManager& manager)
  1227. {
  1228. const auto oldSetup = manager.getAudioDeviceSetup();
  1229. expectEquals (manager.getCurrentAudioDeviceType(), String (mockAName));
  1230. manager.setCurrentAudioDeviceType (mockBName, true);
  1231. expectEquals (manager.getCurrentAudioDeviceType(), String (mockBName));
  1232. const auto newSetup = manager.getAudioDeviceSetup();
  1233. expect (newSetup.outputDeviceName.isNotEmpty());
  1234. // We had no channels enabled, which means we don't need to open a new input device
  1235. expect (newSetup.inputDeviceName.isEmpty());
  1236. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 0);
  1237. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1238. expect (manager.getCurrentAudioDevice() != nullptr);
  1239. }
  1240. void closeDeviceByRequestingEmptyNames (AudioDeviceManager& manager)
  1241. {
  1242. auto setup = manager.getAudioDeviceSetup();
  1243. setup.inputDeviceName = "";
  1244. setup.outputDeviceName = "";
  1245. expect (manager.setAudioDeviceSetup (setup, true).isEmpty());
  1246. const auto newSetup = manager.getAudioDeviceSetup();
  1247. expectEquals (newSetup.inputChannels.countNumberOfSetBits(), 2);
  1248. expectEquals (newSetup.outputChannels.countNumberOfSetBits(), 2);
  1249. expect (newSetup.inputDeviceName.isEmpty());
  1250. expect (newSetup.outputDeviceName.isEmpty());
  1251. expect (manager.getCurrentAudioDevice() == nullptr);
  1252. }
  1253. const String mockAName = "mockA";
  1254. const String mockBName = "mockB";
  1255. const String emptyName = "empty";
  1256. class MockDevice : public AudioIODevice
  1257. {
  1258. public:
  1259. MockDevice (String typeNameIn, String outNameIn, String inNameIn)
  1260. : AudioIODevice ("mock", typeNameIn), outName (outNameIn), inName (inNameIn) {}
  1261. StringArray getOutputChannelNames() override { return { "o1", "o2", "o3" }; }
  1262. StringArray getInputChannelNames() override { return { "i1", "i2", "i3" }; }
  1263. Array<double> getAvailableSampleRates() override { return { 44100.0, 48000.0 }; }
  1264. Array<int> getAvailableBufferSizes() override { return { 128, 256 }; }
  1265. int getDefaultBufferSize() override { return 128; }
  1266. String open (const BigInteger& inputs, const BigInteger& outputs, double sr, int bs) override
  1267. {
  1268. inChannels = inputs;
  1269. outChannels = outputs;
  1270. sampleRate = sr;
  1271. blockSize = bs;
  1272. on = true;
  1273. return {};
  1274. }
  1275. void close() override { on = false; }
  1276. bool isOpen() override { return on; }
  1277. void start (AudioIODeviceCallback*) override { playing = true; }
  1278. void stop() override { playing = false; }
  1279. bool isPlaying() override { return playing; }
  1280. String getLastError() override { return {}; }
  1281. int getCurrentBufferSizeSamples() override { return blockSize; }
  1282. double getCurrentSampleRate() override { return sampleRate; }
  1283. int getCurrentBitDepth() override { return 16; }
  1284. BigInteger getActiveOutputChannels() const override { return outChannels; }
  1285. BigInteger getActiveInputChannels() const override { return inChannels; }
  1286. int getOutputLatencyInSamples() override { return 0; }
  1287. int getInputLatencyInSamples() override { return 0; }
  1288. private:
  1289. String outName, inName;
  1290. BigInteger outChannels, inChannels;
  1291. double sampleRate = 0.0;
  1292. int blockSize = 0;
  1293. bool on = false, playing = false;
  1294. };
  1295. class MockDeviceType : public AudioIODeviceType
  1296. {
  1297. public:
  1298. explicit MockDeviceType (String kind)
  1299. : MockDeviceType (std::move (kind), { "a", "b", "c" }, { "x", "y", "z" }) {}
  1300. MockDeviceType (String kind, StringArray inputNames, StringArray outputNames)
  1301. : AudioIODeviceType (std::move (kind)),
  1302. inNames (std::move (inputNames)),
  1303. outNames (std::move (outputNames)) {}
  1304. void scanForDevices() override {}
  1305. StringArray getDeviceNames (bool isInput) const override
  1306. {
  1307. return getNames (isInput);
  1308. }
  1309. int getDefaultDeviceIndex (bool) const override { return 0; }
  1310. int getIndexOfDevice (AudioIODevice* device, bool isInput) const override
  1311. {
  1312. return getNames (isInput).indexOf (device->getName());
  1313. }
  1314. bool hasSeparateInputsAndOutputs() const override { return true; }
  1315. AudioIODevice* createDevice (const String& outputName, const String& inputName) override
  1316. {
  1317. if (inNames.contains (inputName) || outNames.contains (outputName))
  1318. return new MockDevice (getTypeName(), outputName, inputName);
  1319. return nullptr;
  1320. }
  1321. private:
  1322. const StringArray& getNames (bool isInput) const { return isInput ? inNames : outNames; }
  1323. const StringArray inNames, outNames;
  1324. };
  1325. void initialiseManager (AudioDeviceManager& manager)
  1326. {
  1327. manager.addAudioDeviceType (std::make_unique<MockDeviceType> (mockAName));
  1328. manager.addAudioDeviceType (std::make_unique<MockDeviceType> (mockBName));
  1329. }
  1330. void initialiseManagerWithEmptyDeviceType (AudioDeviceManager& manager)
  1331. {
  1332. manager.addAudioDeviceType (std::make_unique<MockDeviceType> (emptyName, StringArray{}, StringArray{}));
  1333. initialiseManager (manager);
  1334. }
  1335. void initialiseManagerWithDifferentDeviceNames (AudioDeviceManager& manager)
  1336. {
  1337. manager.addAudioDeviceType (std::make_unique<MockDeviceType> ("foo",
  1338. StringArray { "foo in a", "foo in b" },
  1339. StringArray { "foo out a", "foo out b" }));
  1340. manager.addAudioDeviceType (std::make_unique<MockDeviceType> ("bar",
  1341. StringArray { "bar in a", "bar in b" },
  1342. StringArray { "bar out a", "bar out b" }));
  1343. }
  1344. };
  1345. static AudioDeviceManagerTests audioDeviceManagerTests;
  1346. #endif
  1347. } // namespace juce