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.

1016 lines
33KB

  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 (setup.outputDeviceName.isEmpty())
  276. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  277. if (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. String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  357. bool treatAsChosenDevice)
  358. {
  359. jassert (&newSetup != &currentSetup); // this will have no effect
  360. if (newSetup == currentSetup && currentAudioDevice != nullptr)
  361. return {};
  362. if (! (newSetup == currentSetup))
  363. sendChangeMessage();
  364. stopDevice();
  365. if (! newSetup.useDefaultInputChannels)
  366. numInputChansNeeded = newSetup.inputChannels.countNumberOfSetBits();
  367. if (! newSetup.useDefaultOutputChannels)
  368. numOutputChansNeeded = newSetup.outputChannels.countNumberOfSetBits();
  369. auto* type = getCurrentDeviceTypeObject();
  370. if (type == nullptr)
  371. {
  372. deleteCurrentDevice();
  373. if (treatAsChosenDevice)
  374. updateXml();
  375. return {};
  376. }
  377. String error;
  378. if (currentSetup.inputDeviceName != newSetup.inputDeviceName
  379. || currentSetup.outputDeviceName != newSetup.outputDeviceName
  380. || currentAudioDevice == nullptr)
  381. {
  382. deleteCurrentDevice();
  383. scanDevicesIfNeeded();
  384. if (newSetup.outputDeviceName.isNotEmpty() && ! deviceListContains (type, false, newSetup.outputDeviceName))
  385. return "No such device: " + newSetup.outputDeviceName;
  386. if (newSetup.inputDeviceName.isNotEmpty() && ! deviceListContains (type, true, newSetup.inputDeviceName))
  387. return "No such device: " + newSetup.inputDeviceName;
  388. currentAudioDevice.reset (type->createDevice (newSetup.outputDeviceName, newSetup.inputDeviceName));
  389. if (currentAudioDevice == nullptr)
  390. error = "Can't open the audio device!\n\n"
  391. "This may be because another application is currently using the same device - "
  392. "if so, you should close any other applications and try again!";
  393. else
  394. error = currentAudioDevice->getLastError();
  395. if (error.isNotEmpty())
  396. {
  397. deleteCurrentDevice();
  398. return error;
  399. }
  400. if (newSetup.useDefaultInputChannels)
  401. {
  402. inputChannels.clear();
  403. inputChannels.setRange (0, numInputChansNeeded, true);
  404. }
  405. if (newSetup.useDefaultOutputChannels)
  406. {
  407. outputChannels.clear();
  408. outputChannels.setRange (0, numOutputChansNeeded, true);
  409. }
  410. if (newSetup.inputDeviceName.isEmpty()) inputChannels.clear();
  411. if (newSetup.outputDeviceName.isEmpty()) outputChannels.clear();
  412. }
  413. if (! newSetup.useDefaultInputChannels)
  414. inputChannels = newSetup.inputChannels;
  415. if (! newSetup.useDefaultOutputChannels)
  416. outputChannels = newSetup.outputChannels;
  417. currentSetup = newSetup;
  418. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  419. currentSetup.bufferSize = chooseBestBufferSize (newSetup.bufferSize);
  420. error = currentAudioDevice->open (inputChannels,
  421. outputChannels,
  422. currentSetup.sampleRate,
  423. currentSetup.bufferSize);
  424. if (error.isEmpty())
  425. {
  426. currentDeviceType = currentAudioDevice->getTypeName();
  427. currentAudioDevice->start (callbackHandler.get());
  428. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  429. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  430. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  431. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  432. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  433. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  434. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  435. if (treatAsChosenDevice)
  436. updateXml();
  437. }
  438. else
  439. {
  440. deleteCurrentDevice();
  441. }
  442. return error;
  443. }
  444. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  445. {
  446. jassert (currentAudioDevice != nullptr);
  447. auto rates = currentAudioDevice->getAvailableSampleRates();
  448. if (rate > 0 && rates.contains (rate))
  449. return rate;
  450. rate = currentAudioDevice->getCurrentSampleRate();
  451. if (rate > 0 && rates.contains (rate))
  452. return rate;
  453. double lowestAbove44 = 0.0;
  454. for (int i = rates.size(); --i >= 0;)
  455. {
  456. auto sr = rates[i];
  457. if (sr >= 44100.0 && (lowestAbove44 < 1.0 || sr < lowestAbove44))
  458. lowestAbove44 = sr;
  459. }
  460. if (lowestAbove44 > 0.0)
  461. return lowestAbove44;
  462. return rates[0];
  463. }
  464. int AudioDeviceManager::chooseBestBufferSize (int bufferSize) const
  465. {
  466. jassert (currentAudioDevice != nullptr);
  467. if (bufferSize > 0 && currentAudioDevice->getAvailableBufferSizes().contains (bufferSize))
  468. return bufferSize;
  469. return currentAudioDevice->getDefaultBufferSize();
  470. }
  471. void AudioDeviceManager::stopDevice()
  472. {
  473. if (currentAudioDevice != nullptr)
  474. currentAudioDevice->stop();
  475. testSound.reset();
  476. }
  477. void AudioDeviceManager::closeAudioDevice()
  478. {
  479. stopDevice();
  480. currentAudioDevice.reset();
  481. loadMeasurer.reset();
  482. }
  483. void AudioDeviceManager::restartLastAudioDevice()
  484. {
  485. if (currentAudioDevice == nullptr)
  486. {
  487. if (currentSetup.inputDeviceName.isEmpty()
  488. && currentSetup.outputDeviceName.isEmpty())
  489. {
  490. // This method will only reload the last device that was running
  491. // before closeAudioDevice() was called - you need to actually open
  492. // one first, with setAudioDevice().
  493. jassertfalse;
  494. return;
  495. }
  496. AudioDeviceSetup s (currentSetup);
  497. setAudioDeviceSetup (s, false);
  498. }
  499. }
  500. void AudioDeviceManager::updateXml()
  501. {
  502. lastExplicitSettings.reset (new XmlElement ("DEVICESETUP"));
  503. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  504. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  505. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  506. if (currentAudioDevice != nullptr)
  507. {
  508. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  509. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  510. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  511. if (! currentSetup.useDefaultInputChannels)
  512. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  513. if (! currentSetup.useDefaultOutputChannels)
  514. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  515. }
  516. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  517. lastExplicitSettings->createNewChildElement ("MIDIINPUT")
  518. ->setAttribute ("name", enabledMidiInputs[i]->getName());
  519. if (midiInsFromXml.size() > 0)
  520. {
  521. // Add any midi devices that have been enabled before, but which aren't currently
  522. // open because the device has been disconnected.
  523. const StringArray availableMidiDevices (MidiInput::getDevices());
  524. for (int i = 0; i < midiInsFromXml.size(); ++i)
  525. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  526. lastExplicitSettings->createNewChildElement ("MIDIINPUT")
  527. ->setAttribute ("name", midiInsFromXml[i]);
  528. }
  529. if (defaultMidiOutputName.isNotEmpty())
  530. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  531. }
  532. //==============================================================================
  533. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  534. {
  535. {
  536. const ScopedLock sl (audioCallbackLock);
  537. if (callbacks.contains (newCallback))
  538. return;
  539. }
  540. if (currentAudioDevice != nullptr && newCallback != nullptr)
  541. newCallback->audioDeviceAboutToStart (currentAudioDevice.get());
  542. const ScopedLock sl (audioCallbackLock);
  543. callbacks.add (newCallback);
  544. }
  545. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callbackToRemove)
  546. {
  547. if (callbackToRemove != nullptr)
  548. {
  549. bool needsDeinitialising = currentAudioDevice != nullptr;
  550. {
  551. const ScopedLock sl (audioCallbackLock);
  552. needsDeinitialising = needsDeinitialising && callbacks.contains (callbackToRemove);
  553. callbacks.removeFirstMatchingValue (callbackToRemove);
  554. }
  555. if (needsDeinitialising)
  556. callbackToRemove->audioDeviceStopped();
  557. }
  558. }
  559. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  560. int numInputChannels,
  561. float** outputChannelData,
  562. int numOutputChannels,
  563. int numSamples)
  564. {
  565. const ScopedLock sl (audioCallbackLock);
  566. inputLevelGetter->updateLevel (inputChannelData, numInputChannels, numSamples);
  567. outputLevelGetter->updateLevel (const_cast<const float**> (outputChannelData), numOutputChannels, numSamples);
  568. if (callbacks.size() > 0)
  569. {
  570. AudioProcessLoadMeasurer::ScopedTimer timer (loadMeasurer);
  571. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  572. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  573. outputChannelData, numOutputChannels, numSamples);
  574. auto** tempChans = tempBuffer.getArrayOfWritePointers();
  575. for (int i = callbacks.size(); --i > 0;)
  576. {
  577. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  578. tempChans, numOutputChannels, numSamples);
  579. for (int chan = 0; chan < numOutputChannels; ++chan)
  580. {
  581. if (auto* src = tempChans [chan])
  582. if (auto* dst = outputChannelData [chan])
  583. for (int j = 0; j < numSamples; ++j)
  584. dst[j] += src[j];
  585. }
  586. }
  587. }
  588. else
  589. {
  590. for (int i = 0; i < numOutputChannels; ++i)
  591. zeromem (outputChannelData[i], sizeof (float) * (size_t) numSamples);
  592. }
  593. if (testSound != nullptr)
  594. {
  595. auto numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  596. auto* src = testSound->getReadPointer (0, testSoundPosition);
  597. for (int i = 0; i < numOutputChannels; ++i)
  598. for (int j = 0; j < numSamps; ++j)
  599. outputChannelData [i][j] += src[j];
  600. testSoundPosition += numSamps;
  601. if (testSoundPosition >= testSound->getNumSamples())
  602. testSound.reset();
  603. }
  604. }
  605. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  606. {
  607. loadMeasurer.reset (device->getCurrentSampleRate(),
  608. device->getCurrentBufferSizeSamples());
  609. {
  610. const ScopedLock sl (audioCallbackLock);
  611. for (int i = callbacks.size(); --i >= 0;)
  612. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  613. }
  614. sendChangeMessage();
  615. }
  616. void AudioDeviceManager::audioDeviceStoppedInt()
  617. {
  618. sendChangeMessage();
  619. const ScopedLock sl (audioCallbackLock);
  620. loadMeasurer.reset();
  621. for (int i = callbacks.size(); --i >= 0;)
  622. callbacks.getUnchecked(i)->audioDeviceStopped();
  623. }
  624. void AudioDeviceManager::audioDeviceErrorInt (const String& message)
  625. {
  626. const ScopedLock sl (audioCallbackLock);
  627. for (int i = callbacks.size(); --i >= 0;)
  628. callbacks.getUnchecked(i)->audioDeviceError (message);
  629. }
  630. double AudioDeviceManager::getCpuUsage() const
  631. {
  632. return loadMeasurer.getLoadAsProportion();
  633. }
  634. //==============================================================================
  635. void AudioDeviceManager::setMidiInputEnabled (const String& name, const bool enabled)
  636. {
  637. if (enabled != isMidiInputEnabled (name))
  638. {
  639. if (enabled)
  640. {
  641. auto index = MidiInput::getDevices().indexOf (name);
  642. if (index >= 0)
  643. {
  644. if (auto* midiIn = MidiInput::openDevice (index, callbackHandler.get()))
  645. {
  646. enabledMidiInputs.add (midiIn);
  647. midiIn->start();
  648. }
  649. }
  650. }
  651. else
  652. {
  653. for (int i = enabledMidiInputs.size(); --i >= 0;)
  654. if (enabledMidiInputs[i]->getName() == name)
  655. enabledMidiInputs.remove (i);
  656. }
  657. updateXml();
  658. sendChangeMessage();
  659. }
  660. }
  661. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  662. {
  663. for (auto* mi : enabledMidiInputs)
  664. if (mi->getName() == name)
  665. return true;
  666. return false;
  667. }
  668. void AudioDeviceManager::addMidiInputCallback (const String& name, MidiInputCallback* callbackToAdd)
  669. {
  670. removeMidiInputCallback (name, callbackToAdd);
  671. if (name.isEmpty() || isMidiInputEnabled (name))
  672. {
  673. const ScopedLock sl (midiCallbackLock);
  674. MidiCallbackInfo mc;
  675. mc.deviceName = name;
  676. mc.callback = callbackToAdd;
  677. midiCallbacks.add (mc);
  678. }
  679. }
  680. void AudioDeviceManager::removeMidiInputCallback (const String& name, MidiInputCallback* callbackToRemove)
  681. {
  682. for (int i = midiCallbacks.size(); --i >= 0;)
  683. {
  684. auto& mc = midiCallbacks.getReference(i);
  685. if (mc.callback == callbackToRemove && mc.deviceName == name)
  686. {
  687. const ScopedLock sl (midiCallbackLock);
  688. midiCallbacks.remove (i);
  689. }
  690. }
  691. }
  692. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message)
  693. {
  694. if (! message.isActiveSense())
  695. {
  696. const ScopedLock sl (midiCallbackLock);
  697. for (auto& mc : midiCallbacks)
  698. if (mc.deviceName.isEmpty() || mc.deviceName == source->getName())
  699. mc.callback->handleIncomingMidiMessage (source, message);
  700. }
  701. }
  702. //==============================================================================
  703. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  704. {
  705. if (defaultMidiOutputName != deviceName)
  706. {
  707. Array<AudioIODeviceCallback*> oldCallbacks;
  708. {
  709. const ScopedLock sl (audioCallbackLock);
  710. oldCallbacks.swapWith (callbacks);
  711. }
  712. if (currentAudioDevice != nullptr)
  713. for (int i = oldCallbacks.size(); --i >= 0;)
  714. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  715. defaultMidiOutput.reset();
  716. defaultMidiOutputName = deviceName;
  717. if (deviceName.isNotEmpty())
  718. defaultMidiOutput.reset (MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName)));
  719. if (currentAudioDevice != nullptr)
  720. for (auto* c : oldCallbacks)
  721. c->audioDeviceAboutToStart (currentAudioDevice.get());
  722. {
  723. const ScopedLock sl (audioCallbackLock);
  724. oldCallbacks.swapWith (callbacks);
  725. }
  726. updateXml();
  727. sendChangeMessage();
  728. }
  729. }
  730. //==============================================================================
  731. AudioDeviceManager::LevelMeter::LevelMeter() noexcept : level() {}
  732. void AudioDeviceManager::LevelMeter::updateLevel (const float* const* channelData, int numChannels, int numSamples) noexcept
  733. {
  734. if (getReferenceCount() <= 1)
  735. return;
  736. auto localLevel = level.get();
  737. if (numChannels > 0)
  738. {
  739. for (int j = 0; j < numSamples; ++j)
  740. {
  741. float s = 0;
  742. for (int i = 0; i < numChannels; ++i)
  743. s += std::abs (channelData[i][j]);
  744. s /= (float) numChannels;
  745. const float decayFactor = 0.99992f;
  746. if (s > localLevel)
  747. localLevel = s;
  748. else if (localLevel > 0.001f)
  749. localLevel *= decayFactor;
  750. else
  751. localLevel = 0;
  752. }
  753. }
  754. else
  755. {
  756. localLevel = 0;
  757. }
  758. level = localLevel;
  759. }
  760. double AudioDeviceManager::LevelMeter::getCurrentLevel() const noexcept
  761. {
  762. jassert (getReferenceCount() > 1);
  763. return level.get();
  764. }
  765. void AudioDeviceManager::playTestSound()
  766. {
  767. { // cunningly nested to swap, unlock and delete in that order.
  768. std::unique_ptr<AudioBuffer<float>> oldSound;
  769. {
  770. const ScopedLock sl (audioCallbackLock);
  771. std::swap (oldSound, testSound);
  772. }
  773. }
  774. testSoundPosition = 0;
  775. if (currentAudioDevice != nullptr)
  776. {
  777. auto sampleRate = currentAudioDevice->getCurrentSampleRate();
  778. auto soundLength = (int) sampleRate;
  779. double frequency = 440.0;
  780. float amplitude = 0.5f;
  781. auto phasePerSample = MathConstants<double>::twoPi / (sampleRate / frequency);
  782. std::unique_ptr<AudioBuffer<float>> newSound (new AudioBuffer<float> (1, soundLength));
  783. for (int i = 0; i < soundLength; ++i)
  784. newSound->setSample (0, i, amplitude * (float) std::sin (i * phasePerSample));
  785. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  786. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  787. {
  788. const ScopedLock sl (audioCallbackLock);
  789. std::swap (testSound, newSound);
  790. }
  791. }
  792. }
  793. int AudioDeviceManager::getXRunCount() const noexcept
  794. {
  795. auto deviceXRuns = (currentAudioDevice != nullptr ? currentAudioDevice->getXRunCount() : -1);
  796. return jmax (0, deviceXRuns) + loadMeasurer.getXRunCount();
  797. }
  798. } // namespace juce