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.

1021 lines
34KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20. {
  21. return outputDeviceName == other.outputDeviceName
  22. && inputDeviceName == other.inputDeviceName
  23. && sampleRate == other.sampleRate
  24. && bufferSize == other.bufferSize
  25. && inputChannels == other.inputChannels
  26. && useDefaultInputChannels == other.useDefaultInputChannels
  27. && outputChannels == other.outputChannels
  28. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  29. }
  30. bool AudioDeviceManager::AudioDeviceSetup::operator!= (const AudioDeviceManager::AudioDeviceSetup& other) const
  31. {
  32. return ! operator== (other);
  33. }
  34. //==============================================================================
  35. class AudioDeviceManager::CallbackHandler : public AudioIODeviceCallback,
  36. public MidiInputCallback,
  37. public AudioIODeviceType::Listener
  38. {
  39. public:
  40. CallbackHandler (AudioDeviceManager& adm) noexcept : owner (adm) {}
  41. private:
  42. void audioDeviceIOCallback (const float** ins, int numIns, float** outs, int numOuts, int numSamples) override
  43. {
  44. owner.audioDeviceIOCallbackInt (ins, numIns, outs, numOuts, numSamples);
  45. }
  46. void audioDeviceAboutToStart (AudioIODevice* device) override
  47. {
  48. owner.audioDeviceAboutToStartInt (device);
  49. }
  50. void audioDeviceStopped() override
  51. {
  52. owner.audioDeviceStoppedInt();
  53. }
  54. void audioDeviceError (const String& message) override
  55. {
  56. owner.audioDeviceErrorInt (message);
  57. }
  58. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message) override
  59. {
  60. owner.handleIncomingMidiMessageInt (source, message);
  61. }
  62. void audioDeviceListChanged() override
  63. {
  64. owner.audioDeviceListChanged();
  65. }
  66. AudioDeviceManager& owner;
  67. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CallbackHandler)
  68. };
  69. //==============================================================================
  70. AudioDeviceManager::AudioDeviceManager()
  71. {
  72. callbackHandler.reset (new CallbackHandler (*this));
  73. }
  74. AudioDeviceManager::~AudioDeviceManager()
  75. {
  76. currentAudioDevice.reset();
  77. defaultMidiOutput.reset();
  78. }
  79. //==============================================================================
  80. void AudioDeviceManager::createDeviceTypesIfNeeded()
  81. {
  82. if (availableDeviceTypes.size() == 0)
  83. {
  84. OwnedArray<AudioIODeviceType> types;
  85. createAudioDeviceTypes (types);
  86. for (auto* t : types)
  87. addAudioDeviceType (t);
  88. types.clear (false);
  89. if (auto* first = availableDeviceTypes.getFirst())
  90. currentDeviceType = first->getTypeName();
  91. }
  92. }
  93. const OwnedArray<AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  94. {
  95. scanDevicesIfNeeded();
  96. return availableDeviceTypes;
  97. }
  98. void AudioDeviceManager::audioDeviceListChanged()
  99. {
  100. if (currentAudioDevice != nullptr)
  101. {
  102. auto isCurrentDeviceStillAvailable = [&]
  103. {
  104. for (auto* dt : availableDeviceTypes)
  105. if (currentAudioDevice->getTypeName() == dt->getTypeName())
  106. for (auto& dn : dt->getDeviceNames())
  107. if (currentAudioDevice->getName() == dn)
  108. return true;
  109. return false;
  110. };
  111. if (! isCurrentDeviceStillAvailable())
  112. {
  113. closeAudioDevice();
  114. std::unique_ptr<XmlElement> e (createStateXml());
  115. if (e == nullptr)
  116. initialiseDefault (preferredDeviceName, &currentSetup);
  117. else
  118. initialiseFromXML (*e, true, preferredDeviceName, &currentSetup);
  119. }
  120. if (currentAudioDevice != nullptr)
  121. {
  122. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  123. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  124. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  125. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  126. }
  127. }
  128. sendChangeMessage();
  129. }
  130. //==============================================================================
  131. static void addIfNotNull (OwnedArray<AudioIODeviceType>& list, AudioIODeviceType* const device)
  132. {
  133. if (device != nullptr)
  134. list.add (device);
  135. }
  136. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray<AudioIODeviceType>& list)
  137. {
  138. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_WASAPI (false));
  139. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_WASAPI (true));
  140. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_DirectSound());
  141. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_ASIO());
  142. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_CoreAudio());
  143. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_iOSAudio());
  144. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_ALSA());
  145. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_JACK());
  146. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_Bela());
  147. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_Oboe());
  148. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_OpenSLES());
  149. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_Android());
  150. }
  151. void AudioDeviceManager::addAudioDeviceType (AudioIODeviceType* newDeviceType)
  152. {
  153. if (newDeviceType != nullptr)
  154. {
  155. jassert (lastDeviceTypeConfigs.size() == availableDeviceTypes.size());
  156. availableDeviceTypes.add (newDeviceType);
  157. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  158. newDeviceType->addListener (callbackHandler.get());
  159. }
  160. }
  161. static bool deviceListContains (AudioIODeviceType* type, bool isInput, const String& name)
  162. {
  163. for (auto& deviceName : type->getDeviceNames (isInput))
  164. if (deviceName.trim().equalsIgnoreCase (name.trim()))
  165. return true;
  166. return false;
  167. }
  168. //==============================================================================
  169. String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  170. const int numOutputChannelsNeeded,
  171. const XmlElement* const xml,
  172. const bool selectDefaultDeviceOnFailure,
  173. const String& preferredDefaultDeviceName,
  174. const AudioDeviceSetup* preferredSetupOptions)
  175. {
  176. scanDevicesIfNeeded();
  177. numInputChansNeeded = numInputChannelsNeeded;
  178. numOutputChansNeeded = numOutputChannelsNeeded;
  179. preferredDeviceName = preferredDefaultDeviceName;
  180. if (xml != nullptr && xml->hasTagName ("DEVICESETUP"))
  181. return initialiseFromXML (*xml, selectDefaultDeviceOnFailure,
  182. preferredDeviceName, preferredSetupOptions);
  183. return initialiseDefault (preferredDeviceName, preferredSetupOptions);
  184. }
  185. String AudioDeviceManager::initialiseDefault (const String& preferredDefaultDeviceName,
  186. const AudioDeviceSetup* preferredSetupOptions)
  187. {
  188. AudioDeviceSetup setup;
  189. if (preferredSetupOptions != nullptr)
  190. {
  191. setup = *preferredSetupOptions;
  192. }
  193. else if (preferredDefaultDeviceName.isNotEmpty())
  194. {
  195. for (auto* type : availableDeviceTypes)
  196. {
  197. for (auto& out : type->getDeviceNames (false))
  198. {
  199. if (out.matchesWildcard (preferredDefaultDeviceName, true))
  200. {
  201. setup.outputDeviceName = out;
  202. break;
  203. }
  204. }
  205. for (auto& in : type->getDeviceNames (true))
  206. {
  207. if (in.matchesWildcard (preferredDefaultDeviceName, true))
  208. {
  209. setup.inputDeviceName = in;
  210. break;
  211. }
  212. }
  213. }
  214. }
  215. insertDefaultDeviceNames (setup);
  216. return setAudioDeviceSetup (setup, false);
  217. }
  218. String AudioDeviceManager::initialiseFromXML (const XmlElement& xml,
  219. bool selectDefaultDeviceOnFailure,
  220. const String& preferredDefaultDeviceName,
  221. const AudioDeviceSetup* preferredSetupOptions)
  222. {
  223. lastExplicitSettings.reset (new XmlElement (xml));
  224. String error;
  225. AudioDeviceSetup setup;
  226. if (preferredSetupOptions != nullptr)
  227. setup = *preferredSetupOptions;
  228. if (xml.getStringAttribute ("audioDeviceName").isNotEmpty())
  229. {
  230. setup.inputDeviceName = setup.outputDeviceName
  231. = xml.getStringAttribute ("audioDeviceName");
  232. }
  233. else
  234. {
  235. setup.inputDeviceName = xml.getStringAttribute ("audioInputDeviceName");
  236. setup.outputDeviceName = xml.getStringAttribute ("audioOutputDeviceName");
  237. }
  238. currentDeviceType = xml.getStringAttribute ("deviceType");
  239. if (findType (currentDeviceType) == nullptr)
  240. {
  241. if (auto* type = findType (setup.inputDeviceName, setup.outputDeviceName))
  242. currentDeviceType = type->getTypeName();
  243. else if (auto* firstType = availableDeviceTypes.getFirst())
  244. currentDeviceType = firstType->getTypeName();
  245. }
  246. setup.bufferSize = xml.getIntAttribute ("audioDeviceBufferSize", setup.bufferSize);
  247. setup.sampleRate = xml.getDoubleAttribute ("audioDeviceRate", setup.sampleRate);
  248. setup.inputChannels .parseString (xml.getStringAttribute ("audioDeviceInChans", "11"), 2);
  249. setup.outputChannels.parseString (xml.getStringAttribute ("audioDeviceOutChans", "11"), 2);
  250. setup.useDefaultInputChannels = ! xml.hasAttribute ("audioDeviceInChans");
  251. setup.useDefaultOutputChannels = ! xml.hasAttribute ("audioDeviceOutChans");
  252. error = setAudioDeviceSetup (setup, true);
  253. midiInsFromXml.clear();
  254. forEachXmlChildElementWithTagName (xml, c, "MIDIINPUT")
  255. midiInsFromXml.add (c->getStringAttribute ("name"));
  256. for (auto& m : MidiInput::getDevices())
  257. setMidiInputEnabled (m, midiInsFromXml.contains (m));
  258. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  259. error = initialise (numInputChansNeeded, numOutputChansNeeded,
  260. nullptr, false, preferredDefaultDeviceName);
  261. setDefaultMidiOutput (xml.getStringAttribute ("defaultMidiOutput"));
  262. return error;
  263. }
  264. String AudioDeviceManager::initialiseWithDefaultDevices (int numInputChannelsNeeded,
  265. int numOutputChannelsNeeded)
  266. {
  267. lastExplicitSettings.reset();
  268. return initialise (numInputChannelsNeeded, numOutputChannelsNeeded,
  269. nullptr, false, {}, nullptr);
  270. }
  271. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  272. {
  273. if (auto* type = getCurrentDeviceTypeObject())
  274. {
  275. if (numOutputChansNeeded > 0 && setup.outputDeviceName.isEmpty())
  276. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  277. if (numInputChansNeeded > 0 && setup.inputDeviceName.isEmpty())
  278. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  279. }
  280. }
  281. XmlElement* AudioDeviceManager::createStateXml() const
  282. {
  283. return createCopyIfNotNull (lastExplicitSettings.get());
  284. }
  285. //==============================================================================
  286. void AudioDeviceManager::scanDevicesIfNeeded()
  287. {
  288. if (listNeedsScanning)
  289. {
  290. listNeedsScanning = false;
  291. createDeviceTypesIfNeeded();
  292. for (auto* type : availableDeviceTypes)
  293. type->scanForDevices();
  294. }
  295. }
  296. AudioIODeviceType* AudioDeviceManager::findType (const String& typeName)
  297. {
  298. scanDevicesIfNeeded();
  299. for (auto* type : availableDeviceTypes)
  300. if (type->getTypeName() == typeName)
  301. return type;
  302. return {};
  303. }
  304. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  305. {
  306. scanDevicesIfNeeded();
  307. for (auto* type : availableDeviceTypes)
  308. if ((inputName.isNotEmpty() && deviceListContains (type, true, inputName))
  309. || (outputName.isNotEmpty() && deviceListContains (type, false, outputName)))
  310. return type;
  311. return {};
  312. }
  313. AudioDeviceManager::AudioDeviceSetup AudioDeviceManager::getAudioDeviceSetup() const
  314. {
  315. return currentSetup;
  316. }
  317. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup) const
  318. {
  319. setup = currentSetup;
  320. }
  321. void AudioDeviceManager::deleteCurrentDevice()
  322. {
  323. currentAudioDevice.reset();
  324. currentSetup.inputDeviceName.clear();
  325. currentSetup.outputDeviceName.clear();
  326. }
  327. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type, bool treatAsChosenDevice)
  328. {
  329. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  330. {
  331. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  332. && currentDeviceType != type)
  333. {
  334. if (currentAudioDevice != nullptr)
  335. {
  336. closeAudioDevice();
  337. Thread::sleep (1500); // allow a moment for OS devices to sort themselves out, to help
  338. // avoid things like DirectSound/ASIO clashes
  339. }
  340. currentDeviceType = type;
  341. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  342. insertDefaultDeviceNames (s);
  343. setAudioDeviceSetup (s, treatAsChosenDevice);
  344. sendChangeMessage();
  345. break;
  346. }
  347. }
  348. }
  349. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  350. {
  351. for (auto* type : availableDeviceTypes)
  352. if (type->getTypeName() == currentDeviceType)
  353. return type;
  354. return availableDeviceTypes.getFirst();
  355. }
  356. static void updateSetupChannels (AudioDeviceManager::AudioDeviceSetup& setup, int defaultNumIns, int defaultNumOuts)
  357. {
  358. auto updateChannels = [](const String& deviceName, BigInteger& channels, int defaultNumChannels)
  359. {
  360. if (deviceName.isEmpty())
  361. {
  362. channels.clear();
  363. }
  364. else if (defaultNumChannels != -1)
  365. {
  366. channels.clear();
  367. channels.setRange (0, defaultNumChannels, true);
  368. }
  369. };
  370. updateChannels (setup.inputDeviceName, setup.inputChannels, setup.useDefaultInputChannels ? defaultNumIns : -1);
  371. updateChannels (setup.outputDeviceName, setup.outputChannels, setup.useDefaultOutputChannels ? defaultNumOuts : -1);
  372. }
  373. String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  374. bool treatAsChosenDevice)
  375. {
  376. jassert (&newSetup != &currentSetup); // this will have no effect
  377. if (newSetup == currentSetup && currentAudioDevice != nullptr)
  378. return {};
  379. if (getCurrentDeviceTypeObject() == nullptr)
  380. {
  381. deleteCurrentDevice();
  382. if (treatAsChosenDevice)
  383. updateXml();
  384. return {};
  385. }
  386. stopDevice();
  387. if (newSetup != currentSetup)
  388. sendChangeMessage();
  389. String error;
  390. if (currentSetup.inputDeviceName != newSetup.inputDeviceName
  391. || currentSetup.outputDeviceName != newSetup.outputDeviceName
  392. || currentAudioDevice == nullptr)
  393. {
  394. deleteCurrentDevice();
  395. scanDevicesIfNeeded();
  396. auto* type = getCurrentDeviceTypeObject();
  397. if (newSetup.outputDeviceName.isNotEmpty() && ! deviceListContains (type, false, newSetup.outputDeviceName))
  398. return "No such device: " + newSetup.outputDeviceName;
  399. if (newSetup.inputDeviceName.isNotEmpty() && ! deviceListContains (type, true, newSetup.inputDeviceName))
  400. return "No such device: " + newSetup.inputDeviceName;
  401. currentAudioDevice.reset (type->createDevice (newSetup.outputDeviceName, newSetup.inputDeviceName));
  402. if (currentAudioDevice == nullptr)
  403. error = "Can't open the audio device!\n\n"
  404. "This may be because another application is currently using the same device - "
  405. "if so, you should close any other applications and try again!";
  406. else
  407. error = currentAudioDevice->getLastError();
  408. if (error.isNotEmpty())
  409. {
  410. deleteCurrentDevice();
  411. return error;
  412. }
  413. }
  414. currentSetup = newSetup;
  415. if (! currentSetup.useDefaultInputChannels) numInputChansNeeded = currentSetup.inputChannels.countNumberOfSetBits();
  416. if (! currentSetup.useDefaultOutputChannels) numOutputChansNeeded = currentSetup.outputChannels.countNumberOfSetBits();
  417. updateSetupChannels (currentSetup, numInputChansNeeded, numOutputChansNeeded);
  418. if (currentSetup.inputChannels.isZero() && currentSetup.outputChannels.isZero())
  419. {
  420. if (treatAsChosenDevice)
  421. updateXml();
  422. return {};
  423. }
  424. currentSetup.sampleRate = chooseBestSampleRate (currentSetup.sampleRate);
  425. currentSetup.bufferSize = chooseBestBufferSize (currentSetup.bufferSize);
  426. error = currentAudioDevice->open (currentSetup.inputChannels,
  427. currentSetup.outputChannels,
  428. currentSetup.sampleRate,
  429. currentSetup.bufferSize);
  430. if (error.isEmpty())
  431. {
  432. currentDeviceType = currentAudioDevice->getTypeName();
  433. currentAudioDevice->start (callbackHandler.get());
  434. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  435. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  436. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  437. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  438. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  439. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  440. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  441. if (treatAsChosenDevice)
  442. updateXml();
  443. }
  444. else
  445. {
  446. deleteCurrentDevice();
  447. }
  448. return error;
  449. }
  450. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  451. {
  452. jassert (currentAudioDevice != nullptr);
  453. auto rates = currentAudioDevice->getAvailableSampleRates();
  454. if (rate > 0 && rates.contains (rate))
  455. return rate;
  456. rate = currentAudioDevice->getCurrentSampleRate();
  457. if (rate > 0 && rates.contains (rate))
  458. return rate;
  459. double lowestAbove44 = 0.0;
  460. for (int i = rates.size(); --i >= 0;)
  461. {
  462. auto sr = rates[i];
  463. if (sr >= 44100.0 && (lowestAbove44 < 1.0 || sr < lowestAbove44))
  464. lowestAbove44 = sr;
  465. }
  466. if (lowestAbove44 > 0.0)
  467. return lowestAbove44;
  468. return rates[0];
  469. }
  470. int AudioDeviceManager::chooseBestBufferSize (int bufferSize) const
  471. {
  472. jassert (currentAudioDevice != nullptr);
  473. if (bufferSize > 0 && currentAudioDevice->getAvailableBufferSizes().contains (bufferSize))
  474. return bufferSize;
  475. return currentAudioDevice->getDefaultBufferSize();
  476. }
  477. void AudioDeviceManager::stopDevice()
  478. {
  479. if (currentAudioDevice != nullptr)
  480. currentAudioDevice->stop();
  481. testSound.reset();
  482. }
  483. void AudioDeviceManager::closeAudioDevice()
  484. {
  485. stopDevice();
  486. currentAudioDevice.reset();
  487. loadMeasurer.reset();
  488. }
  489. void AudioDeviceManager::restartLastAudioDevice()
  490. {
  491. if (currentAudioDevice == nullptr)
  492. {
  493. if (currentSetup.inputDeviceName.isEmpty()
  494. && currentSetup.outputDeviceName.isEmpty())
  495. {
  496. // This method will only reload the last device that was running
  497. // before closeAudioDevice() was called - you need to actually open
  498. // one first, with setAudioDevice().
  499. jassertfalse;
  500. return;
  501. }
  502. AudioDeviceSetup s (currentSetup);
  503. setAudioDeviceSetup (s, false);
  504. }
  505. }
  506. void AudioDeviceManager::updateXml()
  507. {
  508. lastExplicitSettings.reset (new XmlElement ("DEVICESETUP"));
  509. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  510. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  511. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  512. if (currentAudioDevice != nullptr)
  513. {
  514. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  515. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  516. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  517. if (! currentSetup.useDefaultInputChannels)
  518. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  519. if (! currentSetup.useDefaultOutputChannels)
  520. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  521. }
  522. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  523. lastExplicitSettings->createNewChildElement ("MIDIINPUT")
  524. ->setAttribute ("name", enabledMidiInputs[i]->getName());
  525. if (midiInsFromXml.size() > 0)
  526. {
  527. // Add any midi devices that have been enabled before, but which aren't currently
  528. // open because the device has been disconnected.
  529. const StringArray availableMidiDevices (MidiInput::getDevices());
  530. for (int i = 0; i < midiInsFromXml.size(); ++i)
  531. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  532. lastExplicitSettings->createNewChildElement ("MIDIINPUT")
  533. ->setAttribute ("name", midiInsFromXml[i]);
  534. }
  535. if (defaultMidiOutputName.isNotEmpty())
  536. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  537. }
  538. //==============================================================================
  539. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  540. {
  541. {
  542. const ScopedLock sl (audioCallbackLock);
  543. if (callbacks.contains (newCallback))
  544. return;
  545. }
  546. if (currentAudioDevice != nullptr && newCallback != nullptr)
  547. newCallback->audioDeviceAboutToStart (currentAudioDevice.get());
  548. const ScopedLock sl (audioCallbackLock);
  549. callbacks.add (newCallback);
  550. }
  551. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callbackToRemove)
  552. {
  553. if (callbackToRemove != nullptr)
  554. {
  555. bool needsDeinitialising = currentAudioDevice != nullptr;
  556. {
  557. const ScopedLock sl (audioCallbackLock);
  558. needsDeinitialising = needsDeinitialising && callbacks.contains (callbackToRemove);
  559. callbacks.removeFirstMatchingValue (callbackToRemove);
  560. }
  561. if (needsDeinitialising)
  562. callbackToRemove->audioDeviceStopped();
  563. }
  564. }
  565. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  566. int numInputChannels,
  567. float** outputChannelData,
  568. int numOutputChannels,
  569. int numSamples)
  570. {
  571. const ScopedLock sl (audioCallbackLock);
  572. inputLevelGetter->updateLevel (inputChannelData, numInputChannels, numSamples);
  573. outputLevelGetter->updateLevel (const_cast<const float**> (outputChannelData), numOutputChannels, numSamples);
  574. if (callbacks.size() > 0)
  575. {
  576. AudioProcessLoadMeasurer::ScopedTimer timer (loadMeasurer);
  577. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  578. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  579. outputChannelData, numOutputChannels, numSamples);
  580. auto** tempChans = tempBuffer.getArrayOfWritePointers();
  581. for (int i = callbacks.size(); --i > 0;)
  582. {
  583. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  584. tempChans, numOutputChannels, numSamples);
  585. for (int chan = 0; chan < numOutputChannels; ++chan)
  586. {
  587. if (auto* src = tempChans [chan])
  588. if (auto* dst = outputChannelData [chan])
  589. for (int j = 0; j < numSamples; ++j)
  590. dst[j] += src[j];
  591. }
  592. }
  593. }
  594. else
  595. {
  596. for (int i = 0; i < numOutputChannels; ++i)
  597. zeromem (outputChannelData[i], sizeof (float) * (size_t) numSamples);
  598. }
  599. if (testSound != nullptr)
  600. {
  601. auto numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  602. auto* src = testSound->getReadPointer (0, testSoundPosition);
  603. for (int i = 0; i < numOutputChannels; ++i)
  604. for (int j = 0; j < numSamps; ++j)
  605. outputChannelData [i][j] += src[j];
  606. testSoundPosition += numSamps;
  607. if (testSoundPosition >= testSound->getNumSamples())
  608. testSound.reset();
  609. }
  610. }
  611. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  612. {
  613. loadMeasurer.reset (device->getCurrentSampleRate(),
  614. device->getCurrentBufferSizeSamples());
  615. {
  616. const ScopedLock sl (audioCallbackLock);
  617. for (int i = callbacks.size(); --i >= 0;)
  618. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  619. }
  620. sendChangeMessage();
  621. }
  622. void AudioDeviceManager::audioDeviceStoppedInt()
  623. {
  624. sendChangeMessage();
  625. const ScopedLock sl (audioCallbackLock);
  626. loadMeasurer.reset();
  627. for (int i = callbacks.size(); --i >= 0;)
  628. callbacks.getUnchecked(i)->audioDeviceStopped();
  629. }
  630. void AudioDeviceManager::audioDeviceErrorInt (const String& message)
  631. {
  632. const ScopedLock sl (audioCallbackLock);
  633. for (int i = callbacks.size(); --i >= 0;)
  634. callbacks.getUnchecked(i)->audioDeviceError (message);
  635. }
  636. double AudioDeviceManager::getCpuUsage() const
  637. {
  638. return loadMeasurer.getLoadAsProportion();
  639. }
  640. //==============================================================================
  641. void AudioDeviceManager::setMidiInputEnabled (const String& name, const bool enabled)
  642. {
  643. if (enabled != isMidiInputEnabled (name))
  644. {
  645. if (enabled)
  646. {
  647. auto index = MidiInput::getDevices().indexOf (name);
  648. if (index >= 0)
  649. {
  650. if (auto* midiIn = MidiInput::openDevice (index, callbackHandler.get()))
  651. {
  652. enabledMidiInputs.add (midiIn);
  653. midiIn->start();
  654. }
  655. }
  656. }
  657. else
  658. {
  659. for (int i = enabledMidiInputs.size(); --i >= 0;)
  660. if (enabledMidiInputs[i]->getName() == name)
  661. enabledMidiInputs.remove (i);
  662. }
  663. updateXml();
  664. sendChangeMessage();
  665. }
  666. }
  667. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  668. {
  669. for (auto* mi : enabledMidiInputs)
  670. if (mi->getName() == name)
  671. return true;
  672. return false;
  673. }
  674. void AudioDeviceManager::addMidiInputCallback (const String& name, MidiInputCallback* callbackToAdd)
  675. {
  676. removeMidiInputCallback (name, callbackToAdd);
  677. if (name.isEmpty() || isMidiInputEnabled (name))
  678. {
  679. const ScopedLock sl (midiCallbackLock);
  680. MidiCallbackInfo mc;
  681. mc.deviceName = name;
  682. mc.callback = callbackToAdd;
  683. midiCallbacks.add (mc);
  684. }
  685. }
  686. void AudioDeviceManager::removeMidiInputCallback (const String& name, MidiInputCallback* callbackToRemove)
  687. {
  688. for (int i = midiCallbacks.size(); --i >= 0;)
  689. {
  690. auto& mc = midiCallbacks.getReference(i);
  691. if (mc.callback == callbackToRemove && mc.deviceName == name)
  692. {
  693. const ScopedLock sl (midiCallbackLock);
  694. midiCallbacks.remove (i);
  695. }
  696. }
  697. }
  698. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message)
  699. {
  700. if (! message.isActiveSense())
  701. {
  702. const ScopedLock sl (midiCallbackLock);
  703. for (auto& mc : midiCallbacks)
  704. if (mc.deviceName.isEmpty() || mc.deviceName == source->getName())
  705. mc.callback->handleIncomingMidiMessage (source, message);
  706. }
  707. }
  708. //==============================================================================
  709. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  710. {
  711. if (defaultMidiOutputName != deviceName)
  712. {
  713. Array<AudioIODeviceCallback*> oldCallbacks;
  714. {
  715. const ScopedLock sl (audioCallbackLock);
  716. oldCallbacks.swapWith (callbacks);
  717. }
  718. if (currentAudioDevice != nullptr)
  719. for (int i = oldCallbacks.size(); --i >= 0;)
  720. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  721. defaultMidiOutput.reset();
  722. defaultMidiOutputName = deviceName;
  723. if (deviceName.isNotEmpty())
  724. defaultMidiOutput.reset (MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName)));
  725. if (currentAudioDevice != nullptr)
  726. for (auto* c : oldCallbacks)
  727. c->audioDeviceAboutToStart (currentAudioDevice.get());
  728. {
  729. const ScopedLock sl (audioCallbackLock);
  730. oldCallbacks.swapWith (callbacks);
  731. }
  732. updateXml();
  733. sendChangeMessage();
  734. }
  735. }
  736. //==============================================================================
  737. AudioDeviceManager::LevelMeter::LevelMeter() noexcept : level() {}
  738. void AudioDeviceManager::LevelMeter::updateLevel (const float* const* channelData, int numChannels, int numSamples) noexcept
  739. {
  740. if (getReferenceCount() <= 1)
  741. return;
  742. auto localLevel = level.get();
  743. if (numChannels > 0)
  744. {
  745. for (int j = 0; j < numSamples; ++j)
  746. {
  747. float s = 0;
  748. for (int i = 0; i < numChannels; ++i)
  749. s += std::abs (channelData[i][j]);
  750. s /= (float) numChannels;
  751. const float decayFactor = 0.99992f;
  752. if (s > localLevel)
  753. localLevel = s;
  754. else if (localLevel > 0.001f)
  755. localLevel *= decayFactor;
  756. else
  757. localLevel = 0;
  758. }
  759. }
  760. else
  761. {
  762. localLevel = 0;
  763. }
  764. level = localLevel;
  765. }
  766. double AudioDeviceManager::LevelMeter::getCurrentLevel() const noexcept
  767. {
  768. jassert (getReferenceCount() > 1);
  769. return level.get();
  770. }
  771. void AudioDeviceManager::playTestSound()
  772. {
  773. { // cunningly nested to swap, unlock and delete in that order.
  774. std::unique_ptr<AudioBuffer<float>> oldSound;
  775. {
  776. const ScopedLock sl (audioCallbackLock);
  777. std::swap (oldSound, testSound);
  778. }
  779. }
  780. testSoundPosition = 0;
  781. if (currentAudioDevice != nullptr)
  782. {
  783. auto sampleRate = currentAudioDevice->getCurrentSampleRate();
  784. auto soundLength = (int) sampleRate;
  785. double frequency = 440.0;
  786. float amplitude = 0.5f;
  787. auto phasePerSample = MathConstants<double>::twoPi / (sampleRate / frequency);
  788. std::unique_ptr<AudioBuffer<float>> newSound (new AudioBuffer<float> (1, soundLength));
  789. for (int i = 0; i < soundLength; ++i)
  790. newSound->setSample (0, i, amplitude * (float) std::sin (i * phasePerSample));
  791. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  792. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  793. {
  794. const ScopedLock sl (audioCallbackLock);
  795. std::swap (testSound, newSound);
  796. }
  797. }
  798. }
  799. int AudioDeviceManager::getXRunCount() const noexcept
  800. {
  801. auto deviceXRuns = (currentAudioDevice != nullptr ? currentAudioDevice->getXRunCount() : -1);
  802. return jmax (0, deviceXRuns) + loadMeasurer.getXRunCount();
  803. }
  804. } // namespace juce